diff --git a/Application/EdFi.Ods.Api/Container/Modules/ApplicationModule.cs b/Application/EdFi.Ods.Api/Container/Modules/ApplicationModule.cs index 4fe8550363..6f4f185ff5 100644 --- a/Application/EdFi.Ods.Api/Container/Modules/ApplicationModule.cs +++ b/Application/EdFi.Ods.Api/Container/Modules/ApplicationModule.cs @@ -259,10 +259,6 @@ void RegisterModels() .AsSelf() .SingleInstance(); - builder.RegisterGeneric(typeof(GetDeletedResourceModelByIds<,,>)) - .AsSelf() - .SingleInstance(); - builder.RegisterGeneric(typeof(ValidateResourceModel<,,,>)) .AsSelf() .SingleInstance(); @@ -296,11 +292,6 @@ void RegisterPipeLineStepProviders() .As() .SingleInstance(); - builder.RegisterType() - .As() - .As() - .SingleInstance(); - builder.RegisterType() .As() .As() diff --git a/Application/EdFi.Ods.Api/Container/Modules/PostgresSpecificModule.cs b/Application/EdFi.Ods.Api/Container/Modules/PostgresSpecificModule.cs index 2b86f69e2a..896bf8c14b 100644 --- a/Application/EdFi.Ods.Api/Container/Modules/PostgresSpecificModule.cs +++ b/Application/EdFi.Ods.Api/Container/Modules/PostgresSpecificModule.cs @@ -3,6 +3,7 @@ // The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. // See the LICENSE and NOTICES files in the project root for more information. +using System.Data.Common; using Autofac; using EdFi.Common.Configuration; using EdFi.Ods.Common.Configuration; @@ -10,7 +11,11 @@ using EdFi.Ods.Common.Infrastructure.Activities; using EdFi.Ods.Common.Infrastructure.Configuration; using EdFi.Ods.Common.Infrastructure.PostgreSql; +using EdFi.Ods.Generator.Database.Engines.PostgreSql; +using EdFi.Ods.Generator.Database.NamingConventions; using EdFi.Ods.Security.Authorization; +using Npgsql; +using SqlKata.Compilers; namespace EdFi.Ods.Api.Container.Modules { @@ -34,6 +39,16 @@ public override void ApplyConfigurationSpecificRegistrations(ContainerBuilder bu builder.RegisterType() .As() .SingleInstance(); + + builder.RegisterInstance(NpgsqlFactory.Instance) + .As(); + + builder.Register(ctx => new PostgresCompiler()); + + // Register PostgreSQL naming convention + builder.RegisterType() + .As() + .SingleInstance(); } } } diff --git a/Application/EdFi.Ods.Api/Container/Modules/SqlServerSpecificModule.cs b/Application/EdFi.Ods.Api/Container/Modules/SqlServerSpecificModule.cs index dc9f201be8..523448ed3a 100644 --- a/Application/EdFi.Ods.Api/Container/Modules/SqlServerSpecificModule.cs +++ b/Application/EdFi.Ods.Api/Container/Modules/SqlServerSpecificModule.cs @@ -3,6 +3,8 @@ // The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. // See the LICENSE and NOTICES files in the project root for more information. +using System.Data.Common; +using System.Data.SqlClient; using Autofac; using EdFi.Common.Configuration; using EdFi.Ods.Common.Configuration; @@ -10,7 +12,10 @@ using EdFi.Ods.Common.Infrastructure.Activities; using EdFi.Ods.Common.Infrastructure.Configuration; using EdFi.Ods.Common.Infrastructure.SqlServer; +using EdFi.Ods.Generator.Database.Engines.SqlServer; +using EdFi.Ods.Generator.Database.NamingConventions; using EdFi.Ods.Security.Authorization; +using SqlKata.Compilers; namespace EdFi.Ods.Api.Container.Modules { @@ -34,6 +39,16 @@ public override void ApplyConfigurationSpecificRegistrations(ContainerBuilder bu builder.RegisterType() .As() .SingleInstance(); + + builder.RegisterInstance(SqlClientFactory.Instance) + .As(); + + builder.Register(ctx => new SqlServerCompiler()); + + // Register SQL Server SQL naming convention + builder.RegisterType() + .As() + .SingleInstance(); } } } \ No newline at end of file diff --git a/Application/EdFi.Ods.Api/Controllers/DataManagementControllerBase.cs b/Application/EdFi.Ods.Api/Controllers/DataManagementControllerBase.cs index aa70056af4..5da213863a 100644 --- a/Application/EdFi.Ods.Api/Controllers/DataManagementControllerBase.cs +++ b/Application/EdFi.Ods.Api/Controllers/DataManagementControllerBase.cs @@ -14,7 +14,6 @@ using EdFi.Ods.Api.Filters; using EdFi.Ods.Api.Infrastructure.Pipelines.Factories; using EdFi.Ods.Api.Infrastructure.Pipelines.Get; -using EdFi.Ods.Api.Infrastructure.Pipelines.GetDeletedResource; using EdFi.Ods.Api.Infrastructure.Pipelines.GetMany; using EdFi.Ods.Api.Infrastructure.Pipelines.Put; using EdFi.Ods.Common; @@ -62,7 +61,6 @@ public abstract class DataManagementControllerBase DeletePipeline; protected Lazy> GetByIdPipeline; - protected Lazy> GetDeletedResourcePipeline; protected Lazy> GetManyPipeline; protected Lazy> PutPipeline; @@ -87,10 +85,6 @@ protected DataManagementControllerBase( GetManyPipeline = new Lazy> (pipelineFactory.CreateGetManyPipeline); - // Change queries resource pipeline for deleted objects. - GetDeletedResourcePipeline = new Lazy> - (pipelineFactory.CreateGetDeletedResourcePipeline); - PutPipeline = new Lazy> (pipelineFactory.CreatePutPipeline); diff --git a/Application/EdFi.Ods.Api/EdFi.Ods.Api.csproj b/Application/EdFi.Ods.Api/EdFi.Ods.Api.csproj index 81d21b1d34..65b6755040 100644 --- a/Application/EdFi.Ods.Api/EdFi.Ods.Api.csproj +++ b/Application/EdFi.Ods.Api/EdFi.Ods.Api.csproj @@ -34,11 +34,13 @@ + + diff --git a/Application/EdFi.Ods.Api/Helpers/ControllerHelpers.cs b/Application/EdFi.Ods.Api/Helpers/ControllerHelpers.cs new file mode 100644 index 0000000000..9b3b931183 --- /dev/null +++ b/Application/EdFi.Ods.Api/Helpers/ControllerHelpers.cs @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System.Net; +using Microsoft.AspNetCore.Mvc; + +namespace EdFi.Ods.Api.Helpers +{ + public static class ControllerHelpers + { + /// + /// Gets an IActionResult returning a 404 Not Found status with no response body. + /// + /// + public static IActionResult NotFound() + { + return new ObjectResult(null) + { + StatusCode = (int) HttpStatusCode.NotFound, + }; + } + } +} diff --git a/Application/EdFi.Ods.Api/Infrastructure/Pipelines/Factories/IPipelineFactory.cs b/Application/EdFi.Ods.Api/Infrastructure/Pipelines/Factories/IPipelineFactory.cs index eeac8b3eef..ab5375b770 100644 --- a/Application/EdFi.Ods.Api/Infrastructure/Pipelines/Factories/IPipelineFactory.cs +++ b/Application/EdFi.Ods.Api/Infrastructure/Pipelines/Factories/IPipelineFactory.cs @@ -4,7 +4,6 @@ // See the LICENSE and NOTICES files in the project root for more information. using EdFi.Ods.Api.Infrastructure.Pipelines.Get; -using EdFi.Ods.Api.Infrastructure.Pipelines.GetDeletedResource; using EdFi.Ods.Api.Infrastructure.Pipelines.GetMany; using EdFi.Ods.Api.Infrastructure.Pipelines.Put; using EdFi.Ods.Common; @@ -22,9 +21,6 @@ GetManyPipeline CreateGetManyPipeline CreateGetDeletedResourcePipeline() - where TEntityModel : class; - PutPipeline CreatePutPipeline() where TEntityModel : class, IHasIdentifier, new() where TResourceModel : IHasETag; diff --git a/Application/EdFi.Ods.Api/Infrastructure/Pipelines/Factories/PipelineFactory.cs b/Application/EdFi.Ods.Api/Infrastructure/Pipelines/Factories/PipelineFactory.cs index bab5bc1a7e..4f129c8ccb 100644 --- a/Application/EdFi.Ods.Api/Infrastructure/Pipelines/Factories/PipelineFactory.cs +++ b/Application/EdFi.Ods.Api/Infrastructure/Pipelines/Factories/PipelineFactory.cs @@ -8,13 +8,11 @@ using System.Linq; using EdFi.Common.InversionOfControl; using EdFi.Ods.Api.Infrastructure.Pipelines.Get; -using EdFi.Ods.Api.Infrastructure.Pipelines.GetDeletedResource; using EdFi.Ods.Api.Infrastructure.Pipelines.GetMany; using EdFi.Ods.Api.Infrastructure.Pipelines.Put; using EdFi.Ods.Common; using EdFi.Ods.Common.Infrastructure.Pipelines; using EdFi.Ods.Common.Infrastructure.Pipelines.Delete; -using EdFi.Ods.Common.Infrastructure.Pipelines.GetDeletedResource; using EdFi.Ods.Common.Infrastructure.Pipelines.GetMany; namespace EdFi.Ods.Api.Infrastructure.Pipelines.Factories @@ -25,21 +23,18 @@ public class PipelineFactory : IPipelineFactory private readonly IDeletePipelineStepsProvider deletePipelineStepsProvider; private readonly IGetBySpecificationPipelineStepsProvider getBySpecificationPipelineStepsProvider; private readonly IGetPipelineStepsProvider getPipelineStepsProvider; - private readonly IGetDeletedResourceIdsPipelineStepsProvider getDeletedResourceIdsPipelineStepsProvider; private readonly IPutPipelineStepsProvider putPipelineStepsProvider; public PipelineFactory( IServiceLocator locator, IGetPipelineStepsProvider getPipelineStepsProvider, IGetBySpecificationPipelineStepsProvider getBySpecificationPipelineStepsProvider, - IGetDeletedResourceIdsPipelineStepsProvider getDeletedResourceIdsPipelineStepsProvider, IPutPipelineStepsProvider putPipelineStepsProvider, IDeletePipelineStepsProvider deletePipelineStepsProvider) { _locator = locator; this.getPipelineStepsProvider = getPipelineStepsProvider; this.getBySpecificationPipelineStepsProvider = getBySpecificationPipelineStepsProvider; - this.getDeletedResourceIdsPipelineStepsProvider = getDeletedResourceIdsPipelineStepsProvider; this.putPipelineStepsProvider = putPipelineStepsProvider; this.deletePipelineStepsProvider = deletePipelineStepsProvider; } @@ -71,18 +66,6 @@ public GetManyPipeline CreateGetManyPipeline(steps); } - public GetDeletedResourcePipeline CreateGetDeletedResourcePipeline() - where TEntityModel : class - { - var stepsTypes = getDeletedResourceIdsPipelineStepsProvider.GetSteps(); - - var steps = - ResolvePipelineSteps, GetDeletedResourceResult, TResourceModel, - TEntityModel>(stepsTypes); - - return new GetDeletedResourcePipeline(steps); - } - public PutPipeline CreatePutPipeline() where TEntityModel : class, IHasIdentifier, new() where TResourceModel : IHasETag diff --git a/Application/EdFi.Ods.Api/Infrastructure/Pipelines/Factories/PipelineStepsProviders.cs b/Application/EdFi.Ods.Api/Infrastructure/Pipelines/Factories/PipelineStepsProviders.cs index 7d079db24b..4945729800 100644 --- a/Application/EdFi.Ods.Api/Infrastructure/Pipelines/Factories/PipelineStepsProviders.cs +++ b/Application/EdFi.Ods.Api/Infrastructure/Pipelines/Factories/PipelineStepsProviders.cs @@ -42,20 +42,6 @@ public Type[] GetSteps() } } - /// - /// Provides the core Ed-Fi ODS API steps for "GetTrackedDelete" access. - /// - public class GetDeletedResourceIdsPipelineStepsProvider : IGetDeletedResourceIdsPipelineStepsProvider - { - public Type[] GetSteps() - { - return new[] - { - typeof(GetDeletedResourceModelByIds<,,>), - }; - } - } - /// /// Provides the core Ed-Fi ODS API steps for "Upsert" persistence. /// diff --git a/Application/EdFi.Ods.Api/Infrastructure/Pipelines/GetDeletedResource/GetDeletedResourceContext.cs b/Application/EdFi.Ods.Api/Infrastructure/Pipelines/GetDeletedResource/GetDeletedResourceContext.cs deleted file mode 100644 index 560b8b8877..0000000000 --- a/Application/EdFi.Ods.Api/Infrastructure/Pipelines/GetDeletedResource/GetDeletedResourceContext.cs +++ /dev/null @@ -1,25 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// Licensed to the Ed-Fi Alliance under one or more agreements. -// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. -// See the LICENSE and NOTICES files in the project root for more information. - -using System; -using EdFi.Ods.Api.Infrastructure.Pipelines; - -namespace EdFi.Ods.Common.Infrastructure.Pipelines.GetDeletedResource -{ - public class GetDeletedResourceContext : IHasIdentifier, IHasPersistentModel - where TEntityModel : class - { - public GetDeletedResourceContext(IQueryParameters queryParameters) - { - QueryParameters = queryParameters; - } - - public Guid Id { get; set; } - - public TEntityModel PersistentModel { get; set; } - - public IQueryParameters QueryParameters { get; } - } -} diff --git a/Application/EdFi.Ods.Api/Infrastructure/Pipelines/GetDeletedResource/GetDeletedResourcePipeline.cs b/Application/EdFi.Ods.Api/Infrastructure/Pipelines/GetDeletedResource/GetDeletedResourcePipeline.cs deleted file mode 100644 index 657a95cedf..0000000000 --- a/Application/EdFi.Ods.Api/Infrastructure/Pipelines/GetDeletedResource/GetDeletedResourcePipeline.cs +++ /dev/null @@ -1,19 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// Licensed to the Ed-Fi Alliance under one or more agreements. -// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. -// See the LICENSE and NOTICES files in the project root for more information. - -using EdFi.Ods.Common.Infrastructure.Pipelines; -using EdFi.Ods.Common.Infrastructure.Pipelines.GetDeletedResource; - -namespace EdFi.Ods.Api.Infrastructure.Pipelines.GetDeletedResource -{ - public class GetDeletedResourcePipeline:PipelineBase, GetDeletedResourceResult> - where TEntityModel : class - { - public GetDeletedResourcePipeline(IStep, GetDeletedResourceResult>[] steps) - : base(steps) - { - } - } -} diff --git a/Application/EdFi.Ods.Api/Infrastructure/Pipelines/GetDeletedResource/GetDeletedResourceResult.cs b/Application/EdFi.Ods.Api/Infrastructure/Pipelines/GetDeletedResource/GetDeletedResourceResult.cs deleted file mode 100644 index 7ee061cc55..0000000000 --- a/Application/EdFi.Ods.Api/Infrastructure/Pipelines/GetDeletedResource/GetDeletedResourceResult.cs +++ /dev/null @@ -1,16 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// Licensed to the Ed-Fi Alliance under one or more agreements. -// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. -// See the LICENSE and NOTICES files in the project root for more information. - -using EdFi.Ods.Common.Infrastructure.Pipelines; - -namespace EdFi.Ods.Api.Infrastructure.Pipelines.GetDeletedResource -{ - public class GetDeletedResourceResult: PipelineResultBase, IHasResourceChangeDetails - { - public bool ResourceWasCreated { get; set; } - public bool ResourceWasUpdated { get; set; } - public bool ResourceWasDeleted { get; set; } - } -} \ No newline at end of file diff --git a/Application/EdFi.Ods.Api/Infrastructure/Pipelines/Steps/GetDeletedResourceModelByIds.cs b/Application/EdFi.Ods.Api/Infrastructure/Pipelines/Steps/GetDeletedResourceModelByIds.cs deleted file mode 100644 index f3a7c1649a..0000000000 --- a/Application/EdFi.Ods.Api/Infrastructure/Pipelines/Steps/GetDeletedResourceModelByIds.cs +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// Licensed to the Ed-Fi Alliance under one or more agreements. -// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. -// See the LICENSE and NOTICES files in the project root for more information. - -using System.Threading; -using System.Threading.Tasks; -using EdFi.Ods.Api.Infrastructure.Pipelines.GetDeletedResource; -using EdFi.Ods.Common; -using EdFi.Ods.Common.Infrastructure.Pipelines; -using EdFi.Ods.Common.Infrastructure.Pipelines.GetDeletedResource; - -namespace EdFi.Ods.Api.Infrastructure.Pipelines.Steps -{ - public class GetDeletedResourceModelByIds - : IStep - where TContext : GetDeletedResourceContext - where TResult : PipelineResultBase - where TEntityModel : class, IHasIdentifier - { - private readonly IGetDeletedResourceIds _repository; - - public GetDeletedResourceModelByIds(IGetDeletedResourceIds repository) - { - _repository = repository; - } - - public Task ExecuteAsync(TContext context, TResult result, CancellationToken cancellationToken) - { - throw new System.NotImplementedException(); - } - } -} diff --git a/Application/EdFi.Ods.Api/Repositories/InstanceSecurityRepository.cs b/Application/EdFi.Ods.Api/Repositories/InstanceSecurityRepository.cs index 58b1a8ac9e..83a614dab0 100644 --- a/Application/EdFi.Ods.Api/Repositories/InstanceSecurityRepository.cs +++ b/Application/EdFi.Ods.Api/Repositories/InstanceSecurityRepository.cs @@ -4,6 +4,7 @@ using EdFi.Common; using EdFi.Ods.Api.Caching; using EdFi.Ods.Common.Context; +using EdFi.Ods.Common.Exceptions; using EdFi.Security.DataAccess.Models; using Action = EdFi.Security.DataAccess.Models.Action; @@ -53,7 +54,14 @@ public virtual Action GetActionByName(string actionName) var instanceSecurityRepoCacheObject = InstanceSecurityRepositoryCache.GetCache() .GetSecurityRepository(instanceId); - return instanceSecurityRepoCacheObject.Actions.First(a => a.ActionName.Equals(actionName, StringComparison.InvariantCultureIgnoreCase)); + var action = instanceSecurityRepoCacheObject.Actions.FirstOrDefault(a => a.ActionName.Equals(actionName, StringComparison.InvariantCultureIgnoreCase)); + + if (action == null) + { + throw new ApiSecurityConfigurationException($"Action '{actionName}' not found in the security metadata."); + } + + return action; } public virtual AuthorizationStrategy GetAuthorizationStrategyByName(string authorizationStrategyName) diff --git a/Application/EdFi.Ods.Common/Extensions/ResourceExtensions.cs b/Application/EdFi.Ods.Common/Extensions/ResourceExtensions.cs index 2c8e218843..f330183e9f 100644 --- a/Application/EdFi.Ods.Common/Extensions/ResourceExtensions.cs +++ b/Application/EdFi.Ods.Common/Extensions/ResourceExtensions.cs @@ -3,6 +3,7 @@ // The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. // See the LICENSE and NOTICES files in the project root for more information. +using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; @@ -199,8 +200,10 @@ public static string SchemaUriSegment(this Resource resource) => resource /// /// The resource class that is being inspected. /// true if the resource class has a discriminator; otherwise false. + [Obsolete("This extension method doesn't make sense in the context of a resource that is derived and combines multiple entities. The Discriminator is an Entity-specific concept. Be explicit, and use the Entity's HasDiscriminator extension method instead.")] public static bool HasDiscriminator(this ResourceClassBase resourceClass) { + // NOTE: This returns unexpected values for resources that are derived. return resourceClass.Entity?.HasDiscriminator() == true; } diff --git a/Application/EdFi.Ods.Common/Infrastructure/Pipelines/IPipelineStepsProvider.cs b/Application/EdFi.Ods.Common/Infrastructure/Pipelines/IPipelineStepsProvider.cs index b21f620407..47f5e333ed 100644 --- a/Application/EdFi.Ods.Common/Infrastructure/Pipelines/IPipelineStepsProvider.cs +++ b/Application/EdFi.Ods.Common/Infrastructure/Pipelines/IPipelineStepsProvider.cs @@ -15,7 +15,6 @@ public interface IPipelineStepsProvider public interface IGetPipelineStepsProvider : IPipelineStepsProvider { } public interface IGetBySpecificationPipelineStepsProvider : IPipelineStepsProvider { } - public interface IGetDeletedResourceIdsPipelineStepsProvider : IPipelineStepsProvider { } public interface IPutPipelineStepsProvider : IPipelineStepsProvider { } public interface IDeletePipelineStepsProvider : IPipelineStepsProvider { } diff --git a/Application/EdFi.Ods.Common/Models/Definitions/AggregateDefinition.cs b/Application/EdFi.Ods.Common/Models/Definitions/AggregateDefinition.cs index 2bfdc6e477..fd2951162e 100644 --- a/Application/EdFi.Ods.Common/Models/Definitions/AggregateDefinition.cs +++ b/Application/EdFi.Ods.Common/Models/Definitions/AggregateDefinition.cs @@ -28,5 +28,7 @@ public AggregateDefinition(FullName aggregateRootEntityName, FullName[] aggregat public FullName AggregateRootEntityName { get; set; } public FullName[] AggregateEntityNames { get; set; } + + public override string ToString() => AggregateRootEntityName.ToString(); } } diff --git a/Application/EdFi.Ods.Common/Models/Definitions/AggregateExtensionDefinition.cs b/Application/EdFi.Ods.Common/Models/Definitions/AggregateExtensionDefinition.cs index d2d0de203c..6f873c9399 100644 --- a/Application/EdFi.Ods.Common/Models/Definitions/AggregateExtensionDefinition.cs +++ b/Application/EdFi.Ods.Common/Models/Definitions/AggregateExtensionDefinition.cs @@ -38,5 +38,7 @@ public AggregateExtensionDefinition(FullName aggregateRootEntityName, FullName[] /// Gets the full names of the extension entities to be added to the aggregate. /// public FullName[] ExtensionEntityNames { get; set; } + + public override string ToString() => $"{AggregateRootEntityName} (extensions)"; } } diff --git a/Application/EdFi.Ods.Common/Models/Definitions/AssociationDefinition.cs b/Application/EdFi.Ods.Common/Models/Definitions/AssociationDefinition.cs index c7c8370aa8..f945100162 100644 --- a/Application/EdFi.Ods.Common/Models/Definitions/AssociationDefinition.cs +++ b/Application/EdFi.Ods.Common/Models/Definitions/AssociationDefinition.cs @@ -75,5 +75,42 @@ public AssociationDefinition( public bool PotentiallyLogical { get; set; } public IDictionary ConstraintNames { get; set; } + + public override string ToString() + { + string cardinality; + + switch (Cardinality) + { + case Cardinality.OneToZeroOrMore: + cardinality = "(1)-->(*)"; + break; + + case Cardinality.OneToOneOrMore: + cardinality = "(1)-->(+)"; + break; + + case Cardinality.OneToOne: + cardinality = "(1)-->(1)"; + break; + + case Cardinality.OneToOneInheritance: + cardinality = "<|---"; + break; + + case Cardinality.OneToOneExtension: + cardinality = "(1)-->(1X)"; + break; + + case Cardinality.OneToZeroOrOneExtension: + cardinality = "(1)-->(1X?)"; + break; + + default: + throw new NotImplementedException($"Unimplemented cardinality: '{Cardinality}."); + } + + return $"{PrimaryEntityFullName}{cardinality}{SecondaryEntityFullName}"; + } } } diff --git a/Application/EdFi.Ods.Common/Models/Definitions/EntityDefinition.cs b/Application/EdFi.Ods.Common/Models/Definitions/EntityDefinition.cs index 0278919de1..ddafe32793 100644 --- a/Application/EdFi.Ods.Common/Models/Definitions/EntityDefinition.cs +++ b/Application/EdFi.Ods.Common/Models/Definitions/EntityDefinition.cs @@ -7,13 +7,15 @@ using System.Collections.Generic; using EdFi.Common.Configuration; using EdFi.Ods.Common.Configuration; +using EdFi.Ods.Common.Models.Domain; +using EdFi.Ods.Common.Models.Dynamic; using EdFi.Ods.Common.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace EdFi.Ods.Common.Models.Definitions { - public class EntityDefinition + public class EntityDefinition : DynamicModel { /// /// Initializes a new instance of the class. @@ -45,7 +47,7 @@ public EntityDefinition( { Schema = schema; Name = name; - TableNames = tableNameByDatabaseEngine ?? new Dictionary(); + TableNames = tableNameByDatabaseEngine ?? new Dictionary { { DatabaseEngine.SqlServer, name } }; LocallyDefinedProperties = locallyDefinedProperties; Identifiers = identifiers; IsAbstract = isAbstract; @@ -58,8 +60,25 @@ public EntityDefinition( public string Name { get; set; } + private IDictionary _tableNames; + [JsonConverter(typeof(DictionaryStringByDatabaseEngine))] - public IDictionary TableNames { get; set; } + public IDictionary TableNames + { + get + { + if (_tableNames == null) + { + _tableNames = new Dictionary {{DatabaseEngine.SqlServer, Name}}; + } + + return _tableNames; + } + set + { + _tableNames = value; + } + } public EntityPropertyDefinition[] LocallyDefinedProperties { get; set; } @@ -72,5 +91,7 @@ public EntityDefinition( public bool IsDeprecated { get; set; } public string[] DeprecationReasons { get; set; } + + public override string ToString() => new FullName(Schema, Name).ToString(); } } diff --git a/Application/EdFi.Ods.Common/Models/Definitions/EntityIdentifierDefinition.cs b/Application/EdFi.Ods.Common/Models/Definitions/EntityIdentifierDefinition.cs index e395483ac2..58431ca258 100644 --- a/Application/EdFi.Ods.Common/Models/Definitions/EntityIdentifierDefinition.cs +++ b/Application/EdFi.Ods.Common/Models/Definitions/EntityIdentifierDefinition.cs @@ -45,5 +45,7 @@ public EntityIdentifierDefinition( public bool IsUpdatable { get; set; } public IDictionary ConstraintNames { get; set; } + + public override string ToString() => $"{IdentifierName} ({string.Join(", ", IdentifyingPropertyNames)})"; } } diff --git a/Application/EdFi.Ods.Common/Models/Definitions/EntityPropertyDefinition.cs b/Application/EdFi.Ods.Common/Models/Definitions/EntityPropertyDefinition.cs index cd89c159d5..c5e82210a7 100644 --- a/Application/EdFi.Ods.Common/Models/Definitions/EntityPropertyDefinition.cs +++ b/Application/EdFi.Ods.Common/Models/Definitions/EntityPropertyDefinition.cs @@ -51,9 +51,23 @@ public EntityPropertyDefinition( DeprecationReasons = deprecationReasons; } + private IDictionary _columnNames; + [JsonConverter(typeof(DictionaryStringByDatabaseEngine))] - public IDictionary ColumnNames { get; set; } + public IDictionary ColumnNames + { + get + { + if (_columnNames == null) + { + _columnNames = new Dictionary {{DatabaseEngine.SqlServer, PropertyName}}; + } + return _columnNames; + } + set => _columnNames = value; + } + public string PropertyName { get; set; } public PropertyType PropertyType { get; set; } @@ -67,5 +81,7 @@ public EntityPropertyDefinition( public bool IsDeprecated { get; set; } public string[] DeprecationReasons { get; set; } + + public override string ToString() => PropertyName; } } diff --git a/Application/EdFi.Ods.Common/Models/Definitions/SchemaDefinition.cs b/Application/EdFi.Ods.Common/Models/Definitions/SchemaDefinition.cs index 78a98550e7..c4c8992dca 100644 --- a/Application/EdFi.Ods.Common/Models/Definitions/SchemaDefinition.cs +++ b/Application/EdFi.Ods.Common/Models/Definitions/SchemaDefinition.cs @@ -30,5 +30,7 @@ public SchemaDefinition(string logicalName, string physicalName, string version public string PhysicalName { get; set; } public string Version { get; set; } + + public override string ToString() => PhysicalName; } } diff --git a/Application/EdFi.Ods.Common/Models/Domain/DomainModelProvider.cs b/Application/EdFi.Ods.Common/Models/Domain/DomainModelProvider.cs index e9b30b3ca2..fd8525d13b 100644 --- a/Application/EdFi.Ods.Common/Models/Domain/DomainModelProvider.cs +++ b/Application/EdFi.Ods.Common/Models/Domain/DomainModelProvider.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; using System.Linq; +using EdFi.Ods.Common.Models.Definitions; namespace EdFi.Ods.Common.Models.Domain { @@ -13,12 +14,24 @@ public class DomainModelProvider : IDomainModelProvider { private readonly Lazy _domainModel; - public DomainModelProvider(IEnumerable domainModelDefinitionsProviders) + public DomainModelProvider( + IEnumerable domainModelDefinitionsProviders, + IDomainModelDefinitionsTransformer[] domainModelDefinitionsTransformers) { var domainModelBuilder = new DomainModelBuilder(); - domainModelBuilder.AddDomainModelDefinitionsList( - domainModelDefinitionsProviders.Select(p => p.GetDomainModelDefinitions())); + var domainModelDefinitions = domainModelDefinitionsProviders + .Select(p => p.GetDomainModelDefinitions()) + .ToList(); + + IEnumerable transformedDomainModelDefinitions = domainModelDefinitions; + + foreach (var transformer in domainModelDefinitionsTransformers) + { + transformedDomainModelDefinitions = transformer.TransformDefinitions(transformedDomainModelDefinitions); + } + + domainModelBuilder.AddDomainModelDefinitionsList(transformedDomainModelDefinitions); _domainModel = new Lazy(() => domainModelBuilder.Build()); } diff --git a/Application/EdFi.Ods.Common/Models/Domain/Entity.cs b/Application/EdFi.Ods.Common/Models/Domain/Entity.cs index 796256d121..fb1c7c7c10 100644 --- a/Application/EdFi.Ods.Common/Models/Domain/Entity.cs +++ b/Application/EdFi.Ods.Common/Models/Domain/Entity.cs @@ -14,12 +14,13 @@ using EdFi.Ods.Common.Conventions; using EdFi.Ods.Common.Extensions; using EdFi.Ods.Common.Models.Definitions; +using EdFi.Ods.Common.Models.Dynamic; using EdFi.Ods.Common.Models.Resource; using EdFi.Ods.Common.Utils.Extensions; namespace EdFi.Ods.Common.Models.Domain { - public class Entity + public class Entity : DynamicModel { private readonly Lazy _aggregateExtensionChildren; private readonly Lazy _aggregateExtensionOneToOnes; @@ -48,6 +49,8 @@ public class Entity /// The incoming internal Entity(DomainModel domainModel, EntityDefinition entityDefinition) { + this.CopyDynamicPropertiesFrom(entityDefinition); + DomainModel = domainModel; Schema = entityDefinition.Schema; @@ -398,6 +401,24 @@ public Entity TypeHierarchyRootEntity /// public AssociationView EdFiStandardEntityAssociation => _edFiStandardEntityAssociation.Value; + /// + /// Gets the alternate key identifiers logically inherited from the entity's base type hierarchy. + /// + public IReadOnlyList InheritedAlternateIdentifiers + { + get + { + if (BaseEntity == null) + { + return new EntityIdentifier[0]; + } + + return BaseEntity.InheritedAlternateIdentifiers + .Concat(BaseEntity.AlternateIdentifiers) + .ToList(); + } + } + /// /// Gets all the properties logically inherited via the entity's base type hierarchy, with the identifying properties first, followed by non-identifying properties. /// @@ -668,6 +689,9 @@ public IReadOnlyList InheritedNonNavigableOneToOnes public bool IsAggregateRoot => DomainModel.AggregateFullNameByEntityFullName[FullName] == FullName; + /// + /// Indicates whether the entity represents a descriptor. + /// public bool IsLookup => this.IsLookupEntity(); /// @@ -691,7 +715,10 @@ public IReadOnlyList InheritedNonNavigableOneToOnes public IReadOnlyList SelfReferencingAssociations => OutgoingAssociations.Where(a => a.IsSelfReferencing) .ToList(); - public bool IsDescriptorEntity => this.IsDescriptorEntity(); + /// + /// Indicates whether the entity is a concrete descriptor entity (i.e. an entity derived from the abstract base descriptor). + /// + public bool IsDescriptorEntity => IsDerived && BaseEntity?.IsDescriptorBaseEntity() == true; public string Description { get; } @@ -790,7 +817,7 @@ private static List BuildChildToAggregateRootPropertyMappings(E /// public override string ToString() { - return Name; + return FullName.ToString(); } } } diff --git a/Application/EdFi.Ods.Common/Models/Domain/EntityExtensions.cs b/Application/EdFi.Ods.Common/Models/Domain/EntityExtensions.cs index c49ac982b0..60dcf897f1 100644 --- a/Application/EdFi.Ods.Common/Models/Domain/EntityExtensions.cs +++ b/Application/EdFi.Ods.Common/Models/Domain/EntityExtensions.cs @@ -140,6 +140,12 @@ public static IEnumerable GetAllExtensions(this Entity entity) => entity public static bool IsDescriptorBaseEntity(this Entity entity) => entity.FullName.Equals(new FullName(EdFiConventions.PhysicalSchemaName, "Descriptor")); + public static bool IsEducationOrganizationBaseEntity(this Entity entity) + => entity.FullName.Equals(new FullName(EdFiConventions.PhysicalSchemaName, "EducationOrganization")); + + public static bool IsEducationOrganizationDerivedEntity(this Entity entity) + => entity.BaseEntity?.FullName == new FullName(EdFiConventions.PhysicalSchemaName, "EducationOrganization"); + /// /// Indicates whether the supplied has a discriminator. /// @@ -256,5 +262,35 @@ public static string TableName(this Entity entity, DatabaseEngine databaseEngine ? tableName : explicitTableName ?? entity.Name; } + + /// + /// Gets domain-meaningful identifying properties for the entity (which will be from an alternate identifier for entities + /// identified using a surrogate identifier). + /// + /// The to be evaluated. + /// A list of domain-meaningful identifying properties or an empty list if entity has a surrogate identifier and no available alternate identifier is defined. + public static IReadOnlyList NaturalIdentifyingProperties(this Entity entity) + { + // If this entity has a surrogate identifier, use the first alternate key's properties (if present) + if (entity.Identifier.IsSurrogateIdentifier()) + { + // Get the FIRST available alternate identifier (that is not defined for the "Id" property) + var alternateIdentifier = entity + .InheritedAlternateIdentifiers + .Concat(entity.AlternateIdentifiers) + .FirstOrDefault(ak => !ak.IsResourceIdentifier()); + + if (alternateIdentifier == null) + { + // No alternate identifier defined, return an empty array + return new EntityProperty[0]; + } + + return alternateIdentifier.Properties; + } + + // Just return the PK properties + return entity.Identifier.Properties; + } } } diff --git a/Application/EdFi.Ods.Common/Models/Domain/EntityIdentifier.cs b/Application/EdFi.Ods.Common/Models/Domain/EntityIdentifier.cs index 31ed4b9172..b2dc7d2ec9 100644 --- a/Application/EdFi.Ods.Common/Models/Domain/EntityIdentifier.cs +++ b/Application/EdFi.Ods.Common/Models/Domain/EntityIdentifier.cs @@ -15,7 +15,6 @@ namespace EdFi.Ods.Common.Models.Domain public class EntityIdentifier { private readonly Lazy> _identifyingProperties; - private readonly IReadOnlyList _identifyingPropertyNames; /// /// Initializes a new instance of the class using the supplied name and properties. @@ -25,14 +24,14 @@ public EntityIdentifier(EntityIdentifierDefinition entityIdentifierDefinition) { Name = entityIdentifierDefinition.IdentifierName; - _identifyingPropertyNames = entityIdentifierDefinition.IdentifyingPropertyNames.ToReadOnlyList(); IsPrimary = entityIdentifierDefinition.IsPrimary; IsUpdatable = entityIdentifierDefinition.IsUpdatable; _identifyingProperties = new Lazy>( () => - _identifyingPropertyNames.Select(x => Entity.PropertyByName.GetValueOrThrow(x, "Identifying property '{0}' not found on entity.")) - .ToList()); + entityIdentifierDefinition.IdentifyingPropertyNames + .Select(x => Entity.PropertyByName.GetValueOrThrow(x, $"Identifying property '{{0}}' not found on entity '{Entity.Name}' (available properties are: '{string.Join("', '", Entity.PropertyByName.Keys)}').")) + .ToList()); ConstraintByDatabaseEngine = entityIdentifierDefinition.ConstraintNames; } diff --git a/Application/EdFi.Ods.Common/Models/Domain/EntityIdentifierExtensions.cs b/Application/EdFi.Ods.Common/Models/Domain/EntityIdentifierExtensions.cs new file mode 100644 index 0000000000..b832ae955b --- /dev/null +++ b/Application/EdFi.Ods.Common/Models/Domain/EntityIdentifierExtensions.cs @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System.Linq; + +namespace EdFi.Ods.Common.Models.Domain +{ + public static class EntityIdentifierExtensions + { + /// + /// Indicates whether the is the identifier is the alternate identifier added + /// for the boilerplate "Id" property. + /// + /// The identifier to be evaluated. + /// true if the identifier is the alternate identifier added for the boilerplate "Id" property; otherwise false. + /// This method was added to allow the "Id" identifier to be easily excluded from the collection. + public static bool IsResourceIdentifier(this EntityIdentifier entityIdentifier) + { + return entityIdentifier.Properties.Count == 1 && entityIdentifier.Properties.Any(p => p.PropertyName == "Id"); + } + + /// + /// Indicates whether the is semantically a surrogate identifier, but does not necessarily + /// indicate this is where the value is physically assigned by the server (surrogate identifier values are assigned + /// only in the base type's identifier). + /// + /// The to be evaluated. + /// true if the identifier is a surrogate identifier; otherwise false. + /// + /// A surrogate identifier is a single-column primary key whose value is server-assigned (e.g. defined as an + /// IDENTITY column in SQL Server, or an integer column whose value is initialized using a SEQUENCE object). Such an + /// identifier is still considered a surrogate identifier when it appears on derived entities, however the surrogate + /// definition will be found on the base entity. + /// + public static bool IsSurrogateIdentifier(this EntityIdentifier entityIdentifier) + { + return entityIdentifier.IsPrimary + && entityIdentifier.Properties.Count == 1 + && entityIdentifier.Properties.First().IsServerAssigned; + } + + /// + /// Indicates whether the represents the root definition of a surrogate identifier + /// (as opposed to the identifier that appears on a derived entity of such a type). + /// + /// The to be evaluated. + /// true if the identifier is the definition of a surrogate identifier; otherwise false. + /// + /// A surrogate identifier is a single-column primary key whose value is server-assigned (e.g. defined as an + /// IDENTITY column in SQL Server, or an integer column whose value is initialized using a SEQUENCE object). Such an + /// identifier is still considered a surrogate identifier when it appears on derived entities, however the surrogate + /// definition will be found on the base entity. + /// + public static bool IsSurrogateIdentifierDefinition(this EntityIdentifier entityIdentifier) + { + return entityIdentifier.IsSurrogateIdentifier() && !entityIdentifier.Entity.IsDerived; + } + } +} diff --git a/Application/EdFi.Ods.Common/Models/Domain/EntityProperty.cs b/Application/EdFi.Ods.Common/Models/Domain/EntityProperty.cs index 44a60fa0c8..c4af463e98 100644 --- a/Application/EdFi.Ods.Common/Models/Domain/EntityProperty.cs +++ b/Application/EdFi.Ods.Common/Models/Domain/EntityProperty.cs @@ -19,8 +19,10 @@ namespace EdFi.Ods.Common.Models.Domain /// public class EntityProperty : DomainPropertyBase { - private Lazy _lookupEntity; + private Lazy _descriptorEntity; private Lazy _isUnified; + private Lazy _definingProperty; + private Lazy _definingConcreteProperty; /// /// Initializes a new instance of the class using the specified property definition. @@ -66,95 +68,47 @@ private void InitializeLazyMembers() _isUnified = new Lazy( () => IncomingAssociations.Count > 1); - _lookupEntity = new Lazy( + _definingProperty = new Lazy(() => GetDefiningProperty(restrictToConcreteEntity: false)); + + _definingConcreteProperty = new Lazy(() => GetDefiningProperty(restrictToConcreteEntity: true)); + + _descriptorEntity = new Lazy( () => { - // Detached properties are not lookup properties - if (Entity == null) + if (DefiningConcreteProperty?.Entity?.IsDescriptorEntity == true && DefiningConcreteProperty.Entity != Entity) { - return null; + return DefiningConcreteProperty.Entity; } - // Is this property a TypeId or DescriptorId on the table? If so, it's not a lookup property. - if (DescriptorEntitySpecification.IsEdFiDescriptorEntity(Entity.Name) - && PropertyName == Entity.Name + "Id") // TODO: Embedded convention - Types/descriptor properties use entity name + "Id" suffix - { - return null; - } - - var currentAssociation = IncomingAssociations.FirstOrDefault( - x => - x.AssociationType == AssociationViewType.FromBase - || x.AssociationType == AssociationViewType.OneToOneIncoming - || x.AssociationType == AssociationViewType.ManyToOne - - // Prevent processing self-recursive relationships with key unification on current property (prevent endless loop) - && !(x.IsSelfReferencing && PropertyName.EqualsIgnoreCase( - x.PropertyMappingByThisName[PropertyName] - .OtherProperty.PropertyName))); - - if (currentAssociation == null) - { - return null; - } - - var currentThisProperty = this; - - while (currentAssociation != null) - { - var otherProperty = currentAssociation.PropertyMappingByThisName[currentThisProperty.PropertyName] - .OtherProperty; - - if (ModelComparers.EntityProperty.Equals(currentThisProperty, otherProperty)) - { - throw new Exception( - "Association property mapping endpoints refer to the same property."); - } - - currentThisProperty = otherProperty; - - // Stop looking if we've hit a lookup table (Type or Descriptor) - if (currentThisProperty.Entity.IsLookup) - { - break; - } - - currentAssociation = otherProperty.IncomingAssociations.FirstOrDefault( - x => - x.AssociationType == AssociationViewType.FromBase - || x.AssociationType == AssociationViewType.OneToOneIncoming - || x.AssociationType == AssociationViewType.ManyToOne - && !(x.IsSelfReferencing && currentThisProperty.PropertyName.EqualsIgnoreCase( - x.PropertyMappingByThisName[ - currentThisProperty - .PropertyName] - .OtherProperty - .PropertyName))); - } - - return - currentThisProperty.Entity.IsLookup - && currentThisProperty.Entity.Aggregate != Entity.Aggregate - ? currentThisProperty.Entity - : null; + return null; }); } + [Obsolete("Use IsDescriptorUsage.")] public bool IsLookup + { + get => IsDescriptorUsage; + } + + /// + /// Indicates whether the property represents the usage of a descriptor. + /// + public bool IsDescriptorUsage { get { - // This prevents a known inconsistency in the Ed-Fi ODS from being reported as a descriptor lookup - if (PropertyName == "PriorDescriptorId") // TODO: Embedded convention - hardcoded logic - { - return false; - } - - return LookupEntity != null - && DescriptorEntitySpecification.IsEdFiDescriptorEntity(LookupEntity.Name); + return DescriptorEntity != null && !IncomingAssociations.Any(a => a.IsSelfReferencing); } } + /// + /// Gets the corresponding property in the base entity, if current entity is derived; otherwise null. + /// + public EntityProperty BaseProperty + { + get => Entity.BaseAssociation?.PropertyMappingByThisName[PropertyName].OtherProperty; + } + /// /// Indicates whether or not the property participates in key unification (is a property /// introduced by multiple associations, indicating deep referential integrity in @@ -167,12 +121,26 @@ public bool IsLookup /// from the corresponding lookup entity (as opposed to migrated into the entity via an association /// from a non-lookup entity). /// - public bool IsDirectLookup => IsLookup && IncomingAssociations.Any(x => x.OtherEntity == LookupEntity); + [Obsolete("Use IsDirectDescriptorUsage instead.")] + public bool IsDirectLookup => IsDirectDescriptorUsage; + + /// + /// Indicates whether the the property is a descriptor value that is directly referenced + /// from the corresponding descriptor entity (as opposed to migrated into the entity via an association + /// from a non-descriptor entity). + /// + public bool IsDirectDescriptorUsage => IsDescriptorUsage && IncomingAssociations.Any(x => x.OtherEntity == DescriptorEntity); /// - /// Gets the type or descriptor lookup entity (if applicable); otherwise null. + /// Gets the corresponding descriptor entity (if applicable); otherwise null. + /// + [Obsolete("Use DescriptorEntity instead.")] + public Entity LookupEntity => DescriptorEntity; + + /// + /// Gets the corresponding descriptor entity (if applicable); otherwise null. /// - public Entity LookupEntity => _lookupEntity.Value; + public Entity DescriptorEntity => _descriptorEntity.Value; /// /// Gets the associations that contribute the property to the current entity. @@ -246,6 +214,64 @@ public bool HasRoleNameApplied /// public bool IsLocallyDefined { get; internal set; } + /// + /// Gets the where the property was originally defined in a concrete entity (i.e. it will not + /// return the property of the abstract base entity). If the property is part of a foreign key relationship, the property + /// returned will be a property associated with a different . + /// + /// + /// For properties that are identifying properties of an abstract base type (e.g. descriptors, + /// education organizations, student program associations, etc.), this will return the property of the concrete (derived) + /// . + /// + /// + public EntityProperty DefiningConcreteProperty + { + get => _definingConcreteProperty.Value; + } + + /// + /// Gets the where the property was originally defined in the model regardless of whether + /// the original definition is in a concrete or abstract entity. If the property is part of a foreign key relationship, the property returned will be a property associated + /// with a different . + /// + /// + /// For properties that are identifying properties of an abstract base type (e.g. descriptors, + /// education organizations, student program associations, etc.), this will return that property (rather than the property + /// as it is represented in the concrete (derived) . + /// + /// + public EntityProperty DefiningProperty + { + get => _definingProperty.Value; + } + + private EntityProperty GetDefiningProperty(bool restrictToConcreteEntity) + { + if (IsLocallyDefined) + { + return this; + } + + var currentProperty = this; + + while (currentProperty.IncomingAssociations.Any(a => + a.AssociationType == AssociationViewType.ManyToOne + || a.AssociationType == AssociationViewType.OneToOneIncoming + // Follow relationship into the core Ed-Fi model from an extension + || a.AssociationType == AssociationViewType.FromCore + // Follow base type relationships if they don't originate there, or are explicitly allowed by caller + || (a.AssociationType == AssociationViewType.FromBase + && (a.OtherProperties.Any(p => !p.IsLocallyDefined) || !restrictToConcreteEntity)))) + { + currentProperty = currentProperty.IncomingAssociations.First() + .PropertyMappingByThisName[currentProperty.PropertyName] + .OtherProperty; + } + + return currentProperty; + } + /// /// Indicates whether the current property is deprecated. /// @@ -255,5 +281,7 @@ public bool HasRoleNameApplied /// Indicates reasons over the property when it is deprecated. /// public string[] DeprecationReasons { get; set; } + + public override string ToString() => PropertyName; } } diff --git a/Application/EdFi.Ods.Common/Models/Domain/EntityPropertyExtensions.cs b/Application/EdFi.Ods.Common/Models/Domain/EntityPropertyExtensions.cs new file mode 100644 index 0000000000..d80055263e --- /dev/null +++ b/Application/EdFi.Ods.Common/Models/Domain/EntityPropertyExtensions.cs @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +namespace EdFi.Ods.Common.Models.Domain +{ + public static class EntityPropertyExtensions + { + /// + /// Indicates whether the is semantically a surrogate identifier, but does not necessarily + /// indicate this is where the value is physically assigned by the server (surrogate identifier values are assigned + /// only in the base type's identifier). + /// + /// The to be evaluated. + /// true if the property is a surrogate identifier; otherwise false. + /// + /// A surrogate identifier is a single-column primary key whose value is server-assigned (e.g. defined as an + /// IDENTITY column in SQL Server, or an integer column whose value is initialized using a SEQUENCE object). Such an + /// identifier is still considered a surrogate identifier when it appears on derived entities, however the surrogate + /// definition will be found on the base entity. + /// + public static bool IsSurrogateIdentifier(this EntityProperty entityProperty) + { + return entityProperty.IsIdentifying && entityProperty.Entity.Identifier.IsSurrogateIdentifier(); + } + + /// + /// Indicates whether the represents the root definition of a surrogate identifier + /// (as opposed to the identifier that appears on a derived entity of such a type). + /// + /// The to be evaluated. + /// true if the property is the definition of a surrogate identifier; otherwise false. + /// + /// A surrogate identifier is a single-column primary key whose value is server-assigned (e.g. defined as an + /// IDENTITY column in SQL Server, or an integer column whose value is initialized using a SEQUENCE object). Such an + /// identifier is still considered a surrogate identifier when it appears on derived entities, however the surrogate + /// definition will be found on the base entity. + /// + public static bool IsSurrogateIdentifierDefinition(this EntityProperty entityProperty) + { + return (entityProperty.IsIdentifying && entityProperty.Entity.Identifier.IsSurrogateIdentifierDefinition()); + } + + /// + /// Indicates whether the represents a usage of a surrogate identifier of another + /// entity. + /// + /// The property to be evaluated. + /// true if the property represents the usage of a surrogate identifier of another entity; otherwise false. + public static bool IsSurrogateIdentifierUsage(this EntityProperty entityProperty) + { + return entityProperty.DefiningProperty.IsSurrogateIdentifierDefinition() + && !entityProperty.IsSurrogateIdentifier(); + } + } +} diff --git a/Application/EdFi.Ods.Common/Models/Domain/EntitySpecification.cs b/Application/EdFi.Ods.Common/Models/Domain/EntitySpecification.cs index b11a569ec8..bd72c28d3f 100644 --- a/Application/EdFi.Ods.Common/Models/Domain/EntitySpecification.cs +++ b/Application/EdFi.Ods.Common/Models/Domain/EntitySpecification.cs @@ -15,6 +15,12 @@ public static bool IsLookupEntity(this Entity entity) return entity.IsDescriptorEntity(); } + /// + /// Indicates whether the specific type name matches the convention for an entity derived from the abstract Descriptor + /// entity, but does not represent the abstract Descriptor entity itself. + /// + /// The name of the type to be evaluated. + /// true if the type name matches the convention for a Descriptor-derived entity; otherwise false. public static bool IsDescriptorEntity(this Entity entity) { return DescriptorEntitySpecification.IsEdFiDescriptorEntity(entity.Name); @@ -24,15 +30,5 @@ public static bool IsPersonEntity(this Entity entity) { return PersonEntitySpecification.IsPersonEntity(entity.Name); } - - public static bool HasServerAssignedSurrogateId(this Entity entity) - { - //People and the base descriptors have server assigned surrogate ids. - return entity.Identifier.Properties.Any( - p => - p.IsServerAssigned - && !p.Entity.IsDerived - && p.Entity.IsAggregateRoot); - } } } diff --git a/Application/EdFi.Ods.Common/Models/DomainModelDefinitionsJsonFileSystemProvider.cs b/Application/EdFi.Ods.Common/Models/DomainModelDefinitionsJsonFileSystemProvider.cs index 840af987e6..df1d286936 100644 --- a/Application/EdFi.Ods.Common/Models/DomainModelDefinitionsJsonFileSystemProvider.cs +++ b/Application/EdFi.Ods.Common/Models/DomainModelDefinitionsJsonFileSystemProvider.cs @@ -5,6 +5,7 @@ using System; using System.IO; +using EdFi.Ods.Common.Extensions; using EdFi.Ods.Common.Models.Definitions; using Newtonsoft.Json; diff --git a/Application/EdFi.Ods.Common/Models/Dynamic/DynamicModel.cs b/Application/EdFi.Ods.Common/Models/Dynamic/DynamicModel.cs new file mode 100644 index 0000000000..eedc0de8d5 --- /dev/null +++ b/Application/EdFi.Ods.Common/Models/Dynamic/DynamicModel.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Generic; +using System.Dynamic; +using System.Linq; +using System.Reflection; + +namespace EdFi.Ods.Common.Models.Dynamic +{ + public class DynamicModel : DynamicObject, IDynamicModel + { + private readonly IDictionary _properties + = new Dictionary(StringComparer.OrdinalIgnoreCase); + + IDictionary IDynamicModel.DynamicProperties + { + get => _properties; + } + + public override bool TrySetMember(SetMemberBinder binder, object value) + { + if (binder.Name == "DynamicProperties") + return false; + + var propertyInfo = GetType().GetProperty(binder.Name); + + if (propertyInfo != null) + { + propertyInfo.SetValue(this, value); + + return true; + } + + _properties[binder.Name] = value; + + return true; + } + + public override bool TryGetMember(GetMemberBinder binder, out object result) + { + result = null; + + if (binder.Name == "DynamicProperties") + return false; + + var propertyInfo = GetType().GetProperty(binder.Name); + + if (propertyInfo != null) + { + result = propertyInfo.GetValue(this); + + return true; + } + + if (!_properties.TryGetValue(binder.Name, out result)) + { + // Default the value to null + result = null; + } + + return true; + } + + public override IEnumerable GetDynamicMemberNames() + { + return _properties.GetType() + .GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .Select(x => x.Name) + .Except(new [] {"DynamicProperties"}) + .Concat(_properties.Keys); + } + } +} \ No newline at end of file diff --git a/Application/EdFi.Ods.Common/Models/Dynamic/IDynamicModel.cs b/Application/EdFi.Ods.Common/Models/Dynamic/IDynamicModel.cs new file mode 100644 index 0000000000..245b370827 --- /dev/null +++ b/Application/EdFi.Ods.Common/Models/Dynamic/IDynamicModel.cs @@ -0,0 +1,9 @@ +using System.Collections.Generic; + +namespace EdFi.Ods.Common.Models.Dynamic +{ + public interface IDynamicModel + { + IDictionary DynamicProperties { get; } + } +} \ No newline at end of file diff --git a/Application/EdFi.Ods.Common/Models/Dynamic/IDynamicModelExtensions.cs b/Application/EdFi.Ods.Common/Models/Dynamic/IDynamicModelExtensions.cs new file mode 100644 index 0000000000..2693595c80 --- /dev/null +++ b/Application/EdFi.Ods.Common/Models/Dynamic/IDynamicModelExtensions.cs @@ -0,0 +1,13 @@ +namespace EdFi.Ods.Common.Models.Dynamic +{ + public static class IDynamicModelExtensions + { + public static void CopyDynamicPropertiesFrom(this IDynamicModel target, IDynamicModel source) + { + foreach (var kvp in source.DynamicProperties) + { + target.DynamicProperties[kvp.Key] = kvp.Value; + } + } + } +} \ No newline at end of file diff --git a/Application/EdFi.Ods.Common/Models/Graphs/ResourceModelExtensions.cs b/Application/EdFi.Ods.Common/Models/Graphs/ResourceModelExtensions.cs index b1b685d17b..ef28367eb6 100644 --- a/Application/EdFi.Ods.Common/Models/Graphs/ResourceModelExtensions.cs +++ b/Application/EdFi.Ods.Common/Models/Graphs/ResourceModelExtensions.cs @@ -50,7 +50,7 @@ public ResourceLoadGraphFactory(IResourceModelProvider resourceModelProvider, // Add direct descriptor associations .Concat( res.AllContainedItemTypesOrSelf.SelectMany( - rc => rc.Properties.Where(p => p.IsDirectLookup) + rc => rc.Properties.Where(p => p.IsDirectDescriptorUsage) .Select( p => new AssociationViewEdge( p.DescriptorResource, diff --git a/Application/EdFi.Ods.Common/Models/IDomainModelDefinitionsTransformer.cs b/Application/EdFi.Ods.Common/Models/IDomainModelDefinitionsTransformer.cs new file mode 100644 index 0000000000..76319c07aa --- /dev/null +++ b/Application/EdFi.Ods.Common/Models/IDomainModelDefinitionsTransformer.cs @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System.Collections.Generic; +using EdFi.Ods.Common.Models.Definitions; + +namespace EdFi.Ods.Common.Models +{ + public interface IDomainModelDefinitionsTransformer + { + IEnumerable TransformDefinitions(IEnumerable definitions); + } +} diff --git a/Application/EdFi.Ods.Common/Models/Resource/Collection.cs b/Application/EdFi.Ods.Common/Models/Resource/Collection.cs index 3e55bf0dfb..f5b1b07ab4 100644 --- a/Application/EdFi.Ods.Common/Models/Resource/Collection.cs +++ b/Application/EdFi.Ods.Common/Models/Resource/Collection.cs @@ -19,7 +19,7 @@ internal Collection(ResourceClassBase resourceClass, AssociationView association Association = association; FilterContext = filterContext ?? FilterContext.NullFilterContext; - ItemType = new ResourceChildItem(resourceClass.ResourceModel, association.OtherEntity, FilterContext, resourceClass); + ItemType = new ResourceChildItem(this, resourceClass.ResourceModel, association.OtherEntity, FilterContext, resourceClass); if (FilterContext.Definition != null) { @@ -140,5 +140,10 @@ private void ValidateCompositeCollectionArguments(Collection[] collections) string.Join("', '", distinctAssociations.Select(a => a.Name)))); } } + + public override string JsonPath + { + get => $"{Parent.JsonPath}.{JsonPropertyName}[*]"; + } } } diff --git a/Application/EdFi.Ods.Common/Models/Resource/EmbeddedObject.cs b/Application/EdFi.Ods.Common/Models/Resource/EmbeddedObject.cs index 035a7bc319..61c12969f2 100644 --- a/Application/EdFi.Ods.Common/Models/Resource/EmbeddedObject.cs +++ b/Application/EdFi.Ods.Common/Models/Resource/EmbeddedObject.cs @@ -18,7 +18,7 @@ internal EmbeddedObject(ResourceClassBase resourceClass, AssociationView associa : base(resourceClass, association.Name) { Association = association; - ObjectType = new ResourceChildItem(resourceClass.ResourceModel, association.OtherEntity, childFilterContext, resourceClass); + ObjectType = new ResourceChildItem(this, resourceClass.ResourceModel, association.OtherEntity, childFilterContext, resourceClass); _parentFullName = Association.ThisEntity.FullName; } diff --git a/Application/EdFi.Ods.Common/Models/Resource/Extension.cs b/Application/EdFi.Ods.Common/Models/Resource/Extension.cs index 838516fd73..7497df60e9 100644 --- a/Application/EdFi.Ods.Common/Models/Resource/Extension.cs +++ b/Application/EdFi.Ods.Common/Models/Resource/Extension.cs @@ -13,10 +13,12 @@ namespace EdFi.Ods.Common.Models.Resource { public class Extension : ResourceMemberBase { - public Extension(ResourceClassBase resourceClass, ResourceChildItem extensionObjectType, string displayName) + private Lazy _objectType; + + public Extension(ResourceClassBase resourceClass, Func extensionObjectType, string displayName) : base(resourceClass, displayName, displayName.ToCamelCase()) { - ObjectType = extensionObjectType; + _objectType = new Lazy(extensionObjectType); if (resourceClass.Entity != null) { @@ -34,20 +36,24 @@ internal Extension( { Association = association; - ObjectType = new ResourceChildItem( + _objectType = new Lazy(() => new ResourceChildItem( + this, resourceClass.ResourceModel, association.OtherEntity, childFilterContext, resourceClass, collectionAssociations, - embeddedObjectAssociations); + embeddedObjectAssociations)); ParentFullName = Association.ThisEntity.FullName; } public AssociationView Association { get; } - public ResourceChildItem ObjectType { get; } + public ResourceChildItem ObjectType + { + get => _objectType.Value; + } public override FullName ParentFullName { get; } } diff --git a/Application/EdFi.Ods.Common/Models/Resource/IResourceSelector.cs b/Application/EdFi.Ods.Common/Models/Resource/IResourceSelector.cs index af4030fcd1..a8e01b321d 100644 --- a/Application/EdFi.Ods.Common/Models/Resource/IResourceSelector.cs +++ b/Application/EdFi.Ods.Common/Models/Resource/IResourceSelector.cs @@ -13,5 +13,7 @@ public interface IResourceSelector IReadOnlyList GetAll(); Resource GetByName(FullName fullName); + + Resource GetByApiCollectionName(string schemaUriSegment, string resourceCollectionName); } } diff --git a/Application/EdFi.Ods.Common/Models/Resource/LinkedCollection.cs b/Application/EdFi.Ods.Common/Models/Resource/LinkedCollection.cs index 98e35bec42..56213e6f15 100644 --- a/Application/EdFi.Ods.Common/Models/Resource/LinkedCollection.cs +++ b/Application/EdFi.Ods.Common/Models/Resource/LinkedCollection.cs @@ -37,5 +37,10 @@ public override FullName ParentFullName { get { return Resource.Entity.FullName; } } + + public override string JsonPath + { + get => $"{Parent.JsonPath}.{JsonPropertyName}[*]"; + } } } diff --git a/Application/EdFi.Ods.Common/Models/Resource/ProfileResourceModel.cs b/Application/EdFi.Ods.Common/Models/Resource/ProfileResourceModel.cs index 80aa50befd..e572949224 100644 --- a/Application/EdFi.Ods.Common/Models/Resource/ProfileResourceModel.cs +++ b/Application/EdFi.Ods.Common/Models/Resource/ProfileResourceModel.cs @@ -3,15 +3,16 @@ // The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. // See the LICENSE and NOTICES files in the project root for more information. +using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Xml.Linq; +using EdFi.Common.Extensions; using EdFi.Common.Utils.Extensions; using EdFi.Ods.Common.Conventions; using EdFi.Ods.Common.Extensions; using EdFi.Ods.Common.Models.Domain; -using EdFi.Ods.Common.Utils.Extensions; namespace EdFi.Ods.Common.Models.Resource { @@ -36,12 +37,22 @@ public ProfileResourceModel(ResourceModel resourceModel, XElement profileDefinit ProfileName = _profileDefinition.AttributeValue("name"); // Removed the lazy reference so that the tests will pass - ResourceByName = new ReadOnlyDictionary(CreateResourceByName(resourceModel)); + ResourceByName = new ReadOnlyDictionary( + CreateResourceByName( + resourceModel, + r => r.FullName)); + + ResourceByApiCollectionName = new ReadOnlyDictionary( + CreateResourceByName( + resourceModel, + r => new FullName(r.SchemaUriSegment(), r.PluralName.ToCamelCase()))); } public string ProfileName { get; } public IReadOnlyDictionary ResourceByName { get; } + + internal IReadOnlyDictionary ResourceByApiCollectionName { get; } public IReadOnlyList Resources => ResourceByName.Values.ToList(); @@ -70,7 +81,7 @@ public bool ResourceIsWritable(FullName resourceName) => ResourceByName.Any( /// /// /// - private Dictionary CreateResourceByName(ResourceModel resourceModel) + private Dictionary CreateResourceByName(ResourceModel resourceModel, Func createKey) { var resourceElts = _profileDefinition.Elements("Resource"); @@ -94,7 +105,7 @@ private Dictionary CreateResourceByName(R var fullName = new FullName(physicalName, resourceName); var sourceResource = ResourceModel.DefaultResourceSelector.GetByName(fullName); - resources[fullName] = new ProfileResourceContentTypes(sourceResource, resourceElt); + resources[createKey(sourceResource)] = new ProfileResourceContentTypes(sourceResource, resourceElt); }); return resources; diff --git a/Application/EdFi.Ods.Common/Models/Resource/ProfilesAppliedResourceModel.cs b/Application/EdFi.Ods.Common/Models/Resource/ProfilesAppliedResourceModel.cs index 2cb81ece1c..d46e38486d 100644 --- a/Application/EdFi.Ods.Common/Models/Resource/ProfilesAppliedResourceModel.cs +++ b/Application/EdFi.Ods.Common/Models/Resource/ProfilesAppliedResourceModel.cs @@ -64,6 +64,11 @@ public IReadOnlyList GetAllResources() return _resourceSelector.GetAll(); } + public Resource GetResourceByApiCollectionName(string schemaUriSegment, string resourceCollectionName) + { + return _resourceSelector.GetByApiCollectionName(schemaUriSegment, resourceCollectionName); + } + /// /// Gets a provider capable of mapping schema names between logical, physical, proper case name and URI segment representations. /// @@ -94,10 +99,26 @@ public IReadOnlyList GetAll() } public Resource GetByName(FullName fullName) + { + return GetByName(fullName, model => model.ResourceByName) + // No resources means there's no Profile in play so we should return the main ResourceModel's resource + ?? UnderlyingResourceSelector.GetByName(fullName); + } + + public Resource GetByApiCollectionName(string schemaUriSegment, string resourceCollectionName) + { + return GetByName( + new FullName(schemaUriSegment, resourceCollectionName), + model => model.ResourceByApiCollectionName) + // No resources means there's no Profile in play so we should return the main ResourceModel's resource + ?? UnderlyingResourceSelector.GetByApiCollectionName(schemaUriSegment, resourceCollectionName); + } + + private Resource GetByName(FullName fullName, Func> getContentTypesByFullName) { var allProfileResources = (from m in _profileResourceModels - let ct = m.ResourceByName.GetValueOrDefault(fullName) + let ct = getContentTypesByFullName(m).GetValueOrDefault(fullName) where ct != null select _usage == ContentTypeUsage.Readable ? ct.Readable @@ -123,8 +144,7 @@ public Resource GetByName(FullName fullName) .ToArray()); } - // No resources means there's no Profile in play so we should return the main ResourceModel's resource - return UnderlyingResourceSelector.GetByName(fullName); + return null; } } } diff --git a/Application/EdFi.Ods.Common/Models/Resource/Reference.cs b/Application/EdFi.Ods.Common/Models/Resource/Reference.cs index f89ab6ceaa..402d44a698 100644 --- a/Application/EdFi.Ods.Common/Models/Resource/Reference.cs +++ b/Application/EdFi.Ods.Common/Models/Resource/Reference.cs @@ -31,7 +31,7 @@ public Reference(ResourceClassBase resourceClass, AssociationView association, s _properties = new Lazy>( () => association.ThisProperties - .Select(p => new ResourceProperty(resourceClass, p)) + .Select(p => new ResourceProperty(this, resourceClass, p)) .ToList()); _referenceTypeProperties = new Lazy>( @@ -96,7 +96,7 @@ public bool IsInherited return false; return - (Parent.Entity.InheritedNavigableOneToOnes.Contains(Association, ModelComparers.AssociationView)); + (Parent.Entity.InheritedNonNavigableParents.Contains(Association, ModelComparers.AssociationView)); } } diff --git a/Application/EdFi.Ods.Common/Models/Resource/Resource.cs b/Application/EdFi.Ods.Common/Models/Resource/Resource.cs index 77e3d6bebf..fa4ad22272 100644 --- a/Application/EdFi.Ods.Common/Models/Resource/Resource.cs +++ b/Application/EdFi.Ods.Common/Models/Resource/Resource.cs @@ -125,5 +125,10 @@ protected override IEnumerable LazyInitializeAllMembers() return base.LazyInitializeAllMembers() .Concat(LinkedCollections); } + + public override string JsonPath + { + get => "$"; + } } } diff --git a/Application/EdFi.Ods.Common/Models/Resource/ResourceChildItem.cs b/Application/EdFi.Ods.Common/Models/Resource/ResourceChildItem.cs index f98ae0eec0..701ca4c65a 100644 --- a/Application/EdFi.Ods.Common/Models/Resource/ResourceChildItem.cs +++ b/Application/EdFi.Ods.Common/Models/Resource/ResourceChildItem.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; using System.Linq; +using EdFi.Common; using EdFi.Ods.Common.Conventions; using EdFi.Ods.Common.Models.Domain; @@ -14,13 +15,18 @@ namespace EdFi.Ods.Common.Models.Resource // Resource (non-top-level) only public class ResourceChildItem : ResourceClassBase, IHasParent { - internal ResourceChildItem(IResourceModel resourceModel, Entity entity, FilterContext childContext, ResourceClassBase parentResource) + private readonly ResourceMemberBase _containingMember; + + internal ResourceChildItem(ResourceMemberBase containingMember, IResourceModel resourceModel, Entity entity, FilterContext childContext, ResourceClassBase parentResource) : base(resourceModel, entity, childContext) { + _containingMember = Preconditions.ThrowIfNull(containingMember, nameof(containingMember)); + Parent = parentResource; } internal ResourceChildItem( + ResourceMemberBase containingMember, IResourceModel resourceModel, Entity entity, FilterContext childContext, @@ -29,6 +35,8 @@ internal ResourceChildItem( Func> embeddedObjectAssociations) : base(resourceModel, entity, childContext, collectionAssociations, embeddedObjectAssociations) { + _containingMember = Preconditions.ThrowIfNull(containingMember, nameof(containingMember)); + Parent = parentResource; } @@ -53,6 +61,7 @@ public ResourceChildItem(string name, ResourceClassBase parentResource) } public ResourceChildItem( + ResourceMemberBase containingMember, IResourceModel resourceModel, FullName fullName, ResourceClassBase parentResource, @@ -61,9 +70,16 @@ public ResourceChildItem( FilterContext filterContext) : base(resourceModel, fullName, collectionAssociations, embeddedObjectAssociations, filterContext) { + _containingMember = Preconditions.ThrowIfNull(containingMember, nameof(containingMember)); + Parent = parentResource; } + public ResourceMemberBase ContainingMember + { + get => _containingMember; + } + /// /// Gets the root class for the current resource. /// @@ -71,6 +87,19 @@ public ResourceChildItem( .Cast() .First(); + public override string JsonPath + { + get + { + if (_containingMember == null) + { + throw new NullReferenceException($"The containing member for ResourceChildItem '{FullName}' has not been initialized."); + } + + return _containingMember.JsonPath; + } + } + /// /// Indicates whether the resource class is part of an extension to an Ed-Fi standard resource (i.e. a "resource extension" as opposed to being part of a new "extension resource"). /// diff --git a/Application/EdFi.Ods.Common/Models/Resource/ResourceClassBase.cs b/Application/EdFi.Ods.Common/Models/Resource/ResourceClassBase.cs index 9d910f36af..f45377eb67 100644 --- a/Application/EdFi.Ods.Common/Models/Resource/ResourceClassBase.cs +++ b/Application/EdFi.Ods.Common/Models/Resource/ResourceClassBase.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading; using EdFi.Common.Extensions; using EdFi.Common.Inflection; using EdFi.Ods.Common.Conventions; @@ -34,6 +35,7 @@ public abstract class ResourceClassBase private Lazy> _allMembers; private Lazy> _allProperties; + private Lazy> _allIdentifyingProperties; private Lazy> _allPropertyByName; private Lazy> _collectionByName; @@ -48,6 +50,9 @@ public abstract class ResourceClassBase private Lazy> _propertyByName; private Lazy> _referenceByName; + private IEnumerable _allPropertiesRaw; + + internal Lazy>> UnifiedPropertiesByPropertyName; protected internal ResourceClassBase(IResourceModel resourceModel, Entity entity) : this(resourceModel, entity, null) { } @@ -67,7 +72,7 @@ protected internal ResourceClassBase( Entity entity, FilterContext filterContext, Func> collectionAssociations, - Func> embbededObjectAssociations) + Func> embeddedObjectAssociations) { Entity = entity; FullName = new FullName(entity.Schema, entity.Name); @@ -80,7 +85,7 @@ protected internal ResourceClassBase( // Initialize lists _properties = LazyInitializeProperties(Entity); - _embeddedObjects = LazyInitializeEmbeddedObjects(embbededObjectAssociations); + _embeddedObjects = LazyInitializeEmbeddedObjects(embeddedObjectAssociations); _collections = LazyInitializeCollections(collectionAssociations); _references = LazyInitializeReferences(Entity); _containedItemTypes = LazyInitializeContainedTypes(); @@ -253,6 +258,11 @@ public string PluralName public Entity Entity { get; } + /// + /// Gets all the identifying properties defined on, or introduced by references to this resource class (with identifying properties listed before non-identifying properties). + /// + public virtual IReadOnlyList AllIdentifyingProperties => _allIdentifyingProperties.Value; + /// /// Gets the identifying properties of the resource that are introduced in the local context, including those in references, as necessary. /// @@ -367,7 +377,7 @@ private Lazy> LazyInitializeReferences(Entity entity) entity.BaseEntity != null ? entity.BaseEntity.NonNavigableParents : new AssociationView[0]) - .Where(a => !a.OtherEntity.IsLookupEntity()) // Don't generate references associations to Types/Descriptors + .Where(a => !a.OtherEntity.IsDescriptorEntity) // Don't generate references associations to Types/Descriptors .Select( a => new Reference( this, @@ -469,18 +479,31 @@ private Lazy> LazyInitializeExtensions(Entity entity) // Create an implicit extension class .Select( - x => new Extension( - this, - new ResourceChildItem( - ResourceModel, - new FullName(x.SchemaPhysicalName, $"{entity.Name}Extension"), + x => + { + Extension extension = null; + + extension = new Extension( this, - () => extensionCollections.Where( - a => a.OtherEntity.Schema == x.SchemaPhysicalName), - () => extensionOneToOnes.Where( - a => a.OtherEntity.Schema == x.SchemaPhysicalName), - FilterContext.GetExtensionContext(x.SchemaProperCaseName)), - x.SchemaProperCaseName)); + () => new ResourceChildItem( + extension, + ResourceModel, + new FullName( + x.SchemaPhysicalName, + $"{entity.Name}Extension"), + this, + () => extensionCollections.Where( + a => a.OtherEntity.Schema + == x.SchemaPhysicalName), + () => extensionOneToOnes.Where( + a => a.OtherEntity.Schema + == x.SchemaPhysicalName), + FilterContext.GetExtensionContext( + x.SchemaProperCaseName)), + x.SchemaProperCaseName); + + return extension; + }); extensions.AddRange(implicitExtensionsFromCollections); @@ -501,18 +524,31 @@ private Lazy> LazyInitializeExtensions(Entity entity) .PhysicalName }) .Select( - x => new Extension( - this, - new ResourceChildItem( - ResourceModel, - new FullName(x.SchemaPhysicalName, $"{entity.Name}Extension"), + x => + { + Extension extension = null; + + extension = new Extension( this, - () => extensionCollections.Where( - a => a.OtherEntity.Schema == x.SchemaPhysicalName), - () => extensionOneToOnes.Where( - a => a.OtherEntity.Schema == x.SchemaPhysicalName), - FilterContext.GetExtensionContext(x.SchemaProperCaseName)), - x.SchemaProperCaseName)); + () => new ResourceChildItem( + extension, + ResourceModel, + new FullName( + x.SchemaPhysicalName, + $"{entity.Name}Extension"), + this, + () => extensionCollections.Where( + a => a.OtherEntity.Schema + == x.SchemaPhysicalName), + () => extensionOneToOnes.Where( + a => a.OtherEntity.Schema + == x.SchemaPhysicalName), + FilterContext.GetExtensionContext( + x.SchemaProperCaseName)), + x.SchemaProperCaseName); + + return extension; + }); extensions.AddRange(implicitExtensionsFromEmbeddedObjects); @@ -544,7 +580,7 @@ private Lazy> LazyInitializeProperties(Entity en : new EntityProperty[0]) .Concat( entity.Properties - .Where(p => p.IsLocallyDefined || p.IsDirectLookup)) + .Where(p => p.IsLocallyDefined || p.IsDirectDescriptorUsage)) .Select(p => new ResourceProperty(this, p)) .Where(p => ResourceSpecification.IsAllowableResourceProperty(p.PropertyName)) .Where(rp => FilterContext.MemberFilter.ShouldInclude(rp.PropertyName)) @@ -556,29 +592,41 @@ private Lazy> LazyInitializeProperties(Entity en private void LazyInitializeDerivedCollections() { - _allProperties = new Lazy>( - () => - - // Add locally defined identifying properties first - Properties.Where(p => p.IsIdentifying) - - // Add reference properties, identifying references first, followed by required, and then optional - .Concat( - References - .OrderByDescending( - r => (r.Association.IsIdentifying ? 100: 0) - + (r.IsRequired ? 10 : 0)) - .SelectMany(r => r.Properties)) - - // Add non-identifying properties - .Concat(Properties.Where(p => !p.IsIdentifying)) - .Distinct(ModelComparers.ResourcePropertyNameOnly) - .ToList()); + _allPropertiesRaw = + // Add locally defined identifying properties first + Properties.Where(p => p.IsIdentifying) + + // Add reference properties, identifying references first, followed by required, and then optional + .Concat( + References + .OrderByDescending( + r => (r.Association.IsIdentifying ? 100: 0) + + (r.IsRequired ? 10 : 0)) + .SelectMany(r => r.Properties)) + + // Add non-identifying properties + .Concat(Properties.Where(p => !p.IsIdentifying)) + .ToArray(); + _allProperties = new Lazy>( + () => _allPropertiesRaw + .Distinct(ModelComparers.ResourcePropertyNameOnly) + .ToList()); + _allPropertyByName = new Lazy>( () => AllProperties.ToDictionary(x => x.PropertyName, x => x, StringComparer.InvariantCultureIgnoreCase)); + UnifiedPropertiesByPropertyName = new Lazy>>( + () => _allPropertiesRaw.GroupBy(rp => rp.PropertyName) + .Where(g => g.Count() > 1) + .ToDictionary( + g => g.Key, + g => (IReadOnlyList) g.ToArray(), + StringComparer.OrdinalIgnoreCase)); + + _allIdentifyingProperties = new Lazy>(() => _allProperties.Value.Where(p => p.IsIdentifying).ToArray()); + _propertyByName = new Lazy>( () => Properties @@ -726,5 +774,7 @@ private static void ValidateCompositeResourceArguments(ResourceClassBase[] resou public bool IsDeprecated { get; set; } public string[] DeprecationReasons { get; set; } + + public abstract string JsonPath { get; } } } diff --git a/Application/EdFi.Ods.Common/Models/Resource/ResourceMemberBase.cs b/Application/EdFi.Ods.Common/Models/Resource/ResourceMemberBase.cs index bcacad504e..b2ec0518cc 100644 --- a/Application/EdFi.Ods.Common/Models/Resource/ResourceMemberBase.cs +++ b/Application/EdFi.Ods.Common/Models/Resource/ResourceMemberBase.cs @@ -83,6 +83,11 @@ public IEnumerable GetLineage() /// A string that represents the current object. /// public override string ToString() => PropertyName; + + public virtual string JsonPath + { + get => $"{Parent.JsonPath}.{JsonPropertyName}"; + } } public static class JsonNamingConvention diff --git a/Application/EdFi.Ods.Common/Models/Resource/ResourceModel.cs b/Application/EdFi.Ods.Common/Models/Resource/ResourceModel.cs index 456495e03e..3ccfa9d3fe 100644 --- a/Application/EdFi.Ods.Common/Models/Resource/ResourceModel.cs +++ b/Application/EdFi.Ods.Common/Models/Resource/ResourceModel.cs @@ -26,6 +26,14 @@ public interface IResourceModel /// The matching resource. Resource GetResourceByFullName(FullName resourceFullName); + /// + /// Gets the Resource using the schema and collection name representation as used on the API. + /// + /// The URI representation of the schema of the resource. + /// The pluralized collection name of the resource. + /// The matching resource. + Resource GetResourceByApiCollectionName(string schemaUriSegment, string resourceCollectionName); + /// /// Get a read-only list of all the resources available in the model. /// @@ -57,13 +65,13 @@ public ResourceModel(DomainModel domainModel) _domainModel = domainModel; _resourceByName = new Dictionary(); - DefaultResourceSelector = new ResourceSelector(_resourceByName); - // Add all aggregate roots to the resource model domainModel - .Entities - .Where(a => a.IsAggregateRoot) - .ForEach(AddResource); + .Entities + .Where(a => a.IsAggregateRoot) + .ForEach(AddResource); + + DefaultResourceSelector = new ResourceSelector(_resourceByName); } internal IResourceSelector DefaultResourceSelector { get; } @@ -89,11 +97,18 @@ IResourceSelector IHasContextualResourceSelector.SetContextualResourceSelector(I return DefaultResourceSelector; } + /// public Resource GetResourceByFullName(FullName fullName) { return ResourceSelector.GetByName(fullName); } + /// + public Resource GetResourceByApiCollectionName(string schemaUriSegment, string resourceCollectionName) + { + return ResourceSelector.GetByApiCollectionName(schemaUriSegment, resourceCollectionName); + } + public IReadOnlyList GetAllResources() { return ResourceSelector.GetAll(); diff --git a/Application/EdFi.Ods.Common/Models/Resource/ResourceProperty.cs b/Application/EdFi.Ods.Common/Models/Resource/ResourceProperty.cs index 906da3b7b3..6704def15f 100644 --- a/Application/EdFi.Ods.Common/Models/Resource/ResourceProperty.cs +++ b/Application/EdFi.Ods.Common/Models/Resource/ResourceProperty.cs @@ -3,15 +3,14 @@ // The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. // See the LICENSE and NOTICES files in the project root for more information. +using System; +using System.Collections.Generic; using System.Data; using System.Linq; -using System.Xml; using EdFi.Common.Extensions; using EdFi.Common.Utils.Extensions; -using EdFi.Ods.Common.Extensions; using EdFi.Ods.Common.Models.Domain; using EdFi.Ods.Common.Specifications; -using EdFi.Ods.Common.Utils.Extensions; namespace EdFi.Ods.Common.Models.Resource { @@ -51,16 +50,25 @@ public PropertyCharacteristics( public class ResourceProperty : ResourceMemberBase { + private ResourceMemberBase _containingMember; + private Lazy> _unifiedProperties; + private Lazy _descriptorResource; + public ResourceProperty(ResourceClassBase resourceClass, EntityProperty entityProperty) + : this(null, resourceClass, entityProperty) { } + + public ResourceProperty(ResourceMemberBase containingMember, ResourceClassBase resourceClass, EntityProperty entityProperty) : base(resourceClass, GetResourcePropertyName(entityProperty)) { + _containingMember = containingMember; + EntityProperty = entityProperty; string personType; // Assign property characteristics - IsLookup = entityProperty.IsLookup; - IsDirectLookup = entityProperty.IsDirectLookup; + IsDescriptorUsage = entityProperty.IsDescriptorUsage; + IsDirectDescriptorUsage = entityProperty.IsDirectDescriptorUsage; IsIdentifying = entityProperty.IsIdentifying || UniqueIdSpecification.TryGetUniqueIdPersonType(entityProperty.PropertyName, out personType) @@ -69,13 +77,7 @@ public ResourceProperty(ResourceClassBase resourceClass, EntityProperty entityPr IsLocallyDefined = entityProperty.IsLocallyDefined; IsServerAssigned = entityProperty.IsServerAssigned; - LookupTypeName = entityProperty.LookupEntity == null - ? null - : entityProperty.LookupEntity.Name; - - DescriptorResource = entityProperty.LookupEntity == null - ? null - : resourceClass?.ResourceModel?.GetResourceByFullName(entityProperty.LookupEntity.FullName); + DescriptorName = entityProperty.DescriptorEntity?.Name; PropertyType = GetResourcePropertyType(entityProperty); Description = entityProperty.Description; @@ -86,6 +88,8 @@ public ResourceProperty(ResourceClassBase resourceClass, EntityProperty entityPr // produces a different result. Base class properties should retain their lineage // when "merged" into the resource model. ParentFullName = EntityProperty.Entity.FullName; + + InitializeLazyMembers(); } public ResourceProperty( @@ -102,32 +106,50 @@ public ResourceProperty( DeprecationReasons = resourceClass.DeprecationReasons; // Assign property characteristics - IsDirectLookup = characteristics.IsDirectLookup; + IsDirectDescriptorUsage = characteristics.IsDirectLookup; IsIdentifying = characteristics.IsIdentifying; IsLocallyDefined = characteristics.IsLocallyDefined; IsServerAssigned = characteristics.IsServerAssigned; - LookupTypeName = characteristics.LookupEntityName == null - ? null - : characteristics.LookupEntityName.Value.Name; + DescriptorName = characteristics.LookupEntityName?.Name; - DescriptorResource = characteristics.LookupEntityName == null - ? null - : resourceClass?.ResourceModel?.GetResourceByFullName(characteristics.LookupEntityName.GetValueOrDefault()); - if (resourceClass.Entity != null) { ParentFullName = resourceClass.Entity.FullName; } + + InitializeLazyMembers(); + } + + private void InitializeLazyMembers() + { + _unifiedProperties = new Lazy>( + () => + { + if (ResourceClass.UnifiedPropertiesByPropertyName.Value.TryGetValue(PropertyName, out var unifiedProperties)) + { + return unifiedProperties.Except(new[] {this}).ToArray(); + } + + return new ResourceProperty[0]; + }); + + _descriptorResource = new Lazy( + () => EntityProperty.DescriptorEntity == null + ? null + : ResourceClass?.ResourceModel?.GetResourceByFullName(EntityProperty.DescriptorEntity.FullName)); } + + public string DescriptorName { get; } - public string LookupTypeName { get; } + [Obsolete("Use DescriptorName instead.")] + public string LookupTypeName => DescriptorName; /// /// For descriptors, gets the representing the descriptor referenced by the property; /// otherwise null. /// - public Resource DescriptorResource { get; } + public Resource DescriptorResource { get => _descriptorResource.Value; } public EntityProperty EntityProperty { get; } @@ -139,7 +161,13 @@ public ResourceProperty( public string[] DeprecationReasons { get; set; } - public bool IsDirectLookup { get; } + public bool IsDirectDescriptorUsage { get; } + + [Obsolete("Use IsDirectDescriptorUsage instead.")] + public bool IsDirectLookup + { + get => IsDirectDescriptorUsage; + } /// /// Indicates whether the property is part of the identity of the resource. @@ -150,8 +178,17 @@ public ResourceProperty( public bool IsLocallyDefined { get; } - public bool IsLookup { get; } + [Obsolete("Use IsDescriptorUsage instead.")] + public bool IsLookup + { + get => IsDescriptorUsage; + } + /// + /// Indicates whether the property represents the usage of a descriptor. + /// + public bool IsDescriptorUsage { get; } + public bool IsServerAssigned { get; } /// @@ -180,7 +217,7 @@ public bool IsInherited private PropertyType GetResourcePropertyType(EntityProperty property) { - if (property.IsLookup) + if (property.IsDescriptorUsage) { // NOTE: the property length for lookups has changed in data standard 3.0. // The new formula is: 255 (namespace max length) + 1 (separator length) + 50 (code value max length), or 306 @@ -218,7 +255,7 @@ private static PropertyType GetBasePersonUniqueIdPropertyType(EntityProperty pro private static string GetResourcePropertyName(EntityProperty property) { // Simplistic conversion using conventions - if (property.IsLookup) + if (property.IsDescriptorUsage) { return property.PropertyName.TrimSuffix("Id"); } @@ -264,5 +301,28 @@ private bool IsUsiWithTransformedResourcePropertyName(EntityProperty property) return UniqueIdSpecification.IsUSI(property.PropertyName) && UniqueIdSpecification.TryGetUniqueIdPersonType(PropertyName, out notUsed); } + + public override string JsonPath + { + get + { + if (_containingMember == null) + { + return base.JsonPath; + } + + return $"{_containingMember?.JsonPath ?? Parent.JsonPath}.{JsonPropertyName}"; + } + } + + /// + /// Gets any other instances present on other references + /// that are unifying properties -- properties whose values (if present) must all + /// match because they are unified into a single database column for persistence. + /// + public IReadOnlyList UnifiedProperties + { + get => _unifiedProperties.Value; + } } } diff --git a/Application/EdFi.Ods.Common/Models/Resource/ResourceSelector.cs b/Application/EdFi.Ods.Common/Models/Resource/ResourceSelector.cs index b6b2d67a74..5893db9559 100644 --- a/Application/EdFi.Ods.Common/Models/Resource/ResourceSelector.cs +++ b/Application/EdFi.Ods.Common/Models/Resource/ResourceSelector.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Linq; +using EdFi.Common.Extensions; using EdFi.Ods.Common.Extensions; using EdFi.Ods.Common.Models.Domain; @@ -13,10 +14,15 @@ namespace EdFi.Ods.Common.Models.Resource public class ResourceSelector : IResourceSelector { private readonly IDictionary _resourceByFullName; + private readonly Dictionary _resourceByCollectionName; public ResourceSelector(IDictionary resourceByFullName) { _resourceByFullName = resourceByFullName; + + _resourceByCollectionName = resourceByFullName.ToDictionary( + kvp => new FullName(kvp.Value.SchemaUriSegment(), kvp.Value.PluralName.ToCamelCase()), + kvp => kvp.Value); } public IReadOnlyList GetAll() @@ -29,6 +35,11 @@ public Resource GetByName(FullName fullName) return _resourceByFullName.GetValueOrThrow(fullName, "FullName {0} was not located in ResourceSelector."); } + public Resource GetByApiCollectionName(string schemaUriSegment, string resourceCollectionName) + { + return _resourceByCollectionName.GetValueOrThrow(new FullName(schemaUriSegment, resourceCollectionName), $"Resource collection for /{schemaUriSegment}/{resourceCollectionName} was not located in ResourceSelector."); + } + public Resource GetBySchemaProperCaseNameAndName(string properCaseName, string name) { return _resourceByFullName.GetValueOrThrow(new FullName(properCaseName, name), "Resource '{0}' not found."); diff --git a/Application/EdFi.Ods.Common/Specifications/DescriptorEntitySpecification.cs b/Application/EdFi.Ods.Common/Specifications/DescriptorEntitySpecification.cs index 063b535dd7..14a5c8ec07 100644 --- a/Application/EdFi.Ods.Common/Specifications/DescriptorEntitySpecification.cs +++ b/Application/EdFi.Ods.Common/Specifications/DescriptorEntitySpecification.cs @@ -11,11 +11,23 @@ namespace EdFi.Ods.Common.Specifications { public class DescriptorEntitySpecification { + /// + /// Indicates whether the specific matches the convention for an entity derived from the abstract Descriptor + /// entity, but does not represent the abstract Descriptor entity itself. + /// + /// The to be evaluated. + /// true if the type name matches the convention for a Descriptor-derived entity; otherwise false. public static bool IsEdFiDescriptorEntity(Type type) { return IsEdFiDescriptorEntity(type.Name); } + /// + /// Indicates whether the specific type name matches the convention for an entity derived from the abstract Descriptor + /// entity, but does not represent the abstract Descriptor entity itself. + /// + /// The name of the type to be evaluated. + /// true if the type name matches the convention for a Descriptor-derived entity; otherwise false. public static bool IsEdFiDescriptorEntity(string typeName) { return typeName.EndsWithIgnoreCase("Descriptor") diff --git a/Application/EdFi.Ods.Features/ChangeQueries/AvailableChangeVersion.cs b/Application/EdFi.Ods.Features/ChangeQueries/AvailableChangeVersion.cs index a6f610ac98..16234ff4d3 100644 --- a/Application/EdFi.Ods.Features/ChangeQueries/AvailableChangeVersion.cs +++ b/Application/EdFi.Ods.Features/ChangeQueries/AvailableChangeVersion.cs @@ -15,11 +15,13 @@ public class AvailableChangeVersion /// /// Gets or sets the earliest (oldest) change version that is available, or 0 if no version is available. /// + [DataMember(Name = "oldestChangeVersion")] public long OldestChangeVersion { get; set; } /// /// Gets or sets the most recent (newest) change version that is available, or 0 if no version is available. /// + [DataMember(Name = "newestChangeVersion")] public long NewestChangeVersion { get; set; } } } diff --git a/Application/EdFi.Ods.Features/ChangeQueries/ChangeQueriesDatabaseConstants.cs b/Application/EdFi.Ods.Features/ChangeQueries/ChangeQueriesDatabaseConstants.cs index a32a3d9692..fd0564f750 100644 --- a/Application/EdFi.Ods.Features/ChangeQueries/ChangeQueriesDatabaseConstants.cs +++ b/Application/EdFi.Ods.Features/ChangeQueries/ChangeQueriesDatabaseConstants.cs @@ -13,18 +13,24 @@ public class ChangeQueriesDatabaseConstants public const string SchemaName = "changes"; /// - /// Gets the logical schema name for Change Events. + /// Gets the column name used for tracking changed records /// - public const string LogicalSchemaName = "ChangeQueries"; + public const string ChangeVersionColumnName = "ChangeVersion"; /// - /// Gets the column name used for tracking changed records + /// Prefix applied to the schema name holding the tracked change tables for a data standard schema. /// - public const string ChangeVersionColumnName = "ChangeVersion"; + public const string TrackedChangesSchemaPrefix = "tracked_changes_"; /// - /// Prefix applied to the schema name holding the tracked delete tables for a data standard schema. + /// Prefix applied to the identifier column name containing the previous value. + /// + public const string OldKeyValueColumnPrefix = "Old"; + + /// + /// Prefix applied to the identifier column name containing the new value. /// - public const string TrackedDeletesSchemaPrefix = "Tracked_Deletes_"; + public const string NewKeyValueColumnPrefix = "New"; + public const string TrackedChangesAlias = "c"; } } diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Controllers/DeletesController.cs b/Application/EdFi.Ods.Features/ChangeQueries/Controllers/DeletesController.cs new file mode 100644 index 0000000000..1b4f369beb --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Controllers/DeletesController.cs @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System.Net.Mime; +using System.Threading.Tasks; +using EdFi.Ods.Api.Helpers; +using EdFi.Ods.Common.Configuration; +using EdFi.Ods.Common.Constants; +using EdFi.Ods.Common.Models; +using EdFi.Ods.Common.Models.Queries; +using EdFi.Ods.Common.Security.Claims; +using EdFi.Ods.Common.Serialization; +using EdFi.Ods.Features.ChangeQueries.Repositories.DeletedItems; +using EdFi.Ods.Security.Authorization; +using EdFi.Security.DataAccess.Repositories; +using log4net; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Newtonsoft.Json; + +namespace EdFi.Ods.Features.ChangeQueries.Controllers +{ + [Authorize] + [ApiController] + [Produces("application/json")] + [Route("{schema}/{resource}/deletes")] + public class DeletesController : ControllerBase + { + private readonly IDomainModelProvider _domainModelProvider; + private readonly IDeletedItemsResourceDataProvider _deletedItemsResourceDataProvider; + private readonly IAuthorizationContextProvider _authorizationContextProvider; + private readonly IResourceClaimUriProvider _resourceClaimUriProvider; + private readonly ISecurityRepository _securityRepository; + private readonly ILog _logger = LogManager.GetLogger(typeof(DeletesController)); + private readonly bool _isEnabled; + + public DeletesController( + IDomainModelProvider domainModelProvider, + IDeletedItemsResourceDataProvider deletedItemsResourceDataProvider, + IAuthorizationContextProvider authorizationContextProvider, + IResourceClaimUriProvider resourceClaimUriProvider, + ISecurityRepository securityRepository, + ApiSettings apiSettings) + { + _domainModelProvider = domainModelProvider; + _deletedItemsResourceDataProvider = deletedItemsResourceDataProvider; + _authorizationContextProvider = authorizationContextProvider; + _resourceClaimUriProvider = resourceClaimUriProvider; + _securityRepository = securityRepository; + + _isEnabled = apiSettings.IsFeatureEnabled(ApiFeature.ChangeQueries.GetConfigKeyName()); + } + + [HttpGet] + public async Task Get(string schema, string resource, [FromQuery] UrlQueryParametersRequest urlQueryParametersRequest) + { + if (!_isEnabled) + { + _logger.Debug("ChangeQueries is not enabled."); + + return ControllerHelpers.NotFound(); + } + + var resourceClass = _domainModelProvider.GetDomainModel().ResourceModel.GetResourceByApiCollectionName(schema, resource); + + if (resourceClass == null) + { + return ControllerHelpers.NotFound(); + } + + // Set authorization context (should this be moved?) + _authorizationContextProvider.SetResourceUris(_resourceClaimUriProvider.GetResourceClaimUris(resourceClass)); + _authorizationContextProvider.SetAction(_securityRepository.GetActionByName("ReadChanges").ActionUri); + + // TODO: Validate the parameter here rather than deeper in the call stack + var queryParameter = new QueryParameters(urlQueryParametersRequest); + + var deletedItemsResponse = await _deletedItemsResourceDataProvider.GetResourceDataAsync(resourceClass, queryParameter); + + // Add the total count, if requested + if (urlQueryParametersRequest.TotalCount) + { + Response.Headers.Add("Total-Count", deletedItemsResponse.Count.ToString()); + } + + // Explicitly serialize the response to remain backwards compatible with pre .net core + return new ContentResult + { + Content = JsonConvert.SerializeObject(deletedItemsResponse.Items, new Iso8601UtcDateOnlyConverter()), + ContentType = MediaTypeNames.Application.Json, + StatusCode = StatusCodes.Status200OK + }; + } + } +} \ No newline at end of file diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Controllers/KeyChangesController.cs b/Application/EdFi.Ods.Features/ChangeQueries/Controllers/KeyChangesController.cs new file mode 100644 index 0000000000..fce1d5b380 --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Controllers/KeyChangesController.cs @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System.Net.Mime; +using System.Threading.Tasks; +using EdFi.Ods.Api.Helpers; +using EdFi.Ods.Common.Configuration; +using EdFi.Ods.Common.Constants; +using EdFi.Ods.Common.Models; +using EdFi.Ods.Common.Models.Queries; +using EdFi.Ods.Common.Security.Claims; +using EdFi.Ods.Common.Serialization; +using EdFi.Ods.Features.ChangeQueries.Repositories.KeyChanges; +using EdFi.Ods.Security.Authorization; +using EdFi.Security.DataAccess.Repositories; +using log4net; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Newtonsoft.Json; + +namespace EdFi.Ods.Features.ChangeQueries.Controllers +{ + [Authorize] + [ApiController] + [Produces("application/json")] + [Route("{schema}/{resource}/keyChanges")] + public class KeyChangesController : ControllerBase + { + private readonly IDomainModelProvider _domainModelProvider; + private readonly IKeyChangesResourceDataProvider _keyChangesResourceDataProvider; + private readonly IAuthorizationContextProvider _authorizationContextProvider; + private readonly IResourceClaimUriProvider _resourceClaimUriProvider; + private readonly ISecurityRepository _securityRepository; + + private readonly ILog _logger = LogManager.GetLogger(typeof(KeyChangesController)); + private readonly bool _isEnabled; + + public KeyChangesController( + IDomainModelProvider domainModelProvider, + IKeyChangesResourceDataProvider keyChangesResourceDataProvider, + IAuthorizationContextProvider authorizationContextProvider, + IResourceClaimUriProvider resourceClaimUriProvider, + ISecurityRepository securityRepository, + ApiSettings apiSettings) + { + _domainModelProvider = domainModelProvider; + _keyChangesResourceDataProvider = keyChangesResourceDataProvider; + _authorizationContextProvider = authorizationContextProvider; + _resourceClaimUriProvider = resourceClaimUriProvider; + _securityRepository = securityRepository; + + _isEnabled = apiSettings.IsFeatureEnabled(ApiFeature.ChangeQueries.GetConfigKeyName()); + } + + [HttpGet] + public async Task Get(string schema, string resource, [FromQuery] UrlQueryParametersRequest urlQueryParametersRequest) + { + if (!_isEnabled) + { + _logger.Debug("ChangeQueries is not enabled."); + + return ControllerHelpers.NotFound(); + } + + var resourceClass = _domainModelProvider.GetDomainModel().ResourceModel.GetResourceByApiCollectionName(schema, resource); + + if (resourceClass == null) + { + return ControllerHelpers.NotFound(); + } + + // Set authorization context (should this be moved to an authorization component?) + _authorizationContextProvider.SetResourceUris(_resourceClaimUriProvider.GetResourceClaimUris(resourceClass)); + _authorizationContextProvider.SetAction(_securityRepository.GetActionByName("ReadChanges").ActionUri); + + // TODO: Validate the parameters here (and rather than deeper in the call stack) + var queryParameter = new QueryParameters(urlQueryParametersRequest); + + var keyChangesResponse = await _keyChangesResourceDataProvider.GetResourceDataAsync(resourceClass, queryParameter); + + // Add the total count, if requested + if (urlQueryParametersRequest.TotalCount) + { + Response.Headers.Add("Total-Count", keyChangesResponse.Count.ToString()); + } + + // Explicitly serialize the response to remain backwards compatible with .NET Framework implementation responses + return new ContentResult + { + Content = JsonConvert.SerializeObject(keyChangesResponse.Items, new Iso8601UtcDateOnlyConverter()), + ContentType = MediaTypeNames.Application.Json, + StatusCode = StatusCodes.Status200OK + }; + } + } +} diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Controllers/SnapshotsController.cs b/Application/EdFi.Ods.Features/ChangeQueries/Controllers/SnapshotsController.cs index 812d27efd7..c012262897 100644 --- a/Application/EdFi.Ods.Features/ChangeQueries/Controllers/SnapshotsController.cs +++ b/Application/EdFi.Ods.Features/ChangeQueries/Controllers/SnapshotsController.cs @@ -6,10 +6,11 @@ using System; using System.Net; using System.Threading.Tasks; +using EdFi.Ods.Api.Helpers; using EdFi.Ods.Common.Configuration; using EdFi.Ods.Common.Constants; using EdFi.Ods.Common.Models.Queries; -using EdFi.Ods.Features.ChangeQueries.Repositories; +using EdFi.Ods.Features.ChangeQueries.Repositories.Snapshots; using log4net; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; @@ -43,10 +44,7 @@ public async Task GetAll([FromQuery] UrlQueryParametersRequest ur _logger.Debug($"{nameof(SnapshotsController)} was matched to handle the request, but the '{ApiFeature.ChangeQueries}' feature is disabled."); // Not Found - return new ObjectResult(null) - { - StatusCode = (int) HttpStatusCode.NotFound, - }; + return ControllerHelpers.NotFound(); } var snapshots = await _getSnapshots.GetAllAsync(new QueryParameters(urlQueryParametersRequest)); @@ -61,10 +59,7 @@ public virtual async Task Get(Guid id) _logger.Debug($"{nameof(SnapshotsController)} was matched to handle the request, but the '{ApiFeature.ChangeQueries}' feature is disabled."); // Not Found - return new ObjectResult(null) - { - StatusCode = (int) HttpStatusCode.NotFound, - }; + return ControllerHelpers.NotFound(); } var snapshot = await _getSnapshots.GetByIdAsync(id); @@ -72,10 +67,7 @@ public virtual async Task Get(Guid id) if (snapshot == null) { // Not Found - return new ObjectResult(null) - { - StatusCode = (int) HttpStatusCode.NotFound, - }; + return ControllerHelpers.NotFound(); } return Ok(snapshot); diff --git a/Application/EdFi.Ods.Features/Conventions/DeletesRouteConvention.cs b/Application/EdFi.Ods.Features/ChangeQueries/Conventions/DeletesRouteConvention.cs similarity index 95% rename from Application/EdFi.Ods.Features/Conventions/DeletesRouteConvention.cs rename to Application/EdFi.Ods.Features/ChangeQueries/Conventions/DeletesRouteConvention.cs index 724d8622a6..ac04abc34c 100644 --- a/Application/EdFi.Ods.Features/Conventions/DeletesRouteConvention.cs +++ b/Application/EdFi.Ods.Features/ChangeQueries/Conventions/DeletesRouteConvention.cs @@ -7,11 +7,11 @@ using System.Reflection; using EdFi.Common.Configuration; using EdFi.Ods.Api.Constants; -using EdFi.Ods.Features.Controllers; using EdFi.Ods.Common.Configuration; +using EdFi.Ods.Features.ChangeQueries.Controllers; using Microsoft.AspNetCore.Mvc.ApplicationModels; -namespace EdFi.Ods.Features.Conventions +namespace EdFi.Ods.Features.ChangeQueries.Conventions { public class DeletesRouteConvention : IApplicationModelConvention { diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Conventions/KeyChangesRouteConvention.cs b/Application/EdFi.Ods.Features/ChangeQueries/Conventions/KeyChangesRouteConvention.cs new file mode 100644 index 0000000000..4f30845ee7 --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Conventions/KeyChangesRouteConvention.cs @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System.Linq; +using System.Reflection; +using EdFi.Common.Configuration; +using EdFi.Ods.Api.Constants; +using EdFi.Ods.Common.Configuration; +using EdFi.Ods.Features.ChangeQueries.Controllers; +using Microsoft.AspNetCore.Mvc.ApplicationModels; + +namespace EdFi.Ods.Features.ChangeQueries.Conventions +{ + public class KeyChangesRouteConvention : IApplicationModelConvention + { + private readonly ApiSettings _apiSettings; + + public KeyChangesRouteConvention(ApiSettings apiSettings) + { + _apiSettings = apiSettings; + } + + public void Apply(ApplicationModel application) + { + var controller = + application.Controllers.FirstOrDefault( + x => x.ControllerType == typeof(KeyChangesController).GetTypeInfo()); + + if (controller != null) + { + var routePrefix = new AttributeRouteModel {Template = CreateRouteTemplate()}; + + foreach (var selector in controller.Selectors) + { + if (selector.AttributeRouteModel != null) + { + selector.AttributeRouteModel = AttributeRouteModel.CombineAttributeRouteModel( + routePrefix, + selector.AttributeRouteModel); + } + } + } + + string CreateRouteTemplate() + { + string template = $"{RouteConstants.DataManagementRoutePrefix}/"; + + if (_apiSettings.GetApiMode() == ApiMode.YearSpecific) + { + template += RouteConstants.SchoolYearFromRoute; + } + + if (_apiSettings.GetApiMode() == ApiMode.InstanceYearSpecific) + { + template += RouteConstants.InstanceIdFromRoute; + template += RouteConstants.SchoolYearFromRoute; + } + + return template; + } + } + } +} diff --git a/Application/EdFi.Ods.Features/ChangeQueries/DomainModelEnhancers/NHibernateEntityTypeDomainModelEnhancer.cs b/Application/EdFi.Ods.Features/ChangeQueries/DomainModelEnhancers/NHibernateEntityTypeDomainModelEnhancer.cs new file mode 100644 index 0000000000..c3d3fa9e67 --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/DomainModelEnhancers/NHibernateEntityTypeDomainModelEnhancer.cs @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Reflection; +using EdFi.Ods.Common.Attributes; +using EdFi.Ods.Common.Models.Domain; +using log4net; +using NHibernate; +using NHibernate.Metadata; + +namespace EdFi.Ods.Features.ChangeQueries.DomainModelEnhancers +{ + public interface IDomainModelEnhancer + { + void Enhance(DomainModel domainModel); + } + + public class NHibernateEntityTypeDomainModelEnhancer : IDomainModelEnhancer + { + private readonly ILog _logger = LogManager.GetLogger(typeof(NHibernateEntityTypeDomainModelEnhancer)); + + private readonly ISessionFactory _sessionFactory; + + public NHibernateEntityTypeDomainModelEnhancer(ISessionFactory sessionFactory) + { + _sessionFactory = sessionFactory; + } + + public void Enhance(DomainModel domainModel) + { + var allClassMetadata = _sessionFactory.GetAllClassMetadata(); + + foreach (KeyValuePair classMetadata in allClassMetadata) + { + var mappedEntityType = classMetadata.Value.MappedClass; + string schema = mappedEntityType.GetCustomAttribute()?.Schema; + + var expectedFullName = new FullName(schema, mappedEntityType.Name); + + if (domainModel.EntityByFullName.TryGetValue(expectedFullName, out var entity)) + { + (entity as dynamic).NHibernateEntityType = mappedEntityType; + } + else + { + _logger.Debug($"Unable to locate entity '{expectedFullName}' for NHibernate entity type '{mappedEntityType.FullName}'. .NET Type will not be available on the entity in the model."); + } + } + } + } +} diff --git a/Application/EdFi.Ods.Features/ChangeQueries/GetDeletedResourceIds.cs b/Application/EdFi.Ods.Features/ChangeQueries/GetDeletedResourceIds.cs deleted file mode 100644 index 1c38558bee..0000000000 --- a/Application/EdFi.Ods.Features/ChangeQueries/GetDeletedResourceIds.cs +++ /dev/null @@ -1,83 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// Licensed to the Ed-Fi Alliance under one or more agreements. -// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. -// See the LICENSE and NOTICES files in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Linq; -using EdFi.Common.Configuration; -using EdFi.Common.Extensions; -using EdFi.Ods.Api.Infrastructure.Pipelines; -using EdFi.Ods.Common; -using EdFi.Ods.Common.Configuration; -using EdFi.Ods.Common.Extensions; -using EdFi.Ods.Common.Infrastructure; -using EdFi.Ods.Common.Infrastructure.Repositories; -using EdFi.Ods.Common.Models; -using EdFi.Ods.Common.Models.Domain; -using NHibernate; -using NHibernate.Transform; - -namespace EdFi.Ods.Features.ChangeQueries -{ - public class GetDeletedResourceIds : NHibernateRepositoryOperationBase, IGetDeletedResourceIds - { - private readonly ISessionFactory _sessionFactory; - private readonly IDomainModelProvider _domainModelProvider; - private readonly DatabaseEngine _databaseEngine; - - public GetDeletedResourceIds( - ISessionFactory sessionFactory, - IDomainModelProvider domainModelProvider, - DatabaseEngine databaseEngine) - : base(sessionFactory) - { - _sessionFactory = sessionFactory; - _domainModelProvider = domainModelProvider; - _databaseEngine = databaseEngine; - } - - public IReadOnlyList Execute(string schemaUriSegment, string urlResourcePluralName, IQueryParameters queryParameters) - { - var entity = _domainModelProvider.GetDomainModel().ResourceModel.GetAllResources().SingleOrDefault( - r => r.SchemaUriSegment() == schemaUriSegment && - r.PluralName.EqualsIgnoreCase(urlResourcePluralName))?.Entity; - - if (entity == null) - { - throw new ArgumentException( - $"Unable to find entity for provided schema uri segment {schemaUriSegment} and url resource {urlResourcePluralName}."); - } - - var cmdSql = $"SELECT Id, {ChangeQueriesDatabaseConstants.ChangeVersionColumnName}" + - $" FROM {ChangeQueriesDatabaseConstants.TrackedDeletesSchemaPrefix}{entity.Schema}.{entity.TableName(_databaseEngine)}"; - - if (queryParameters.MinChangeVersion.HasValue) - { - cmdSql += $" WHERE {ChangeQueriesDatabaseConstants.ChangeVersionColumnName} >= {queryParameters.MinChangeVersion.Value}"; - } - - if (queryParameters.MaxChangeVersion.HasValue) - { - cmdSql += queryParameters.MinChangeVersion.HasValue - ? " AND " - : " WHERE "; - - cmdSql += $"{ChangeQueriesDatabaseConstants.ChangeVersionColumnName} <= {queryParameters.MaxChangeVersion.Value}"; - } - - cmdSql += $" ORDER BY {ChangeQueriesDatabaseConstants.ChangeVersionColumnName}"; - - using (var sessionScope = new SessionScope(_sessionFactory)) - { - var query = sessionScope.Session.CreateSQLQuery(cmdSql) - .SetFirstResult(queryParameters.Offset ?? 0) - .SetMaxResults(queryParameters.Limit ?? 25) - .SetResultTransformer(Transformers.AliasToBean()); - - return query.List().ToReadOnlyList(); - } - } - } -} diff --git a/Application/EdFi.Ods.Features/ChangeQueries/GetDeletedResourceIdsAuthorizationDecorator.cs b/Application/EdFi.Ods.Features/ChangeQueries/GetDeletedResourceIdsAuthorizationDecorator.cs deleted file mode 100644 index b7c665889a..0000000000 --- a/Application/EdFi.Ods.Features/ChangeQueries/GetDeletedResourceIdsAuthorizationDecorator.cs +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// Licensed to the Ed-Fi Alliance under one or more agreements. -// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. -// See the LICENSE and NOTICES files in the project root for more information. - -using System.Collections.Generic; -using EdFi.Ods.Api.Infrastructure.Pipelines; -using EdFi.Ods.Common; -using EdFi.Ods.Common.Models; -using EdFi.Ods.Common.Security.Claims; -using EdFi.Ods.Security.Authorization.Repositories; -using EdFi.Security.DataAccess.Repositories; - -namespace EdFi.Ods.Features.ChangeQueries -{ - public class GetDeletedResourceIdsAuthorizationDecorator - : RepositoryOperationAuthorizationDecoratorBase, IGetDeletedResourceIds - where T : class, IHasIdentifier, IDateVersionedEntity - { - private readonly IGetDeletedResourceIds _next; - private readonly ISecurityRepository _securityRepository; - - public GetDeletedResourceIdsAuthorizationDecorator( - IGetDeletedResourceIds next, - ISecurityRepository securityRepository, - IAuthorizationContextProvider authorizationContextProvider, - IEdFiAuthorizationProvider authorizationProvider) - : base(authorizationContextProvider, authorizationProvider) - { - _next = next; - _securityRepository = securityRepository; - } - - public IReadOnlyList Execute(string schema, string resource, IQueryParameters queryParameters) - { - return null; - } - } -} diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Modules/ChangeQueriesModule.cs b/Application/EdFi.Ods.Features/ChangeQueries/Modules/ChangeQueriesModule.cs index 64255a13eb..d36a3164c5 100644 --- a/Application/EdFi.Ods.Features/ChangeQueries/Modules/ChangeQueriesModule.cs +++ b/Application/EdFi.Ods.Features/ChangeQueries/Modules/ChangeQueriesModule.cs @@ -4,7 +4,6 @@ // See the LICENSE and NOTICES files in the project root for more information. using Autofac; -using EdFi.Ods.Api.Infrastructure.Pipelines; using EdFi.Ods.Features.Conventions; using EdFi.Ods.Common.Configuration; using EdFi.Ods.Common.Constants; @@ -18,8 +17,14 @@ using EdFi.Ods.Common.Database; using EdFi.Ods.Features.ChangeQueries.ExceptionHandling; using EdFi.Ods.Api.ExceptionHandling; +using EdFi.Ods.Common.Models.Domain; using EdFi.Ods.Features.ChangeQueries.Repositories; using EdFi.Ods.Features.ChangeQueries.Conventions; +using EdFi.Ods.Features.ChangeQueries.DomainModelEnhancers; +using EdFi.Ods.Features.ChangeQueries.Repositories.Authorization; +using EdFi.Ods.Features.ChangeQueries.Repositories.DeletedItems; +using EdFi.Ods.Features.ChangeQueries.Repositories.KeyChanges; +using EdFi.Ods.Features.ChangeQueries.Repositories.Snapshots; namespace EdFi.Ods.Features.ChangeQueries.Modules { @@ -32,51 +37,112 @@ public ChangeQueriesModule(ApiSettings apiSettings) public override void ApplyConfigurationSpecificRegistrations(ContainerBuilder builder) { - builder.RegisterType() - .As() - .SingleInstance(); - - builder.RegisterType() - .As() - .SingleInstance(); - - builder.RegisterType() - .As() - .SingleInstance(); - - builder.RegisterType() - .As() - .SingleInstance(); - + // Change Queries support in NHibernate mappings builder.RegisterType() .As() .SingleInstance(); - // Routing - builder.RegisterType() - .As() + AddSupportForAvailableChanges(); + AddSupportForSnapshots(); + AddSupportForDeletes(); + AddSupportForKeyChanges(); + AddSupportForAuthorization(); + + // General Tracked Changes query support + builder.RegisterType() + .As() .SingleInstance(); + + void AddSupportForAvailableChanges() + { + // Available changes support + builder.RegisterType() + .As() + .SingleInstance(); - // Publishing components / services - builder.RegisterType() - .As() - .SingleInstance(); + builder.RegisterType() + .As() + .SingleInstance(); + } - builder.RegisterType() - .As() - .SingleInstance(); + void AddSupportForSnapshots() + { + // Snapshots support + builder.RegisterType() + .As() + .SingleInstance(); + + builder.RegisterType() + .As() + .SingleInstance(); + + builder.RegisterType() + .As() + .SingleInstance(); - builder.RegisterDecorator< + builder.RegisterDecorator< SnapshotSuffixDatabaseNameReplacementTokenProvider, IDatabaseNameReplacementTokenProvider>(); - builder.RegisterType() - .As() - .SingleInstance(); + builder.RegisterType() + .As() + .SingleInstance(); - builder.RegisterType() - .As() - .SingleInstance(); + builder.RegisterType() + .As() + .SingleInstance(); + } + + void AddSupportForDeletes() + { + // Deletes support + builder.RegisterType() + .As() + .SingleInstance(); + + builder.RegisterType() + .As() + .SingleInstance(); + + builder.RegisterType() + .As() + .SingleInstance(); + + builder.RegisterType() + .As() + .SingleInstance(); + } + + void AddSupportForKeyChanges() + { + // KeyChanges support + builder.RegisterType() + .As() + .SingleInstance(); + + builder.RegisterType() + .As() + .SingleInstance(); + + builder.RegisterType() + .As() + .SingleInstance(); + + builder.RegisterType() + .As() + .SingleInstance(); + } + + void AddSupportForAuthorization() + { + // General authorization support + builder.RegisterType() + .As() + .SingleInstance(); + + builder.RegisterDecorator(); + builder.RegisterDecorator(); + } } } } diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/Authorization/DeletedItemsQueryFactoryAuthorizationDecorator.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/Authorization/DeletedItemsQueryFactoryAuthorizationDecorator.cs new file mode 100644 index 0000000000..fbdae7e737 --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/Authorization/DeletedItemsQueryFactoryAuthorizationDecorator.cs @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using EdFi.Ods.Common.Models; +using EdFi.Ods.Common.Models.Resource; +using EdFi.Ods.Common.Security.Claims; +using EdFi.Ods.Features.ChangeQueries.DomainModelEnhancers; +using EdFi.Ods.Features.ChangeQueries.Repositories.DeletedItems; +using EdFi.Ods.Features.ChangeQueries.Repositories.KeyChanges; +using EdFi.Ods.Generator.Database.NamingConventions; +using SqlKata; + +namespace EdFi.Ods.Features.ChangeQueries.Repositories.Authorization +{ + public class DeletedItemsQueryFactoryAuthorizationDecorator : TrackedChangesQueryFactoryAuthorizationDecoratorBase, IDeletedItemsQueryFactory + { + private readonly IDeletedItemsQueryFactory _next; + + public DeletedItemsQueryFactoryAuthorizationDecorator( + IDeletedItemsQueryFactory next, + IAuthorizationContextProvider authorizationContextProvider, + IEdFiAuthorizationProvider edFiAuthorizationProvider, + IDatabaseNamingConvention namingConvention, + IDomainModelProvider domainModelProvider, + IDomainModelEnhancer domainModelEnhancer) + : base(authorizationContextProvider, edFiAuthorizationProvider, namingConvention, domainModelProvider, domainModelEnhancer) + { + _next = next; + } + + public Query CreateMainQuery(Resource resource) + { + var mainQuery = _next.CreateMainQuery(resource); + + ApplyAuthorizationFilters(resource, mainQuery); + + return mainQuery; + } + } +} diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/Authorization/KeyChangesQueryFactoryAuthorizationDecorator.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/Authorization/KeyChangesQueryFactoryAuthorizationDecorator.cs new file mode 100644 index 0000000000..4572c59abf --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/Authorization/KeyChangesQueryFactoryAuthorizationDecorator.cs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using EdFi.Ods.Common.Models; +using EdFi.Ods.Common.Models.Resource; +using EdFi.Ods.Common.Security.Claims; +using EdFi.Ods.Features.ChangeQueries.DomainModelEnhancers; +using EdFi.Ods.Features.ChangeQueries.Repositories.KeyChanges; +using EdFi.Ods.Generator.Database.NamingConventions; +using SqlKata; + +namespace EdFi.Ods.Features.ChangeQueries.Repositories.Authorization +{ + public class KeyChangesQueryFactoryAuthorizationDecorator : TrackedChangesQueryFactoryAuthorizationDecoratorBase, IKeyChangesQueryFactory + { + private readonly IKeyChangesQueryFactory _next; + + public KeyChangesQueryFactoryAuthorizationDecorator( + IKeyChangesQueryFactory next, + IAuthorizationContextProvider authorizationContextProvider, + IEdFiAuthorizationProvider edFiAuthorizationProvider, + IDatabaseNamingConvention namingConvention, + IDomainModelProvider domainModelProvider, + IDomainModelEnhancer domainModelEnhancer) + : base(authorizationContextProvider, edFiAuthorizationProvider, namingConvention, domainModelProvider, domainModelEnhancer) + { + _next = next; + } + + public Query CreateMainQuery(Resource resource) + { + var mainQuery = _next.CreateMainQuery(resource); + + ApplyAuthorizationFilters(resource, mainQuery); + + return mainQuery; + } + } +} diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/Authorization/TrackedChangesQueryFactoryAuthorizationDecoratorBase.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/Authorization/TrackedChangesQueryFactoryAuthorizationDecoratorBase.cs new file mode 100644 index 0000000000..ae18ba6857 --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/Authorization/TrackedChangesQueryFactoryAuthorizationDecoratorBase.cs @@ -0,0 +1,138 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System; +using System.Security; +using System.Security.Claims; +using EdFi.Common.Utils.Extensions; +using EdFi.Ods.Common.Models; +using EdFi.Ods.Common.Models.Resource; +using EdFi.Ods.Common.Security.Claims; +using EdFi.Ods.Features.ChangeQueries.DomainModelEnhancers; +using EdFi.Ods.Generator.Database.NamingConventions; +using SqlKata; + +namespace EdFi.Ods.Features.ChangeQueries.Repositories.Authorization +{ + public class TrackedChangesQueryFactoryAuthorizationDecoratorBase + { + private readonly IAuthorizationContextProvider _authorizationContextProvider; + private readonly IEdFiAuthorizationProvider _edFiAuthorizationProvider; + private readonly IDatabaseNamingConvention _namingConvention; + + protected TrackedChangesQueryFactoryAuthorizationDecoratorBase( + IAuthorizationContextProvider authorizationContextProvider, + IEdFiAuthorizationProvider edFiAuthorizationProvider, + IDatabaseNamingConvention namingConvention, + IDomainModelProvider domainModelProvider, + IDomainModelEnhancer domainModelEnhancer) + { + _authorizationContextProvider = authorizationContextProvider; + _edFiAuthorizationProvider = edFiAuthorizationProvider; + _namingConvention = namingConvention; + + domainModelEnhancer.Enhance(domainModelProvider.GetDomainModel()); + } + + protected void ApplyAuthorizationFilters(Resource resource, Query query) + { + Type entityType = ((dynamic)resource.Entity).NHibernateEntityType; + + if (entityType == null) + { + throw new SecurityException( + $"Unable to perform authorization because entity type for '{resource.Entity.FullName}' could not be identified."); + } + + var authorizationContext = new EdFiAuthorizationContext( + ClaimsPrincipal.Current, + _authorizationContextProvider.GetResourceUris(), + _authorizationContextProvider.GetAction(), + entityType); + + var filters = _edFiAuthorizationProvider.GetAuthorizationFilters(authorizationContext); + + var filterIndex = 0; + + // Apply authorization filters + foreach (var filter in filters) + { + // TODO: Decompose this conditional logic into an array of injected IDeletedItemsAuthorizationFilterHandler instances + if (filter.FilterName == "Namespace") + { + string namespaceColumnName = + _namingConvention.ColumnName($"{ChangeQueriesDatabaseConstants.OldKeyValueColumnPrefix}Namespace"); + + if (filter.ClaimValues.Length == 1) + { + query.WhereLike(namespaceColumnName, filter.ClaimValues[0]); + } + else if (filter.ClaimValues.Length > 1) + { + query.Where( + q => q.Where( + q2 => + { + filter.ClaimValues.ForEach(cv => q2.OrWhereLike(namespaceColumnName, cv)); + + return q2; + })); + } + else + { + // This should never happen + throw new SecurityException("No namespaces found in claims."); + } + } + // Determine if this matches the relationship-based authorization strategy naming pattern + else if (filter.FilterName.Contains("To")) + { + // If the endpoint names do not match, then use an authorization view join + if (filter.ClaimEndpointName != filter.SubjectEndpointName) + { + // TODO: For v5.3, view and filter names don't match due to the new EdOrgIdToEdOrgId auth view generalization + string viewName = filter.FilterName; + + string trackedChangesPropertyName = resource.Entity.IsDerived + ? GetBasePropertyNameForSubjectEndpointName() + : filter.SubjectEndpointName; + + // Generalize relationships-based naming convention + query.Join( + $"auth.{_namingConvention.IdentifierName(viewName)} AS rba{filterIndex}", + $"c.{_namingConvention.ColumnName($"{ChangeQueriesDatabaseConstants.OldKeyValueColumnPrefix}{trackedChangesPropertyName}")}", + $"rba{filterIndex}.{_namingConvention.ColumnName(filter.SubjectEndpointName)}"); + + // Apply claim value criteria + query.WhereIn($"rba{filterIndex}.{_namingConvention.ColumnName(filter.ClaimEndpointName)}", filter.ClaimValues); + } + else + { + // Apply claim value criteria directly to the column value + query.WhereIn($"c.{_namingConvention.ColumnName($"{ChangeQueriesDatabaseConstants.OldKeyValueColumnPrefix}{filter.ClaimEndpointName}")}", filter.ClaimValues); + } + } + else + { + throw new SecurityException( + $"Support for filtering with filter '{filter.FilterName}' has not been implemented."); + } + + filterIndex++; + + string GetBasePropertyNameForSubjectEndpointName() + { + if (!resource.Entity.PropertyByName.TryGetValue(filter.SubjectEndpointName, out var entityProperty)) + { + throw new Exception( + $"Unable to find property '{filter.SubjectEndpointName}' on entity '{resource.Entity.FullName}'."); + } + + return entityProperty.BaseProperty.PropertyName; + } + } + } + } +} diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/DeletedItems/DeletedItemsQueriesPreparer.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/DeletedItems/DeletedItemsQueriesPreparer.cs new file mode 100644 index 0000000000..fbe815a16c --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/DeletedItems/DeletedItemsQueriesPreparer.cs @@ -0,0 +1,43 @@ +using EdFi.Ods.Common; +using EdFi.Ods.Common.Configuration; +using EdFi.Ods.Common.Models.Resource; +using EdFi.Ods.Generator.Database.NamingConventions; +using log4net; +using SqlKata; +using SqlKata.Compilers; +using SqlKata.Execution; + +namespace EdFi.Ods.Features.ChangeQueries.Repositories.DeletedItems +{ + public class DeletedItemsQueriesPreparer : TrackedChangesQueriesPreparerBase, IDeletedItemsQueriesPreparer + { + private readonly Compiler _sqlCompiler; + private readonly ILog _logger = LogManager.GetLogger(typeof(DeletedItemsQueriesPreparer)); + + public DeletedItemsQueriesPreparer(Compiler sqlCompiler, IDefaultPageSizeLimitProvider defaultPageSizeLimitProvider, IDatabaseNamingConvention namingConvention) + : base(sqlCompiler, defaultPageSizeLimitProvider, namingConvention) + { + _sqlCompiler = sqlCompiler; + } + + protected override Query PrepareDataQuery( + QueryFactory db, + Query mainQuery, + IQueryParameters queryParameters, + Resource resource) + { + var query = db.FromQuery(mainQuery); + + ApplyPaging(query, queryParameters); + ApplyChangeVersionCriteria(query, queryParameters); + + if (_logger.IsDebugEnabled) + { + var sqlResult = _sqlCompiler.Compile(query); + _logger.Debug(sqlResult.Sql); + } + + return query; + } + } +} \ No newline at end of file diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/DeletedItems/DeletedItemsQueryFactory.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/DeletedItems/DeletedItemsQueryFactory.cs new file mode 100644 index 0000000000..2380f0092d --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/DeletedItems/DeletedItemsQueryFactory.cs @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System.Collections.Concurrent; +using System.Linq; +using EdFi.Ods.Common.Models.Domain; +using EdFi.Ods.Common.Models.Resource; +using EdFi.Ods.Generator.Database.NamingConventions; +using SqlKata; + +namespace EdFi.Ods.Features.ChangeQueries.Repositories.DeletedItems +{ + public class DeletedItemsQueryFactory : IDeletedItemsQueryFactory + { + private readonly IDatabaseNamingConvention _namingConvention; + private readonly ITrackedChangesIdentifierProjectionsProvider _trackedChangesIdentifierProjectionsProvider; + + private const string SourceTableAlias = "src"; + + private readonly ConcurrentDictionary _queryByResourceName = new ConcurrentDictionary(); + + public DeletedItemsQueryFactory(IDatabaseNamingConvention namingConvention, ITrackedChangesIdentifierProjectionsProvider trackedChangesIdentifierProjectionsProvider) + { + _namingConvention = namingConvention; + _trackedChangesIdentifierProjectionsProvider = trackedChangesIdentifierProjectionsProvider; + } + + public Query CreateMainQuery(Resource resource) + { + // Optimize by caching the constructed query + var templateQuery = _queryByResourceName.GetOrAdd(resource.FullName, fn => CreateTemplateQuery(resource)); + + // Copy the query before returning it (to preserve original) + return templateQuery.Clone(); + } + + private Query CreateTemplateQuery(Resource resource) + { + var entity = resource.Entity; + + var identifierProjections = _trackedChangesIdentifierProjectionsProvider.GetIdentifierProjections(resource); + + var templateQuery = QueryFactoryHelper.CreateBaseTrackedChangesQuery(_namingConvention, entity) + .Select( + $"{ChangeQueriesDatabaseConstants.TrackedChangesAlias}.{_namingConvention.ColumnName("Id")}", + $"{ChangeQueriesDatabaseConstants.TrackedChangesAlias}.{_namingConvention.ColumnName(ChangeQueriesDatabaseConstants.ChangeVersionColumnName)}") + .Select(QueryFactoryHelper.IdentifyingColumns(identifierProjections, columnGroups: ColumnGroups.OldValue)) + .OrderBy($"{ChangeQueriesDatabaseConstants.TrackedChangesAlias}.{_namingConvention.ColumnName(ChangeQueriesDatabaseConstants.ChangeVersionColumnName)}"); + + QueryFactoryHelper.ApplyDiscriminatorCriteriaForDerivedEntities(templateQuery, entity, _namingConvention); + + // Deletes-specific query filters + ApplySourceTableExclusionForUndeletedItems(); + ApplyDeletesOnlyCriteria(); + + return templateQuery; + + void ApplySourceTableExclusionForUndeletedItems() + { + // Source table exclusion to prevent items that have been re-added during the same change window from showing up as deletes + templateQuery.LeftJoin( + $"{_namingConvention.Schema(entity)}.{_namingConvention.TableName(entity)} AS {SourceTableAlias}", + join => + { + foreach (var projection in identifierProjections) + { + @join.On( + $"{ChangeQueriesDatabaseConstants.TrackedChangesAlias}.{projection.ChangeTableJoinColumnName}", + $"{SourceTableAlias}.{projection.SourceTableJoinColumnName}"); + } + + return @join; + }); + + templateQuery.WhereNull(string.Concat(SourceTableAlias, ".", identifierProjections.First().SourceTableJoinColumnName)); + } + + void ApplyDeletesOnlyCriteria() + { + // Only return deletes + var firstIdentifierProperty = (entity.IsDerived + ? entity.BaseEntity + : entity).Identifier.Properties.First(); + + string columnName = _namingConvention.ColumnName( + $"{ChangeQueriesDatabaseConstants.NewKeyValueColumnPrefix}{firstIdentifierProperty.PropertyName}"); + + templateQuery.WhereNull($"{ChangeQueriesDatabaseConstants.TrackedChangesAlias}.{columnName}"); + } + } + } +} diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/DeletedItems/DeletedItemsResourceDataProvider.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/DeletedItems/DeletedItemsResourceDataProvider.cs new file mode 100644 index 0000000000..7f1c33ef4e --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/DeletedItems/DeletedItemsResourceDataProvider.cs @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System; +using System.Data.Common; +using System.Threading.Tasks; +using EdFi.Ods.Common; +using EdFi.Ods.Common.Database; +using EdFi.Ods.Common.Models.Resource; +using EdFi.Ods.Features.ChangeQueries.Resources; +using EdFi.Ods.Generator.Database.NamingConventions; + +namespace EdFi.Ods.Features.ChangeQueries.Repositories.DeletedItems +{ + public class DeletedItemsResourceDataProvider + : TrackedChangesResourceDataProviderBase, IDeletedItemsResourceDataProvider + { + private readonly IDeletedItemsQueryFactory _deletedItemsQueryFactory; + private readonly IDatabaseNamingConvention _namingConvention; + private readonly ITrackedChangesIdentifierProjectionsProvider _trackedChangesIdentifierProjectionsProvider; + + public DeletedItemsResourceDataProvider( + DbProviderFactory dbProviderFactory, + IOdsDatabaseConnectionStringProvider odsDatabaseConnectionStringProvider, + IDeletedItemsQueriesPreparer deletedItemsQueriesPreparer, + IDeletedItemsQueryFactory deletedItemsQueryFactory, + IDatabaseNamingConvention namingConvention, + ITrackedChangesIdentifierProjectionsProvider trackedChangesIdentifierProjectionsProvider) + : base(dbProviderFactory, odsDatabaseConnectionStringProvider, deletedItemsQueriesPreparer, namingConvention) + { + _deletedItemsQueryFactory = deletedItemsQueryFactory; + _namingConvention = namingConvention; + _trackedChangesIdentifierProjectionsProvider = trackedChangesIdentifierProjectionsProvider; + } + + public async Task> GetResourceDataAsync(Resource resource, IQueryParameters queryParameters) + { + var templateQuery = _deletedItemsQueryFactory.CreateMainQuery(resource); + var identifierProjections = _trackedChangesIdentifierProjectionsProvider.GetIdentifierProjections(resource); + + string changeVersionColumnName = _namingConvention.ColumnName(ChangeQueriesDatabaseConstants.ChangeVersionColumnName); + string idColumnName = _namingConvention.ColumnName("Id"); + + return await base.GetResourceDataAsync( + resource, + queryParameters, + templateQuery, + itemData => + new DeletedResourceItem + { + Id = (Guid) itemData[idColumnName], + ChangeVersion = (long) itemData[changeVersionColumnName], + KeyValues = GetIdentifierKeyValues(identifierProjections, itemData, ColumnGroups.OldValue), + }); + } + } +} diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/DeletedItems/IDeletedItemsQueriesPreparer.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/DeletedItems/IDeletedItemsQueriesPreparer.cs new file mode 100644 index 0000000000..7b90c32ef2 --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/DeletedItems/IDeletedItemsQueriesPreparer.cs @@ -0,0 +1,9 @@ +namespace EdFi.Ods.Features.ChangeQueries.Repositories.DeletedItems +{ + /// + /// Provides a marker interface for use in injecting the correct implementation of + /// into artifacts related to processing + /// deleted item requests. + /// + public interface IDeletedItemsQueriesPreparer : ITrackedChangesQueriesPreparer { } +} \ No newline at end of file diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/DeletedItems/IDeletedItemsQueryFactory.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/DeletedItems/IDeletedItemsQueryFactory.cs new file mode 100644 index 0000000000..7769d6c0a3 --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/DeletedItems/IDeletedItemsQueryFactory.cs @@ -0,0 +1,9 @@ +namespace EdFi.Ods.Features.ChangeQueries.Repositories.DeletedItems +{ + /// + /// Provides a marker interface for use in injecting the correct implementation of + /// into artifacts related to processing + /// deleted item requests. + /// + public interface IDeletedItemsQueryFactory : ITrackedChangesQueryFactory { } +} \ No newline at end of file diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/DeletedItems/IDeletedItemsResourceDataProvider.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/DeletedItems/IDeletedItemsResourceDataProvider.cs new file mode 100644 index 0000000000..9867a73c3a --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/DeletedItems/IDeletedItemsResourceDataProvider.cs @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System.Threading.Tasks; +using EdFi.Ods.Common; +using EdFi.Ods.Common.Models.Resource; +using EdFi.Ods.Features.ChangeQueries.Resources; + +namespace EdFi.Ods.Features.ChangeQueries.Repositories.DeletedItems +{ + /// + /// Defines a method for obtaining the data needed to provide a response to a deleted item API request. + /// + public interface IDeletedItemsResourceDataProvider + { + Task> GetResourceDataAsync(Resource resource, IQueryParameters queryParameters); + } +} diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/ITrackedChangesIdentifierProjectionsProvider.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/ITrackedChangesIdentifierProjectionsProvider.cs new file mode 100644 index 0000000000..c2586e8caa --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/ITrackedChangesIdentifierProjectionsProvider.cs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using EdFi.Ods.Common.Models.Resource; + +namespace EdFi.Ods.Features.ChangeQueries.Repositories +{ + public interface ITrackedChangesIdentifierProjectionsProvider + { + QueryProjection[] GetIdentifierProjections(Resource resource); + } +} diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/ITrackedChangesQueriesPreparer.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/ITrackedChangesQueriesPreparer.cs new file mode 100644 index 0000000000..d976f18c37 --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/ITrackedChangesQueriesPreparer.cs @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System.Data.Common; +using EdFi.Ods.Common; +using EdFi.Ods.Common.Models.Resource; +using EdFi.Ods.Features.ChangeQueries.Repositories.DeletedItems; +using SqlKata; + +namespace EdFi.Ods.Features.ChangeQueries.Repositories +{ + /// + /// Defines a method for preparing the queries for a tracked changes request. + /// + public interface ITrackedChangesQueriesPreparer + { + TrackedChangesQueries PrepareQueries( + DbConnection connection, + Query mainQuery, + IQueryParameters queryParameters, + Resource resource); + } +} diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/ITrackedChangesQueryFactory.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/ITrackedChangesQueryFactory.cs new file mode 100644 index 0000000000..fd90def049 --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/ITrackedChangesQueryFactory.cs @@ -0,0 +1,16 @@ +using EdFi.Ods.Common.Models.Resource; +using SqlKata; + +namespace EdFi.Ods.Features.ChangeQueries.Repositories +{ + public interface ITrackedChangesQueryFactory + { + /// + /// Gets the query that determines basis for inclusion/exclusion of records in the query (and where authorization + /// filters should be applied). + /// + /// The resource that is the subject of the query. + /// The Query for further modification and execution. + Query CreateMainQuery(Resource resource); + } +} \ No newline at end of file diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/KeyChanges/IKeyChangesQueriesPreparer.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/KeyChanges/IKeyChangesQueriesPreparer.cs new file mode 100644 index 0000000000..3388ee11c9 --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/KeyChanges/IKeyChangesQueriesPreparer.cs @@ -0,0 +1,9 @@ +namespace EdFi.Ods.Features.ChangeQueries.Repositories.KeyChanges +{ + /// + /// Provides a marker interface for use in injecting the correct implementation of + /// into artifacts related to processing + /// key change requests. + /// + public interface IKeyChangesQueriesPreparer : ITrackedChangesQueriesPreparer { } +} \ No newline at end of file diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/KeyChanges/IKeyChangesQueryFactory.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/KeyChanges/IKeyChangesQueryFactory.cs new file mode 100644 index 0000000000..008e7e3137 --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/KeyChanges/IKeyChangesQueryFactory.cs @@ -0,0 +1,9 @@ +namespace EdFi.Ods.Features.ChangeQueries.Repositories.KeyChanges +{ + /// + /// Provides a marker interface for use in injecting the correct implementation of + /// into artifacts related to processing + /// key change requests. + /// + public interface IKeyChangesQueryFactory : ITrackedChangesQueryFactory { } +} \ No newline at end of file diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/KeyChanges/IKeyChangesResourceDataProvider.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/KeyChanges/IKeyChangesResourceDataProvider.cs new file mode 100644 index 0000000000..95a0713396 --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/KeyChanges/IKeyChangesResourceDataProvider.cs @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System.Threading.Tasks; +using EdFi.Ods.Common; +using EdFi.Ods.Common.Models.Resource; +using EdFi.Ods.Features.ChangeQueries.Resources; + +namespace EdFi.Ods.Features.ChangeQueries.Repositories.KeyChanges +{ + /// + /// Defines a method for obtaining the data needed to provide a response to a key changes API request. + /// + public interface IKeyChangesResourceDataProvider + { + Task> GetResourceDataAsync(Resource resource, IQueryParameters queryParameters); + } +} diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/KeyChanges/KeyChangesQueriesPreparer.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/KeyChanges/KeyChangesQueriesPreparer.cs new file mode 100644 index 0000000000..e5039ab395 --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/KeyChanges/KeyChangesQueriesPreparer.cs @@ -0,0 +1,101 @@ +using EdFi.Ods.Common; +using EdFi.Ods.Common.Configuration; +using EdFi.Ods.Common.Models.Resource; +using EdFi.Ods.Features.ChangeQueries.Repositories.DeletedItems; +using EdFi.Ods.Generator.Database.NamingConventions; +using log4net; +using SqlKata; +using SqlKata.Compilers; +using SqlKata.Execution; + +namespace EdFi.Ods.Features.ChangeQueries.Repositories.KeyChanges +{ + public class KeyChangesQueriesPreparer : TrackedChangesQueriesPreparerBase, IKeyChangesQueriesPreparer + { + private readonly ILog _logger = LogManager.GetLogger(typeof(DeletedItemsQueriesPreparer)); + + private readonly Compiler _sqlCompiler; + private readonly IDatabaseNamingConvention _namingConvention; + private readonly ITrackedChangesIdentifierProjectionsProvider _trackedChangesIdentifierProjectionsProvider; + + public KeyChangesQueriesPreparer( + Compiler sqlCompiler, + IDefaultPageSizeLimitProvider defaultPageSizeLimitProvider, IDatabaseNamingConvention namingConvention, + ITrackedChangesIdentifierProjectionsProvider trackedChangesIdentifierProjectionsProvider) + : base(sqlCompiler, defaultPageSizeLimitProvider, namingConvention) + { + _sqlCompiler = sqlCompiler; + _namingConvention = namingConvention; + _trackedChangesIdentifierProjectionsProvider = trackedChangesIdentifierProjectionsProvider; + } + + protected override Query PrepareDataQuery( + QueryFactory db, + Query mainQuery, + IQueryParameters queryParameters, + Resource resource) + { + // Apply the change version filtering to the main query (the CTE in this case) + ApplyChangeVersionCriteria(mainQuery, queryParameters); + + // Create the data query that uses the CTE (i.e. the "main" query provided) + var dataQuery = CreateDataQuery(mainQuery, resource); + + var preparedDataQuery = db.FromQuery(dataQuery); + + // Apply paging + ApplyPaging(preparedDataQuery, queryParameters); + + if (_logger.IsDebugEnabled) + { + var sqlResult = _sqlCompiler.Compile(preparedDataQuery); + _logger.Debug(sqlResult.Sql); + } + + return preparedDataQuery; + } + + private Query CreateDataQuery(Query changeWindowVersionsCteQuery, Resource resource) + { + var entity = resource.Entity; + + string idColumnName = _namingConvention.ColumnName("Id"); + string changeVersionColumnName = _namingConvention.ColumnName(ChangeQueriesDatabaseConstants.ChangeVersionColumnName); + + string changeQueriesTableName = + $"{ChangeQueriesDatabaseConstants.TrackedChangesSchemaPrefix}{_namingConvention.Schema(entity)}.{_namingConvention.TableName(entity)}"; + + string oldAlias = + $"{_namingConvention.IdentifierName(ChangeQueriesDatabaseConstants.TrackedChangesAlias, suffix: "_old")}"; + + string newAlias = + $"{_namingConvention.IdentifierName(ChangeQueriesDatabaseConstants.TrackedChangesAlias, suffix: "_new")}"; + + string changeWindowCteName = _namingConvention.IdentifierName("ChangeWindow"); + const string ChangeWindowAlias = "cw"; + + string initialChangeVersionColumnName = _namingConvention.ColumnName("InitialChangeVersion"); + string finalChangeVersionColumnName = _namingConvention.ColumnName("FinalChangeVersion"); + + var identifierProjections = _trackedChangesIdentifierProjectionsProvider.GetIdentifierProjections(resource); + + var dataQuery = new Query($"{changeWindowCteName} AS {ChangeWindowAlias}") + .With(changeWindowCteName, changeWindowVersionsCteQuery) + .Join( + $"{changeQueriesTableName} AS {oldAlias}", + j => j.On($"{ChangeWindowAlias}.{idColumnName}", $"{oldAlias}.{idColumnName}") + .On($"{ChangeWindowAlias}.{initialChangeVersionColumnName}", $"{oldAlias}.{changeVersionColumnName}")) + .Join( + $"{changeQueriesTableName} AS {newAlias}", + j => j.On($"{ChangeWindowAlias}.{idColumnName}", $"{newAlias}.{idColumnName}") + .On($"{ChangeWindowAlias}.{finalChangeVersionColumnName}", $"{newAlias}.{changeVersionColumnName}")) + .Select( + $"{ChangeWindowAlias}.{idColumnName}", + $"{ChangeWindowAlias}.{finalChangeVersionColumnName} AS {changeVersionColumnName}") + .Select(QueryFactoryHelper.IdentifyingColumns(identifierProjections, oldAlias, newAlias)) + .OrderBy($"{ChangeWindowAlias}.{finalChangeVersionColumnName}"); + + return dataQuery; + } + } +} \ No newline at end of file diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/KeyChanges/KeyChangesQueryFactory.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/KeyChanges/KeyChangesQueryFactory.cs new file mode 100644 index 0000000000..4db2762cd0 --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/KeyChanges/KeyChangesQueryFactory.cs @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System.Collections.Concurrent; +using System.Linq; +using EdFi.Ods.Common.Models.Domain; +using EdFi.Ods.Common.Models.Resource; +using EdFi.Ods.Generator.Database.NamingConventions; +using SqlKata; + +namespace EdFi.Ods.Features.ChangeQueries.Repositories.KeyChanges +{ + public class KeyChangesQueryFactory : IKeyChangesQueryFactory + { + private readonly IDatabaseNamingConvention _namingConvention; + + private readonly ConcurrentDictionary _templateQueryByResourceName = new ConcurrentDictionary(); + + public KeyChangesQueryFactory(IDatabaseNamingConvention namingConvention) + { + _namingConvention = namingConvention; + } + + public Query CreateMainQuery(Resource resource) + { + // Optimize by caching the constructed query + var templateQuery = _templateQueryByResourceName.GetOrAdd(resource.FullName, fn => CreateTemplateQuery(resource)); + + // Copy the query before returning it (to preserve original) + return templateQuery.Clone(); + } + + private Query CreateTemplateQuery(Resource resource) + { + /* + var changeWindow = new Query("tracked_changes_edfi.studentschoolassociation AS c") + .Select("c.id") + .SelectRaw("MIN(c.ChangeVersion) as initialchangeversion") + .SelectRaw("MAX(c.ChangeVersion) as finalchangeversion") + .GroupBy("c.id"); + + var query = new Query("changewindow as cw") + .With("changewindow", changeWindow) + .Join("tracked_changes_edfi.studentschoolassociation as c_old", + j => j.On("cw.id", "c_old.id") + .On("cw.initialchangeversion", "c_old.changeversion")) + .Join("tracked_changes_edfi.studentschoolassociation as c_new", + j => j.On("cw.id", "c_new.id") + .On("cw.finalchangeversion", "c_new.changeversion")) + .Select("cw.id", "cw.finalchangeversion as changeversion", + "c_old.oldentrydate AS oldentrydate", "c_new.newentrydate AS newentrydate", + "c_old.oldschoolid AS oldschoolid", "c_new.newschoolid AS newschoolid", + "c_old.oldstudentuniqueid AS oldstudentuniqueid", "c_new.newstudentuniqueid AS newstudentuniqueid" + ) + .OrderBy("cw.finalchangeversion") + .Skip(0) + .Limit(25) + */ + + // Derive column names + string idColumnFqn = $"{ChangeQueriesDatabaseConstants.TrackedChangesAlias}.{_namingConvention.ColumnName("Id")}"; + var changeVersionColumnFqn = $"{ChangeQueriesDatabaseConstants.TrackedChangesAlias}.{_namingConvention.ColumnName(ChangeQueriesDatabaseConstants.ChangeVersionColumnName)}"; + string initialChangeVersionColumnName = _namingConvention.ColumnName("InitialChangeVersion"); + string finalChangeVersionColumnName = _namingConvention.ColumnName("FinalChangeVersion"); + + var entity = resource.Entity; + + // Build the CTE query + var changeWindowVersionsCteQuery = QueryFactoryHelper.CreateBaseTrackedChangesQuery(_namingConvention, entity) + .Select(idColumnFqn) + .SelectRaw( $"MIN({changeVersionColumnFqn}) AS {initialChangeVersionColumnName}") + .SelectRaw( $"MAX({changeVersionColumnFqn}) AS {finalChangeVersionColumnName}") + .GroupBy(idColumnFqn); + + QueryFactoryHelper.ApplyDiscriminatorCriteriaForDerivedEntities( + changeWindowVersionsCteQuery, + entity, + _namingConvention); + + // Apply criteria for only including key changes + var firstIdentifierProperty = (entity.IsDerived ? entity.BaseEntity : entity) + .Identifier.Properties.First(); + + string columnName = _namingConvention.ColumnName( + $"{ChangeQueriesDatabaseConstants.NewKeyValueColumnPrefix}{firstIdentifierProperty.PropertyName}"); + + changeWindowVersionsCteQuery.WhereNotNull($"{ChangeQueriesDatabaseConstants.TrackedChangesAlias}.{columnName}"); + + return changeWindowVersionsCteQuery; + } + } +} diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/KeyChanges/KeyChangesResourceDataProvider.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/KeyChanges/KeyChangesResourceDataProvider.cs new file mode 100644 index 0000000000..0b71c30af2 --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/KeyChanges/KeyChangesResourceDataProvider.cs @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System; +using System.Data.Common; +using System.Threading.Tasks; +using EdFi.Ods.Common; +using EdFi.Ods.Common.Database; +using EdFi.Ods.Common.Models.Resource; +using EdFi.Ods.Features.ChangeQueries.Resources; +using EdFi.Ods.Generator.Database.NamingConventions; + +namespace EdFi.Ods.Features.ChangeQueries.Repositories.KeyChanges +{ + public class KeyChangesResourceDataProvider + : TrackedChangesResourceDataProviderBase, IKeyChangesResourceDataProvider + { + private readonly IDatabaseNamingConvention _namingConvention; + private readonly IKeyChangesQueryFactory _keyChangesQueryFactory; + private readonly ITrackedChangesIdentifierProjectionsProvider _trackedChangesIdentifierProjectionsProvider; + + public KeyChangesResourceDataProvider( + DbProviderFactory dbProviderFactory, + IOdsDatabaseConnectionStringProvider odsDatabaseConnectionStringProvider, + IKeyChangesQueriesPreparer keyChangesQueriesPreparer, + IDatabaseNamingConvention namingConvention, + IKeyChangesQueryFactory keyChangesQueryFactory, + ITrackedChangesIdentifierProjectionsProvider trackedChangesIdentifierProjectionsProvider) + : base(dbProviderFactory, odsDatabaseConnectionStringProvider, keyChangesQueriesPreparer, namingConvention) + { + _namingConvention = namingConvention; + _keyChangesQueryFactory = keyChangesQueryFactory; + _trackedChangesIdentifierProjectionsProvider = trackedChangesIdentifierProjectionsProvider; + } + + public async Task> GetResourceDataAsync(Resource resource, IQueryParameters queryParameters) + { + var changeWindowCteQuery = _keyChangesQueryFactory.CreateMainQuery(resource); + var identifierProjections = _trackedChangesIdentifierProjectionsProvider.GetIdentifierProjections(resource); + + string changeVersionColumnName = _namingConvention.ColumnName(ChangeQueriesDatabaseConstants.ChangeVersionColumnName); + string idColumnName = _namingConvention.ColumnName("Id"); + + return await base.GetResourceDataAsync( + resource, + queryParameters, + changeWindowCteQuery, + itemData => + new KeyChange + { + Id = (Guid)itemData[idColumnName], + ChangeVersion = (long) itemData[changeVersionColumnName], + OldKeyValues = GetIdentifierKeyValues(identifierProjections, itemData, ColumnGroups.OldValue), + NewKeyValues = GetIdentifierKeyValues(identifierProjections, itemData, ColumnGroups.NewValue), + }); + } + } +} diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/QueryFactoryHelper.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/QueryFactoryHelper.cs new file mode 100644 index 0000000000..8505499c3e --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/QueryFactoryHelper.cs @@ -0,0 +1,51 @@ +using System.Linq; +using EdFi.Ods.Common.Models.Domain; +using EdFi.Ods.Generator.Database.NamingConventions; +using SqlKata; +using static EdFi.Ods.Features.ChangeQueries.ChangeQueriesDatabaseConstants; + +namespace EdFi.Ods.Features.ChangeQueries.Repositories +{ + public static class QueryFactoryHelper + { + public static void ApplyDiscriminatorCriteriaForDerivedEntities( + Query query, + Entity entity, + IDatabaseNamingConvention namingConvention) + { + // Add discriminator criteria, for derived types with a Discriminator on the base type only + if (entity.IsDerived) + { + query.Where($"{TrackedChangesAlias}.{namingConvention.ColumnName("Discriminator")}", entity.FullName.ToString()); + } + } + + public static string[] IdentifyingColumns( + QueryProjection[] identifierProjections, + string oldColumnAlias = TrackedChangesAlias, + string newColumnAlias = TrackedChangesAlias, + ColumnGroups columnGroups = ColumnGroups.OldValue | ColumnGroups.NewValue) + { + string[] selectColumns = identifierProjections.SelectMany(x => x.SelectColumns) + .Where(sc => (sc.ColumnGroup & columnGroups) != 0) + .Select(sc => $"{(sc.ColumnGroup == ColumnGroups.OldValue ? oldColumnAlias : newColumnAlias)}.{sc.ColumnName}") + .ToArray(); + + return selectColumns; + } + + public static Query CreateBaseTrackedChangesQuery(IDatabaseNamingConvention namingConvention, Entity entity) + { + var (changeTableSchema, changeTableName) = entity.IsDerived + ? (TrackedChangesSchemaPrefix + namingConvention.Schema(entity.BaseEntity), + namingConvention.TableName(entity.BaseEntity)) + : (TrackedChangesSchemaPrefix + namingConvention.Schema(entity), + namingConvention.TableName(entity)); + + var templateQuery = + new Query($"{changeTableSchema}.{changeTableName} AS {TrackedChangesAlias}"); + + return templateQuery; + } + } +} \ No newline at end of file diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/QueryProjection.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/QueryProjection.cs new file mode 100644 index 0000000000..04cf0fd372 --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/QueryProjection.cs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System; + +namespace EdFi.Ods.Features.ChangeQueries.Repositories +{ + public class QueryProjection + { + public string JsonPropertyName { get; set; } + + public SelectColumn[] SelectColumns { get; set; } + + public string ChangeTableJoinColumnName { get; set; } + + public string SourceTableJoinColumnName { get; set; } + + public bool IsDescriptorUsage { get; set; } + } + + public class SelectColumn + { + public string ColumnName { get; set; } + + public string JsonPropertyName { get; set; } + + /// + /// Indicates whether the column represents an old or new value. + /// + public ColumnGroups ColumnGroup { get; set; } + } + + [Flags] + public enum ColumnGroups + { + OldValue = 1, + NewValue = 2, + } +} diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/ResourceData.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/ResourceData.cs new file mode 100644 index 0000000000..8dffbc872e --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/ResourceData.cs @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System.Collections.Generic; + +namespace EdFi.Ods.Features.ChangeQueries.Repositories +{ + public class ResourceData + { + public IReadOnlyList Items { get; set; } + public long? Count { get; set; } + } +} diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/GetSnapshots.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/Snapshots/GetSnapshots.cs similarity index 97% rename from Application/EdFi.Ods.Features/ChangeQueries/Repositories/GetSnapshots.cs rename to Application/EdFi.Ods.Features/ChangeQueries/Repositories/Snapshots/GetSnapshots.cs index 0093e8609d..51fdc7db3d 100644 --- a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/GetSnapshots.cs +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/Snapshots/GetSnapshots.cs @@ -14,7 +14,7 @@ using NHibernate; using NHibernate.Transform; -namespace EdFi.Ods.Features.ChangeQueries.Repositories +namespace EdFi.Ods.Features.ChangeQueries.Repositories.Snapshots { public class GetSnapshots : NHibernateRepositoryOperationBase, IGetSnapshots { diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/IGetSnapshots.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/Snapshots/IGetSnapshots.cs similarity index 90% rename from Application/EdFi.Ods.Features/ChangeQueries/Repositories/IGetSnapshots.cs rename to Application/EdFi.Ods.Features/ChangeQueries/Repositories/Snapshots/IGetSnapshots.cs index 964cb598c8..f37e0773bf 100644 --- a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/IGetSnapshots.cs +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/Snapshots/IGetSnapshots.cs @@ -9,7 +9,7 @@ using EdFi.Ods.Common; using EdFi.Ods.Features.ChangeQueries.Resources; -namespace EdFi.Ods.Features.ChangeQueries.Repositories +namespace EdFi.Ods.Features.ChangeQueries.Repositories.Snapshots { public interface IGetSnapshots { diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/TrackedChangesIdentifierProjectionsProvider.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/TrackedChangesIdentifierProjectionsProvider.cs new file mode 100644 index 0000000000..2ae3483f0f --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/TrackedChangesIdentifierProjectionsProvider.cs @@ -0,0 +1,178 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using EdFi.Common.Extensions; +using EdFi.Ods.Common.Models.Domain; +using EdFi.Ods.Common.Models.Resource; +using EdFi.Ods.Generator.Database.NamingConventions; + +namespace EdFi.Ods.Features.ChangeQueries.Repositories +{ + public class TrackedChangesIdentifierProjectionsProvider : ITrackedChangesIdentifierProjectionsProvider + { + private readonly IDatabaseNamingConvention _namingConvention; + + public TrackedChangesIdentifierProjectionsProvider(IDatabaseNamingConvention namingConvention) + { + _namingConvention = namingConvention; + } + + private readonly ConcurrentDictionary _queryProjectionsByResourceFullName = + new ConcurrentDictionary(); + + public QueryProjection[] GetIdentifierProjections(Resource resource) + { + return _queryProjectionsByResourceFullName.GetOrAdd(resource.FullName, + _ => CreateIdentifierProjections(resource)); + } + + private QueryProjection[] CreateIdentifierProjections(Resource resource) + { + var entity = resource.Entity; + + var projections = resource + .IdentifyingProperties + .Select( + rp => + { + var changeTableJoinProperty = (entity.IsDerived ? rp.EntityProperty.BaseProperty : rp.EntityProperty); + + return new QueryProjection + { + JsonPropertyName = rp.JsonPropertyName, + SelectColumns = GetSelectColumns(rp).ToArray(), + IsDescriptorUsage = rp.IsDescriptorUsage, + + // Columns for performing join to source table (if necessary) + ChangeTableJoinColumnName = _namingConvention.ColumnName($"{ChangeQueriesDatabaseConstants.OldKeyValueColumnPrefix}{changeTableJoinProperty.PropertyName}"), + SourceTableJoinColumnName = _namingConvention.ColumnName(rp.EntityProperty), + }; + }) + .ToArray(); + + return projections; + + IEnumerable GetSelectColumns(ResourceProperty resourceProperty) + { + var entityProperty = resourceProperty.EntityProperty; + + // This handles usages of DescriptorIds and USIs + if (entityProperty.IsSurrogateIdentifierUsage()) + { + string[] SplitTerms(string text) => Regex.Matches(text, "([A-Z][^A-Z]+|[A-Z]+(?![^A-Z]))").SelectMany(m => m.Captures.Select(c => c.Value)).ToArray(); + string[] TrimFinalTerm(string[] terms) => terms.Take(terms.Length - 1).ToArray(); + + var allTerms = SplitTerms(entityProperty.PropertyName); + var baseTerms = TrimFinalTerm(allTerms); + + // For Descriptors, this returns Namespace/CodeValue, for Student/Staff/Parent it returns the UniqueId + var naturalIdentifyingProperties = entityProperty.DefiningProperty.Entity.NaturalIdentifyingProperties(); + + foreach (var naturalIdentifyingProperty in naturalIdentifyingProperties) + { + var naturalTerms = SplitTerms(naturalIdentifyingProperty.PropertyName); + + var changeQueryColumnName = + string.Join(string.Empty, baseTerms.TakeWhile(t => t != naturalTerms[0]).Concat(naturalTerms)); + + yield return new SelectColumn + { + ColumnGroup = ColumnGroups.OldValue, + ColumnName = _namingConvention.ColumnName($"{ChangeQueriesDatabaseConstants.OldKeyValueColumnPrefix}{changeQueryColumnName}"), + JsonPropertyName = changeQueryColumnName.ToCamelCase(), + }; + + yield return new SelectColumn + { + ColumnGroup = ColumnGroups.NewValue, + ColumnName = _namingConvention.ColumnName($"{ChangeQueriesDatabaseConstants.NewKeyValueColumnPrefix}{changeQueryColumnName}"), + JsonPropertyName = changeQueryColumnName.ToCamelCase(), + }; + } + + yield break; + } + + // Handle identifying properties that are surrogate ids by performing column expansion to use the alternate identifier + // (e.g. Student/Staff/Parent USI -> UniqueId, concrete Descriptors -> Namespace, CodeValue) + if (entityProperty.IsSurrogateIdentifier()) + { + var naturalIdentifyingProperties = entityProperty.Entity.NaturalIdentifyingProperties(); + + foreach (var naturalIdentifyingProperty in naturalIdentifyingProperties) + { + yield return new SelectColumn + { + ColumnGroup = ColumnGroups.OldValue, + ColumnName = _namingConvention.ColumnName( + $"{ChangeQueriesDatabaseConstants.OldKeyValueColumnPrefix}{naturalIdentifyingProperty.PropertyName}"), + + JsonPropertyName = naturalIdentifyingProperty.PropertyName.ToCamelCase(), + }; + + yield return new SelectColumn + { + ColumnGroup = ColumnGroups.NewValue, + ColumnName = _namingConvention.ColumnName( + $"{ChangeQueriesDatabaseConstants.NewKeyValueColumnPrefix}{naturalIdentifyingProperty.PropertyName}"), + + JsonPropertyName = naturalIdentifyingProperty.PropertyName.ToCamelCase(), + }; + } + + yield break; + } + + if (IsDerivedFromEntityWithDiscriminator(entityProperty.Entity)) + { + yield return new SelectColumn + { + ColumnGroup = ColumnGroups.OldValue, + ColumnName = _namingConvention.ColumnName( + $"{ChangeQueriesDatabaseConstants.OldKeyValueColumnPrefix}{entityProperty.BaseProperty.PropertyName}"), + + JsonPropertyName = resourceProperty.JsonPropertyName, + }; + + yield return new SelectColumn + { + ColumnGroup = ColumnGroups.NewValue, + ColumnName = _namingConvention.ColumnName( + $"{ChangeQueriesDatabaseConstants.NewKeyValueColumnPrefix}{entityProperty.BaseProperty.PropertyName}"), + + JsonPropertyName = resourceProperty.JsonPropertyName, + }; + + yield break; + } + + // Just return the raw columns + yield return new SelectColumn + { + ColumnGroup = ColumnGroups.OldValue, + ColumnName = _namingConvention.ColumnName( + $"{ChangeQueriesDatabaseConstants.OldKeyValueColumnPrefix}{entityProperty.PropertyName}"), + + JsonPropertyName = resourceProperty.JsonPropertyName, + }; + + yield return new SelectColumn + { + ColumnGroup = ColumnGroups.NewValue, + ColumnName = _namingConvention.ColumnName( + $"{ChangeQueriesDatabaseConstants.NewKeyValueColumnPrefix}{entityProperty.PropertyName}"), + + JsonPropertyName = resourceProperty.JsonPropertyName, + }; + } + + bool IsDerivedFromEntityWithDiscriminator(Entity entity) => entity.BaseEntity?.HasDiscriminator() == true; + } + } +} diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/TrackedChangesQueries.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/TrackedChangesQueries.cs new file mode 100644 index 0000000000..d5a4050ee7 --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/TrackedChangesQueries.cs @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using SqlKata; + +namespace EdFi.Ods.Features.ChangeQueries.Repositories.DeletedItems +{ + public class TrackedChangesQueries + { + public TrackedChangesQueries(Query mainQuery, Query countQuery) + { + MainQuery = mainQuery; + CountQuery = countQuery; + } + + /// + /// Gets the main driving query for the results (i.e. a query that should be filtered for authorization purposes). + /// + public Query MainQuery { get; } + + /// + /// Gets the count query for the results (i.e. a query that should be filtered for authorization purposes). + /// + public Query CountQuery { get; } + } +} diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/TrackedChangesQueriesPreparercs.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/TrackedChangesQueriesPreparercs.cs new file mode 100644 index 0000000000..2eb5842254 --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/TrackedChangesQueriesPreparercs.cs @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System; +using System.Data.Common; +using EdFi.Ods.Common; +using EdFi.Ods.Common.Configuration; +using EdFi.Ods.Common.Models.Resource; +using EdFi.Ods.Features.ChangeQueries.Repositories.DeletedItems; +using EdFi.Ods.Generator.Database.NamingConventions; +using log4net; +using SqlKata; +using SqlKata.Compilers; +using SqlKata.Execution; + +namespace EdFi.Ods.Features.ChangeQueries.Repositories +{ + public abstract class TrackedChangesQueriesPreparerBase : ITrackedChangesQueriesPreparer + { + private readonly ILog _logger = LogManager.GetLogger(typeof(TrackedChangesQueriesPreparerBase)); + + private readonly Compiler _sqlCompiler; + private readonly IDefaultPageSizeLimitProvider _defaultPageSizeLimitProvider; + private readonly IDatabaseNamingConvention _namingConvention; + + protected TrackedChangesQueriesPreparerBase( + Compiler sqlCompiler, + IDefaultPageSizeLimitProvider defaultPageSizeLimitProvider, + IDatabaseNamingConvention namingConvention) + { + _sqlCompiler = sqlCompiler; + _defaultPageSizeLimitProvider = defaultPageSizeLimitProvider; + _namingConvention = namingConvention; + } + + public TrackedChangesQueries PrepareQueries( + DbConnection connection, + Query mainQuery, + IQueryParameters queryParameters, + Resource resource) + { + var db = new QueryFactory(connection, _sqlCompiler); + + if (_logger.IsDebugEnabled) + { + db.Logger = compiled => { _logger.Debug(compiled.ToString()); }; + } + + // Prepare the queries + var queries = new TrackedChangesQueries( + PrepareDataQuery(db, mainQuery, queryParameters, resource), + PrepareCountQuery(db, mainQuery, queryParameters)); + + return queries; + } + + protected abstract Query PrepareDataQuery( + QueryFactory db, + Query mainQuery, + IQueryParameters queryParameters, + Resource resource); + + protected virtual Query PrepareCountQuery(QueryFactory db, Query mainQuery, IQueryParameters queryParameters) + { + if (queryParameters.TotalCount) + { + var countQuery = db.FromQuery(mainQuery); + ApplyChangeVersionCriteria(countQuery, queryParameters); + + return countQuery; + } + + return null; + } + + protected void ApplyPaging(Query query, IQueryParameters queryParameters) + { + query.Offset(queryParameters.Offset ?? 0); + query.Limit(Math.Min(queryParameters.Limit ?? 25, _defaultPageSizeLimitProvider.GetDefaultPageSizeLimit())); + } + + protected void ApplyChangeVersionCriteria(Query query, IQueryParameters queryParameters) + { + if (queryParameters.MinChangeVersion.HasValue || queryParameters.MaxChangeVersion.HasValue) + { + query.Where( + q => q.Where( + q2 => + { + if (queryParameters.MinChangeVersion.HasValue) + { + q2.Where( + $"{ChangeQueriesDatabaseConstants.TrackedChangesAlias}.{_namingConvention.ColumnName(ChangeQueriesDatabaseConstants.ChangeVersionColumnName)}", + ">=", + new Variable("@MinChangeVersion")); + } + + if (queryParameters.MaxChangeVersion.HasValue) + { + q2.Where( + $"{ChangeQueriesDatabaseConstants.TrackedChangesAlias}.{_namingConvention.ColumnName(ChangeQueriesDatabaseConstants.ChangeVersionColumnName)}", + "<=", + new Variable("@MaxChangeVersion")); + } + + return q2; + }) + .OrWhereNull($"{ChangeQueriesDatabaseConstants.TrackedChangesAlias}.{_namingConvention.ColumnName(ChangeQueriesDatabaseConstants.ChangeVersionColumnName)}")); + } + + if (queryParameters.MinChangeVersion.HasValue) + { + query.Variables["@MinChangeVersion"] = queryParameters.MinChangeVersion; + } + + if (queryParameters.MinChangeVersion.HasValue) + { + query.Variables["@MaxChangeVersion"] = queryParameters.MaxChangeVersion; + } + } + } +} diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Repositories/TrackedChangesResourceDataProviderBase.cs b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/TrackedChangesResourceDataProviderBase.cs new file mode 100644 index 0000000000..473aa38fdf --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Repositories/TrackedChangesResourceDataProviderBase.cs @@ -0,0 +1,122 @@ +using System; +using System.Collections.Generic; +using System.Data.Common; +using System.Linq; +using System.Threading.Tasks; +using EdFi.Common.Extensions; +using EdFi.Ods.Common; +using EdFi.Ods.Common.Database; +using EdFi.Ods.Common.Models.Resource; +using EdFi.Ods.Generator.Database.NamingConventions; +using SqlKata; +using SqlKata.Execution; + +namespace EdFi.Ods.Features.ChangeQueries.Repositories +{ + public abstract class TrackedChangesResourceDataProviderBase + { + private readonly DbProviderFactory _dbProviderFactory; + private readonly IOdsDatabaseConnectionStringProvider _odsDatabaseConnectionStringProvider; + private readonly ITrackedChangesQueriesPreparer _deletedItemsQueriesPreparer; + private readonly IDatabaseNamingConvention _namingConvention; + + protected TrackedChangesResourceDataProviderBase( + DbProviderFactory dbProviderFactory, + IOdsDatabaseConnectionStringProvider odsDatabaseConnectionStringProvider, + ITrackedChangesQueriesPreparer deletedItemsQueriesPreparer, + IDatabaseNamingConvention namingConvention) + { + _dbProviderFactory = dbProviderFactory; + _odsDatabaseConnectionStringProvider = odsDatabaseConnectionStringProvider; + _deletedItemsQueriesPreparer = deletedItemsQueriesPreparer; + _namingConvention = namingConvention; + } + + protected async Task> GetResourceDataAsync(Resource resource, IQueryParameters queryParameters, + Query templateQuery, Func, TItem> createItem) + { + await using var conn = _dbProviderFactory.CreateConnection(); + + conn.ConnectionString = _odsDatabaseConnectionStringProvider.GetConnectionString(); + await conn.OpenAsync(); + + var queries = _deletedItemsQueriesPreparer.PrepareQueries(conn, templateQuery, queryParameters, resource); + + var responseData = new ResourceData() + { + Items = await GetDataAsync(queries.MainQuery), + Count = await GetCountAsync(queries.CountQuery), + }; + + return responseData; + + async Task> GetDataAsync(Query dataQuery) + { + if (dataQuery != null) + { + // Execute query, casting to strong type to avoid use of dynamic + var rawData = (List) await dataQuery.GetAsync(); + + var items = rawData + .Cast>() + .Select(createItem) + .ToList(); + + return items; + } + + return null; + } + + async Task GetCountAsync(Query countQuery) + { + if (queryParameters.TotalCount) + { + var count = await countQuery.CountAsync(); + return Convert.ToInt64(count); + } + + return null; + } + } + + protected Dictionary GetIdentifierKeyValues( + QueryProjection[] identifierProjections, + IDictionary itemData, + ColumnGroups columnGroup) + { + var keyValues = new Dictionary(); + + foreach (var identifierMetadata in identifierProjections) + { + if (identifierMetadata.IsDescriptorUsage) + { + string namespaceColumn = identifierMetadata.SelectColumns.Where(c => c.ColumnGroup == columnGroup).FirstOrDefault(c => c.ColumnName.EndsWithIgnoreCase("Namespace"))?.ColumnName; + string codeValueColumn = identifierMetadata.SelectColumns.Where(c => c.ColumnGroup == columnGroup).FirstOrDefault(c => c.ColumnName.EndsWithIgnoreCase("CodeValue"))?.ColumnName; + + if (namespaceColumn == null) + { + throw new Exception("Unable to find Namespace column in deleted item query results for building a descriptor URI."); + } + + if (codeValueColumn == null) + { + throw new Exception("Unable to find CodeValue column in deleted item query results for building a descriptor URI."); + } + + keyValues[identifierMetadata.JsonPropertyName] = + $"{itemData[namespaceColumn]}#{itemData[codeValueColumn]}"; + } + else + { + foreach (var selectColumn in identifierMetadata.SelectColumns.Where(c => c.ColumnGroup == columnGroup)) + { + keyValues[selectColumn.JsonPropertyName] = itemData[selectColumn.ColumnName]; + } + } + } + + return keyValues; + } + } +} \ No newline at end of file diff --git a/Application/EdFi.Ods.Common/Models/DeletedResource.cs b/Application/EdFi.Ods.Features/ChangeQueries/Resources/DeletedResourceItem.cs similarity index 53% rename from Application/EdFi.Ods.Common/Models/DeletedResource.cs rename to Application/EdFi.Ods.Features/ChangeQueries/Resources/DeletedResourceItem.cs index c877ff7a4e..5faef759e6 100644 --- a/Application/EdFi.Ods.Common/Models/DeletedResource.cs +++ b/Application/EdFi.Ods.Features/ChangeQueries/Resources/DeletedResourceItem.cs @@ -1,19 +1,26 @@ -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // Licensed to the Ed-Fi Alliance under one or more agreements. // The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. // See the LICENSE and NOTICES files in the project root for more information. using System; +using System.Collections.Generic; using System.Runtime.Serialization; +using EdFi.Ods.Common; +using Newtonsoft.Json; -namespace EdFi.Ods.Common.Models +namespace EdFi.Ods.Features.ChangeQueries.Resources { - public class DeletedResource + [DataContract] + public class DeletedResourceItem { [DataMember(Name="id")] + [JsonConverter(typeof(GuidConverter))] public Guid Id { get; set; } [DataMember(Name="changeVersion")] public long ChangeVersion { get; set; } - } -} + + [DataMember(Name="keyValues")] + public IDictionary KeyValues { get; set; } + }} diff --git a/Application/EdFi.Ods.Features/ChangeQueries/Resources/KeyChange.cs b/Application/EdFi.Ods.Features/ChangeQueries/Resources/KeyChange.cs new file mode 100644 index 0000000000..cce1335e41 --- /dev/null +++ b/Application/EdFi.Ods.Features/ChangeQueries/Resources/KeyChange.cs @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; +using EdFi.Ods.Common; +using Newtonsoft.Json; + +namespace EdFi.Ods.Features.ChangeQueries.Resources +{ + [DataContract] + public class KeyChange + { + [DataMember(Name="id")] + [JsonConverter(typeof(GuidConverter))] + public Guid Id { get; set; } + + [DataMember(Name="changeVersion")] + public long ChangeVersion { get; set; } + + [DataMember(Name="oldKeyValues")] + public IDictionary OldKeyValues { get; set; } + + [DataMember(Name="newKeyValues")] + public IDictionary NewKeyValues { get; set; } + } +} diff --git a/Application/EdFi.Ods.Features/Composites/CompositeResourceModelBuilder.cs b/Application/EdFi.Ods.Features/Composites/CompositeResourceModelBuilder.cs index e79581d257..e7b8de3775 100644 --- a/Application/EdFi.Ods.Features/Composites/CompositeResourceModelBuilder.cs +++ b/Application/EdFi.Ods.Features/Composites/CompositeResourceModelBuilder.cs @@ -115,14 +115,14 @@ public void ProjectProperties( property.DisplayName ?? property.ResourceProperty.PropertyName, property.ResourceProperty.PropertyType, new PropertyCharacteristics( - entityProperty.IsLookup, - entityProperty.IsDirectLookup, + entityProperty.IsDescriptorUsage, + entityProperty.IsDirectDescriptorUsage, entityProperty.IsIdentifying, true, // All projected properties are "local" properties on the new object entityProperty.IsServerAssigned, - entityProperty.LookupEntity == null + entityProperty.DescriptorEntity == null ? null as FullName? - : entityProperty.LookupEntity.FullName), + : entityProperty.DescriptorEntity.FullName), property.ResourceProperty.Description)); } else diff --git a/Application/EdFi.Ods.Features/Composites/Infrastructure/HqlBuilder.cs b/Application/EdFi.Ods.Features/Composites/Infrastructure/HqlBuilder.cs index 323c51ab52..6da778671b 100644 --- a/Application/EdFi.Ods.Features/Composites/Infrastructure/HqlBuilder.cs +++ b/Application/EdFi.Ods.Features/Composites/Infrastructure/HqlBuilder.cs @@ -285,7 +285,7 @@ public void ApplyChildResource( // Set the parameter values builderContext.CurrentQueryFilterParameterValueByName[parameterName] = valueFilter.Values - .Select(x => _descriptorsCache.GetId(filterProperty.LookupTypeName, x)) + .Select(x => _descriptorsCache.GetId(filterProperty.DescriptorName, x)) .ToArray(); } else @@ -295,7 +295,7 @@ public void ApplyChildResource( = (parametersAsObject as int[]) .Concat( valueFilter.Values - .Select(x => _descriptorsCache.GetId(filterProperty.LookupTypeName, x)) + .Select(x => _descriptorsCache.GetId(filterProperty.DescriptorName, x)) ) .ToArray(); } @@ -533,7 +533,7 @@ public void ProjectProperties( { builderContext.PropertyProjections.Add(p); - if (p.ResourceProperty.EntityProperty.IsLookup) + if (p.ResourceProperty.EntityProperty.IsDescriptorUsage) { string lookupAlias = builderContext.AliasGenerator.GetNextAlias(); @@ -792,10 +792,10 @@ private void ProcessQueryStringParameters(HqlBuilderContext builderContext, Comp string personType; // Handle Lookup conversions - if (targetProperty.IsLookup) + if (targetProperty.IsDescriptorUsage) { var id = _descriptorsCache.GetId( - targetProperty.LookupTypeName, + targetProperty.DescriptorName, Convert.ToString(queryStringParameter.Value)); criteriaPropertyName = targetProperty.EntityProperty.PropertyName; diff --git a/Application/EdFi.Ods.Features/Controllers/DeletesController.cs b/Application/EdFi.Ods.Features/Controllers/DeletesController.cs deleted file mode 100644 index 5073361382..0000000000 --- a/Application/EdFi.Ods.Features/Controllers/DeletesController.cs +++ /dev/null @@ -1,56 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// Licensed to the Ed-Fi Alliance under one or more agreements. -// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. -// See the LICENSE and NOTICES files in the project root for more information. - -using System.Net.Mime; -using EdFi.Ods.Api.Infrastructure.Pipelines; -using EdFi.Ods.Common.Configuration; -using EdFi.Ods.Common.Constants; -using EdFi.Ods.Common.Models.Queries; -using log4net; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Newtonsoft.Json; - -namespace EdFi.Ods.Features.Controllers -{ - [Authorize] - [ApiController] - [Produces("application/json")] - [Route("{schema}/{resource}/deletes")] - public class DeletesController : ControllerBase - { - private readonly IGetDeletedResourceIds _getDeletedResourceIdsRepository; - private readonly ILog _logger = LogManager.GetLogger(typeof(DeletesController)); - private readonly bool _isEnabled; - - public DeletesController(IGetDeletedResourceIds getDeletedResourceIds, ApiSettings apiSettings) - { - _getDeletedResourceIdsRepository = getDeletedResourceIds; - _isEnabled = apiSettings.IsFeatureEnabled(ApiFeature.ChangeQueries.GetConfigKeyName()); - } - - [HttpGet] - public IActionResult Get(string schema, string resource, [FromQuery] UrlQueryParametersRequest urlQueryParametersRequest) - { - if (!_isEnabled) - { - _logger.Debug("ChangeQueries is not enabled."); - return NotFound(); - } - var queryParameter = new QueryParameters(urlQueryParametersRequest); - - var result = _getDeletedResourceIdsRepository.Execute(schema, resource, queryParameter); - - // Explicitly serialize the response to remain backwards compatible with pre .net core - return new ContentResult - { - Content = JsonConvert.SerializeObject(result), - ContentType = MediaTypeNames.Application.Json, - StatusCode = StatusCodes.Status200OK - }; - } - } -} \ No newline at end of file diff --git a/Application/EdFi.Ods.Features/EdFi.Ods.Features.csproj b/Application/EdFi.Ods.Features/EdFi.Ods.Features.csproj index c9f6d031bb..361d4893e4 100644 --- a/Application/EdFi.Ods.Features/EdFi.Ods.Features.csproj +++ b/Application/EdFi.Ods.Features/EdFi.Ods.Features.csproj @@ -18,6 +18,8 @@ + + @@ -33,6 +35,8 @@ + + diff --git a/Application/EdFi.Ods.Features/OpenApiMetadata/Factories/OpenApiMetadataDocumentHelper.cs b/Application/EdFi.Ods.Features/OpenApiMetadata/Factories/OpenApiMetadataDocumentHelper.cs index e2bea993dd..76c8efab20 100644 --- a/Application/EdFi.Ods.Features/OpenApiMetadata/Factories/OpenApiMetadataDocumentHelper.cs +++ b/Application/EdFi.Ods.Features/OpenApiMetadata/Factories/OpenApiMetadataDocumentHelper.cs @@ -52,7 +52,7 @@ public static string CamelCaseSegments(string value) => string.Join( value.Split('_') .Select(segment => segment.ToCamelCase())); - public static string PropertyType(ResourceProperty resourceProperty) => resourceProperty.IsLookup + public static string PropertyType(ResourceProperty resourceProperty) => resourceProperty.IsDescriptorUsage || UniqueIdSpecification.IsUniqueId(resourceProperty.JsonPropertyName) ? "string" : resourceProperty.PropertyType.ToOpenApiType(); diff --git a/Application/EdFi.Ods.Features/OpenApiMetadata/Strategies/FactoryStrategies/OpenApiMetadataCompositePathsFactoryStrategy.cs b/Application/EdFi.Ods.Features/OpenApiMetadata/Strategies/FactoryStrategies/OpenApiMetadataCompositePathsFactoryStrategy.cs index 3cba2c6c70..9836d4b2a4 100644 --- a/Application/EdFi.Ods.Features/OpenApiMetadata/Strategies/FactoryStrategies/OpenApiMetadataCompositePathsFactoryStrategy.cs +++ b/Application/EdFi.Ods.Features/OpenApiMetadata/Strategies/FactoryStrategies/OpenApiMetadataCompositePathsFactoryStrategy.cs @@ -193,12 +193,12 @@ private ResourceProperty CreateResourcePropertyForQueryStringParameter( fullModelResourceProperty.PropertyName.ToCamelCase(), fullModelResourceProperty.PropertyType, new PropertyCharacteristics( - entityProperty.IsLookup, - entityProperty.IsDirectLookup, + entityProperty.IsDescriptorUsage, + entityProperty.IsDirectDescriptorUsage, entityProperty.IsIdentifying, true, entityProperty.IsServerAssigned, - entityProperty.LookupEntity?.FullName), + entityProperty.DescriptorEntity?.FullName), fullModelResourceProperty.Description); } diff --git a/Application/EdFi.Ods.Sandbox/EdFi.Ods.Sandbox.csproj b/Application/EdFi.Ods.Sandbox/EdFi.Ods.Sandbox.csproj index a84a331bc9..dbe3046441 100644 --- a/Application/EdFi.Ods.Sandbox/EdFi.Ods.Sandbox.csproj +++ b/Application/EdFi.Ods.Sandbox/EdFi.Ods.Sandbox.csproj @@ -16,7 +16,7 @@ - + diff --git a/Application/EdFi.Ods.Security/Authorization/EdFiAuthorizationProvider.cs b/Application/EdFi.Ods.Security/Authorization/EdFiAuthorizationProvider.cs index 151be3272f..07329df81b 100644 --- a/Application/EdFi.Ods.Security/Authorization/EdFiAuthorizationProvider.cs +++ b/Application/EdFi.Ods.Security/Authorization/EdFiAuthorizationProvider.cs @@ -69,26 +69,11 @@ public EdFiAuthorizationProvider( _bitValuesByAction = new Lazy>( () => new Dictionary { - { - _securityRepository.GetActionByName("Create") - .ActionUri, - 0x1 - }, - { - _securityRepository.GetActionByName("Read") - .ActionUri, - 0x2 - }, - { - _securityRepository.GetActionByName("Update") - .ActionUri, - 0x4 - }, - { - _securityRepository.GetActionByName("Delete") - .ActionUri, - 0x8 - } + { _securityRepository.GetActionByName("Create") .ActionUri, 0x1 }, + { _securityRepository.GetActionByName("Read") .ActionUri, 0x2 }, + { _securityRepository.GetActionByName("Update") .ActionUri, 0x4 }, + { _securityRepository.GetActionByName("Delete") .ActionUri, 0x8 }, + { _securityRepository.GetActionByName("ReadChanges") .ActionUri, 0x10 }, }); } diff --git a/Application/EdFi.Ods.Security/Authorization/Pipeline/AuthorizationContextPipelineFactory.cs b/Application/EdFi.Ods.Security/Authorization/Pipeline/AuthorizationContextPipelineFactory.cs index 98d2f975ae..2f5a63be32 100644 --- a/Application/EdFi.Ods.Security/Authorization/Pipeline/AuthorizationContextPipelineFactory.cs +++ b/Application/EdFi.Ods.Security/Authorization/Pipeline/AuthorizationContextPipelineFactory.cs @@ -6,7 +6,6 @@ using System; using System.Linq; using EdFi.Common.Extensions; -using EdFi.Ods.Common.Extensions; using EdFi.Ods.Common.Infrastructure.Pipelines; namespace EdFi.Ods.Security.Authorization.Pipeline @@ -78,21 +77,4 @@ public Type[] GetSteps() .ToArray(); } } - - public class AuthorizationContextGetDeletedResourceIdsPipelineStepsProviderDecorator : IGetDeletedResourceIdsPipelineStepsProvider - { - private readonly IGetDeletedResourceIdsPipelineStepsProvider _next; - - public AuthorizationContextGetDeletedResourceIdsPipelineStepsProviderDecorator(IGetDeletedResourceIdsPipelineStepsProvider next) - { - _next = next; - } - - public Type[] GetSteps() - { - return _next.GetSteps() - .InsertAtHead(typeof(SetAuthorizationContextForGetDeletedResourceIds<,,,>)) - .ToArray(); - } - } } diff --git a/Application/EdFi.Ods.Security/Authorization/Pipeline/SetAuthorizationContext.cs b/Application/EdFi.Ods.Security/Authorization/Pipeline/SetAuthorizationContext.cs index 4822f1844e..0df4062ab8 100644 --- a/Application/EdFi.Ods.Security/Authorization/Pipeline/SetAuthorizationContext.cs +++ b/Application/EdFi.Ods.Security/Authorization/Pipeline/SetAuthorizationContext.cs @@ -140,21 +140,4 @@ protected override string Action get => SecurityRepository.GetActionByName("Delete").ActionUri; } } - - public class SetAuthorizationContextForGetDeletedResourceIds - : SetAuthorizationContextBase - where TContext : class - where TResult : class - { - public SetAuthorizationContextForGetDeletedResourceIds( - IAuthorizationContextProvider authorizationContextProvider, - ISecurityRepository securityRepository, - IResourceClaimUriProvider resourceClaimUriProvider) - : base(authorizationContextProvider, securityRepository, resourceClaimUriProvider) { } - - protected override string Action - { - get => SecurityRepository.GetActionByName("Read").ActionUri; - } - } } diff --git a/Application/EdFi.Ods.Security/AuthorizationStrategies/Relationships/Filters/RelationshipsAuthorizationFilters.cs b/Application/EdFi.Ods.Security/AuthorizationStrategies/Relationships/Filters/RelationshipsAuthorizationFilters.cs index 33180ac2cd..9ccec6fc80 100644 --- a/Application/EdFi.Ods.Security/AuthorizationStrategies/Relationships/Filters/RelationshipsAuthorizationFilters.cs +++ b/Application/EdFi.Ods.Security/AuthorizationStrategies/Relationships/Filters/RelationshipsAuthorizationFilters.cs @@ -71,6 +71,22 @@ FROM auth.LocalEducationAgencyIdToStudentUSIThroughEdOrgAssociation {newAlias1} WHERE {newAlias1}.LocalEducationAgencyId IN (:LocalEducationAgencyId))", (c, w, p, jt) => c.ApplyJoinFilter(w, p, "LocalEducationAgencyIdToStudentUSIThroughEdOrgAssociation", "StudentUSI", "LocalEducationAgencyId", jt), (t, p) => p.HasPropertyNamed("StudentUSI"))); + + private static readonly Lazy _localEducationAgencyIdToStudentUSIIncludingDeletes + = new Lazy( + () => + new FilterApplicationDetails( + "LocalEducationAgencyIdToStudentUSIIncludingDeletes", + @"StudentUSI IN ( + SELECT {newAlias1}.StudentUSI + FROM auth.LocalEducationAgencyIdToStudentUSIIncludingDeletes {newAlias1} + WHERE {newAlias1}.LocalEducationAgencyId IN (:LocalEducationAgencyId))", + @"{currentAlias}.StudentUSI IN ( + SELECT {newAlias1}.StudentUSI + FROM " + "auth_LocalEducationAgencyIdToStudentUSIIncludingDeletes".GetFullNameForView() + @" {newAlias1} + WHERE {newAlias1}.LocalEducationAgencyId IN (:LocalEducationAgencyId))", + (c, w, p, jt) => c.ApplyJoinFilter(w, p, "LocalEducationAgencyIdToStudentUSIIncludingDeletes", "StudentUSI", "LocalEducationAgencyId", jt), + (t, p) => p.HasPropertyNamed("StudentUSI"))); private static readonly Lazy _schoolIdToStudentUSI = new Lazy( @@ -104,6 +120,22 @@ FROM auth.SchoolIdToStudentUSIThroughEdOrgAssociation {newAlias1} (c, w, p, jt) => c.ApplyJoinFilter(w, p, "SchoolIdToStudentUSIThroughEdOrgAssociation", "StudentUSI", "SchoolId", jt), (t, p) => p.HasPropertyNamed("StudentUSI"))); + private static readonly Lazy _schoolIdToStudentUSIIncludingDeletes + = new Lazy( + () => + new FilterApplicationDetails( + "SchoolIdToStudentUSIIncludingDeletes", + @"StudentUSI IN ( + SELECT {newAlias1}.StudentUSI + FROM auth.SchoolIdToStudentUSIIncludingDeletes {newAlias1} + WHERE {newAlias1}.SchoolId IN (:SchoolId))", + @"{currentAlias}.StudentUSI IN ( + SELECT {newAlias1}.StudentUSI + FROM " + "auth_SchoolIdToStudentUSIIncludingDeletes".GetFullNameForView() + @" {newAlias1} + WHERE {newAlias1}.SchoolId IN (:SchoolId))", + (c, w, p, jt) => c.ApplyJoinFilter(w, p, "SchoolIdToStudentUSIIncludingDeletes", "StudentUSI", "SchoolId", jt), + (t, p) => p.HasPropertyNamed("StudentUSI"))); + private static readonly Lazy _localEducationAgencyIdToStaffUSI = new Lazy( () => @@ -120,6 +152,22 @@ FROM auth.LocalEducationAgencyIdToStaffUSI {newAlias1} (c, w, p, jt) => c.ApplyJoinFilter(w, p, "LocalEducationAgencyIdToStaffUSI", "StaffUSI", "LocalEducationAgencyId", jt), (t, p) => p.HasPropertyNamed("StaffUSI"))); + private static readonly Lazy _localEducationAgencyIdToStaffUSIIncludingDeletes + = new Lazy( + () => + new FilterApplicationDetails( + "LocalEducationAgencyIdToStaffUSIIncludingDeletes", + @"StaffUSI IN ( + SELECT {newAlias1}.StaffUSI + FROM auth.LocalEducationAgencyIdToStaffUSIIncludingDeletes {newAlias1} + WHERE {newAlias1}.LocalEducationAgencyId IN (:LocalEducationAgencyId))", + @"{currentAlias}.StaffUSI IN ( + SELECT {newAlias1}.StaffUSI + FROM " + "auth_LocalEducationAgencyIdToStaffUSIIncludingDeletes".GetFullNameForView() + @" {newAlias1} + WHERE {newAlias1}.LocalEducationAgencyId IN (:LocalEducationAgencyId))", + (c, w, p, jt) => c.ApplyJoinFilter(w, p, "LocalEducationAgencyIdToStaffUSIIncludingDeletes", "StaffUSI", "LocalEducationAgencyId", jt), + (t, p) => p.HasPropertyNamed("StaffUSI"))); + private static readonly Lazy _schoolIdToStaffUSI = new Lazy( () => @@ -136,6 +184,22 @@ FROM auth.SchoolIdToStaffUSI {newAlias1} (c, w, p, jt) => c.ApplyJoinFilter(w, p, "SchoolIdToStaffUSI", "StaffUSI", "SchoolId", jt), (t, p) => p.HasPropertyNamed("StaffUSI"))); + private static readonly Lazy _schoolIdToStaffUSIIncludingDeletes + = new Lazy( + () => + new FilterApplicationDetails( + "SchoolIdToStaffUSIIncludingDeletes", + @"StaffUSI IN ( + SELECT {newAlias1}.StaffUSI + FROM auth.SchoolIdToStaffUSIIncludingDeletes {newAlias1} + WHERE {newAlias1}.SchoolId IN (:SchoolId))", + @"{currentAlias}.StaffUSI IN ( + SELECT {newAlias1}.StaffUSI + FROM " + "auth_SchoolIdToStaffUSIIncludingDeletes".GetFullNameForView() + @" {newAlias1} + WHERE {newAlias1}.SchoolId IN (:SchoolId))", + (c, w, p, jt) => c.ApplyJoinFilter(w, p, "SchoolIdToStaffUSIIncludingDeletes", "StaffUSI", "SchoolId", jt), + (t, p) => p.HasPropertyNamed("StaffUSI"))); + private static readonly Lazy _localEducationAgencyIdToParentUSI = new Lazy( () => @@ -152,6 +216,22 @@ FROM auth.LocalEducationAgencyIdToParentUSI {newAlias1} (c, w, p, jt) => c.ApplyJoinFilter(w, p, "LocalEducationAgencyIdToParentUSI", "ParentUSI", "LocalEducationAgencyId", jt), (t, p) => p.HasPropertyNamed("ParentUSI"))); + private static readonly Lazy _localEducationAgencyIdToParentUSIIncludingDeletes + = new Lazy( + () => + new FilterApplicationDetails( + "LocalEducationAgencyIdToParentUSIIncludingDeletes", + @"ParentUSI IN ( + SELECT {newAlias1}.ParentUSI + FROM auth.LocalEducationAgencyIdToParentUSIIncludingDeletes {newAlias1} + WHERE {newAlias1}.LocalEducationAgencyId IN (:LocalEducationAgencyId))", + @"{currentAlias}.ParentUSI IN ( + SELECT {newAlias1}.ParentUSI + FROM " + "auth_LocalEducationAgencyIdToParentUSIIncludingDeletes".GetFullNameForView() + @" {newAlias1} + WHERE {newAlias1}.LocalEducationAgencyId IN (:LocalEducationAgencyId))", + (c, w, p, jt) => c.ApplyJoinFilter(w, p, "LocalEducationAgencyIdToParentUSIIncludingDeletes", "ParentUSI", "LocalEducationAgencyId", jt), + (t, p) => p.HasPropertyNamed("ParentUSI"))); + private static readonly Lazy _parentUSIToSchoolId = new Lazy( () => @@ -168,6 +248,22 @@ FROM auth.ParentUSIToSchoolId {newAlias1} (c, w, p, jt) => c.ApplyJoinFilter(w, p, "ParentUSIToSchoolId", "ParentUSI", "SchoolId", jt), (t, p) => p.HasPropertyNamed("ParentUSI"))); + private static readonly Lazy _parentUSIToSchoolIdIncludingDeletes + = new Lazy( + () => + new FilterApplicationDetails( + "ParentUSIToSchoolIdIncludingDeletes", + @"ParentUSI IN ( + SELECT {newAlias1}.ParentUSI + FROM auth.ParentUSIToSchoolIdIncludingDeletes {newAlias1} + WHERE {newAlias1}.SchoolId IN (:SchoolId))", + @"{currentAlias}.ParentUSI IN ( + SELECT {newAlias1}.ParentUSI + FROM " + "auth_ParentUSIToSchoolIdIncludingDeletes".GetFullNameForView() + @" {newAlias1} + WHERE {newAlias1}.SchoolId IN (:SchoolId))", + (c, w, p, jt) => c.ApplyJoinFilter(w, p, "ParentUSIToSchoolIdIncludingDeletes", "ParentUSI", "SchoolId", jt), + (t, p) => p.HasPropertyNamed("ParentUSI"))); + private static readonly Lazy _educationOrganizationIdToLocalEducationAgencyId = new Lazy( () => @@ -335,17 +431,30 @@ public static FilterApplicationDetails StateEducationAgencyIdToStateEducationAge public static FilterApplicationDetails LocalEducationAgencyIdToStudentUSIThroughEdOrgAssociation => _localEducationAgencyIdToStudentUSIThroughEdOrgAssociation.Value; + public static FilterApplicationDetails LocalEducationAgencyIdToStudentUSIIncludingDeletes + => _localEducationAgencyIdToStudentUSIIncludingDeletes.Value; + public static FilterApplicationDetails SchoolIdToStudentUSI => _schoolIdToStudentUSI.Value; public static FilterApplicationDetails SchoolIdToStudentUSIThroughEdOrgAssociation => _schoolIdToStudentUSIThroughEdOrgAssociation.Value; + + public static FilterApplicationDetails SchoolIdToStudentUSIIncludingDeletes => _schoolIdToStudentUSIIncludingDeletes.Value; public static FilterApplicationDetails LocalEducationAgencyIdToStaffUSI => _localEducationAgencyIdToStaffUSI.Value; + public static FilterApplicationDetails LocalEducationAgencyIdToStaffUSIIncludingDeletes => _localEducationAgencyIdToStaffUSIIncludingDeletes.Value; + public static FilterApplicationDetails SchoolIdToStaffUSI => _schoolIdToStaffUSI.Value; + + public static FilterApplicationDetails SchoolIdToStaffUSIIncludingDeletes => _schoolIdToStaffUSIIncludingDeletes.Value; public static FilterApplicationDetails LocalEducationAgencyIdToParentUSI => _localEducationAgencyIdToParentUSI.Value; + + public static FilterApplicationDetails LocalEducationAgencyIdToParentUSIIncludingDeletes => _localEducationAgencyIdToParentUSIIncludingDeletes.Value; public static FilterApplicationDetails ParentUSIToSchoolId => _parentUSIToSchoolId.Value; + + public static FilterApplicationDetails ParentUSIToSchoolIdIncludingDeletes => _parentUSIToSchoolIdIncludingDeletes.Value; public static FilterApplicationDetails EducationOrganizationIdToLocalEducationAgencyId => _educationOrganizationIdToLocalEducationAgencyId.Value; diff --git a/Application/EdFi.Ods.Security/AuthorizationStrategies/Relationships/RelationshipsAuthorizationContextDataProviderFactory.cs b/Application/EdFi.Ods.Security/AuthorizationStrategies/Relationships/RelationshipsAuthorizationContextDataProviderFactory.cs index 9caecfc10a..6e8f73a489 100644 --- a/Application/EdFi.Ods.Security/AuthorizationStrategies/Relationships/RelationshipsAuthorizationContextDataProviderFactory.cs +++ b/Application/EdFi.Ods.Security/AuthorizationStrategies/Relationships/RelationshipsAuthorizationContextDataProviderFactory.cs @@ -53,7 +53,7 @@ public IRelationshipsAuthorizationContextDataProvider GetProvider( { throw new NotSupportedException( string.Format( - "Unable to locate a relationships authorization context data provider for entity type '{0}'. Does it have any properties related to relationship-based authorization, and should it be getting authorized using a relationships-based authorization strategy?", + "Unable to locate a relationships authorization context data provider for entity type '{0}'. Does it actually have any properties related to relationship-based authorization, and should it really be getting authorized using a relationships-based authorization strategy?", entityType.FullName), ex); } diff --git a/Application/EdFi.Ods.Security/AuthorizationStrategies/Relationships/RelationshipsWithEdOrgsAndPeopleIncludingDeletesAuthorizationStrategy.cs b/Application/EdFi.Ods.Security/AuthorizationStrategies/Relationships/RelationshipsWithEdOrgsAndPeopleIncludingDeletesAuthorizationStrategy.cs new file mode 100644 index 0000000000..0329747d10 --- /dev/null +++ b/Application/EdFi.Ods.Security/AuthorizationStrategies/Relationships/RelationshipsWithEdOrgsAndPeopleIncludingDeletesAuthorizationStrategy.cs @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System.Linq; +using EdFi.Common.Utils.Extensions; +using EdFi.Ods.Common.Specifications; +using EdFi.Ods.Security.Authorization; + +namespace EdFi.Ods.Security.AuthorizationStrategies.Relationships +{ + public class RelationshipsWithEdOrgsAndPeopleIncludingDeletesAuthorizationStrategy + : RelationshipsAuthorizationStrategyBase + where TContextData : RelationshipsAuthorizationContextData, new() + { + public RelationshipsWithEdOrgsAndPeopleIncludingDeletesAuthorizationStrategy(IConcreteEducationOrganizationIdAuthorizationContextDataTransformer concreteEducationOrganizationIdAuthorizationContextDataTransformer) + : base(concreteEducationOrganizationIdAuthorizationContextDataTransformer) { } + + protected override void BuildAuthorizationSegments( + AuthorizationBuilder authorizationBuilder, + string[] authorizationContextPropertyNames) + { + // For person USIs, use the view that incorporates the deleted associations + authorizationContextPropertyNames + .Where(PersonEntitySpecification.IsPersonIdentifier) + .ForEach(pn => authorizationBuilder.ClaimsMustBeAssociatedWith(pn, "IncludingDeletes")); + + // For EdOrgs, use the standard views + authorizationContextPropertyNames + .Where(pn => !PersonEntitySpecification.IsPersonIdentifier(pn)) + .ForEach(pn => authorizationBuilder.ClaimsMustBeAssociatedWith(pn)); + } + } +} diff --git a/Application/EdFi.Ods.Security/AuthorizationStrategies/Relationships/RelationshipsWithLocalEducationAgenciesAndPeopleIncludingDeletesAuthorizationStrategyFilterConfigurator.cs b/Application/EdFi.Ods.Security/AuthorizationStrategies/Relationships/RelationshipsWithLocalEducationAgenciesAndPeopleIncludingDeletesAuthorizationStrategyFilterConfigurator.cs new file mode 100644 index 0000000000..d8334e2216 --- /dev/null +++ b/Application/EdFi.Ods.Security/AuthorizationStrategies/Relationships/RelationshipsWithLocalEducationAgenciesAndPeopleIncludingDeletesAuthorizationStrategyFilterConfigurator.cs @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System.Collections.Generic; +using EdFi.Ods.Common.Infrastructure.Filtering; +using EdFi.Ods.Security.AuthorizationStrategies.Relationships.Filters; + +namespace EdFi.Ods.Security.AuthorizationStrategies.Relationships +{ + public class RelationshipsWithLocalEducationAgenciesAndPeopleIncludingDeletesAuthorizationStrategyFilterConfigurator + : INHibernateFilterConfigurator + { + /// + /// Gets the NHibernate filter definitions and a functional delegate for determining when to apply them. + /// + /// A read-only list of filter application details to be applied to the NHibernate configuration and entity mappings. + public IReadOnlyList GetFilters() + { + var filters = new List + { + // Local Education Agency to Person relationships + RelationshipsAuthorizationFilters.LocalEducationAgencyIdToStudentUSIIncludingDeletes, + RelationshipsAuthorizationFilters.LocalEducationAgencyIdToStaffUSIIncludingDeletes, + RelationshipsAuthorizationFilters.LocalEducationAgencyIdToParentUSIIncludingDeletes, + + // School to Person relationships + RelationshipsAuthorizationFilters.SchoolIdToStudentUSIIncludingDeletes, + RelationshipsAuthorizationFilters.SchoolIdToStaffUSIIncludingDeletes, + RelationshipsAuthorizationFilters.ParentUSIToSchoolIdIncludingDeletes, + }; + + return filters; + } + } +} diff --git a/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0030-AddColumnChangeVersionForTables.sql b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0030-AddColumnChangeVersionForTables.sql index b7373d90cc..ff121c4fc0 100644 --- a/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0030-AddColumnChangeVersionForTables.sql +++ b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0030-AddColumnChangeVersionForTables.sql @@ -3,201 +3,300 @@ -- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. -- See the LICENSE and NOTICES files in the project root for more information. +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[AcademicWeek]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[AcademicWeek] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[Account]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[Account] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; -ALTER TABLE [edfi].[AccountCode] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; - +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[AccountabilityRating]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[AccountabilityRating] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[AccountCode]') AND name = 'ChangeVersion') +ALTER TABLE [edfi].[AccountCode] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; + +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[Actual]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[Actual] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[Assessment]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[Assessment] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[AssessmentItem]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[AssessmentItem] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[AssessmentScoreRangeLearningStandard]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[AssessmentScoreRangeLearningStandard] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[BellSchedule]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[BellSchedule] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[Budget]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[Budget] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[Calendar]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[Calendar] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[CalendarDate]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[CalendarDate] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[ClassPeriod]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[ClassPeriod] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[Cohort]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[Cohort] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[CommunityProviderLicense]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[CommunityProviderLicense] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[CompetencyObjective]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[CompetencyObjective] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[ContractedStaff]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[ContractedStaff] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[Course]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[Course] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[CourseOffering]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[CourseOffering] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[CourseTranscript]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[CourseTranscript] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[Credential]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[Credential] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[Descriptor]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[Descriptor] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[DisciplineAction]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[DisciplineAction] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[DisciplineIncident]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[DisciplineIncident] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[EducationContent]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[EducationContent] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[EducationOrganization]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[EducationOrganization] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[EducationOrganizationInterventionPrescriptionAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[EducationOrganizationInterventionPrescriptionAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[EducationOrganizationNetworkAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[EducationOrganizationNetworkAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[EducationOrganizationPeerAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[EducationOrganizationPeerAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[FeederSchoolAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[FeederSchoolAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[GeneralStudentProgramAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[GeneralStudentProgramAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[Grade]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[Grade] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[GradebookEntry]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[GradebookEntry] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[GradingPeriod]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[GradingPeriod] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[GraduationPlan]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[GraduationPlan] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[Intervention]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[Intervention] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[InterventionPrescription]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[InterventionPrescription] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[InterventionStudy]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[InterventionStudy] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[LearningObjective]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[LearningObjective] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[LearningStandard]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[LearningStandard] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[LearningStandardEquivalenceAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[LearningStandardEquivalenceAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[Location]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[Location] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[ObjectiveAssessment]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[ObjectiveAssessment] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[OpenStaffPosition]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[OpenStaffPosition] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[Parent]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[Parent] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[Payroll]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[Payroll] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[Person]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[Person] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[PostSecondaryEvent]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[PostSecondaryEvent] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[Program]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[Program] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[ReportCard]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[ReportCard] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[RestraintEvent]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[RestraintEvent] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[SchoolYearType]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[SchoolYearType] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[Section]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[Section] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[SectionAttendanceTakenEvent]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[SectionAttendanceTakenEvent] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[Session]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[Session] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[Staff]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[Staff] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StaffAbsenceEvent]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StaffAbsenceEvent] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StaffCohortAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StaffCohortAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StaffDisciplineIncidentAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StaffDisciplineIncidentAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StaffEducationOrganizationAssignmentAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StaffEducationOrganizationAssignmentAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StaffEducationOrganizationContactAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StaffEducationOrganizationContactAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StaffEducationOrganizationEmploymentAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StaffEducationOrganizationEmploymentAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StaffLeave]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StaffLeave] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StaffProgramAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StaffProgramAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StaffSchoolAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StaffSchoolAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StaffSectionAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StaffSectionAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[Student]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[Student] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StudentAcademicRecord]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StudentAcademicRecord] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StudentAssessment]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StudentAssessment] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StudentCohortAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StudentCohortAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StudentCompetencyObjective]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StudentCompetencyObjective] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StudentDisciplineIncidentAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StudentDisciplineIncidentAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StudentDisciplineIncidentBehaviorAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StudentDisciplineIncidentBehaviorAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StudentDisciplineIncidentNonOffenderAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StudentDisciplineIncidentNonOffenderAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StudentEducationOrganizationAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StudentEducationOrganizationAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StudentEducationOrganizationResponsibilityAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StudentEducationOrganizationResponsibilityAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StudentGradebookEntry]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StudentGradebookEntry] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StudentInterventionAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StudentInterventionAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StudentInterventionAttendanceEvent]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StudentInterventionAttendanceEvent] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StudentLearningObjective]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StudentLearningObjective] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StudentParentAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StudentParentAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StudentProgramAttendanceEvent]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StudentProgramAttendanceEvent] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StudentSchoolAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StudentSchoolAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StudentSchoolAttendanceEvent]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StudentSchoolAttendanceEvent] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StudentSectionAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StudentSectionAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[StudentSectionAttendanceEvent]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[StudentSectionAttendanceEvent] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[Survey]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[Survey] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[SurveyCourseAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[SurveyCourseAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[SurveyProgramAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[SurveyProgramAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[SurveyQuestion]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[SurveyQuestion] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[SurveyQuestionResponse]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[SurveyQuestionResponse] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[SurveyResponse]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[SurveyResponse] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[SurveyResponseEducationOrganizationTargetAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[SurveyResponseEducationOrganizationTargetAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[SurveyResponseStaffTargetAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[SurveyResponseStaffTargetAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[SurveySection]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[SurveySection] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[SurveySectionAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[SurveySectionAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[SurveySectionResponse]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[SurveySectionResponse] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[SurveySectionResponseEducationOrganizationTargetAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[SurveySectionResponseEducationOrganizationTargetAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[edfi].[SurveySectionResponseStaffTargetAssociation]') AND name = 'ChangeVersion') ALTER TABLE [edfi].[SurveySectionResponseStaffTargetAssociation] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; diff --git a/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0050-CreateTrackedDeleteTables.sql b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0050-CreateTrackedDeleteTables.sql deleted file mode 100644 index 2787abb406..0000000000 --- a/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0050-CreateTrackedDeleteTables.sql +++ /dev/null @@ -1,2655 +0,0 @@ --- SPDX-License-Identifier: Apache-2.0 --- Licensed to the Ed-Fi Alliance under one or more agreements. --- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. --- See the LICENSE and NOTICES files in the project root for more information. - -CREATE TABLE [tracked_deletes_edfi].[AbsenceEventCategoryDescriptor] -( - AbsenceEventCategoryDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AbsenceEventCategoryDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[AcademicHonorCategoryDescriptor] -( - AcademicHonorCategoryDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AcademicHonorCategoryDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[AcademicSubjectDescriptor] -( - AcademicSubjectDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AcademicSubjectDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[AcademicWeek] -( - SchoolId [INT] NOT NULL, - WeekIdentifier [NVARCHAR](80) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AcademicWeek PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[AccommodationDescriptor] -( - AccommodationDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AccommodationDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[Account] -( - AccountIdentifier [NVARCHAR](50) NOT NULL, - EducationOrganizationId [INT] NOT NULL, - FiscalYear [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_Account PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[AccountClassificationDescriptor] -( - AccountClassificationDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AccountClassificationDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[AccountCode] -( - AccountClassificationDescriptorId [INT] NOT NULL, - AccountCodeNumber [NVARCHAR](50) NOT NULL, - EducationOrganizationId [INT] NOT NULL, - FiscalYear [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AccountCode PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[AccountabilityRating] -( - EducationOrganizationId [INT] NOT NULL, - RatingTitle [NVARCHAR](60) NOT NULL, - SchoolYear [SMALLINT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AccountabilityRating PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[AchievementCategoryDescriptor] -( - AchievementCategoryDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AchievementCategoryDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[Actual] -( - AccountIdentifier [NVARCHAR](50) NOT NULL, - AsOfDate [DATE] NOT NULL, - EducationOrganizationId [INT] NOT NULL, - FiscalYear [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_Actual PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[AdditionalCreditTypeDescriptor] -( - AdditionalCreditTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AdditionalCreditTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[AddressTypeDescriptor] -( - AddressTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AddressTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[AdministrationEnvironmentDescriptor] -( - AdministrationEnvironmentDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AdministrationEnvironmentDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[AdministrativeFundingControlDescriptor] -( - AdministrativeFundingControlDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AdministrativeFundingControlDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[AncestryEthnicOriginDescriptor] -( - AncestryEthnicOriginDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AncestryEthnicOriginDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[Assessment] -( - AssessmentIdentifier [NVARCHAR](60) NOT NULL, - Namespace [NVARCHAR](255) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_Assessment PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[AssessmentCategoryDescriptor] -( - AssessmentCategoryDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AssessmentCategoryDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[AssessmentIdentificationSystemDescriptor] -( - AssessmentIdentificationSystemDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AssessmentIdentificationSystemDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[AssessmentItem] -( - AssessmentIdentifier [NVARCHAR](60) NOT NULL, - IdentificationCode [NVARCHAR](60) NOT NULL, - Namespace [NVARCHAR](255) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AssessmentItem PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[AssessmentItemCategoryDescriptor] -( - AssessmentItemCategoryDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AssessmentItemCategoryDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[AssessmentItemResultDescriptor] -( - AssessmentItemResultDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AssessmentItemResultDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[AssessmentPeriodDescriptor] -( - AssessmentPeriodDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AssessmentPeriodDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[AssessmentReportingMethodDescriptor] -( - AssessmentReportingMethodDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AssessmentReportingMethodDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[AssessmentScoreRangeLearningStandard] -( - AssessmentIdentifier [NVARCHAR](60) NOT NULL, - Namespace [NVARCHAR](255) NOT NULL, - ScoreRangeId [NVARCHAR](60) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AssessmentScoreRangeLearningStandard PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[AttemptStatusDescriptor] -( - AttemptStatusDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AttemptStatusDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[AttendanceEventCategoryDescriptor] -( - AttendanceEventCategoryDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_AttendanceEventCategoryDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[BehaviorDescriptor] -( - BehaviorDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_BehaviorDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[BellSchedule] -( - BellScheduleName [NVARCHAR](60) NOT NULL, - SchoolId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_BellSchedule PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[Budget] -( - AccountIdentifier [NVARCHAR](50) NOT NULL, - AsOfDate [DATE] NOT NULL, - EducationOrganizationId [INT] NOT NULL, - FiscalYear [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_Budget PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CTEProgramServiceDescriptor] -( - CTEProgramServiceDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CTEProgramServiceDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[Calendar] -( - CalendarCode [NVARCHAR](60) NOT NULL, - SchoolId [INT] NOT NULL, - SchoolYear [SMALLINT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_Calendar PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CalendarDate] -( - CalendarCode [NVARCHAR](60) NOT NULL, - Date [DATE] NOT NULL, - SchoolId [INT] NOT NULL, - SchoolYear [SMALLINT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CalendarDate PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CalendarEventDescriptor] -( - CalendarEventDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CalendarEventDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CalendarTypeDescriptor] -( - CalendarTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CalendarTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CareerPathwayDescriptor] -( - CareerPathwayDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CareerPathwayDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CharterApprovalAgencyTypeDescriptor] -( - CharterApprovalAgencyTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CharterApprovalAgencyTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CharterStatusDescriptor] -( - CharterStatusDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CharterStatusDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CitizenshipStatusDescriptor] -( - CitizenshipStatusDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CitizenshipStatusDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ClassPeriod] -( - ClassPeriodName [NVARCHAR](60) NOT NULL, - SchoolId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ClassPeriod PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ClassroomPositionDescriptor] -( - ClassroomPositionDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ClassroomPositionDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[Cohort] -( - CohortIdentifier [NVARCHAR](20) NOT NULL, - EducationOrganizationId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_Cohort PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CohortScopeDescriptor] -( - CohortScopeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CohortScopeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CohortTypeDescriptor] -( - CohortTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CohortTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CohortYearTypeDescriptor] -( - CohortYearTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CohortYearTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CommunityOrganization] -( - CommunityOrganizationId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CommunityOrganization PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CommunityProvider] -( - CommunityProviderId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CommunityProvider PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CommunityProviderLicense] -( - CommunityProviderId [INT] NOT NULL, - LicenseIdentifier [NVARCHAR](20) NOT NULL, - LicensingOrganization [NVARCHAR](75) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CommunityProviderLicense PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CompetencyLevelDescriptor] -( - CompetencyLevelDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CompetencyLevelDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CompetencyObjective] -( - EducationOrganizationId [INT] NOT NULL, - Objective [NVARCHAR](60) NOT NULL, - ObjectiveGradeLevelDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CompetencyObjective PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ContactTypeDescriptor] -( - ContactTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ContactTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ContentClassDescriptor] -( - ContentClassDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ContentClassDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ContinuationOfServicesReasonDescriptor] -( - ContinuationOfServicesReasonDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ContinuationOfServicesReasonDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ContractedStaff] -( - AccountIdentifier [NVARCHAR](50) NOT NULL, - AsOfDate [DATE] NOT NULL, - EducationOrganizationId [INT] NOT NULL, - FiscalYear [INT] NOT NULL, - StaffUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ContractedStaff PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CostRateDescriptor] -( - CostRateDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CostRateDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CountryDescriptor] -( - CountryDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CountryDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[Course] -( - CourseCode [NVARCHAR](60) NOT NULL, - EducationOrganizationId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_Course PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CourseAttemptResultDescriptor] -( - CourseAttemptResultDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CourseAttemptResultDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CourseDefinedByDescriptor] -( - CourseDefinedByDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CourseDefinedByDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CourseGPAApplicabilityDescriptor] -( - CourseGPAApplicabilityDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CourseGPAApplicabilityDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CourseIdentificationSystemDescriptor] -( - CourseIdentificationSystemDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CourseIdentificationSystemDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CourseLevelCharacteristicDescriptor] -( - CourseLevelCharacteristicDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CourseLevelCharacteristicDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CourseOffering] -( - LocalCourseCode [NVARCHAR](60) NOT NULL, - SchoolId [INT] NOT NULL, - SchoolYear [SMALLINT] NOT NULL, - SessionName [NVARCHAR](60) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CourseOffering PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CourseRepeatCodeDescriptor] -( - CourseRepeatCodeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CourseRepeatCodeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CourseTranscript] -( - CourseAttemptResultDescriptorId [INT] NOT NULL, - CourseCode [NVARCHAR](60) NOT NULL, - CourseEducationOrganizationId [INT] NOT NULL, - EducationOrganizationId [INT] NOT NULL, - SchoolYear [SMALLINT] NOT NULL, - StudentUSI [INT] NOT NULL, - TermDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CourseTranscript PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[Credential] -( - CredentialIdentifier [NVARCHAR](60) NOT NULL, - StateOfIssueStateAbbreviationDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_Credential PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CredentialFieldDescriptor] -( - CredentialFieldDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CredentialFieldDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CredentialTypeDescriptor] -( - CredentialTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CredentialTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CreditCategoryDescriptor] -( - CreditCategoryDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CreditCategoryDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CreditTypeDescriptor] -( - CreditTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CreditTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[CurriculumUsedDescriptor] -( - CurriculumUsedDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_CurriculumUsedDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[DeliveryMethodDescriptor] -( - DeliveryMethodDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_DeliveryMethodDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[Descriptor] -( - DescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_Descriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[DiagnosisDescriptor] -( - DiagnosisDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_DiagnosisDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[DiplomaLevelDescriptor] -( - DiplomaLevelDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_DiplomaLevelDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[DiplomaTypeDescriptor] -( - DiplomaTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_DiplomaTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[DisabilityDescriptor] -( - DisabilityDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_DisabilityDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[DisabilityDesignationDescriptor] -( - DisabilityDesignationDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_DisabilityDesignationDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[DisabilityDeterminationSourceTypeDescriptor] -( - DisabilityDeterminationSourceTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_DisabilityDeterminationSourceTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[DisciplineAction] -( - DisciplineActionIdentifier [NVARCHAR](20) NOT NULL, - DisciplineDate [DATE] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_DisciplineAction PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[DisciplineActionLengthDifferenceReasonDescriptor] -( - DisciplineActionLengthDifferenceReasonDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_DisciplineActionLengthDifferenceReasonDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[DisciplineDescriptor] -( - DisciplineDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_DisciplineDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[DisciplineIncident] -( - IncidentIdentifier [NVARCHAR](20) NOT NULL, - SchoolId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_DisciplineIncident PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[DisciplineIncidentParticipationCodeDescriptor] -( - DisciplineIncidentParticipationCodeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_DisciplineIncidentParticipationCodeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[EducationContent] -( - ContentIdentifier [NVARCHAR](225) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_EducationContent PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[EducationOrganization] -( - EducationOrganizationId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_EducationOrganization PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[EducationOrganizationCategoryDescriptor] -( - EducationOrganizationCategoryDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_EducationOrganizationCategoryDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[EducationOrganizationIdentificationSystemDescriptor] -( - EducationOrganizationIdentificationSystemDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_EducationOrganizationIdentificationSystemDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[EducationOrganizationInterventionPrescriptionAssociation] -( - EducationOrganizationId [INT] NOT NULL, - InterventionPrescriptionEducationOrganizationId [INT] NOT NULL, - InterventionPrescriptionIdentificationCode [NVARCHAR](60) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_EducationOrganizationInterventionPrescriptionAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[EducationOrganizationNetwork] -( - EducationOrganizationNetworkId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_EducationOrganizationNetwork PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[EducationOrganizationNetworkAssociation] -( - EducationOrganizationNetworkId [INT] NOT NULL, - MemberEducationOrganizationId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_EducationOrganizationNetworkAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[EducationOrganizationPeerAssociation] -( - EducationOrganizationId [INT] NOT NULL, - PeerEducationOrganizationId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_EducationOrganizationPeerAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[EducationPlanDescriptor] -( - EducationPlanDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_EducationPlanDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[EducationServiceCenter] -( - EducationServiceCenterId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_EducationServiceCenter PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[EducationalEnvironmentDescriptor] -( - EducationalEnvironmentDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_EducationalEnvironmentDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ElectronicMailTypeDescriptor] -( - ElectronicMailTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ElectronicMailTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[EmploymentStatusDescriptor] -( - EmploymentStatusDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_EmploymentStatusDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[EntryGradeLevelReasonDescriptor] -( - EntryGradeLevelReasonDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_EntryGradeLevelReasonDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[EntryTypeDescriptor] -( - EntryTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_EntryTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[EventCircumstanceDescriptor] -( - EventCircumstanceDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_EventCircumstanceDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ExitWithdrawTypeDescriptor] -( - ExitWithdrawTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ExitWithdrawTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[FeederSchoolAssociation] -( - BeginDate [DATE] NOT NULL, - FeederSchoolId [INT] NOT NULL, - SchoolId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_FeederSchoolAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[GeneralStudentProgramAssociation] -( - BeginDate [DATE] NOT NULL, - EducationOrganizationId [INT] NOT NULL, - ProgramEducationOrganizationId [INT] NOT NULL, - ProgramName [NVARCHAR](60) NOT NULL, - ProgramTypeDescriptorId [INT] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_GeneralStudentProgramAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[Grade] -( - BeginDate [DATE] NOT NULL, - GradeTypeDescriptorId [INT] NOT NULL, - GradingPeriodDescriptorId [INT] NOT NULL, - GradingPeriodSchoolYear [SMALLINT] NOT NULL, - GradingPeriodSequence [INT] NOT NULL, - LocalCourseCode [NVARCHAR](60) NOT NULL, - SchoolId [INT] NOT NULL, - SchoolYear [SMALLINT] NOT NULL, - SectionIdentifier [NVARCHAR](255) NOT NULL, - SessionName [NVARCHAR](60) NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_Grade PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[GradeLevelDescriptor] -( - GradeLevelDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_GradeLevelDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[GradePointAverageTypeDescriptor] -( - GradePointAverageTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_GradePointAverageTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[GradeTypeDescriptor] -( - GradeTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_GradeTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[GradebookEntry] -( - DateAssigned [DATE] NOT NULL, - GradebookEntryTitle [NVARCHAR](60) NOT NULL, - LocalCourseCode [NVARCHAR](60) NOT NULL, - SchoolId [INT] NOT NULL, - SchoolYear [SMALLINT] NOT NULL, - SectionIdentifier [NVARCHAR](255) NOT NULL, - SessionName [NVARCHAR](60) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_GradebookEntry PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[GradebookEntryTypeDescriptor] -( - GradebookEntryTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_GradebookEntryTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[GradingPeriod] -( - GradingPeriodDescriptorId [INT] NOT NULL, - PeriodSequence [INT] NOT NULL, - SchoolId [INT] NOT NULL, - SchoolYear [SMALLINT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_GradingPeriod PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[GradingPeriodDescriptor] -( - GradingPeriodDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_GradingPeriodDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[GraduationPlan] -( - EducationOrganizationId [INT] NOT NULL, - GraduationPlanTypeDescriptorId [INT] NOT NULL, - GraduationSchoolYear [SMALLINT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_GraduationPlan PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[GraduationPlanTypeDescriptor] -( - GraduationPlanTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_GraduationPlanTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[GunFreeSchoolsActReportingStatusDescriptor] -( - GunFreeSchoolsActReportingStatusDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_GunFreeSchoolsActReportingStatusDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[HomelessPrimaryNighttimeResidenceDescriptor] -( - HomelessPrimaryNighttimeResidenceDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_HomelessPrimaryNighttimeResidenceDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[HomelessProgramServiceDescriptor] -( - HomelessProgramServiceDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_HomelessProgramServiceDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[IdentificationDocumentUseDescriptor] -( - IdentificationDocumentUseDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_IdentificationDocumentUseDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[IncidentLocationDescriptor] -( - IncidentLocationDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_IncidentLocationDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[IndicatorDescriptor] -( - IndicatorDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_IndicatorDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[IndicatorGroupDescriptor] -( - IndicatorGroupDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_IndicatorGroupDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[IndicatorLevelDescriptor] -( - IndicatorLevelDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_IndicatorLevelDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[InstitutionTelephoneNumberTypeDescriptor] -( - InstitutionTelephoneNumberTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_InstitutionTelephoneNumberTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[InteractivityStyleDescriptor] -( - InteractivityStyleDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_InteractivityStyleDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[InternetAccessDescriptor] -( - InternetAccessDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_InternetAccessDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[Intervention] -( - EducationOrganizationId [INT] NOT NULL, - InterventionIdentificationCode [NVARCHAR](60) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_Intervention PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[InterventionClassDescriptor] -( - InterventionClassDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_InterventionClassDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[InterventionEffectivenessRatingDescriptor] -( - InterventionEffectivenessRatingDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_InterventionEffectivenessRatingDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[InterventionPrescription] -( - EducationOrganizationId [INT] NOT NULL, - InterventionPrescriptionIdentificationCode [NVARCHAR](60) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_InterventionPrescription PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[InterventionStudy] -( - EducationOrganizationId [INT] NOT NULL, - InterventionStudyIdentificationCode [NVARCHAR](60) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_InterventionStudy PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[LanguageDescriptor] -( - LanguageDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_LanguageDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[LanguageInstructionProgramServiceDescriptor] -( - LanguageInstructionProgramServiceDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_LanguageInstructionProgramServiceDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[LanguageUseDescriptor] -( - LanguageUseDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_LanguageUseDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[LearningObjective] -( - LearningObjectiveId [NVARCHAR](60) NOT NULL, - Namespace [NVARCHAR](255) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_LearningObjective PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[LearningStandard] -( - LearningStandardId [NVARCHAR](60) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_LearningStandard PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[LearningStandardCategoryDescriptor] -( - LearningStandardCategoryDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_LearningStandardCategoryDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[LearningStandardEquivalenceAssociation] -( - Namespace [NVARCHAR](255) NOT NULL, - SourceLearningStandardId [NVARCHAR](60) NOT NULL, - TargetLearningStandardId [NVARCHAR](60) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_LearningStandardEquivalenceAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[LearningStandardEquivalenceStrengthDescriptor] -( - LearningStandardEquivalenceStrengthDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_LearningStandardEquivalenceStrengthDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[LearningStandardScopeDescriptor] -( - LearningStandardScopeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_LearningStandardScopeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[LevelOfEducationDescriptor] -( - LevelOfEducationDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_LevelOfEducationDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[LicenseStatusDescriptor] -( - LicenseStatusDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_LicenseStatusDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[LicenseTypeDescriptor] -( - LicenseTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_LicenseTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[LimitedEnglishProficiencyDescriptor] -( - LimitedEnglishProficiencyDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_LimitedEnglishProficiencyDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[LocalEducationAgency] -( - LocalEducationAgencyId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_LocalEducationAgency PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[LocalEducationAgencyCategoryDescriptor] -( - LocalEducationAgencyCategoryDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_LocalEducationAgencyCategoryDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[LocaleDescriptor] -( - LocaleDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_LocaleDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[Location] -( - ClassroomIdentificationCode [NVARCHAR](60) NOT NULL, - SchoolId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_Location PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[MagnetSpecialProgramEmphasisSchoolDescriptor] -( - MagnetSpecialProgramEmphasisSchoolDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_MagnetSpecialProgramEmphasisSchoolDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[MediumOfInstructionDescriptor] -( - MediumOfInstructionDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_MediumOfInstructionDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[MethodCreditEarnedDescriptor] -( - MethodCreditEarnedDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_MethodCreditEarnedDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[MigrantEducationProgramServiceDescriptor] -( - MigrantEducationProgramServiceDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_MigrantEducationProgramServiceDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[MonitoredDescriptor] -( - MonitoredDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_MonitoredDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[NeglectedOrDelinquentProgramDescriptor] -( - NeglectedOrDelinquentProgramDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_NeglectedOrDelinquentProgramDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[NeglectedOrDelinquentProgramServiceDescriptor] -( - NeglectedOrDelinquentProgramServiceDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_NeglectedOrDelinquentProgramServiceDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[NetworkPurposeDescriptor] -( - NetworkPurposeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_NetworkPurposeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ObjectiveAssessment] -( - AssessmentIdentifier [NVARCHAR](60) NOT NULL, - IdentificationCode [NVARCHAR](60) NOT NULL, - Namespace [NVARCHAR](255) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ObjectiveAssessment PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[OldEthnicityDescriptor] -( - OldEthnicityDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_OldEthnicityDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[OpenStaffPosition] -( - EducationOrganizationId [INT] NOT NULL, - RequisitionNumber [NVARCHAR](20) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_OpenStaffPosition PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[OperationalStatusDescriptor] -( - OperationalStatusDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_OperationalStatusDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[OrganizationDepartment] -( - OrganizationDepartmentId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_OrganizationDepartment PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[OtherNameTypeDescriptor] -( - OtherNameTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_OtherNameTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[Parent] -( - ParentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_Parent PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ParticipationDescriptor] -( - ParticipationDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ParticipationDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ParticipationStatusDescriptor] -( - ParticipationStatusDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ParticipationStatusDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[Payroll] -( - AccountIdentifier [NVARCHAR](50) NOT NULL, - AsOfDate [DATE] NOT NULL, - EducationOrganizationId [INT] NOT NULL, - FiscalYear [INT] NOT NULL, - StaffUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_Payroll PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[PerformanceBaseConversionDescriptor] -( - PerformanceBaseConversionDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_PerformanceBaseConversionDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[PerformanceLevelDescriptor] -( - PerformanceLevelDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_PerformanceLevelDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[Person] -( - PersonId [NVARCHAR](32) NOT NULL, - SourceSystemDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_Person PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[PersonalInformationVerificationDescriptor] -( - PersonalInformationVerificationDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_PersonalInformationVerificationDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[PlatformTypeDescriptor] -( - PlatformTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_PlatformTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[PopulationServedDescriptor] -( - PopulationServedDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_PopulationServedDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[PostSecondaryEvent] -( - EventDate [DATE] NOT NULL, - PostSecondaryEventCategoryDescriptorId [INT] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_PostSecondaryEvent PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[PostSecondaryEventCategoryDescriptor] -( - PostSecondaryEventCategoryDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_PostSecondaryEventCategoryDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[PostSecondaryInstitution] -( - PostSecondaryInstitutionId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_PostSecondaryInstitution PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[PostSecondaryInstitutionLevelDescriptor] -( - PostSecondaryInstitutionLevelDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_PostSecondaryInstitutionLevelDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[PostingResultDescriptor] -( - PostingResultDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_PostingResultDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ProficiencyDescriptor] -( - ProficiencyDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ProficiencyDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[Program] -( - EducationOrganizationId [INT] NOT NULL, - ProgramName [NVARCHAR](60) NOT NULL, - ProgramTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_Program PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ProgramAssignmentDescriptor] -( - ProgramAssignmentDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ProgramAssignmentDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ProgramCharacteristicDescriptor] -( - ProgramCharacteristicDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ProgramCharacteristicDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ProgramSponsorDescriptor] -( - ProgramSponsorDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ProgramSponsorDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ProgramTypeDescriptor] -( - ProgramTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ProgramTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ProgressDescriptor] -( - ProgressDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ProgressDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ProgressLevelDescriptor] -( - ProgressLevelDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ProgressLevelDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ProviderCategoryDescriptor] -( - ProviderCategoryDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ProviderCategoryDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ProviderProfitabilityDescriptor] -( - ProviderProfitabilityDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ProviderProfitabilityDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ProviderStatusDescriptor] -( - ProviderStatusDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ProviderStatusDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[PublicationStatusDescriptor] -( - PublicationStatusDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_PublicationStatusDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[QuestionFormDescriptor] -( - QuestionFormDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_QuestionFormDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[RaceDescriptor] -( - RaceDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_RaceDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ReasonExitedDescriptor] -( - ReasonExitedDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ReasonExitedDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ReasonNotTestedDescriptor] -( - ReasonNotTestedDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ReasonNotTestedDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[RecognitionTypeDescriptor] -( - RecognitionTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_RecognitionTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[RelationDescriptor] -( - RelationDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_RelationDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[RepeatIdentifierDescriptor] -( - RepeatIdentifierDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_RepeatIdentifierDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ReportCard] -( - EducationOrganizationId [INT] NOT NULL, - GradingPeriodDescriptorId [INT] NOT NULL, - GradingPeriodSchoolId [INT] NOT NULL, - GradingPeriodSchoolYear [SMALLINT] NOT NULL, - GradingPeriodSequence [INT] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ReportCard PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ReporterDescriptionDescriptor] -( - ReporterDescriptionDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ReporterDescriptionDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ResidencyStatusDescriptor] -( - ResidencyStatusDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ResidencyStatusDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ResponseIndicatorDescriptor] -( - ResponseIndicatorDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ResponseIndicatorDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ResponsibilityDescriptor] -( - ResponsibilityDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ResponsibilityDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[RestraintEvent] -( - RestraintEventIdentifier [NVARCHAR](20) NOT NULL, - SchoolId [INT] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_RestraintEvent PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[RestraintEventReasonDescriptor] -( - RestraintEventReasonDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_RestraintEventReasonDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ResultDatatypeTypeDescriptor] -( - ResultDatatypeTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ResultDatatypeTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[RetestIndicatorDescriptor] -( - RetestIndicatorDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_RetestIndicatorDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[School] -( - SchoolId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_School PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SchoolCategoryDescriptor] -( - SchoolCategoryDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SchoolCategoryDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SchoolChoiceImplementStatusDescriptor] -( - SchoolChoiceImplementStatusDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SchoolChoiceImplementStatusDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SchoolFoodServiceProgramServiceDescriptor] -( - SchoolFoodServiceProgramServiceDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SchoolFoodServiceProgramServiceDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SchoolTypeDescriptor] -( - SchoolTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SchoolTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[Section] -( - LocalCourseCode [NVARCHAR](60) NOT NULL, - SchoolId [INT] NOT NULL, - SchoolYear [SMALLINT] NOT NULL, - SectionIdentifier [NVARCHAR](255) NOT NULL, - SessionName [NVARCHAR](60) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_Section PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SectionAttendanceTakenEvent] -( - CalendarCode [NVARCHAR](60) NOT NULL, - Date [DATE] NOT NULL, - LocalCourseCode [NVARCHAR](60) NOT NULL, - SchoolId [INT] NOT NULL, - SchoolYear [SMALLINT] NOT NULL, - SectionIdentifier [NVARCHAR](255) NOT NULL, - SessionName [NVARCHAR](60) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SectionAttendanceTakenEvent PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SectionCharacteristicDescriptor] -( - SectionCharacteristicDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SectionCharacteristicDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SeparationDescriptor] -( - SeparationDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SeparationDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SeparationReasonDescriptor] -( - SeparationReasonDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SeparationReasonDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[ServiceDescriptor] -( - ServiceDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_ServiceDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[Session] -( - SchoolId [INT] NOT NULL, - SchoolYear [SMALLINT] NOT NULL, - SessionName [NVARCHAR](60) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_Session PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SexDescriptor] -( - SexDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SexDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SourceSystemDescriptor] -( - SourceSystemDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SourceSystemDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SpecialEducationProgramServiceDescriptor] -( - SpecialEducationProgramServiceDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SpecialEducationProgramServiceDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SpecialEducationSettingDescriptor] -( - SpecialEducationSettingDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SpecialEducationSettingDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[Staff] -( - StaffUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_Staff PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StaffAbsenceEvent] -( - AbsenceEventCategoryDescriptorId [INT] NOT NULL, - EventDate [DATE] NOT NULL, - StaffUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StaffAbsenceEvent PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StaffClassificationDescriptor] -( - StaffClassificationDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StaffClassificationDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StaffCohortAssociation] -( - BeginDate [DATE] NOT NULL, - CohortIdentifier [NVARCHAR](20) NOT NULL, - EducationOrganizationId [INT] NOT NULL, - StaffUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StaffCohortAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StaffDisciplineIncidentAssociation] -( - IncidentIdentifier [NVARCHAR](20) NOT NULL, - SchoolId [INT] NOT NULL, - StaffUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StaffDisciplineIncidentAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StaffEducationOrganizationAssignmentAssociation] -( - BeginDate [DATE] NOT NULL, - EducationOrganizationId [INT] NOT NULL, - StaffClassificationDescriptorId [INT] NOT NULL, - StaffUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StaffEducationOrganizationAssignmentAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StaffEducationOrganizationContactAssociation] -( - ContactTitle [NVARCHAR](75) NOT NULL, - EducationOrganizationId [INT] NOT NULL, - StaffUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StaffEducationOrganizationContactAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StaffEducationOrganizationEmploymentAssociation] -( - EducationOrganizationId [INT] NOT NULL, - EmploymentStatusDescriptorId [INT] NOT NULL, - HireDate [DATE] NOT NULL, - StaffUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StaffEducationOrganizationEmploymentAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StaffIdentificationSystemDescriptor] -( - StaffIdentificationSystemDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StaffIdentificationSystemDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StaffLeave] -( - BeginDate [DATE] NOT NULL, - StaffLeaveEventCategoryDescriptorId [INT] NOT NULL, - StaffUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StaffLeave PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StaffLeaveEventCategoryDescriptor] -( - StaffLeaveEventCategoryDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StaffLeaveEventCategoryDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StaffProgramAssociation] -( - BeginDate [DATE] NOT NULL, - ProgramEducationOrganizationId [INT] NOT NULL, - ProgramName [NVARCHAR](60) NOT NULL, - ProgramTypeDescriptorId [INT] NOT NULL, - StaffUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StaffProgramAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StaffSchoolAssociation] -( - ProgramAssignmentDescriptorId [INT] NOT NULL, - SchoolId [INT] NOT NULL, - StaffUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StaffSchoolAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StaffSectionAssociation] -( - LocalCourseCode [NVARCHAR](60) NOT NULL, - SchoolId [INT] NOT NULL, - SchoolYear [SMALLINT] NOT NULL, - SectionIdentifier [NVARCHAR](255) NOT NULL, - SessionName [NVARCHAR](60) NOT NULL, - StaffUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StaffSectionAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StateAbbreviationDescriptor] -( - StateAbbreviationDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StateAbbreviationDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StateEducationAgency] -( - StateEducationAgencyId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StateEducationAgency PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[Student] -( - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_Student PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentAcademicRecord] -( - EducationOrganizationId [INT] NOT NULL, - SchoolYear [SMALLINT] NOT NULL, - StudentUSI [INT] NOT NULL, - TermDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentAcademicRecord PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentAssessment] -( - AssessmentIdentifier [NVARCHAR](60) NOT NULL, - Namespace [NVARCHAR](255) NOT NULL, - StudentAssessmentIdentifier [NVARCHAR](60) NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentAssessment PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentCTEProgramAssociation] -( - BeginDate [DATE] NOT NULL, - EducationOrganizationId [INT] NOT NULL, - ProgramEducationOrganizationId [INT] NOT NULL, - ProgramName [NVARCHAR](60) NOT NULL, - ProgramTypeDescriptorId [INT] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentCTEProgramAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentCharacteristicDescriptor] -( - StudentCharacteristicDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentCharacteristicDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentCohortAssociation] -( - BeginDate [DATE] NOT NULL, - CohortIdentifier [NVARCHAR](20) NOT NULL, - EducationOrganizationId [INT] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentCohortAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentCompetencyObjective] -( - GradingPeriodDescriptorId [INT] NOT NULL, - GradingPeriodSchoolId [INT] NOT NULL, - GradingPeriodSchoolYear [SMALLINT] NOT NULL, - GradingPeriodSequence [INT] NOT NULL, - Objective [NVARCHAR](60) NOT NULL, - ObjectiveEducationOrganizationId [INT] NOT NULL, - ObjectiveGradeLevelDescriptorId [INT] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentCompetencyObjective PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentDisciplineIncidentAssociation] -( - IncidentIdentifier [NVARCHAR](20) NOT NULL, - SchoolId [INT] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentDisciplineIncidentAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentDisciplineIncidentBehaviorAssociation] -( - BehaviorDescriptorId [INT] NOT NULL, - IncidentIdentifier [NVARCHAR](20) NOT NULL, - SchoolId [INT] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentDisciplineIncidentBehaviorAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentDisciplineIncidentNonOffenderAssociation] -( - IncidentIdentifier [NVARCHAR](20) NOT NULL, - SchoolId [INT] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentDisciplineIncidentNonOffenderAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentEducationOrganizationAssociation] -( - EducationOrganizationId [INT] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentEducationOrganizationAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentEducationOrganizationResponsibilityAssociation] -( - BeginDate [DATE] NOT NULL, - EducationOrganizationId [INT] NOT NULL, - ResponsibilityDescriptorId [INT] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentEducationOrganizationResponsibilityAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentGradebookEntry] -( - BeginDate [DATE] NOT NULL, - DateAssigned [DATE] NOT NULL, - GradebookEntryTitle [NVARCHAR](60) NOT NULL, - LocalCourseCode [NVARCHAR](60) NOT NULL, - SchoolId [INT] NOT NULL, - SchoolYear [SMALLINT] NOT NULL, - SectionIdentifier [NVARCHAR](255) NOT NULL, - SessionName [NVARCHAR](60) NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentGradebookEntry PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentHomelessProgramAssociation] -( - BeginDate [DATE] NOT NULL, - EducationOrganizationId [INT] NOT NULL, - ProgramEducationOrganizationId [INT] NOT NULL, - ProgramName [NVARCHAR](60) NOT NULL, - ProgramTypeDescriptorId [INT] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentHomelessProgramAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentIdentificationSystemDescriptor] -( - StudentIdentificationSystemDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentIdentificationSystemDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentInterventionAssociation] -( - EducationOrganizationId [INT] NOT NULL, - InterventionIdentificationCode [NVARCHAR](60) NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentInterventionAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentInterventionAttendanceEvent] -( - AttendanceEventCategoryDescriptorId [INT] NOT NULL, - EducationOrganizationId [INT] NOT NULL, - EventDate [DATE] NOT NULL, - InterventionIdentificationCode [NVARCHAR](60) NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentInterventionAttendanceEvent PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentLanguageInstructionProgramAssociation] -( - BeginDate [DATE] NOT NULL, - EducationOrganizationId [INT] NOT NULL, - ProgramEducationOrganizationId [INT] NOT NULL, - ProgramName [NVARCHAR](60) NOT NULL, - ProgramTypeDescriptorId [INT] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentLanguageInstructionProgramAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentLearningObjective] -( - GradingPeriodDescriptorId [INT] NOT NULL, - GradingPeriodSchoolId [INT] NOT NULL, - GradingPeriodSchoolYear [SMALLINT] NOT NULL, - GradingPeriodSequence [INT] NOT NULL, - LearningObjectiveId [NVARCHAR](60) NOT NULL, - Namespace [NVARCHAR](255) NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentLearningObjective PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentMigrantEducationProgramAssociation] -( - BeginDate [DATE] NOT NULL, - EducationOrganizationId [INT] NOT NULL, - ProgramEducationOrganizationId [INT] NOT NULL, - ProgramName [NVARCHAR](60) NOT NULL, - ProgramTypeDescriptorId [INT] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentMigrantEducationProgramAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentNeglectedOrDelinquentProgramAssociation] -( - BeginDate [DATE] NOT NULL, - EducationOrganizationId [INT] NOT NULL, - ProgramEducationOrganizationId [INT] NOT NULL, - ProgramName [NVARCHAR](60) NOT NULL, - ProgramTypeDescriptorId [INT] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentNeglectedOrDelinquentProgramAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentParentAssociation] -( - ParentUSI [INT] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentParentAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentParticipationCodeDescriptor] -( - StudentParticipationCodeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentParticipationCodeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentProgramAssociation] -( - BeginDate [DATE] NOT NULL, - EducationOrganizationId [INT] NOT NULL, - ProgramEducationOrganizationId [INT] NOT NULL, - ProgramName [NVARCHAR](60) NOT NULL, - ProgramTypeDescriptorId [INT] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentProgramAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentProgramAttendanceEvent] -( - AttendanceEventCategoryDescriptorId [INT] NOT NULL, - EducationOrganizationId [INT] NOT NULL, - EventDate [DATE] NOT NULL, - ProgramEducationOrganizationId [INT] NOT NULL, - ProgramName [NVARCHAR](60) NOT NULL, - ProgramTypeDescriptorId [INT] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentProgramAttendanceEvent PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentSchoolAssociation] -( - EntryDate [DATE] NOT NULL, - SchoolId [INT] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentSchoolAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentSchoolAttendanceEvent] -( - AttendanceEventCategoryDescriptorId [INT] NOT NULL, - EventDate [DATE] NOT NULL, - SchoolId [INT] NOT NULL, - SchoolYear [SMALLINT] NOT NULL, - SessionName [NVARCHAR](60) NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentSchoolAttendanceEvent PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentSchoolFoodServiceProgramAssociation] -( - BeginDate [DATE] NOT NULL, - EducationOrganizationId [INT] NOT NULL, - ProgramEducationOrganizationId [INT] NOT NULL, - ProgramName [NVARCHAR](60) NOT NULL, - ProgramTypeDescriptorId [INT] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentSchoolFoodServiceProgramAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentSectionAssociation] -( - BeginDate [DATE] NOT NULL, - LocalCourseCode [NVARCHAR](60) NOT NULL, - SchoolId [INT] NOT NULL, - SchoolYear [SMALLINT] NOT NULL, - SectionIdentifier [NVARCHAR](255) NOT NULL, - SessionName [NVARCHAR](60) NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentSectionAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentSectionAttendanceEvent] -( - AttendanceEventCategoryDescriptorId [INT] NOT NULL, - EventDate [DATE] NOT NULL, - LocalCourseCode [NVARCHAR](60) NOT NULL, - SchoolId [INT] NOT NULL, - SchoolYear [SMALLINT] NOT NULL, - SectionIdentifier [NVARCHAR](255) NOT NULL, - SessionName [NVARCHAR](60) NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentSectionAttendanceEvent PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentSpecialEducationProgramAssociation] -( - BeginDate [DATE] NOT NULL, - EducationOrganizationId [INT] NOT NULL, - ProgramEducationOrganizationId [INT] NOT NULL, - ProgramName [NVARCHAR](60) NOT NULL, - ProgramTypeDescriptorId [INT] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentSpecialEducationProgramAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[StudentTitleIPartAProgramAssociation] -( - BeginDate [DATE] NOT NULL, - EducationOrganizationId [INT] NOT NULL, - ProgramEducationOrganizationId [INT] NOT NULL, - ProgramName [NVARCHAR](60) NOT NULL, - ProgramTypeDescriptorId [INT] NOT NULL, - StudentUSI [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_StudentTitleIPartAProgramAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[Survey] -( - Namespace [NVARCHAR](255) NOT NULL, - SurveyIdentifier [NVARCHAR](60) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_Survey PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SurveyCategoryDescriptor] -( - SurveyCategoryDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SurveyCategoryDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SurveyCourseAssociation] -( - CourseCode [NVARCHAR](60) NOT NULL, - EducationOrganizationId [INT] NOT NULL, - Namespace [NVARCHAR](255) NOT NULL, - SurveyIdentifier [NVARCHAR](60) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SurveyCourseAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SurveyLevelDescriptor] -( - SurveyLevelDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SurveyLevelDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SurveyProgramAssociation] -( - EducationOrganizationId [INT] NOT NULL, - Namespace [NVARCHAR](255) NOT NULL, - ProgramName [NVARCHAR](60) NOT NULL, - ProgramTypeDescriptorId [INT] NOT NULL, - SurveyIdentifier [NVARCHAR](60) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SurveyProgramAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SurveyQuestion] -( - Namespace [NVARCHAR](255) NOT NULL, - QuestionCode [NVARCHAR](60) NOT NULL, - SurveyIdentifier [NVARCHAR](60) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SurveyQuestion PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SurveyQuestionResponse] -( - Namespace [NVARCHAR](255) NOT NULL, - QuestionCode [NVARCHAR](60) NOT NULL, - SurveyIdentifier [NVARCHAR](60) NOT NULL, - SurveyResponseIdentifier [NVARCHAR](60) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SurveyQuestionResponse PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SurveyResponse] -( - Namespace [NVARCHAR](255) NOT NULL, - SurveyIdentifier [NVARCHAR](60) NOT NULL, - SurveyResponseIdentifier [NVARCHAR](60) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SurveyResponse PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SurveyResponseEducationOrganizationTargetAssociation] -( - EducationOrganizationId [INT] NOT NULL, - Namespace [NVARCHAR](255) NOT NULL, - SurveyIdentifier [NVARCHAR](60) NOT NULL, - SurveyResponseIdentifier [NVARCHAR](60) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SurveyResponseEducationOrganizationTargetAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SurveyResponseStaffTargetAssociation] -( - Namespace [NVARCHAR](255) NOT NULL, - StaffUSI [INT] NOT NULL, - SurveyIdentifier [NVARCHAR](60) NOT NULL, - SurveyResponseIdentifier [NVARCHAR](60) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SurveyResponseStaffTargetAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SurveySection] -( - Namespace [NVARCHAR](255) NOT NULL, - SurveyIdentifier [NVARCHAR](60) NOT NULL, - SurveySectionTitle [NVARCHAR](255) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SurveySection PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SurveySectionAssociation] -( - LocalCourseCode [NVARCHAR](60) NOT NULL, - Namespace [NVARCHAR](255) NOT NULL, - SchoolId [INT] NOT NULL, - SchoolYear [SMALLINT] NOT NULL, - SectionIdentifier [NVARCHAR](255) NOT NULL, - SessionName [NVARCHAR](60) NOT NULL, - SurveyIdentifier [NVARCHAR](60) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SurveySectionAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SurveySectionResponse] -( - Namespace [NVARCHAR](255) NOT NULL, - SurveyIdentifier [NVARCHAR](60) NOT NULL, - SurveyResponseIdentifier [NVARCHAR](60) NOT NULL, - SurveySectionTitle [NVARCHAR](255) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SurveySectionResponse PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SurveySectionResponseEducationOrganizationTargetAssociation] -( - EducationOrganizationId [INT] NOT NULL, - Namespace [NVARCHAR](255) NOT NULL, - SurveyIdentifier [NVARCHAR](60) NOT NULL, - SurveyResponseIdentifier [NVARCHAR](60) NOT NULL, - SurveySectionTitle [NVARCHAR](255) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SurveySectionResponseEducationOrganizationTargetAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[SurveySectionResponseStaffTargetAssociation] -( - Namespace [NVARCHAR](255) NOT NULL, - StaffUSI [INT] NOT NULL, - SurveyIdentifier [NVARCHAR](60) NOT NULL, - SurveyResponseIdentifier [NVARCHAR](60) NOT NULL, - SurveySectionTitle [NVARCHAR](255) NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_SurveySectionResponseStaffTargetAssociation PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[TeachingCredentialBasisDescriptor] -( - TeachingCredentialBasisDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_TeachingCredentialBasisDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[TeachingCredentialDescriptor] -( - TeachingCredentialDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_TeachingCredentialDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[TechnicalSkillsAssessmentDescriptor] -( - TechnicalSkillsAssessmentDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_TechnicalSkillsAssessmentDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[TelephoneNumberTypeDescriptor] -( - TelephoneNumberTypeDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_TelephoneNumberTypeDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[TermDescriptor] -( - TermDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_TermDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[TitleIPartAParticipantDescriptor] -( - TitleIPartAParticipantDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_TitleIPartAParticipantDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[TitleIPartAProgramServiceDescriptor] -( - TitleIPartAProgramServiceDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_TitleIPartAProgramServiceDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[TitleIPartASchoolDesignationDescriptor] -( - TitleIPartASchoolDesignationDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_TitleIPartASchoolDesignationDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[TribalAffiliationDescriptor] -( - TribalAffiliationDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_TribalAffiliationDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[VisaDescriptor] -( - VisaDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_VisaDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - -CREATE TABLE [tracked_deletes_edfi].[WeaponDescriptor] -( - WeaponDescriptorId [INT] NOT NULL, - Id uniqueidentifier NOT NULL, - ChangeVersion bigint NOT NULL, - CONSTRAINT PK_WeaponDescriptor PRIMARY KEY CLUSTERED (ChangeVersion) -) - diff --git a/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0052-DropDerivedTablesDeleteTriggers.sql b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0052-DropDerivedTablesDeleteTriggers.sql new file mode 100644 index 0000000000..2f926f24ea --- /dev/null +++ b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0052-DropDerivedTablesDeleteTriggers.sql @@ -0,0 +1,43 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +DROP TRIGGER IF EXISTS [edfi].[edfi_CommunityOrganization_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_CommunityProvider_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Descriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_EducationOrganizationNetwork_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_EducationServiceCenter_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_LocalEducationAgency_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_OrganizationDepartment_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_PostSecondaryInstitution_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_School_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StateEducationAgency_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentCTEProgramAssociation_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentHomelessProgramAssociation_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentLanguageInstructionProgramAssociation_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentMigrantEducationProgramAssociation_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentNeglectedOrDelinquentProgramAssociation_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentProgramAssociation_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentSchoolFoodServiceProgramAssociation_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentSpecialEducationProgramAssociation_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentTitleIPartAProgramAssociation_TR_DeleteTracking] +GO diff --git a/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0054-DropTrackedDeleteTables.sql b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0054-DropTrackedDeleteTables.sql new file mode 100644 index 0000000000..d0d8b2b7b9 --- /dev/null +++ b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0054-DropTrackedDeleteTables.sql @@ -0,0 +1,299 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AbsenceEventCategoryDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AcademicHonorCategoryDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AcademicSubjectDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AcademicWeek] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AccommodationDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[Account] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AccountabilityRating] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AccountClassificationDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AccountCode] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AchievementCategoryDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[Actual] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AdditionalCreditTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AddressTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AdministrationEnvironmentDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AdministrativeFundingControlDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AncestryEthnicOriginDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[Assessment] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AssessmentCategoryDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AssessmentIdentificationSystemDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AssessmentItem] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AssessmentItemCategoryDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AssessmentItemResultDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AssessmentPeriodDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AssessmentReportingMethodDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AssessmentScoreRangeLearningStandard] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AttemptStatusDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[AttendanceEventCategoryDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[BehaviorDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[BellSchedule] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[Budget] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[Calendar] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CalendarDate] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CalendarEventDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CalendarTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CareerPathwayDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CharterApprovalAgencyTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CharterStatusDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CitizenshipStatusDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ClassPeriod] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ClassroomPositionDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[Cohort] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CohortScopeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CohortTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CohortYearTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CommunityOrganization] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CommunityProvider] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CommunityProviderLicense] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CompetencyLevelDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CompetencyObjective] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ContactTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ContentClassDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ContinuationOfServicesReasonDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ContractedStaff] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CostRateDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CountryDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[Course] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CourseAttemptResultDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CourseDefinedByDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CourseGPAApplicabilityDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CourseIdentificationSystemDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CourseLevelCharacteristicDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CourseOffering] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CourseRepeatCodeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CourseTranscript] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[Credential] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CredentialFieldDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CredentialTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CreditCategoryDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CreditTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CTEProgramServiceDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[CurriculumUsedDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[DeliveryMethodDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[Descriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[DiagnosisDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[DiplomaLevelDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[DiplomaTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[DisabilityDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[DisabilityDesignationDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[DisabilityDeterminationSourceTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[DisciplineAction] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[DisciplineActionLengthDifferenceReasonDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[DisciplineDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[DisciplineIncident] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[DisciplineIncidentParticipationCodeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[EducationalEnvironmentDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[EducationContent] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[EducationOrganization] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[EducationOrganizationCategoryDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[EducationOrganizationIdentificationSystemDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[EducationOrganizationInterventionPrescriptionAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[EducationOrganizationNetwork] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[EducationOrganizationNetworkAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[EducationOrganizationPeerAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[EducationPlanDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[EducationServiceCenter] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ElectronicMailTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[EmploymentStatusDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[EntryGradeLevelReasonDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[EntryTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[EventCircumstanceDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ExitWithdrawTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[FeederSchoolAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[GeneralStudentProgramAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[Grade] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[GradebookEntry] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[GradebookEntryTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[GradeLevelDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[GradePointAverageTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[GradeTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[GradingPeriod] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[GradingPeriodDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[GraduationPlan] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[GraduationPlanTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[GunFreeSchoolsActReportingStatusDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[HomelessPrimaryNighttimeResidenceDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[HomelessProgramServiceDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[IdentificationDocumentUseDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[IncidentLocationDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[IndicatorDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[IndicatorGroupDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[IndicatorLevelDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[InstitutionTelephoneNumberTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[InteractivityStyleDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[InternetAccessDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[Intervention] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[InterventionClassDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[InterventionEffectivenessRatingDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[InterventionPrescription] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[InterventionStudy] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[LanguageDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[LanguageInstructionProgramServiceDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[LanguageUseDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[LearningObjective] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[LearningStandard] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[LearningStandardCategoryDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[LearningStandardEquivalenceAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[LearningStandardEquivalenceStrengthDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[LearningStandardScopeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[LevelOfEducationDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[LicenseStatusDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[LicenseTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[LimitedEnglishProficiencyDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[LocaleDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[LocalEducationAgency] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[LocalEducationAgencyCategoryDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[Location] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[MagnetSpecialProgramEmphasisSchoolDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[MediumOfInstructionDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[MethodCreditEarnedDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[MigrantEducationProgramServiceDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[MonitoredDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[NeglectedOrDelinquentProgramDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[NeglectedOrDelinquentProgramServiceDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[NetworkPurposeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ObjectiveAssessment] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[OldEthnicityDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[OpenStaffPosition] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[OperationalStatusDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[OrganizationDepartment] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[OtherNameTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[Parent] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ParticipationDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ParticipationStatusDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[Payroll] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[PerformanceBaseConversionDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[PerformanceLevelDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[Person] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[PersonalInformationVerificationDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[PlatformTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[PopulationServedDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[PostingResultDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[PostSecondaryEvent] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[PostSecondaryEventCategoryDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[PostSecondaryInstitution] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[PostSecondaryInstitutionLevelDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ProficiencyDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[Program] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ProgramAssignmentDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ProgramCharacteristicDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ProgramSponsorDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ProgramTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ProgressDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ProgressLevelDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ProviderCategoryDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ProviderProfitabilityDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ProviderStatusDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[PublicationStatusDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[QuestionFormDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[RaceDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ReasonExitedDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ReasonNotTestedDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[RecognitionTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[RelationDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[RepeatIdentifierDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ReportCard] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ReporterDescriptionDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ResidencyStatusDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ResponseIndicatorDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ResponsibilityDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[RestraintEvent] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[RestraintEventReasonDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ResultDatatypeTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[RetestIndicatorDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[School] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SchoolCategoryDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SchoolChoiceImplementStatusDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SchoolFoodServiceProgramServiceDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SchoolTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SchoolYearType] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[Section] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SectionAttendanceTakenEvent] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SectionCharacteristicDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SeparationDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SeparationReasonDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[ServiceDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[Session] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SexDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SourceSystemDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SpecialEducationProgramServiceDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SpecialEducationSettingDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[Staff] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StaffAbsenceEvent] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StaffClassificationDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StaffCohortAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StaffDisciplineIncidentAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StaffEducationOrganizationAssignmentAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StaffEducationOrganizationContactAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StaffEducationOrganizationEmploymentAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StaffIdentificationSystemDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StaffLeave] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StaffLeaveEventCategoryDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StaffProgramAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StaffSchoolAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StaffSectionAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StateAbbreviationDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StateEducationAgency] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[Student] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentAcademicRecord] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentAssessment] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentCharacteristicDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentCohortAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentCompetencyObjective] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentCTEProgramAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentDisciplineIncidentAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentDisciplineIncidentBehaviorAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentDisciplineIncidentNonOffenderAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentEducationOrganizationAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentEducationOrganizationResponsibilityAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentGradebookEntry] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentHomelessProgramAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentIdentificationSystemDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentInterventionAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentInterventionAttendanceEvent] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentLanguageInstructionProgramAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentLearningObjective] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentMigrantEducationProgramAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentNeglectedOrDelinquentProgramAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentParentAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentParticipationCodeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentProgramAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentProgramAttendanceEvent] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentSchoolAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentSchoolAttendanceEvent] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentSchoolFoodServiceProgramAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentSectionAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentSectionAttendanceEvent] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentSpecialEducationProgramAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[StudentTitleIPartAProgramAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[Survey] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SurveyCategoryDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SurveyCourseAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SurveyLevelDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SurveyProgramAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SurveyQuestion] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SurveyQuestionResponse] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SurveyResponse] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SurveyResponseEducationOrganizationTargetAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SurveyResponseStaffTargetAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SurveySection] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SurveySectionAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SurveySectionResponse] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SurveySectionResponseEducationOrganizationTargetAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[SurveySectionResponseStaffTargetAssociation] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[TeachingCredentialBasisDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[TeachingCredentialDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[TechnicalSkillsAssessmentDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[TelephoneNumberTypeDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[TermDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[TitleIPartAParticipantDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[TitleIPartAProgramServiceDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[TitleIPartASchoolDesignationDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[TribalAffiliationDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[VisaDescriptor] +DROP TABLE IF EXISTS [tracked_deletes_edfi].[WeaponDescriptor] diff --git a/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0045-CreateTrackedDeleteSchema.sql b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0056-DropTrackedDeleteSchema.sql similarity index 65% rename from Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0045-CreateTrackedDeleteSchema.sql rename to Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0056-DropTrackedDeleteSchema.sql index 9f2618d5ad..c2cecfcac0 100644 --- a/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0045-CreateTrackedDeleteSchema.sql +++ b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0056-DropTrackedDeleteSchema.sql @@ -3,6 +3,4 @@ -- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. -- See the LICENSE and NOTICES files in the project root for more information. -IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = N'tracked_deletes_edfi') -EXEC sys.sp_executesql N'CREATE SCHEMA [tracked_deletes_edfi]' -GO \ No newline at end of file +DROP SCHEMA IF EXISTS [tracked_deletes_edfi]; diff --git a/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0070-AddIndexChangeVersionForTables.sql b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0070-AddIndexChangeVersionForTables.sql index f2f665ab2c..1a6689e8fc 100644 --- a/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0070-AddIndexChangeVersionForTables.sql +++ b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0070-AddIndexChangeVersionForTables.sql @@ -16,14 +16,14 @@ BEGIN TRANSACTION COMMIT BEGIN TRANSACTION - IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'edfi.AccountCode') AND name = N'UX_AccountCode_ChangeVersion') - CREATE INDEX [UX_AccountCode_ChangeVersion] ON [edfi].[AccountCode] ([ChangeVersion] ASC) + IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'edfi.AccountabilityRating') AND name = N'UX_AccountabilityRating_ChangeVersion') + CREATE INDEX [UX_AccountabilityRating_ChangeVersion] ON [edfi].[AccountabilityRating] ([ChangeVersion] ASC) GO COMMIT BEGIN TRANSACTION - IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'edfi.AccountabilityRating') AND name = N'UX_AccountabilityRating_ChangeVersion') - CREATE INDEX [UX_AccountabilityRating_ChangeVersion] ON [edfi].[AccountabilityRating] ([ChangeVersion] ASC) + IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'edfi.AccountCode') AND name = N'UX_AccountCode_ChangeVersion') + CREATE INDEX [UX_AccountCode_ChangeVersion] ON [edfi].[AccountCode] ([ChangeVersion] ASC) GO COMMIT diff --git a/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0110-AddSnapshot-Tables.sql b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0110-AddSnapshot-Tables.sql index e9fa72779f..4ec1d76682 100644 --- a/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0110-AddSnapshot-Tables.sql +++ b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0110-AddSnapshot-Tables.sql @@ -1,19 +1,22 @@ --- Table [changes].[Snapshot] -- -CREATE TABLE [changes].[Snapshot] ( - [SnapshotIdentifier] [NVARCHAR](32) NOT NULL, - [SnapshotDateTime] [DATETIME2](7) NOT NULL, - [CreateDate] [DATETIME2] NOT NULL, - [LastModifiedDate] [DATETIME2] NOT NULL, - [Id] [UNIQUEIDENTIFIER] NOT NULL, - CONSTRAINT [Snapshot_PK] PRIMARY KEY CLUSTERED ( - [SnapshotIdentifier] ASC - ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] -) ON [PRIMARY] -GO -ALTER TABLE [changes].[Snapshot] ADD CONSTRAINT [Snapshot_DF_CreateDate] DEFAULT (getdate()) FOR [CreateDate] -GO -ALTER TABLE [changes].[Snapshot] ADD CONSTRAINT [Snapshot_DF_Id] DEFAULT (newid()) FOR [Id] -GO -ALTER TABLE [changes].[Snapshot] ADD CONSTRAINT [Snapshot_DF_LastModifiedDate] DEFAULT (getdate()) FOR [LastModifiedDate] -GO +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[changes].[Snapshot]')) +BEGIN + -- Table [changes].[Snapshot] -- + CREATE TABLE [changes].[Snapshot] ( + [SnapshotIdentifier] [NVARCHAR](32) NOT NULL, + [SnapshotDateTime] [DATETIME2](7) NOT NULL, + [CreateDate] [DATETIME2] NOT NULL, + [LastModifiedDate] [DATETIME2] NOT NULL, + [Id] [UNIQUEIDENTIFIER] NOT NULL, + CONSTRAINT [Snapshot_PK] PRIMARY KEY CLUSTERED ( + [SnapshotIdentifier] 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 [changes].[Snapshot] ADD CONSTRAINT [Snapshot_DF_CreateDate] DEFAULT (getdate()) FOR [CreateDate] + + ALTER TABLE [changes].[Snapshot] ADD CONSTRAINT [Snapshot_DF_Id] DEFAULT (newid()) FOR [Id] + + ALTER TABLE [changes].[Snapshot] ADD CONSTRAINT [Snapshot_DF_LastModifiedDate] DEFAULT (getdate()) FOR [LastModifiedDate] + +END +GO \ No newline at end of file diff --git a/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0130-AddSnapshotExtendedProperties.sql b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0130-AddSnapshotExtendedProperties.sql index 5ec67dd620..9f9ef90d3a 100644 --- a/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0130-AddSnapshotExtendedProperties.sql +++ b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0130-AddSnapshotExtendedProperties.sql @@ -1,8 +1,12 @@ -- Extended Properties [changes].[Snapshot] -- +IF NOT EXISTS (SELECT 1 FROM sys.extended_properties WHERE [major_id] = OBJECT_ID('[changes].[Snapshot]') AND [name] = N'MS_Description' AND [minor_id] = 0) EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Contains information about a snapshot used to create isolation from ongoing changes for API client synchronization.', @level0type=N'SCHEMA', @level0name=N'changes', @level1type=N'TABLE', @level1name=N'Snapshot' GO + +IF NOT EXISTS (SELECT 1 FROM sys.extended_properties WHERE [major_id] = OBJECT_ID('[changes].[Snapshot]') AND [name] = N'MS_Description' AND [minor_id] = (SELECT [column_id] FROM sys.columns WHERE [name] = 'SnapshotIdentifier' AND [object_id] = OBJECT_ID('[changes].[Snapshot]'))) EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'The unique identifier of the snapshot.', @level0type=N'SCHEMA', @level0name=N'changes', @level1type=N'TABLE', @level1name=N'Snapshot', @level2type=N'COLUMN', @level2name=N'SnapshotIdentifier' GO + +IF NOT EXISTS (SELECT 1 FROM sys.extended_properties WHERE [major_id] = OBJECT_ID('[changes].[Snapshot]') AND [name] = N'MS_Description' AND [minor_id] = (SELECT [column_id] FROM sys.columns WHERE [name] = 'SnapshotDateTime' AND [object_id] = OBJECT_ID('[changes].[Snapshot]'))) EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'The date and time that the snapshot was initiated.', @level0type=N'SCHEMA', @level0name=N'changes', @level1type=N'TABLE', @level1name=N'Snapshot', @level2type=N'COLUMN', @level2name=N'SnapshotDateTime' GO - diff --git a/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0200-CreateTrackedChangeTables.sql b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0200-CreateTrackedChangeTables.sql new file mode 100644 index 0000000000..c829e27ae9 --- /dev/null +++ b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0200-CreateTrackedChangeTables.sql @@ -0,0 +1,1938 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = N'tracked_changes_edfi') +EXEC sys.sp_executesql N'CREATE SCHEMA [tracked_changes_edfi]' +GO + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[AcademicWeek]')) +CREATE TABLE [tracked_changes_edfi].[AcademicWeek] +( + OldSchoolId int NOT NULL, + OldWeekIdentifier nvarchar(80) NOT NULL, + NewSchoolId int NULL, + NewWeekIdentifier nvarchar(80) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT AcademicWeek_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[Account]')) +CREATE TABLE [tracked_changes_edfi].[Account] +( + OldAccountIdentifier nvarchar(50) NOT NULL, + OldEducationOrganizationId int NOT NULL, + OldFiscalYear int NOT NULL, + NewAccountIdentifier nvarchar(50) NULL, + NewEducationOrganizationId int NULL, + NewFiscalYear int NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT Account_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[AccountabilityRating]')) +CREATE TABLE [tracked_changes_edfi].[AccountabilityRating] +( + OldEducationOrganizationId int NOT NULL, + OldRatingTitle nvarchar(60) NOT NULL, + OldSchoolYear smallint NOT NULL, + NewEducationOrganizationId int NULL, + NewRatingTitle nvarchar(60) NULL, + NewSchoolYear smallint NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT AccountabilityRating_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[AccountCode]')) +CREATE TABLE [tracked_changes_edfi].[AccountCode] +( + OldAccountClassificationDescriptorId int NOT NULL, + OldAccountClassificationDescriptorNamespace nvarchar(255) NOT NULL, + OldAccountClassificationDescriptorCodeValue nvarchar(50) NOT NULL, + OldAccountCodeNumber nvarchar(50) NOT NULL, + OldEducationOrganizationId int NOT NULL, + OldFiscalYear int NOT NULL, + NewAccountClassificationDescriptorId int NULL, + NewAccountClassificationDescriptorNamespace nvarchar(255) NULL, + NewAccountClassificationDescriptorCodeValue nvarchar(50) NULL, + NewAccountCodeNumber nvarchar(50) NULL, + NewEducationOrganizationId int NULL, + NewFiscalYear int NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT AccountCode_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[Actual]')) +CREATE TABLE [tracked_changes_edfi].[Actual] +( + OldAccountIdentifier nvarchar(50) NOT NULL, + OldAsOfDate date NOT NULL, + OldEducationOrganizationId int NOT NULL, + OldFiscalYear int NOT NULL, + NewAccountIdentifier nvarchar(50) NULL, + NewAsOfDate date NULL, + NewEducationOrganizationId int NULL, + NewFiscalYear int NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT Actual_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[Assessment]')) +CREATE TABLE [tracked_changes_edfi].[Assessment] +( + OldAssessmentIdentifier nvarchar(60) NOT NULL, + OldNamespace nvarchar(255) NOT NULL, + NewAssessmentIdentifier nvarchar(60) NULL, + NewNamespace nvarchar(255) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT Assessment_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[AssessmentItem]')) +CREATE TABLE [tracked_changes_edfi].[AssessmentItem] +( + OldAssessmentIdentifier nvarchar(60) NOT NULL, + OldIdentificationCode nvarchar(60) NOT NULL, + OldNamespace nvarchar(255) NOT NULL, + NewAssessmentIdentifier nvarchar(60) NULL, + NewIdentificationCode nvarchar(60) NULL, + NewNamespace nvarchar(255) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT AssessmentItem_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[AssessmentScoreRangeLearningStandard]')) +CREATE TABLE [tracked_changes_edfi].[AssessmentScoreRangeLearningStandard] +( + OldAssessmentIdentifier nvarchar(60) NOT NULL, + OldNamespace nvarchar(255) NOT NULL, + OldScoreRangeId nvarchar(60) NOT NULL, + NewAssessmentIdentifier nvarchar(60) NULL, + NewNamespace nvarchar(255) NULL, + NewScoreRangeId nvarchar(60) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT AssessmentScoreRangeLearningStandard_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[BellSchedule]')) +CREATE TABLE [tracked_changes_edfi].[BellSchedule] +( + OldBellScheduleName nvarchar(60) NOT NULL, + OldSchoolId int NOT NULL, + NewBellScheduleName nvarchar(60) NULL, + NewSchoolId int NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT BellSchedule_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[Budget]')) +CREATE TABLE [tracked_changes_edfi].[Budget] +( + OldAccountIdentifier nvarchar(50) NOT NULL, + OldAsOfDate date NOT NULL, + OldEducationOrganizationId int NOT NULL, + OldFiscalYear int NOT NULL, + NewAccountIdentifier nvarchar(50) NULL, + NewAsOfDate date NULL, + NewEducationOrganizationId int NULL, + NewFiscalYear int NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT Budget_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[Calendar]')) +CREATE TABLE [tracked_changes_edfi].[Calendar] +( + OldCalendarCode nvarchar(60) NOT NULL, + OldSchoolId int NOT NULL, + OldSchoolYear smallint NOT NULL, + NewCalendarCode nvarchar(60) NULL, + NewSchoolId int NULL, + NewSchoolYear smallint NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT Calendar_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[CalendarDate]')) +CREATE TABLE [tracked_changes_edfi].[CalendarDate] +( + OldCalendarCode nvarchar(60) NOT NULL, + OldDate date NOT NULL, + OldSchoolId int NOT NULL, + OldSchoolYear smallint NOT NULL, + NewCalendarCode nvarchar(60) NULL, + NewDate date NULL, + NewSchoolId int NULL, + NewSchoolYear smallint NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT CalendarDate_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[ClassPeriod]')) +CREATE TABLE [tracked_changes_edfi].[ClassPeriod] +( + OldClassPeriodName nvarchar(60) NOT NULL, + OldSchoolId int NOT NULL, + NewClassPeriodName nvarchar(60) NULL, + NewSchoolId int NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT ClassPeriod_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[Cohort]')) +CREATE TABLE [tracked_changes_edfi].[Cohort] +( + OldCohortIdentifier nvarchar(20) NOT NULL, + OldEducationOrganizationId int NOT NULL, + NewCohortIdentifier nvarchar(20) NULL, + NewEducationOrganizationId int NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT Cohort_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[CommunityProviderLicense]')) +CREATE TABLE [tracked_changes_edfi].[CommunityProviderLicense] +( + OldCommunityProviderId int NOT NULL, + OldLicenseIdentifier nvarchar(20) NOT NULL, + OldLicensingOrganization nvarchar(75) NOT NULL, + NewCommunityProviderId int NULL, + NewLicenseIdentifier nvarchar(20) NULL, + NewLicensingOrganization nvarchar(75) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT CommunityProviderLicense_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[CompetencyObjective]')) +CREATE TABLE [tracked_changes_edfi].[CompetencyObjective] +( + OldEducationOrganizationId int NOT NULL, + OldObjective nvarchar(60) NOT NULL, + OldObjectiveGradeLevelDescriptorId int NOT NULL, + OldObjectiveGradeLevelDescriptorNamespace nvarchar(255) NOT NULL, + OldObjectiveGradeLevelDescriptorCodeValue nvarchar(50) NOT NULL, + NewEducationOrganizationId int NULL, + NewObjective nvarchar(60) NULL, + NewObjectiveGradeLevelDescriptorId int NULL, + NewObjectiveGradeLevelDescriptorNamespace nvarchar(255) NULL, + NewObjectiveGradeLevelDescriptorCodeValue nvarchar(50) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT CompetencyObjective_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[ContractedStaff]')) +CREATE TABLE [tracked_changes_edfi].[ContractedStaff] +( + OldAccountIdentifier nvarchar(50) NOT NULL, + OldAsOfDate date NOT NULL, + OldEducationOrganizationId int NOT NULL, + OldFiscalYear int NOT NULL, + OldStaffUSI int NOT NULL, + OldStaffUniqueId nvarchar(32) NOT NULL, + NewAccountIdentifier nvarchar(50) NULL, + NewAsOfDate date NULL, + NewEducationOrganizationId int NULL, + NewFiscalYear int NULL, + NewStaffUSI int NULL, + NewStaffUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT ContractedStaff_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[Course]')) +CREATE TABLE [tracked_changes_edfi].[Course] +( + OldCourseCode nvarchar(60) NOT NULL, + OldEducationOrganizationId int NOT NULL, + NewCourseCode nvarchar(60) NULL, + NewEducationOrganizationId int NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT Course_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[CourseOffering]')) +CREATE TABLE [tracked_changes_edfi].[CourseOffering] +( + OldLocalCourseCode nvarchar(60) NOT NULL, + OldSchoolId int NOT NULL, + OldSchoolYear smallint NOT NULL, + OldSessionName nvarchar(60) NOT NULL, + NewLocalCourseCode nvarchar(60) NULL, + NewSchoolId int NULL, + NewSchoolYear smallint NULL, + NewSessionName nvarchar(60) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT CourseOffering_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[CourseTranscript]')) +CREATE TABLE [tracked_changes_edfi].[CourseTranscript] +( + OldCourseAttemptResultDescriptorId int NOT NULL, + OldCourseAttemptResultDescriptorNamespace nvarchar(255) NOT NULL, + OldCourseAttemptResultDescriptorCodeValue nvarchar(50) NOT NULL, + OldCourseCode nvarchar(60) NOT NULL, + OldCourseEducationOrganizationId int NOT NULL, + OldEducationOrganizationId int NOT NULL, + OldSchoolYear smallint NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + OldTermDescriptorId int NOT NULL, + OldTermDescriptorNamespace nvarchar(255) NOT NULL, + OldTermDescriptorCodeValue nvarchar(50) NOT NULL, + NewCourseAttemptResultDescriptorId int NULL, + NewCourseAttemptResultDescriptorNamespace nvarchar(255) NULL, + NewCourseAttemptResultDescriptorCodeValue nvarchar(50) NULL, + NewCourseCode nvarchar(60) NULL, + NewCourseEducationOrganizationId int NULL, + NewEducationOrganizationId int NULL, + NewSchoolYear smallint NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + NewTermDescriptorId int NULL, + NewTermDescriptorNamespace nvarchar(255) NULL, + NewTermDescriptorCodeValue nvarchar(50) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT CourseTranscript_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[Credential]')) +CREATE TABLE [tracked_changes_edfi].[Credential] +( + OldCredentialIdentifier nvarchar(60) NOT NULL, + OldStateOfIssueStateAbbreviationDescriptorId int NOT NULL, + OldStateOfIssueStateAbbreviationDescriptorNamespace nvarchar(255) NOT NULL, + OldStateOfIssueStateAbbreviationDescriptorCodeValue nvarchar(50) NOT NULL, + NewCredentialIdentifier nvarchar(60) NULL, + NewStateOfIssueStateAbbreviationDescriptorId int NULL, + NewStateOfIssueStateAbbreviationDescriptorNamespace nvarchar(255) NULL, + NewStateOfIssueStateAbbreviationDescriptorCodeValue nvarchar(50) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT Credential_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[Descriptor]')) +CREATE TABLE [tracked_changes_edfi].[Descriptor] +( + OldDescriptorId int NOT NULL, + OldCodeValue nvarchar(50) NOT NULL, + OldNamespace nvarchar(255) NOT NULL, + NewDescriptorId int NULL, + NewCodeValue nvarchar(50) NULL, + NewNamespace nvarchar(255) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT Descriptor_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[DisciplineAction]')) +CREATE TABLE [tracked_changes_edfi].[DisciplineAction] +( + OldDisciplineActionIdentifier nvarchar(20) NOT NULL, + OldDisciplineDate date NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewDisciplineActionIdentifier nvarchar(20) NULL, + NewDisciplineDate date NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT DisciplineAction_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[DisciplineIncident]')) +CREATE TABLE [tracked_changes_edfi].[DisciplineIncident] +( + OldIncidentIdentifier nvarchar(20) NOT NULL, + OldSchoolId int NOT NULL, + NewIncidentIdentifier nvarchar(20) NULL, + NewSchoolId int NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT DisciplineIncident_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[EducationContent]')) +CREATE TABLE [tracked_changes_edfi].[EducationContent] +( + OldContentIdentifier nvarchar(225) NOT NULL, + NewContentIdentifier nvarchar(225) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT EducationContent_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[EducationOrganization]')) +CREATE TABLE [tracked_changes_edfi].[EducationOrganization] +( + OldEducationOrganizationId int NOT NULL, + NewEducationOrganizationId int NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT EducationOrganization_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[EducationOrganizationInterventionPrescriptionAssociation]')) +CREATE TABLE [tracked_changes_edfi].[EducationOrganizationInterventionPrescriptionAssociation] +( + OldEducationOrganizationId int NOT NULL, + OldInterventionPrescriptionEducationOrganizationId int NOT NULL, + OldInterventionPrescriptionIdentificationCode nvarchar(60) NOT NULL, + NewEducationOrganizationId int NULL, + NewInterventionPrescriptionEducationOrganizationId int NULL, + NewInterventionPrescriptionIdentificationCode nvarchar(60) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT EducationOrganizationInterventionPrescriptionAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[EducationOrganizationNetworkAssociation]')) +CREATE TABLE [tracked_changes_edfi].[EducationOrganizationNetworkAssociation] +( + OldEducationOrganizationNetworkId int NOT NULL, + OldMemberEducationOrganizationId int NOT NULL, + NewEducationOrganizationNetworkId int NULL, + NewMemberEducationOrganizationId int NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT EducationOrganizationNetworkAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[EducationOrganizationPeerAssociation]')) +CREATE TABLE [tracked_changes_edfi].[EducationOrganizationPeerAssociation] +( + OldEducationOrganizationId int NOT NULL, + OldPeerEducationOrganizationId int NOT NULL, + NewEducationOrganizationId int NULL, + NewPeerEducationOrganizationId int NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT EducationOrganizationPeerAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[FeederSchoolAssociation]')) +CREATE TABLE [tracked_changes_edfi].[FeederSchoolAssociation] +( + OldBeginDate date NOT NULL, + OldFeederSchoolId int NOT NULL, + OldSchoolId int NOT NULL, + NewBeginDate date NULL, + NewFeederSchoolId int NULL, + NewSchoolId int NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT FeederSchoolAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[GeneralStudentProgramAssociation]')) +CREATE TABLE [tracked_changes_edfi].[GeneralStudentProgramAssociation] +( + OldBeginDate date NOT NULL, + OldEducationOrganizationId int NOT NULL, + OldProgramEducationOrganizationId int NOT NULL, + OldProgramName nvarchar(60) NOT NULL, + OldProgramTypeDescriptorId int NOT NULL, + OldProgramTypeDescriptorNamespace nvarchar(255) NOT NULL, + OldProgramTypeDescriptorCodeValue nvarchar(50) NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewBeginDate date NULL, + NewEducationOrganizationId int NULL, + NewProgramEducationOrganizationId int NULL, + NewProgramName nvarchar(60) NULL, + NewProgramTypeDescriptorId int NULL, + NewProgramTypeDescriptorNamespace nvarchar(255) NULL, + NewProgramTypeDescriptorCodeValue nvarchar(50) NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT GeneralStudentProgramAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[Grade]')) +CREATE TABLE [tracked_changes_edfi].[Grade] +( + OldBeginDate date NOT NULL, + OldGradeTypeDescriptorId int NOT NULL, + OldGradeTypeDescriptorNamespace nvarchar(255) NOT NULL, + OldGradeTypeDescriptorCodeValue nvarchar(50) NOT NULL, + OldGradingPeriodDescriptorId int NOT NULL, + OldGradingPeriodDescriptorNamespace nvarchar(255) NOT NULL, + OldGradingPeriodDescriptorCodeValue nvarchar(50) NOT NULL, + OldGradingPeriodSchoolYear smallint NOT NULL, + OldGradingPeriodSequence int NOT NULL, + OldLocalCourseCode nvarchar(60) NOT NULL, + OldSchoolId int NOT NULL, + OldSchoolYear smallint NOT NULL, + OldSectionIdentifier nvarchar(255) NOT NULL, + OldSessionName nvarchar(60) NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewBeginDate date NULL, + NewGradeTypeDescriptorId int NULL, + NewGradeTypeDescriptorNamespace nvarchar(255) NULL, + NewGradeTypeDescriptorCodeValue nvarchar(50) NULL, + NewGradingPeriodDescriptorId int NULL, + NewGradingPeriodDescriptorNamespace nvarchar(255) NULL, + NewGradingPeriodDescriptorCodeValue nvarchar(50) NULL, + NewGradingPeriodSchoolYear smallint NULL, + NewGradingPeriodSequence int NULL, + NewLocalCourseCode nvarchar(60) NULL, + NewSchoolId int NULL, + NewSchoolYear smallint NULL, + NewSectionIdentifier nvarchar(255) NULL, + NewSessionName nvarchar(60) NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT Grade_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[GradebookEntry]')) +CREATE TABLE [tracked_changes_edfi].[GradebookEntry] +( + OldDateAssigned date NOT NULL, + OldGradebookEntryTitle nvarchar(60) NOT NULL, + OldLocalCourseCode nvarchar(60) NOT NULL, + OldSchoolId int NOT NULL, + OldSchoolYear smallint NOT NULL, + OldSectionIdentifier nvarchar(255) NOT NULL, + OldSessionName nvarchar(60) NOT NULL, + NewDateAssigned date NULL, + NewGradebookEntryTitle nvarchar(60) NULL, + NewLocalCourseCode nvarchar(60) NULL, + NewSchoolId int NULL, + NewSchoolYear smallint NULL, + NewSectionIdentifier nvarchar(255) NULL, + NewSessionName nvarchar(60) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT GradebookEntry_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[GradingPeriod]')) +CREATE TABLE [tracked_changes_edfi].[GradingPeriod] +( + OldGradingPeriodDescriptorId int NOT NULL, + OldGradingPeriodDescriptorNamespace nvarchar(255) NOT NULL, + OldGradingPeriodDescriptorCodeValue nvarchar(50) NOT NULL, + OldPeriodSequence int NOT NULL, + OldSchoolId int NOT NULL, + OldSchoolYear smallint NOT NULL, + NewGradingPeriodDescriptorId int NULL, + NewGradingPeriodDescriptorNamespace nvarchar(255) NULL, + NewGradingPeriodDescriptorCodeValue nvarchar(50) NULL, + NewPeriodSequence int NULL, + NewSchoolId int NULL, + NewSchoolYear smallint NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT GradingPeriod_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[GraduationPlan]')) +CREATE TABLE [tracked_changes_edfi].[GraduationPlan] +( + OldEducationOrganizationId int NOT NULL, + OldGraduationPlanTypeDescriptorId int NOT NULL, + OldGraduationPlanTypeDescriptorNamespace nvarchar(255) NOT NULL, + OldGraduationPlanTypeDescriptorCodeValue nvarchar(50) NOT NULL, + OldGraduationSchoolYear smallint NOT NULL, + NewEducationOrganizationId int NULL, + NewGraduationPlanTypeDescriptorId int NULL, + NewGraduationPlanTypeDescriptorNamespace nvarchar(255) NULL, + NewGraduationPlanTypeDescriptorCodeValue nvarchar(50) NULL, + NewGraduationSchoolYear smallint NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT GraduationPlan_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[Intervention]')) +CREATE TABLE [tracked_changes_edfi].[Intervention] +( + OldEducationOrganizationId int NOT NULL, + OldInterventionIdentificationCode nvarchar(60) NOT NULL, + NewEducationOrganizationId int NULL, + NewInterventionIdentificationCode nvarchar(60) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT Intervention_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[InterventionPrescription]')) +CREATE TABLE [tracked_changes_edfi].[InterventionPrescription] +( + OldEducationOrganizationId int NOT NULL, + OldInterventionPrescriptionIdentificationCode nvarchar(60) NOT NULL, + NewEducationOrganizationId int NULL, + NewInterventionPrescriptionIdentificationCode nvarchar(60) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT InterventionPrescription_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[InterventionStudy]')) +CREATE TABLE [tracked_changes_edfi].[InterventionStudy] +( + OldEducationOrganizationId int NOT NULL, + OldInterventionStudyIdentificationCode nvarchar(60) NOT NULL, + NewEducationOrganizationId int NULL, + NewInterventionStudyIdentificationCode nvarchar(60) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT InterventionStudy_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[LearningObjective]')) +CREATE TABLE [tracked_changes_edfi].[LearningObjective] +( + OldLearningObjectiveId nvarchar(60) NOT NULL, + OldNamespace nvarchar(255) NOT NULL, + NewLearningObjectiveId nvarchar(60) NULL, + NewNamespace nvarchar(255) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT LearningObjective_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[LearningStandard]')) +CREATE TABLE [tracked_changes_edfi].[LearningStandard] +( + OldLearningStandardId nvarchar(60) NOT NULL, + NewLearningStandardId nvarchar(60) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT LearningStandard_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[LearningStandardEquivalenceAssociation]')) +CREATE TABLE [tracked_changes_edfi].[LearningStandardEquivalenceAssociation] +( + OldNamespace nvarchar(255) NOT NULL, + OldSourceLearningStandardId nvarchar(60) NOT NULL, + OldTargetLearningStandardId nvarchar(60) NOT NULL, + NewNamespace nvarchar(255) NULL, + NewSourceLearningStandardId nvarchar(60) NULL, + NewTargetLearningStandardId nvarchar(60) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT LearningStandardEquivalenceAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[Location]')) +CREATE TABLE [tracked_changes_edfi].[Location] +( + OldClassroomIdentificationCode nvarchar(60) NOT NULL, + OldSchoolId int NOT NULL, + NewClassroomIdentificationCode nvarchar(60) NULL, + NewSchoolId int NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT Location_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[ObjectiveAssessment]')) +CREATE TABLE [tracked_changes_edfi].[ObjectiveAssessment] +( + OldAssessmentIdentifier nvarchar(60) NOT NULL, + OldIdentificationCode nvarchar(60) NOT NULL, + OldNamespace nvarchar(255) NOT NULL, + NewAssessmentIdentifier nvarchar(60) NULL, + NewIdentificationCode nvarchar(60) NULL, + NewNamespace nvarchar(255) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT ObjectiveAssessment_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[OpenStaffPosition]')) +CREATE TABLE [tracked_changes_edfi].[OpenStaffPosition] +( + OldEducationOrganizationId int NOT NULL, + OldRequisitionNumber nvarchar(20) NOT NULL, + NewEducationOrganizationId int NULL, + NewRequisitionNumber nvarchar(20) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT OpenStaffPosition_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[Parent]')) +CREATE TABLE [tracked_changes_edfi].[Parent] +( + OldParentUSI int NOT NULL, + OldParentUniqueId nvarchar(32) NOT NULL, + NewParentUSI int NULL, + NewParentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT Parent_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[Payroll]')) +CREATE TABLE [tracked_changes_edfi].[Payroll] +( + OldAccountIdentifier nvarchar(50) NOT NULL, + OldAsOfDate date NOT NULL, + OldEducationOrganizationId int NOT NULL, + OldFiscalYear int NOT NULL, + OldStaffUSI int NOT NULL, + OldStaffUniqueId nvarchar(32) NOT NULL, + NewAccountIdentifier nvarchar(50) NULL, + NewAsOfDate date NULL, + NewEducationOrganizationId int NULL, + NewFiscalYear int NULL, + NewStaffUSI int NULL, + NewStaffUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT Payroll_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[Person]')) +CREATE TABLE [tracked_changes_edfi].[Person] +( + OldPersonId nvarchar(32) NOT NULL, + OldSourceSystemDescriptorId int NOT NULL, + OldSourceSystemDescriptorNamespace nvarchar(255) NOT NULL, + OldSourceSystemDescriptorCodeValue nvarchar(50) NOT NULL, + NewPersonId nvarchar(32) NULL, + NewSourceSystemDescriptorId int NULL, + NewSourceSystemDescriptorNamespace nvarchar(255) NULL, + NewSourceSystemDescriptorCodeValue nvarchar(50) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT Person_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[PostSecondaryEvent]')) +CREATE TABLE [tracked_changes_edfi].[PostSecondaryEvent] +( + OldEventDate date NOT NULL, + OldPostSecondaryEventCategoryDescriptorId int NOT NULL, + OldPostSecondaryEventCategoryDescriptorNamespace nvarchar(255) NOT NULL, + OldPostSecondaryEventCategoryDescriptorCodeValue nvarchar(50) NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewEventDate date NULL, + NewPostSecondaryEventCategoryDescriptorId int NULL, + NewPostSecondaryEventCategoryDescriptorNamespace nvarchar(255) NULL, + NewPostSecondaryEventCategoryDescriptorCodeValue nvarchar(50) NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT PostSecondaryEvent_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[Program]')) +CREATE TABLE [tracked_changes_edfi].[Program] +( + OldEducationOrganizationId int NOT NULL, + OldProgramName nvarchar(60) NOT NULL, + OldProgramTypeDescriptorId int NOT NULL, + OldProgramTypeDescriptorNamespace nvarchar(255) NOT NULL, + OldProgramTypeDescriptorCodeValue nvarchar(50) NOT NULL, + NewEducationOrganizationId int NULL, + NewProgramName nvarchar(60) NULL, + NewProgramTypeDescriptorId int NULL, + NewProgramTypeDescriptorNamespace nvarchar(255) NULL, + NewProgramTypeDescriptorCodeValue nvarchar(50) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT Program_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[ReportCard]')) +CREATE TABLE [tracked_changes_edfi].[ReportCard] +( + OldEducationOrganizationId int NOT NULL, + OldGradingPeriodDescriptorId int NOT NULL, + OldGradingPeriodDescriptorNamespace nvarchar(255) NOT NULL, + OldGradingPeriodDescriptorCodeValue nvarchar(50) NOT NULL, + OldGradingPeriodSchoolId int NOT NULL, + OldGradingPeriodSchoolYear smallint NOT NULL, + OldGradingPeriodSequence int NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewEducationOrganizationId int NULL, + NewGradingPeriodDescriptorId int NULL, + NewGradingPeriodDescriptorNamespace nvarchar(255) NULL, + NewGradingPeriodDescriptorCodeValue nvarchar(50) NULL, + NewGradingPeriodSchoolId int NULL, + NewGradingPeriodSchoolYear smallint NULL, + NewGradingPeriodSequence int NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT ReportCard_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[RestraintEvent]')) +CREATE TABLE [tracked_changes_edfi].[RestraintEvent] +( + OldRestraintEventIdentifier nvarchar(20) NOT NULL, + OldSchoolId int NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewRestraintEventIdentifier nvarchar(20) NULL, + NewSchoolId int NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT RestraintEvent_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[SchoolYearType]')) +CREATE TABLE [tracked_changes_edfi].[SchoolYearType] +( + OldSchoolYear smallint NOT NULL, + NewSchoolYear smallint NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT SchoolYearType_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[Section]')) +CREATE TABLE [tracked_changes_edfi].[Section] +( + OldLocalCourseCode nvarchar(60) NOT NULL, + OldSchoolId int NOT NULL, + OldSchoolYear smallint NOT NULL, + OldSectionIdentifier nvarchar(255) NOT NULL, + OldSessionName nvarchar(60) NOT NULL, + NewLocalCourseCode nvarchar(60) NULL, + NewSchoolId int NULL, + NewSchoolYear smallint NULL, + NewSectionIdentifier nvarchar(255) NULL, + NewSessionName nvarchar(60) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT Section_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[SectionAttendanceTakenEvent]')) +CREATE TABLE [tracked_changes_edfi].[SectionAttendanceTakenEvent] +( + OldCalendarCode nvarchar(60) NOT NULL, + OldDate date NOT NULL, + OldLocalCourseCode nvarchar(60) NOT NULL, + OldSchoolId int NOT NULL, + OldSchoolYear smallint NOT NULL, + OldSectionIdentifier nvarchar(255) NOT NULL, + OldSessionName nvarchar(60) NOT NULL, + NewCalendarCode nvarchar(60) NULL, + NewDate date NULL, + NewLocalCourseCode nvarchar(60) NULL, + NewSchoolId int NULL, + NewSchoolYear smallint NULL, + NewSectionIdentifier nvarchar(255) NULL, + NewSessionName nvarchar(60) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT SectionAttendanceTakenEvent_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[Session]')) +CREATE TABLE [tracked_changes_edfi].[Session] +( + OldSchoolId int NOT NULL, + OldSchoolYear smallint NOT NULL, + OldSessionName nvarchar(60) NOT NULL, + NewSchoolId int NULL, + NewSchoolYear smallint NULL, + NewSessionName nvarchar(60) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT Session_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[Staff]')) +CREATE TABLE [tracked_changes_edfi].[Staff] +( + OldStaffUSI int NOT NULL, + OldStaffUniqueId nvarchar(32) NOT NULL, + NewStaffUSI int NULL, + NewStaffUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT Staff_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StaffAbsenceEvent]')) +CREATE TABLE [tracked_changes_edfi].[StaffAbsenceEvent] +( + OldAbsenceEventCategoryDescriptorId int NOT NULL, + OldAbsenceEventCategoryDescriptorNamespace nvarchar(255) NOT NULL, + OldAbsenceEventCategoryDescriptorCodeValue nvarchar(50) NOT NULL, + OldEventDate date NOT NULL, + OldStaffUSI int NOT NULL, + OldStaffUniqueId nvarchar(32) NOT NULL, + NewAbsenceEventCategoryDescriptorId int NULL, + NewAbsenceEventCategoryDescriptorNamespace nvarchar(255) NULL, + NewAbsenceEventCategoryDescriptorCodeValue nvarchar(50) NULL, + NewEventDate date NULL, + NewStaffUSI int NULL, + NewStaffUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StaffAbsenceEvent_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StaffCohortAssociation]')) +CREATE TABLE [tracked_changes_edfi].[StaffCohortAssociation] +( + OldBeginDate date NOT NULL, + OldCohortIdentifier nvarchar(20) NOT NULL, + OldEducationOrganizationId int NOT NULL, + OldStaffUSI int NOT NULL, + OldStaffUniqueId nvarchar(32) NOT NULL, + NewBeginDate date NULL, + NewCohortIdentifier nvarchar(20) NULL, + NewEducationOrganizationId int NULL, + NewStaffUSI int NULL, + NewStaffUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StaffCohortAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StaffDisciplineIncidentAssociation]')) +CREATE TABLE [tracked_changes_edfi].[StaffDisciplineIncidentAssociation] +( + OldIncidentIdentifier nvarchar(20) NOT NULL, + OldSchoolId int NOT NULL, + OldStaffUSI int NOT NULL, + OldStaffUniqueId nvarchar(32) NOT NULL, + NewIncidentIdentifier nvarchar(20) NULL, + NewSchoolId int NULL, + NewStaffUSI int NULL, + NewStaffUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StaffDisciplineIncidentAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StaffEducationOrganizationAssignmentAssociation]')) +CREATE TABLE [tracked_changes_edfi].[StaffEducationOrganizationAssignmentAssociation] +( + OldBeginDate date NOT NULL, + OldEducationOrganizationId int NOT NULL, + OldStaffClassificationDescriptorId int NOT NULL, + OldStaffClassificationDescriptorNamespace nvarchar(255) NOT NULL, + OldStaffClassificationDescriptorCodeValue nvarchar(50) NOT NULL, + OldStaffUSI int NOT NULL, + OldStaffUniqueId nvarchar(32) NOT NULL, + NewBeginDate date NULL, + NewEducationOrganizationId int NULL, + NewStaffClassificationDescriptorId int NULL, + NewStaffClassificationDescriptorNamespace nvarchar(255) NULL, + NewStaffClassificationDescriptorCodeValue nvarchar(50) NULL, + NewStaffUSI int NULL, + NewStaffUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StaffEducationOrganizationAssignmentAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StaffEducationOrganizationContactAssociation]')) +CREATE TABLE [tracked_changes_edfi].[StaffEducationOrganizationContactAssociation] +( + OldContactTitle nvarchar(75) NOT NULL, + OldEducationOrganizationId int NOT NULL, + OldStaffUSI int NOT NULL, + OldStaffUniqueId nvarchar(32) NOT NULL, + NewContactTitle nvarchar(75) NULL, + NewEducationOrganizationId int NULL, + NewStaffUSI int NULL, + NewStaffUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StaffEducationOrganizationContactAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StaffEducationOrganizationEmploymentAssociation]')) +CREATE TABLE [tracked_changes_edfi].[StaffEducationOrganizationEmploymentAssociation] +( + OldEducationOrganizationId int NOT NULL, + OldEmploymentStatusDescriptorId int NOT NULL, + OldEmploymentStatusDescriptorNamespace nvarchar(255) NOT NULL, + OldEmploymentStatusDescriptorCodeValue nvarchar(50) NOT NULL, + OldHireDate date NOT NULL, + OldStaffUSI int NOT NULL, + OldStaffUniqueId nvarchar(32) NOT NULL, + NewEducationOrganizationId int NULL, + NewEmploymentStatusDescriptorId int NULL, + NewEmploymentStatusDescriptorNamespace nvarchar(255) NULL, + NewEmploymentStatusDescriptorCodeValue nvarchar(50) NULL, + NewHireDate date NULL, + NewStaffUSI int NULL, + NewStaffUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StaffEducationOrganizationEmploymentAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StaffLeave]')) +CREATE TABLE [tracked_changes_edfi].[StaffLeave] +( + OldBeginDate date NOT NULL, + OldStaffLeaveEventCategoryDescriptorId int NOT NULL, + OldStaffLeaveEventCategoryDescriptorNamespace nvarchar(255) NOT NULL, + OldStaffLeaveEventCategoryDescriptorCodeValue nvarchar(50) NOT NULL, + OldStaffUSI int NOT NULL, + OldStaffUniqueId nvarchar(32) NOT NULL, + NewBeginDate date NULL, + NewStaffLeaveEventCategoryDescriptorId int NULL, + NewStaffLeaveEventCategoryDescriptorNamespace nvarchar(255) NULL, + NewStaffLeaveEventCategoryDescriptorCodeValue nvarchar(50) NULL, + NewStaffUSI int NULL, + NewStaffUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StaffLeave_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StaffProgramAssociation]')) +CREATE TABLE [tracked_changes_edfi].[StaffProgramAssociation] +( + OldBeginDate date NOT NULL, + OldProgramEducationOrganizationId int NOT NULL, + OldProgramName nvarchar(60) NOT NULL, + OldProgramTypeDescriptorId int NOT NULL, + OldProgramTypeDescriptorNamespace nvarchar(255) NOT NULL, + OldProgramTypeDescriptorCodeValue nvarchar(50) NOT NULL, + OldStaffUSI int NOT NULL, + OldStaffUniqueId nvarchar(32) NOT NULL, + NewBeginDate date NULL, + NewProgramEducationOrganizationId int NULL, + NewProgramName nvarchar(60) NULL, + NewProgramTypeDescriptorId int NULL, + NewProgramTypeDescriptorNamespace nvarchar(255) NULL, + NewProgramTypeDescriptorCodeValue nvarchar(50) NULL, + NewStaffUSI int NULL, + NewStaffUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StaffProgramAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StaffSchoolAssociation]')) +CREATE TABLE [tracked_changes_edfi].[StaffSchoolAssociation] +( + OldProgramAssignmentDescriptorId int NOT NULL, + OldProgramAssignmentDescriptorNamespace nvarchar(255) NOT NULL, + OldProgramAssignmentDescriptorCodeValue nvarchar(50) NOT NULL, + OldSchoolId int NOT NULL, + OldStaffUSI int NOT NULL, + OldStaffUniqueId nvarchar(32) NOT NULL, + NewProgramAssignmentDescriptorId int NULL, + NewProgramAssignmentDescriptorNamespace nvarchar(255) NULL, + NewProgramAssignmentDescriptorCodeValue nvarchar(50) NULL, + NewSchoolId int NULL, + NewStaffUSI int NULL, + NewStaffUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StaffSchoolAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StaffSectionAssociation]')) +CREATE TABLE [tracked_changes_edfi].[StaffSectionAssociation] +( + OldLocalCourseCode nvarchar(60) NOT NULL, + OldSchoolId int NOT NULL, + OldSchoolYear smallint NOT NULL, + OldSectionIdentifier nvarchar(255) NOT NULL, + OldSessionName nvarchar(60) NOT NULL, + OldStaffUSI int NOT NULL, + OldStaffUniqueId nvarchar(32) NOT NULL, + NewLocalCourseCode nvarchar(60) NULL, + NewSchoolId int NULL, + NewSchoolYear smallint NULL, + NewSectionIdentifier nvarchar(255) NULL, + NewSessionName nvarchar(60) NULL, + NewStaffUSI int NULL, + NewStaffUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StaffSectionAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[Student]')) +CREATE TABLE [tracked_changes_edfi].[Student] +( + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT Student_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StudentAcademicRecord]')) +CREATE TABLE [tracked_changes_edfi].[StudentAcademicRecord] +( + OldEducationOrganizationId int NOT NULL, + OldSchoolYear smallint NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + OldTermDescriptorId int NOT NULL, + OldTermDescriptorNamespace nvarchar(255) NOT NULL, + OldTermDescriptorCodeValue nvarchar(50) NOT NULL, + NewEducationOrganizationId int NULL, + NewSchoolYear smallint NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + NewTermDescriptorId int NULL, + NewTermDescriptorNamespace nvarchar(255) NULL, + NewTermDescriptorCodeValue nvarchar(50) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StudentAcademicRecord_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StudentAssessment]')) +CREATE TABLE [tracked_changes_edfi].[StudentAssessment] +( + OldAssessmentIdentifier nvarchar(60) NOT NULL, + OldNamespace nvarchar(255) NOT NULL, + OldStudentAssessmentIdentifier nvarchar(60) NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewAssessmentIdentifier nvarchar(60) NULL, + NewNamespace nvarchar(255) NULL, + NewStudentAssessmentIdentifier nvarchar(60) NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StudentAssessment_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StudentCohortAssociation]')) +CREATE TABLE [tracked_changes_edfi].[StudentCohortAssociation] +( + OldBeginDate date NOT NULL, + OldCohortIdentifier nvarchar(20) NOT NULL, + OldEducationOrganizationId int NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewBeginDate date NULL, + NewCohortIdentifier nvarchar(20) NULL, + NewEducationOrganizationId int NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StudentCohortAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StudentCompetencyObjective]')) +CREATE TABLE [tracked_changes_edfi].[StudentCompetencyObjective] +( + OldGradingPeriodDescriptorId int NOT NULL, + OldGradingPeriodDescriptorNamespace nvarchar(255) NOT NULL, + OldGradingPeriodDescriptorCodeValue nvarchar(50) NOT NULL, + OldGradingPeriodSchoolId int NOT NULL, + OldGradingPeriodSchoolYear smallint NOT NULL, + OldGradingPeriodSequence int NOT NULL, + OldObjective nvarchar(60) NOT NULL, + OldObjectiveEducationOrganizationId int NOT NULL, + OldObjectiveGradeLevelDescriptorId int NOT NULL, + OldObjectiveGradeLevelDescriptorNamespace nvarchar(255) NOT NULL, + OldObjectiveGradeLevelDescriptorCodeValue nvarchar(50) NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewGradingPeriodDescriptorId int NULL, + NewGradingPeriodDescriptorNamespace nvarchar(255) NULL, + NewGradingPeriodDescriptorCodeValue nvarchar(50) NULL, + NewGradingPeriodSchoolId int NULL, + NewGradingPeriodSchoolYear smallint NULL, + NewGradingPeriodSequence int NULL, + NewObjective nvarchar(60) NULL, + NewObjectiveEducationOrganizationId int NULL, + NewObjectiveGradeLevelDescriptorId int NULL, + NewObjectiveGradeLevelDescriptorNamespace nvarchar(255) NULL, + NewObjectiveGradeLevelDescriptorCodeValue nvarchar(50) NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StudentCompetencyObjective_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StudentDisciplineIncidentAssociation]')) +CREATE TABLE [tracked_changes_edfi].[StudentDisciplineIncidentAssociation] +( + OldIncidentIdentifier nvarchar(20) NOT NULL, + OldSchoolId int NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewIncidentIdentifier nvarchar(20) NULL, + NewSchoolId int NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StudentDisciplineIncidentAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StudentDisciplineIncidentBehaviorAssociation]')) +CREATE TABLE [tracked_changes_edfi].[StudentDisciplineIncidentBehaviorAssociation] +( + OldBehaviorDescriptorId int NOT NULL, + OldBehaviorDescriptorNamespace nvarchar(255) NOT NULL, + OldBehaviorDescriptorCodeValue nvarchar(50) NOT NULL, + OldIncidentIdentifier nvarchar(20) NOT NULL, + OldSchoolId int NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewBehaviorDescriptorId int NULL, + NewBehaviorDescriptorNamespace nvarchar(255) NULL, + NewBehaviorDescriptorCodeValue nvarchar(50) NULL, + NewIncidentIdentifier nvarchar(20) NULL, + NewSchoolId int NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StudentDisciplineIncidentBehaviorAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StudentDisciplineIncidentNonOffenderAssociation]')) +CREATE TABLE [tracked_changes_edfi].[StudentDisciplineIncidentNonOffenderAssociation] +( + OldIncidentIdentifier nvarchar(20) NOT NULL, + OldSchoolId int NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewIncidentIdentifier nvarchar(20) NULL, + NewSchoolId int NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StudentDisciplineIncidentNonOffenderAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StudentEducationOrganizationAssociation]')) +CREATE TABLE [tracked_changes_edfi].[StudentEducationOrganizationAssociation] +( + OldEducationOrganizationId int NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewEducationOrganizationId int NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StudentEducationOrganizationAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StudentEducationOrganizationResponsibilityAssociation]')) +CREATE TABLE [tracked_changes_edfi].[StudentEducationOrganizationResponsibilityAssociation] +( + OldBeginDate date NOT NULL, + OldEducationOrganizationId int NOT NULL, + OldResponsibilityDescriptorId int NOT NULL, + OldResponsibilityDescriptorNamespace nvarchar(255) NOT NULL, + OldResponsibilityDescriptorCodeValue nvarchar(50) NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewBeginDate date NULL, + NewEducationOrganizationId int NULL, + NewResponsibilityDescriptorId int NULL, + NewResponsibilityDescriptorNamespace nvarchar(255) NULL, + NewResponsibilityDescriptorCodeValue nvarchar(50) NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StudentEducationOrganizationResponsibilityAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StudentGradebookEntry]')) +CREATE TABLE [tracked_changes_edfi].[StudentGradebookEntry] +( + OldBeginDate date NOT NULL, + OldDateAssigned date NOT NULL, + OldGradebookEntryTitle nvarchar(60) NOT NULL, + OldLocalCourseCode nvarchar(60) NOT NULL, + OldSchoolId int NOT NULL, + OldSchoolYear smallint NOT NULL, + OldSectionIdentifier nvarchar(255) NOT NULL, + OldSessionName nvarchar(60) NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewBeginDate date NULL, + NewDateAssigned date NULL, + NewGradebookEntryTitle nvarchar(60) NULL, + NewLocalCourseCode nvarchar(60) NULL, + NewSchoolId int NULL, + NewSchoolYear smallint NULL, + NewSectionIdentifier nvarchar(255) NULL, + NewSessionName nvarchar(60) NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StudentGradebookEntry_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StudentInterventionAssociation]')) +CREATE TABLE [tracked_changes_edfi].[StudentInterventionAssociation] +( + OldEducationOrganizationId int NOT NULL, + OldInterventionIdentificationCode nvarchar(60) NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewEducationOrganizationId int NULL, + NewInterventionIdentificationCode nvarchar(60) NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StudentInterventionAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StudentInterventionAttendanceEvent]')) +CREATE TABLE [tracked_changes_edfi].[StudentInterventionAttendanceEvent] +( + OldAttendanceEventCategoryDescriptorId int NOT NULL, + OldAttendanceEventCategoryDescriptorNamespace nvarchar(255) NOT NULL, + OldAttendanceEventCategoryDescriptorCodeValue nvarchar(50) NOT NULL, + OldEducationOrganizationId int NOT NULL, + OldEventDate date NOT NULL, + OldInterventionIdentificationCode nvarchar(60) NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewAttendanceEventCategoryDescriptorId int NULL, + NewAttendanceEventCategoryDescriptorNamespace nvarchar(255) NULL, + NewAttendanceEventCategoryDescriptorCodeValue nvarchar(50) NULL, + NewEducationOrganizationId int NULL, + NewEventDate date NULL, + NewInterventionIdentificationCode nvarchar(60) NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StudentInterventionAttendanceEvent_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StudentLearningObjective]')) +CREATE TABLE [tracked_changes_edfi].[StudentLearningObjective] +( + OldGradingPeriodDescriptorId int NOT NULL, + OldGradingPeriodDescriptorNamespace nvarchar(255) NOT NULL, + OldGradingPeriodDescriptorCodeValue nvarchar(50) NOT NULL, + OldGradingPeriodSchoolId int NOT NULL, + OldGradingPeriodSchoolYear smallint NOT NULL, + OldGradingPeriodSequence int NOT NULL, + OldLearningObjectiveId nvarchar(60) NOT NULL, + OldNamespace nvarchar(255) NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewGradingPeriodDescriptorId int NULL, + NewGradingPeriodDescriptorNamespace nvarchar(255) NULL, + NewGradingPeriodDescriptorCodeValue nvarchar(50) NULL, + NewGradingPeriodSchoolId int NULL, + NewGradingPeriodSchoolYear smallint NULL, + NewGradingPeriodSequence int NULL, + NewLearningObjectiveId nvarchar(60) NULL, + NewNamespace nvarchar(255) NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StudentLearningObjective_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StudentParentAssociation]')) +CREATE TABLE [tracked_changes_edfi].[StudentParentAssociation] +( + OldParentUSI int NOT NULL, + OldParentUniqueId nvarchar(32) NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewParentUSI int NULL, + NewParentUniqueId nvarchar(32) NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StudentParentAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StudentProgramAttendanceEvent]')) +CREATE TABLE [tracked_changes_edfi].[StudentProgramAttendanceEvent] +( + OldAttendanceEventCategoryDescriptorId int NOT NULL, + OldAttendanceEventCategoryDescriptorNamespace nvarchar(255) NOT NULL, + OldAttendanceEventCategoryDescriptorCodeValue nvarchar(50) NOT NULL, + OldEducationOrganizationId int NOT NULL, + OldEventDate date NOT NULL, + OldProgramEducationOrganizationId int NOT NULL, + OldProgramName nvarchar(60) NOT NULL, + OldProgramTypeDescriptorId int NOT NULL, + OldProgramTypeDescriptorNamespace nvarchar(255) NOT NULL, + OldProgramTypeDescriptorCodeValue nvarchar(50) NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewAttendanceEventCategoryDescriptorId int NULL, + NewAttendanceEventCategoryDescriptorNamespace nvarchar(255) NULL, + NewAttendanceEventCategoryDescriptorCodeValue nvarchar(50) NULL, + NewEducationOrganizationId int NULL, + NewEventDate date NULL, + NewProgramEducationOrganizationId int NULL, + NewProgramName nvarchar(60) NULL, + NewProgramTypeDescriptorId int NULL, + NewProgramTypeDescriptorNamespace nvarchar(255) NULL, + NewProgramTypeDescriptorCodeValue nvarchar(50) NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StudentProgramAttendanceEvent_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StudentSchoolAssociation]')) +CREATE TABLE [tracked_changes_edfi].[StudentSchoolAssociation] +( + OldEntryDate date NOT NULL, + OldSchoolId int NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewEntryDate date NULL, + NewSchoolId int NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StudentSchoolAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StudentSchoolAttendanceEvent]')) +CREATE TABLE [tracked_changes_edfi].[StudentSchoolAttendanceEvent] +( + OldAttendanceEventCategoryDescriptorId int NOT NULL, + OldAttendanceEventCategoryDescriptorNamespace nvarchar(255) NOT NULL, + OldAttendanceEventCategoryDescriptorCodeValue nvarchar(50) NOT NULL, + OldEventDate date NOT NULL, + OldSchoolId int NOT NULL, + OldSchoolYear smallint NOT NULL, + OldSessionName nvarchar(60) NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewAttendanceEventCategoryDescriptorId int NULL, + NewAttendanceEventCategoryDescriptorNamespace nvarchar(255) NULL, + NewAttendanceEventCategoryDescriptorCodeValue nvarchar(50) NULL, + NewEventDate date NULL, + NewSchoolId int NULL, + NewSchoolYear smallint NULL, + NewSessionName nvarchar(60) NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StudentSchoolAttendanceEvent_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StudentSectionAssociation]')) +CREATE TABLE [tracked_changes_edfi].[StudentSectionAssociation] +( + OldBeginDate date NOT NULL, + OldLocalCourseCode nvarchar(60) NOT NULL, + OldSchoolId int NOT NULL, + OldSchoolYear smallint NOT NULL, + OldSectionIdentifier nvarchar(255) NOT NULL, + OldSessionName nvarchar(60) NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewBeginDate date NULL, + NewLocalCourseCode nvarchar(60) NULL, + NewSchoolId int NULL, + NewSchoolYear smallint NULL, + NewSectionIdentifier nvarchar(255) NULL, + NewSessionName nvarchar(60) NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StudentSectionAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[StudentSectionAttendanceEvent]')) +CREATE TABLE [tracked_changes_edfi].[StudentSectionAttendanceEvent] +( + OldAttendanceEventCategoryDescriptorId int NOT NULL, + OldAttendanceEventCategoryDescriptorNamespace nvarchar(255) NOT NULL, + OldAttendanceEventCategoryDescriptorCodeValue nvarchar(50) NOT NULL, + OldEventDate date NOT NULL, + OldLocalCourseCode nvarchar(60) NOT NULL, + OldSchoolId int NOT NULL, + OldSchoolYear smallint NOT NULL, + OldSectionIdentifier nvarchar(255) NOT NULL, + OldSessionName nvarchar(60) NOT NULL, + OldStudentUSI int NOT NULL, + OldStudentUniqueId nvarchar(32) NOT NULL, + NewAttendanceEventCategoryDescriptorId int NULL, + NewAttendanceEventCategoryDescriptorNamespace nvarchar(255) NULL, + NewAttendanceEventCategoryDescriptorCodeValue nvarchar(50) NULL, + NewEventDate date NULL, + NewLocalCourseCode nvarchar(60) NULL, + NewSchoolId int NULL, + NewSchoolYear smallint NULL, + NewSectionIdentifier nvarchar(255) NULL, + NewSessionName nvarchar(60) NULL, + NewStudentUSI int NULL, + NewStudentUniqueId nvarchar(32) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT StudentSectionAttendanceEvent_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[Survey]')) +CREATE TABLE [tracked_changes_edfi].[Survey] +( + OldNamespace nvarchar(255) NOT NULL, + OldSurveyIdentifier nvarchar(60) NOT NULL, + NewNamespace nvarchar(255) NULL, + NewSurveyIdentifier nvarchar(60) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT Survey_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[SurveyCourseAssociation]')) +CREATE TABLE [tracked_changes_edfi].[SurveyCourseAssociation] +( + OldCourseCode nvarchar(60) NOT NULL, + OldEducationOrganizationId int NOT NULL, + OldNamespace nvarchar(255) NOT NULL, + OldSurveyIdentifier nvarchar(60) NOT NULL, + NewCourseCode nvarchar(60) NULL, + NewEducationOrganizationId int NULL, + NewNamespace nvarchar(255) NULL, + NewSurveyIdentifier nvarchar(60) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT SurveyCourseAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[SurveyProgramAssociation]')) +CREATE TABLE [tracked_changes_edfi].[SurveyProgramAssociation] +( + OldEducationOrganizationId int NOT NULL, + OldNamespace nvarchar(255) NOT NULL, + OldProgramName nvarchar(60) NOT NULL, + OldProgramTypeDescriptorId int NOT NULL, + OldProgramTypeDescriptorNamespace nvarchar(255) NOT NULL, + OldProgramTypeDescriptorCodeValue nvarchar(50) NOT NULL, + OldSurveyIdentifier nvarchar(60) NOT NULL, + NewEducationOrganizationId int NULL, + NewNamespace nvarchar(255) NULL, + NewProgramName nvarchar(60) NULL, + NewProgramTypeDescriptorId int NULL, + NewProgramTypeDescriptorNamespace nvarchar(255) NULL, + NewProgramTypeDescriptorCodeValue nvarchar(50) NULL, + NewSurveyIdentifier nvarchar(60) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT SurveyProgramAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[SurveyQuestion]')) +CREATE TABLE [tracked_changes_edfi].[SurveyQuestion] +( + OldNamespace nvarchar(255) NOT NULL, + OldQuestionCode nvarchar(60) NOT NULL, + OldSurveyIdentifier nvarchar(60) NOT NULL, + NewNamespace nvarchar(255) NULL, + NewQuestionCode nvarchar(60) NULL, + NewSurveyIdentifier nvarchar(60) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT SurveyQuestion_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[SurveyQuestionResponse]')) +CREATE TABLE [tracked_changes_edfi].[SurveyQuestionResponse] +( + OldNamespace nvarchar(255) NOT NULL, + OldQuestionCode nvarchar(60) NOT NULL, + OldSurveyIdentifier nvarchar(60) NOT NULL, + OldSurveyResponseIdentifier nvarchar(60) NOT NULL, + NewNamespace nvarchar(255) NULL, + NewQuestionCode nvarchar(60) NULL, + NewSurveyIdentifier nvarchar(60) NULL, + NewSurveyResponseIdentifier nvarchar(60) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT SurveyQuestionResponse_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[SurveyResponse]')) +CREATE TABLE [tracked_changes_edfi].[SurveyResponse] +( + OldNamespace nvarchar(255) NOT NULL, + OldSurveyIdentifier nvarchar(60) NOT NULL, + OldSurveyResponseIdentifier nvarchar(60) NOT NULL, + NewNamespace nvarchar(255) NULL, + NewSurveyIdentifier nvarchar(60) NULL, + NewSurveyResponseIdentifier nvarchar(60) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT SurveyResponse_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[SurveyResponseEducationOrganizationTargetAssociation]')) +CREATE TABLE [tracked_changes_edfi].[SurveyResponseEducationOrganizationTargetAssociation] +( + OldEducationOrganizationId int NOT NULL, + OldNamespace nvarchar(255) NOT NULL, + OldSurveyIdentifier nvarchar(60) NOT NULL, + OldSurveyResponseIdentifier nvarchar(60) NOT NULL, + NewEducationOrganizationId int NULL, + NewNamespace nvarchar(255) NULL, + NewSurveyIdentifier nvarchar(60) NULL, + NewSurveyResponseIdentifier nvarchar(60) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT SurveyResponseEducationOrganizationTargetAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[SurveyResponseStaffTargetAssociation]')) +CREATE TABLE [tracked_changes_edfi].[SurveyResponseStaffTargetAssociation] +( + OldNamespace nvarchar(255) NOT NULL, + OldStaffUSI int NOT NULL, + OldStaffUniqueId nvarchar(32) NOT NULL, + OldSurveyIdentifier nvarchar(60) NOT NULL, + OldSurveyResponseIdentifier nvarchar(60) NOT NULL, + NewNamespace nvarchar(255) NULL, + NewStaffUSI int NULL, + NewStaffUniqueId nvarchar(32) NULL, + NewSurveyIdentifier nvarchar(60) NULL, + NewSurveyResponseIdentifier nvarchar(60) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT SurveyResponseStaffTargetAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[SurveySection]')) +CREATE TABLE [tracked_changes_edfi].[SurveySection] +( + OldNamespace nvarchar(255) NOT NULL, + OldSurveyIdentifier nvarchar(60) NOT NULL, + OldSurveySectionTitle nvarchar(255) NOT NULL, + NewNamespace nvarchar(255) NULL, + NewSurveyIdentifier nvarchar(60) NULL, + NewSurveySectionTitle nvarchar(255) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT SurveySection_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[SurveySectionAssociation]')) +CREATE TABLE [tracked_changes_edfi].[SurveySectionAssociation] +( + OldLocalCourseCode nvarchar(60) NOT NULL, + OldNamespace nvarchar(255) NOT NULL, + OldSchoolId int NOT NULL, + OldSchoolYear smallint NOT NULL, + OldSectionIdentifier nvarchar(255) NOT NULL, + OldSessionName nvarchar(60) NOT NULL, + OldSurveyIdentifier nvarchar(60) NOT NULL, + NewLocalCourseCode nvarchar(60) NULL, + NewNamespace nvarchar(255) NULL, + NewSchoolId int NULL, + NewSchoolYear smallint NULL, + NewSectionIdentifier nvarchar(255) NULL, + NewSessionName nvarchar(60) NULL, + NewSurveyIdentifier nvarchar(60) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT SurveySectionAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[SurveySectionResponse]')) +CREATE TABLE [tracked_changes_edfi].[SurveySectionResponse] +( + OldNamespace nvarchar(255) NOT NULL, + OldSurveyIdentifier nvarchar(60) NOT NULL, + OldSurveyResponseIdentifier nvarchar(60) NOT NULL, + OldSurveySectionTitle nvarchar(255) NOT NULL, + NewNamespace nvarchar(255) NULL, + NewSurveyIdentifier nvarchar(60) NULL, + NewSurveyResponseIdentifier nvarchar(60) NULL, + NewSurveySectionTitle nvarchar(255) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT SurveySectionResponse_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[SurveySectionResponseEducationOrganizationTargetAssociation]')) +CREATE TABLE [tracked_changes_edfi].[SurveySectionResponseEducationOrganizationTargetAssociation] +( + OldEducationOrganizationId int NOT NULL, + OldNamespace nvarchar(255) NOT NULL, + OldSurveyIdentifier nvarchar(60) NOT NULL, + OldSurveyResponseIdentifier nvarchar(60) NOT NULL, + OldSurveySectionTitle nvarchar(255) NOT NULL, + NewEducationOrganizationId int NULL, + NewNamespace nvarchar(255) NULL, + NewSurveyIdentifier nvarchar(60) NULL, + NewSurveyResponseIdentifier nvarchar(60) NULL, + NewSurveySectionTitle nvarchar(255) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT SurveySectionResponseEducationOrganizationTargetAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_edfi].[SurveySectionResponseStaffTargetAssociation]')) +CREATE TABLE [tracked_changes_edfi].[SurveySectionResponseStaffTargetAssociation] +( + OldNamespace nvarchar(255) NOT NULL, + OldStaffUSI int NOT NULL, + OldStaffUniqueId nvarchar(32) NOT NULL, + OldSurveyIdentifier nvarchar(60) NOT NULL, + OldSurveyResponseIdentifier nvarchar(60) NOT NULL, + OldSurveySectionTitle nvarchar(255) NOT NULL, + NewNamespace nvarchar(255) NULL, + NewStaffUSI int NULL, + NewStaffUniqueId nvarchar(32) NULL, + NewSurveyIdentifier nvarchar(60) NULL, + NewSurveyResponseIdentifier nvarchar(60) NULL, + NewSurveySectionTitle nvarchar(255) NULL, + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + Discriminator nvarchar(128) NULL, + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT SurveySectionResponseStaffTargetAssociation_PK PRIMARY KEY CLUSTERED (ChangeVersion) +) + diff --git a/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0040-CreateTriggerUpdateChangeVersionGenerator.sql b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0210-CreateTriggersForChangeVersionAndKeyChanges.sql similarity index 59% rename from Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0040-CreateTriggerUpdateChangeVersionGenerator.sql rename to Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0210-CreateTriggersForChangeVersionAndKeyChanges.sql index 802c4db7dc..be93c28ac2 100644 --- a/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0040-CreateTriggerUpdateChangeVersionGenerator.sql +++ b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0210-CreateTriggersForChangeVersionAndKeyChanges.sql @@ -3,6 +3,9 @@ -- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. -- See the LICENSE and NOTICES files in the project root for more information. +DROP TRIGGER IF EXISTS [edfi].[edfi_AcademicWeek_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_AcademicWeek_TR_UpdateChangeVersion] ON [edfi].[AcademicWeek] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -13,6 +16,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Account_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_Account_TR_UpdateChangeVersion] ON [edfi].[Account] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -23,26 +29,35 @@ BEGIN END GO -CREATE TRIGGER [edfi].[edfi_AccountCode_TR_UpdateChangeVersion] ON [edfi].[AccountCode] AFTER UPDATE AS +DROP TRIGGER IF EXISTS [edfi].[edfi_AccountabilityRating_TR_UpdateChangeVersion] +GO + +CREATE TRIGGER [edfi].[edfi_AccountabilityRating_TR_UpdateChangeVersion] ON [edfi].[AccountabilityRating] AFTER UPDATE AS BEGIN SET NOCOUNT ON; - UPDATE [edfi].[AccountCode] + UPDATE [edfi].[AccountabilityRating] SET ChangeVersion = (NEXT VALUE FOR [changes].[ChangeVersionSequence]) - FROM [edfi].[AccountCode] u + FROM [edfi].[AccountabilityRating] u WHERE EXISTS (SELECT 1 FROM inserted i WHERE i.id = u.id); END GO -CREATE TRIGGER [edfi].[edfi_AccountabilityRating_TR_UpdateChangeVersion] ON [edfi].[AccountabilityRating] AFTER UPDATE AS +DROP TRIGGER IF EXISTS [edfi].[edfi_AccountCode_TR_UpdateChangeVersion] +GO + +CREATE TRIGGER [edfi].[edfi_AccountCode_TR_UpdateChangeVersion] ON [edfi].[AccountCode] AFTER UPDATE AS BEGIN SET NOCOUNT ON; - UPDATE [edfi].[AccountabilityRating] + UPDATE [edfi].[AccountCode] SET ChangeVersion = (NEXT VALUE FOR [changes].[ChangeVersionSequence]) - FROM [edfi].[AccountabilityRating] u + FROM [edfi].[AccountCode] u WHERE EXISTS (SELECT 1 FROM inserted i WHERE i.id = u.id); END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Actual_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_Actual_TR_UpdateChangeVersion] ON [edfi].[Actual] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -53,6 +68,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Assessment_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_Assessment_TR_UpdateChangeVersion] ON [edfi].[Assessment] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -63,6 +81,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_AssessmentItem_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_AssessmentItem_TR_UpdateChangeVersion] ON [edfi].[AssessmentItem] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -73,6 +94,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_AssessmentScoreRangeLearningStandard_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_AssessmentScoreRangeLearningStandard_TR_UpdateChangeVersion] ON [edfi].[AssessmentScoreRangeLearningStandard] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -83,6 +107,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_BellSchedule_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_BellSchedule_TR_UpdateChangeVersion] ON [edfi].[BellSchedule] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -93,6 +120,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Budget_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_Budget_TR_UpdateChangeVersion] ON [edfi].[Budget] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -103,6 +133,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Calendar_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_Calendar_TR_UpdateChangeVersion] ON [edfi].[Calendar] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -113,6 +146,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_CalendarDate_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_CalendarDate_TR_UpdateChangeVersion] ON [edfi].[CalendarDate] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -123,6 +159,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_ClassPeriod_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_ClassPeriod_TR_UpdateChangeVersion] ON [edfi].[ClassPeriod] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -130,9 +169,25 @@ BEGIN SET ChangeVersion = (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM [edfi].[ClassPeriod] u WHERE EXISTS (SELECT 1 FROM inserted i WHERE i.id = u.id); + + -- Handle key changes + INSERT INTO tracked_changes_edfi.ClassPeriod( + OldClassPeriodName, OldSchoolId, + NewClassPeriodName, NewSchoolId, + Id, ChangeVersion) + SELECT + d.ClassPeriodName, d.SchoolId, + i.ClassPeriodName, i.SchoolId, + d.Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + FROM deleted d INNER JOIN inserted i ON d.Id = i.Id + WHERE + d.ClassPeriodName <> i.ClassPeriodName OR d.SchoolId <> i.SchoolId; END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Cohort_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_Cohort_TR_UpdateChangeVersion] ON [edfi].[Cohort] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -143,6 +198,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_CommunityProviderLicense_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_CommunityProviderLicense_TR_UpdateChangeVersion] ON [edfi].[CommunityProviderLicense] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -153,6 +211,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_CompetencyObjective_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_CompetencyObjective_TR_UpdateChangeVersion] ON [edfi].[CompetencyObjective] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -163,6 +224,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_ContractedStaff_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_ContractedStaff_TR_UpdateChangeVersion] ON [edfi].[ContractedStaff] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -173,6 +237,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Course_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_Course_TR_UpdateChangeVersion] ON [edfi].[Course] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -183,6 +250,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_CourseOffering_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_CourseOffering_TR_UpdateChangeVersion] ON [edfi].[CourseOffering] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -190,9 +260,25 @@ BEGIN SET ChangeVersion = (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM [edfi].[CourseOffering] u WHERE EXISTS (SELECT 1 FROM inserted i WHERE i.id = u.id); + + -- Handle key changes + INSERT INTO tracked_changes_edfi.CourseOffering( + OldLocalCourseCode, OldSchoolId, OldSchoolYear, OldSessionName, + NewLocalCourseCode, NewSchoolId, NewSchoolYear, NewSessionName, + Id, ChangeVersion) + SELECT + d.LocalCourseCode, d.SchoolId, d.SchoolYear, d.SessionName, + i.LocalCourseCode, i.SchoolId, i.SchoolYear, i.SessionName, + d.Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + FROM deleted d INNER JOIN inserted i ON d.Id = i.Id + WHERE + d.LocalCourseCode <> i.LocalCourseCode OR d.SchoolId <> i.SchoolId OR d.SchoolYear <> i.SchoolYear OR d.SessionName <> i.SessionName; END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_CourseTranscript_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_CourseTranscript_TR_UpdateChangeVersion] ON [edfi].[CourseTranscript] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -203,6 +289,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Credential_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_Credential_TR_UpdateChangeVersion] ON [edfi].[Credential] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -213,6 +302,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Descriptor_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_Descriptor_TR_UpdateChangeVersion] ON [edfi].[Descriptor] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -223,6 +315,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_DisciplineAction_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_DisciplineAction_TR_UpdateChangeVersion] ON [edfi].[DisciplineAction] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -233,6 +328,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_DisciplineIncident_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_DisciplineIncident_TR_UpdateChangeVersion] ON [edfi].[DisciplineIncident] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -243,6 +341,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_EducationContent_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_EducationContent_TR_UpdateChangeVersion] ON [edfi].[EducationContent] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -253,6 +354,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_EducationOrganization_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_EducationOrganization_TR_UpdateChangeVersion] ON [edfi].[EducationOrganization] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -263,6 +367,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_EducationOrganizationInterventionPrescriptionAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_EducationOrganizationInterventionPrescriptionAssociation_TR_UpdateChangeVersion] ON [edfi].[EducationOrganizationInterventionPrescriptionAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -273,6 +380,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_EducationOrganizationNetworkAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_EducationOrganizationNetworkAssociation_TR_UpdateChangeVersion] ON [edfi].[EducationOrganizationNetworkAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -283,6 +393,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_EducationOrganizationPeerAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_EducationOrganizationPeerAssociation_TR_UpdateChangeVersion] ON [edfi].[EducationOrganizationPeerAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -293,6 +406,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_FeederSchoolAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_FeederSchoolAssociation_TR_UpdateChangeVersion] ON [edfi].[FeederSchoolAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -303,6 +419,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_GeneralStudentProgramAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_GeneralStudentProgramAssociation_TR_UpdateChangeVersion] ON [edfi].[GeneralStudentProgramAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -313,6 +432,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Grade_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_Grade_TR_UpdateChangeVersion] ON [edfi].[Grade] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -320,7 +442,35 @@ BEGIN SET ChangeVersion = (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM [edfi].[Grade] u WHERE EXISTS (SELECT 1 FROM inserted i WHERE i.id = u.id); -END + + -- Handle key changes + INSERT INTO tracked_changes_edfi.Grade( + OldBeginDate, OldGradeTypeDescriptorId, OldGradeTypeDescriptorNamespace, OldGradeTypeDescriptorCodeValue, OldGradingPeriodDescriptorId, OldGradingPeriodDescriptorNamespace, OldGradingPeriodDescriptorCodeValue, OldGradingPeriodSchoolYear, OldGradingPeriodSequence, OldLocalCourseCode, OldSchoolId, OldSchoolYear, OldSectionIdentifier, OldSessionName, OldStudentUSI, OldStudentUniqueId, + NewBeginDate, NewGradeTypeDescriptorId, NewGradeTypeDescriptorNamespace, NewGradeTypeDescriptorCodeValue, NewGradingPeriodDescriptorId, NewGradingPeriodDescriptorNamespace, NewGradingPeriodDescriptorCodeValue, NewGradingPeriodSchoolYear, NewGradingPeriodSequence, NewLocalCourseCode, NewSchoolId, NewSchoolYear, NewSectionIdentifier, NewSessionName, NewStudentUSI, NewStudentUniqueId, + Id, ChangeVersion) + SELECT + d.BeginDate, d.GradeTypeDescriptorId, dj1.Namespace, dj1.CodeValue, d.GradingPeriodDescriptorId, dj2.Namespace, dj2.CodeValue, d.GradingPeriodSchoolYear, d.GradingPeriodSequence, d.LocalCourseCode, d.SchoolId, d.SchoolYear, d.SectionIdentifier, d.SessionName, d.StudentUSI, dj10.StudentUniqueId, + i.BeginDate, i.GradeTypeDescriptorId, ij1.Namespace, ij1.CodeValue, i.GradingPeriodDescriptorId, ij2.Namespace, ij2.CodeValue, i.GradingPeriodSchoolYear, i.GradingPeriodSequence, i.LocalCourseCode, i.SchoolId, i.SchoolYear, i.SectionIdentifier, i.SessionName, i.StudentUSI, ij10.StudentUniqueId, + d.Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + FROM deleted d INNER JOIN inserted i ON d.Id = i.Id + INNER JOIN edfi.Descriptor dj1 + ON d.GradeTypeDescriptorId = dj1.DescriptorId + INNER JOIN edfi.Descriptor dj2 + ON d.GradingPeriodDescriptorId = dj2.DescriptorId + INNER JOIN edfi.Student dj10 + ON d.StudentUSI = dj10.StudentUSI + INNER JOIN edfi.Descriptor ij1 + ON i.GradeTypeDescriptorId = ij1.DescriptorId + INNER JOIN edfi.Descriptor ij2 + ON i.GradingPeriodDescriptorId = ij2.DescriptorId + INNER JOIN edfi.Student ij10 + ON i.StudentUSI = ij10.StudentUSI + WHERE + d.BeginDate <> i.BeginDate OR d.GradeTypeDescriptorId <> i.GradeTypeDescriptorId OR d.GradingPeriodDescriptorId <> i.GradingPeriodDescriptorId OR d.GradingPeriodSchoolYear <> i.GradingPeriodSchoolYear OR d.GradingPeriodSequence <> i.GradingPeriodSequence OR d.LocalCourseCode <> i.LocalCourseCode OR d.SchoolId <> i.SchoolId OR d.SchoolYear <> i.SchoolYear OR d.SectionIdentifier <> i.SectionIdentifier OR d.SessionName <> i.SessionName OR d.StudentUSI <> i.StudentUSI; +END +GO + +DROP TRIGGER IF EXISTS [edfi].[edfi_GradebookEntry_TR_UpdateChangeVersion] GO CREATE TRIGGER [edfi].[edfi_GradebookEntry_TR_UpdateChangeVersion] ON [edfi].[GradebookEntry] AFTER UPDATE AS @@ -330,9 +480,25 @@ BEGIN SET ChangeVersion = (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM [edfi].[GradebookEntry] u WHERE EXISTS (SELECT 1 FROM inserted i WHERE i.id = u.id); + + -- Handle key changes + INSERT INTO tracked_changes_edfi.GradebookEntry( + OldDateAssigned, OldGradebookEntryTitle, OldLocalCourseCode, OldSchoolId, OldSchoolYear, OldSectionIdentifier, OldSessionName, + NewDateAssigned, NewGradebookEntryTitle, NewLocalCourseCode, NewSchoolId, NewSchoolYear, NewSectionIdentifier, NewSessionName, + Id, ChangeVersion) + SELECT + d.DateAssigned, d.GradebookEntryTitle, d.LocalCourseCode, d.SchoolId, d.SchoolYear, d.SectionIdentifier, d.SessionName, + i.DateAssigned, i.GradebookEntryTitle, i.LocalCourseCode, i.SchoolId, i.SchoolYear, i.SectionIdentifier, i.SessionName, + d.Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + FROM deleted d INNER JOIN inserted i ON d.Id = i.Id + WHERE + d.DateAssigned <> i.DateAssigned OR d.GradebookEntryTitle <> i.GradebookEntryTitle OR d.LocalCourseCode <> i.LocalCourseCode OR d.SchoolId <> i.SchoolId OR d.SchoolYear <> i.SchoolYear OR d.SectionIdentifier <> i.SectionIdentifier OR d.SessionName <> i.SessionName; END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_GradingPeriod_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_GradingPeriod_TR_UpdateChangeVersion] ON [edfi].[GradingPeriod] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -343,6 +509,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_GraduationPlan_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_GraduationPlan_TR_UpdateChangeVersion] ON [edfi].[GraduationPlan] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -353,6 +522,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Intervention_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_Intervention_TR_UpdateChangeVersion] ON [edfi].[Intervention] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -363,6 +535,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_InterventionPrescription_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_InterventionPrescription_TR_UpdateChangeVersion] ON [edfi].[InterventionPrescription] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -373,6 +548,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_InterventionStudy_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_InterventionStudy_TR_UpdateChangeVersion] ON [edfi].[InterventionStudy] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -383,6 +561,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_LearningObjective_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_LearningObjective_TR_UpdateChangeVersion] ON [edfi].[LearningObjective] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -393,6 +574,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_LearningStandard_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_LearningStandard_TR_UpdateChangeVersion] ON [edfi].[LearningStandard] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -403,6 +587,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_LearningStandardEquivalenceAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_LearningStandardEquivalenceAssociation_TR_UpdateChangeVersion] ON [edfi].[LearningStandardEquivalenceAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -413,6 +600,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Location_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_Location_TR_UpdateChangeVersion] ON [edfi].[Location] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -420,9 +610,25 @@ BEGIN SET ChangeVersion = (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM [edfi].[Location] u WHERE EXISTS (SELECT 1 FROM inserted i WHERE i.id = u.id); + + -- Handle key changes + INSERT INTO tracked_changes_edfi.Location( + OldClassroomIdentificationCode, OldSchoolId, + NewClassroomIdentificationCode, NewSchoolId, + Id, ChangeVersion) + SELECT + d.ClassroomIdentificationCode, d.SchoolId, + i.ClassroomIdentificationCode, i.SchoolId, + d.Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + FROM deleted d INNER JOIN inserted i ON d.Id = i.Id + WHERE + d.ClassroomIdentificationCode <> i.ClassroomIdentificationCode OR d.SchoolId <> i.SchoolId; END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_ObjectiveAssessment_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_ObjectiveAssessment_TR_UpdateChangeVersion] ON [edfi].[ObjectiveAssessment] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -433,6 +639,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_OpenStaffPosition_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_OpenStaffPosition_TR_UpdateChangeVersion] ON [edfi].[OpenStaffPosition] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -443,6 +652,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Parent_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_Parent_TR_UpdateChangeVersion] ON [edfi].[Parent] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -453,6 +665,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Payroll_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_Payroll_TR_UpdateChangeVersion] ON [edfi].[Payroll] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -463,6 +678,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Person_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_Person_TR_UpdateChangeVersion] ON [edfi].[Person] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -473,6 +691,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_PostSecondaryEvent_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_PostSecondaryEvent_TR_UpdateChangeVersion] ON [edfi].[PostSecondaryEvent] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -483,6 +704,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Program_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_Program_TR_UpdateChangeVersion] ON [edfi].[Program] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -493,6 +717,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_ReportCard_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_ReportCard_TR_UpdateChangeVersion] ON [edfi].[ReportCard] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -503,6 +730,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_RestraintEvent_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_RestraintEvent_TR_UpdateChangeVersion] ON [edfi].[RestraintEvent] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -513,6 +743,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SchoolYearType_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_SchoolYearType_TR_UpdateChangeVersion] ON [edfi].[SchoolYearType] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -523,6 +756,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Section_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_Section_TR_UpdateChangeVersion] ON [edfi].[Section] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -530,9 +766,25 @@ BEGIN SET ChangeVersion = (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM [edfi].[Section] u WHERE EXISTS (SELECT 1 FROM inserted i WHERE i.id = u.id); + + -- Handle key changes + INSERT INTO tracked_changes_edfi.Section( + OldLocalCourseCode, OldSchoolId, OldSchoolYear, OldSectionIdentifier, OldSessionName, + NewLocalCourseCode, NewSchoolId, NewSchoolYear, NewSectionIdentifier, NewSessionName, + Id, ChangeVersion) + SELECT + d.LocalCourseCode, d.SchoolId, d.SchoolYear, d.SectionIdentifier, d.SessionName, + i.LocalCourseCode, i.SchoolId, i.SchoolYear, i.SectionIdentifier, i.SessionName, + d.Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + FROM deleted d INNER JOIN inserted i ON d.Id = i.Id + WHERE + d.LocalCourseCode <> i.LocalCourseCode OR d.SchoolId <> i.SchoolId OR d.SchoolYear <> i.SchoolYear OR d.SectionIdentifier <> i.SectionIdentifier OR d.SessionName <> i.SessionName; END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SectionAttendanceTakenEvent_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_SectionAttendanceTakenEvent_TR_UpdateChangeVersion] ON [edfi].[SectionAttendanceTakenEvent] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -540,9 +792,25 @@ BEGIN SET ChangeVersion = (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM [edfi].[SectionAttendanceTakenEvent] u WHERE EXISTS (SELECT 1 FROM inserted i WHERE i.id = u.id); + + -- Handle key changes + INSERT INTO tracked_changes_edfi.SectionAttendanceTakenEvent( + OldCalendarCode, OldDate, OldLocalCourseCode, OldSchoolId, OldSchoolYear, OldSectionIdentifier, OldSessionName, + NewCalendarCode, NewDate, NewLocalCourseCode, NewSchoolId, NewSchoolYear, NewSectionIdentifier, NewSessionName, + Id, ChangeVersion) + SELECT + d.CalendarCode, d.Date, d.LocalCourseCode, d.SchoolId, d.SchoolYear, d.SectionIdentifier, d.SessionName, + i.CalendarCode, i.Date, i.LocalCourseCode, i.SchoolId, i.SchoolYear, i.SectionIdentifier, i.SessionName, + d.Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + FROM deleted d INNER JOIN inserted i ON d.Id = i.Id + WHERE + d.CalendarCode <> i.CalendarCode OR d.Date <> i.Date OR d.LocalCourseCode <> i.LocalCourseCode OR d.SchoolId <> i.SchoolId OR d.SchoolYear <> i.SchoolYear OR d.SectionIdentifier <> i.SectionIdentifier OR d.SessionName <> i.SessionName; END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Session_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_Session_TR_UpdateChangeVersion] ON [edfi].[Session] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -550,9 +818,25 @@ BEGIN SET ChangeVersion = (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM [edfi].[Session] u WHERE EXISTS (SELECT 1 FROM inserted i WHERE i.id = u.id); + + -- Handle key changes + INSERT INTO tracked_changes_edfi.Session( + OldSchoolId, OldSchoolYear, OldSessionName, + NewSchoolId, NewSchoolYear, NewSessionName, + Id, ChangeVersion) + SELECT + d.SchoolId, d.SchoolYear, d.SessionName, + i.SchoolId, i.SchoolYear, i.SessionName, + d.Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + FROM deleted d INNER JOIN inserted i ON d.Id = i.Id + WHERE + d.SchoolId <> i.SchoolId OR d.SchoolYear <> i.SchoolYear OR d.SessionName <> i.SessionName; END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Staff_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_Staff_TR_UpdateChangeVersion] ON [edfi].[Staff] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -563,6 +847,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StaffAbsenceEvent_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StaffAbsenceEvent_TR_UpdateChangeVersion] ON [edfi].[StaffAbsenceEvent] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -573,6 +860,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StaffCohortAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StaffCohortAssociation_TR_UpdateChangeVersion] ON [edfi].[StaffCohortAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -583,6 +873,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StaffDisciplineIncidentAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StaffDisciplineIncidentAssociation_TR_UpdateChangeVersion] ON [edfi].[StaffDisciplineIncidentAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -593,6 +886,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StaffEducationOrganizationAssignmentAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StaffEducationOrganizationAssignmentAssociation_TR_UpdateChangeVersion] ON [edfi].[StaffEducationOrganizationAssignmentAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -603,6 +899,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StaffEducationOrganizationContactAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StaffEducationOrganizationContactAssociation_TR_UpdateChangeVersion] ON [edfi].[StaffEducationOrganizationContactAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -613,6 +912,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StaffEducationOrganizationEmploymentAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StaffEducationOrganizationEmploymentAssociation_TR_UpdateChangeVersion] ON [edfi].[StaffEducationOrganizationEmploymentAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -623,6 +925,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StaffLeave_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StaffLeave_TR_UpdateChangeVersion] ON [edfi].[StaffLeave] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -633,6 +938,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StaffProgramAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StaffProgramAssociation_TR_UpdateChangeVersion] ON [edfi].[StaffProgramAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -643,6 +951,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StaffSchoolAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StaffSchoolAssociation_TR_UpdateChangeVersion] ON [edfi].[StaffSchoolAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -653,6 +964,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StaffSectionAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StaffSectionAssociation_TR_UpdateChangeVersion] ON [edfi].[StaffSectionAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -660,9 +974,29 @@ BEGIN SET ChangeVersion = (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM [edfi].[StaffSectionAssociation] u WHERE EXISTS (SELECT 1 FROM inserted i WHERE i.id = u.id); + + -- Handle key changes + INSERT INTO tracked_changes_edfi.StaffSectionAssociation( + OldLocalCourseCode, OldSchoolId, OldSchoolYear, OldSectionIdentifier, OldSessionName, OldStaffUSI, OldStaffUniqueId, + NewLocalCourseCode, NewSchoolId, NewSchoolYear, NewSectionIdentifier, NewSessionName, NewStaffUSI, NewStaffUniqueId, + Id, ChangeVersion) + SELECT + d.LocalCourseCode, d.SchoolId, d.SchoolYear, d.SectionIdentifier, d.SessionName, d.StaffUSI, dj5.StaffUniqueId, + i.LocalCourseCode, i.SchoolId, i.SchoolYear, i.SectionIdentifier, i.SessionName, i.StaffUSI, ij5.StaffUniqueId, + d.Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + FROM deleted d INNER JOIN inserted i ON d.Id = i.Id + INNER JOIN edfi.Staff dj5 + ON d.StaffUSI = dj5.StaffUSI + INNER JOIN edfi.Staff ij5 + ON i.StaffUSI = ij5.StaffUSI + WHERE + d.LocalCourseCode <> i.LocalCourseCode OR d.SchoolId <> i.SchoolId OR d.SchoolYear <> i.SchoolYear OR d.SectionIdentifier <> i.SectionIdentifier OR d.SessionName <> i.SessionName OR d.StaffUSI <> i.StaffUSI; END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Student_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_Student_TR_UpdateChangeVersion] ON [edfi].[Student] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -673,6 +1007,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentAcademicRecord_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StudentAcademicRecord_TR_UpdateChangeVersion] ON [edfi].[StudentAcademicRecord] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -683,6 +1020,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentAssessment_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StudentAssessment_TR_UpdateChangeVersion] ON [edfi].[StudentAssessment] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -693,6 +1033,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentCohortAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StudentCohortAssociation_TR_UpdateChangeVersion] ON [edfi].[StudentCohortAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -703,6 +1046,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentCompetencyObjective_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StudentCompetencyObjective_TR_UpdateChangeVersion] ON [edfi].[StudentCompetencyObjective] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -713,6 +1059,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentDisciplineIncidentAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StudentDisciplineIncidentAssociation_TR_UpdateChangeVersion] ON [edfi].[StudentDisciplineIncidentAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -723,6 +1072,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentDisciplineIncidentBehaviorAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StudentDisciplineIncidentBehaviorAssociation_TR_UpdateChangeVersion] ON [edfi].[StudentDisciplineIncidentBehaviorAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -733,6 +1085,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentDisciplineIncidentNonOffenderAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StudentDisciplineIncidentNonOffenderAssociation_TR_UpdateChangeVersion] ON [edfi].[StudentDisciplineIncidentNonOffenderAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -743,6 +1098,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentEducationOrganizationAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StudentEducationOrganizationAssociation_TR_UpdateChangeVersion] ON [edfi].[StudentEducationOrganizationAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -753,6 +1111,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentEducationOrganizationResponsibilityAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StudentEducationOrganizationResponsibilityAssociation_TR_UpdateChangeVersion] ON [edfi].[StudentEducationOrganizationResponsibilityAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -763,6 +1124,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentGradebookEntry_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StudentGradebookEntry_TR_UpdateChangeVersion] ON [edfi].[StudentGradebookEntry] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -770,9 +1134,29 @@ BEGIN SET ChangeVersion = (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM [edfi].[StudentGradebookEntry] u WHERE EXISTS (SELECT 1 FROM inserted i WHERE i.id = u.id); + + -- Handle key changes + INSERT INTO tracked_changes_edfi.StudentGradebookEntry( + OldBeginDate, OldDateAssigned, OldGradebookEntryTitle, OldLocalCourseCode, OldSchoolId, OldSchoolYear, OldSectionIdentifier, OldSessionName, OldStudentUSI, OldStudentUniqueId, + NewBeginDate, NewDateAssigned, NewGradebookEntryTitle, NewLocalCourseCode, NewSchoolId, NewSchoolYear, NewSectionIdentifier, NewSessionName, NewStudentUSI, NewStudentUniqueId, + Id, ChangeVersion) + SELECT + d.BeginDate, d.DateAssigned, d.GradebookEntryTitle, d.LocalCourseCode, d.SchoolId, d.SchoolYear, d.SectionIdentifier, d.SessionName, d.StudentUSI, dj8.StudentUniqueId, + i.BeginDate, i.DateAssigned, i.GradebookEntryTitle, i.LocalCourseCode, i.SchoolId, i.SchoolYear, i.SectionIdentifier, i.SessionName, i.StudentUSI, ij8.StudentUniqueId, + d.Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + FROM deleted d INNER JOIN inserted i ON d.Id = i.Id + INNER JOIN edfi.Student dj8 + ON d.StudentUSI = dj8.StudentUSI + INNER JOIN edfi.Student ij8 + ON i.StudentUSI = ij8.StudentUSI + WHERE + d.BeginDate <> i.BeginDate OR d.DateAssigned <> i.DateAssigned OR d.GradebookEntryTitle <> i.GradebookEntryTitle OR d.LocalCourseCode <> i.LocalCourseCode OR d.SchoolId <> i.SchoolId OR d.SchoolYear <> i.SchoolYear OR d.SectionIdentifier <> i.SectionIdentifier OR d.SessionName <> i.SessionName OR d.StudentUSI <> i.StudentUSI; END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentInterventionAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StudentInterventionAssociation_TR_UpdateChangeVersion] ON [edfi].[StudentInterventionAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -783,6 +1167,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentInterventionAttendanceEvent_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StudentInterventionAttendanceEvent_TR_UpdateChangeVersion] ON [edfi].[StudentInterventionAttendanceEvent] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -793,6 +1180,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentLearningObjective_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StudentLearningObjective_TR_UpdateChangeVersion] ON [edfi].[StudentLearningObjective] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -803,6 +1193,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentParentAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StudentParentAssociation_TR_UpdateChangeVersion] ON [edfi].[StudentParentAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -813,6 +1206,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentProgramAttendanceEvent_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StudentProgramAttendanceEvent_TR_UpdateChangeVersion] ON [edfi].[StudentProgramAttendanceEvent] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -823,6 +1219,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentSchoolAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StudentSchoolAssociation_TR_UpdateChangeVersion] ON [edfi].[StudentSchoolAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -830,9 +1229,29 @@ BEGIN SET ChangeVersion = (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM [edfi].[StudentSchoolAssociation] u WHERE EXISTS (SELECT 1 FROM inserted i WHERE i.id = u.id); + + -- Handle key changes + INSERT INTO tracked_changes_edfi.StudentSchoolAssociation( + OldEntryDate, OldSchoolId, OldStudentUSI, OldStudentUniqueId, + NewEntryDate, NewSchoolId, NewStudentUSI, NewStudentUniqueId, + Id, ChangeVersion) + SELECT + d.EntryDate, d.SchoolId, d.StudentUSI, dj2.StudentUniqueId, + i.EntryDate, i.SchoolId, i.StudentUSI, ij2.StudentUniqueId, + d.Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + FROM deleted d INNER JOIN inserted i ON d.Id = i.Id + INNER JOIN edfi.Student dj2 + ON d.StudentUSI = dj2.StudentUSI + INNER JOIN edfi.Student ij2 + ON i.StudentUSI = ij2.StudentUSI + WHERE + d.EntryDate <> i.EntryDate OR d.SchoolId <> i.SchoolId OR d.StudentUSI <> i.StudentUSI; END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentSchoolAttendanceEvent_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StudentSchoolAttendanceEvent_TR_UpdateChangeVersion] ON [edfi].[StudentSchoolAttendanceEvent] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -840,9 +1259,33 @@ BEGIN SET ChangeVersion = (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM [edfi].[StudentSchoolAttendanceEvent] u WHERE EXISTS (SELECT 1 FROM inserted i WHERE i.id = u.id); + + -- Handle key changes + INSERT INTO tracked_changes_edfi.StudentSchoolAttendanceEvent( + OldAttendanceEventCategoryDescriptorId, OldAttendanceEventCategoryDescriptorNamespace, OldAttendanceEventCategoryDescriptorCodeValue, OldEventDate, OldSchoolId, OldSchoolYear, OldSessionName, OldStudentUSI, OldStudentUniqueId, + NewAttendanceEventCategoryDescriptorId, NewAttendanceEventCategoryDescriptorNamespace, NewAttendanceEventCategoryDescriptorCodeValue, NewEventDate, NewSchoolId, NewSchoolYear, NewSessionName, NewStudentUSI, NewStudentUniqueId, + Id, ChangeVersion) + SELECT + d.AttendanceEventCategoryDescriptorId, dj0.Namespace, dj0.CodeValue, d.EventDate, d.SchoolId, d.SchoolYear, d.SessionName, d.StudentUSI, dj5.StudentUniqueId, + i.AttendanceEventCategoryDescriptorId, ij0.Namespace, ij0.CodeValue, i.EventDate, i.SchoolId, i.SchoolYear, i.SessionName, i.StudentUSI, ij5.StudentUniqueId, + d.Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + FROM deleted d INNER JOIN inserted i ON d.Id = i.Id + INNER JOIN edfi.Descriptor dj0 + ON d.AttendanceEventCategoryDescriptorId = dj0.DescriptorId + INNER JOIN edfi.Student dj5 + ON d.StudentUSI = dj5.StudentUSI + INNER JOIN edfi.Descriptor ij0 + ON i.AttendanceEventCategoryDescriptorId = ij0.DescriptorId + INNER JOIN edfi.Student ij5 + ON i.StudentUSI = ij5.StudentUSI + WHERE + d.AttendanceEventCategoryDescriptorId <> i.AttendanceEventCategoryDescriptorId OR d.EventDate <> i.EventDate OR d.SchoolId <> i.SchoolId OR d.SchoolYear <> i.SchoolYear OR d.SessionName <> i.SessionName OR d.StudentUSI <> i.StudentUSI; END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentSectionAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StudentSectionAssociation_TR_UpdateChangeVersion] ON [edfi].[StudentSectionAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -850,9 +1293,29 @@ BEGIN SET ChangeVersion = (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM [edfi].[StudentSectionAssociation] u WHERE EXISTS (SELECT 1 FROM inserted i WHERE i.id = u.id); + + -- Handle key changes + INSERT INTO tracked_changes_edfi.StudentSectionAssociation( + OldBeginDate, OldLocalCourseCode, OldSchoolId, OldSchoolYear, OldSectionIdentifier, OldSessionName, OldStudentUSI, OldStudentUniqueId, + NewBeginDate, NewLocalCourseCode, NewSchoolId, NewSchoolYear, NewSectionIdentifier, NewSessionName, NewStudentUSI, NewStudentUniqueId, + Id, ChangeVersion) + SELECT + d.BeginDate, d.LocalCourseCode, d.SchoolId, d.SchoolYear, d.SectionIdentifier, d.SessionName, d.StudentUSI, dj6.StudentUniqueId, + i.BeginDate, i.LocalCourseCode, i.SchoolId, i.SchoolYear, i.SectionIdentifier, i.SessionName, i.StudentUSI, ij6.StudentUniqueId, + d.Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + FROM deleted d INNER JOIN inserted i ON d.Id = i.Id + INNER JOIN edfi.Student dj6 + ON d.StudentUSI = dj6.StudentUSI + INNER JOIN edfi.Student ij6 + ON i.StudentUSI = ij6.StudentUSI + WHERE + d.BeginDate <> i.BeginDate OR d.LocalCourseCode <> i.LocalCourseCode OR d.SchoolId <> i.SchoolId OR d.SchoolYear <> i.SchoolYear OR d.SectionIdentifier <> i.SectionIdentifier OR d.SessionName <> i.SessionName OR d.StudentUSI <> i.StudentUSI; END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentSectionAttendanceEvent_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_StudentSectionAttendanceEvent_TR_UpdateChangeVersion] ON [edfi].[StudentSectionAttendanceEvent] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -860,9 +1323,33 @@ BEGIN SET ChangeVersion = (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM [edfi].[StudentSectionAttendanceEvent] u WHERE EXISTS (SELECT 1 FROM inserted i WHERE i.id = u.id); + + -- Handle key changes + INSERT INTO tracked_changes_edfi.StudentSectionAttendanceEvent( + OldAttendanceEventCategoryDescriptorId, OldAttendanceEventCategoryDescriptorNamespace, OldAttendanceEventCategoryDescriptorCodeValue, OldEventDate, OldLocalCourseCode, OldSchoolId, OldSchoolYear, OldSectionIdentifier, OldSessionName, OldStudentUSI, OldStudentUniqueId, + NewAttendanceEventCategoryDescriptorId, NewAttendanceEventCategoryDescriptorNamespace, NewAttendanceEventCategoryDescriptorCodeValue, NewEventDate, NewLocalCourseCode, NewSchoolId, NewSchoolYear, NewSectionIdentifier, NewSessionName, NewStudentUSI, NewStudentUniqueId, + Id, ChangeVersion) + SELECT + d.AttendanceEventCategoryDescriptorId, dj0.Namespace, dj0.CodeValue, d.EventDate, d.LocalCourseCode, d.SchoolId, d.SchoolYear, d.SectionIdentifier, d.SessionName, d.StudentUSI, dj7.StudentUniqueId, + i.AttendanceEventCategoryDescriptorId, ij0.Namespace, ij0.CodeValue, i.EventDate, i.LocalCourseCode, i.SchoolId, i.SchoolYear, i.SectionIdentifier, i.SessionName, i.StudentUSI, ij7.StudentUniqueId, + d.Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + FROM deleted d INNER JOIN inserted i ON d.Id = i.Id + INNER JOIN edfi.Descriptor dj0 + ON d.AttendanceEventCategoryDescriptorId = dj0.DescriptorId + INNER JOIN edfi.Student dj7 + ON d.StudentUSI = dj7.StudentUSI + INNER JOIN edfi.Descriptor ij0 + ON i.AttendanceEventCategoryDescriptorId = ij0.DescriptorId + INNER JOIN edfi.Student ij7 + ON i.StudentUSI = ij7.StudentUSI + WHERE + d.AttendanceEventCategoryDescriptorId <> i.AttendanceEventCategoryDescriptorId OR d.EventDate <> i.EventDate OR d.LocalCourseCode <> i.LocalCourseCode OR d.SchoolId <> i.SchoolId OR d.SchoolYear <> i.SchoolYear OR d.SectionIdentifier <> i.SectionIdentifier OR d.SessionName <> i.SessionName OR d.StudentUSI <> i.StudentUSI; END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Survey_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_Survey_TR_UpdateChangeVersion] ON [edfi].[Survey] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -873,6 +1360,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveyCourseAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_SurveyCourseAssociation_TR_UpdateChangeVersion] ON [edfi].[SurveyCourseAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -883,6 +1373,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveyProgramAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_SurveyProgramAssociation_TR_UpdateChangeVersion] ON [edfi].[SurveyProgramAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -893,6 +1386,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveyQuestion_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_SurveyQuestion_TR_UpdateChangeVersion] ON [edfi].[SurveyQuestion] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -903,6 +1399,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveyQuestionResponse_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_SurveyQuestionResponse_TR_UpdateChangeVersion] ON [edfi].[SurveyQuestionResponse] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -913,6 +1412,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveyResponse_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_SurveyResponse_TR_UpdateChangeVersion] ON [edfi].[SurveyResponse] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -923,6 +1425,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveyResponseEducationOrganizationTargetAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_SurveyResponseEducationOrganizationTargetAssociation_TR_UpdateChangeVersion] ON [edfi].[SurveyResponseEducationOrganizationTargetAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -933,6 +1438,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveyResponseStaffTargetAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_SurveyResponseStaffTargetAssociation_TR_UpdateChangeVersion] ON [edfi].[SurveyResponseStaffTargetAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -943,6 +1451,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveySection_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_SurveySection_TR_UpdateChangeVersion] ON [edfi].[SurveySection] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -953,6 +1464,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveySectionAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_SurveySectionAssociation_TR_UpdateChangeVersion] ON [edfi].[SurveySectionAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -960,9 +1474,25 @@ BEGIN SET ChangeVersion = (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM [edfi].[SurveySectionAssociation] u WHERE EXISTS (SELECT 1 FROM inserted i WHERE i.id = u.id); + + -- Handle key changes + INSERT INTO tracked_changes_edfi.SurveySectionAssociation( + OldLocalCourseCode, OldNamespace, OldSchoolId, OldSchoolYear, OldSectionIdentifier, OldSessionName, OldSurveyIdentifier, + NewLocalCourseCode, NewNamespace, NewSchoolId, NewSchoolYear, NewSectionIdentifier, NewSessionName, NewSurveyIdentifier, + Id, ChangeVersion) + SELECT + d.LocalCourseCode, d.Namespace, d.SchoolId, d.SchoolYear, d.SectionIdentifier, d.SessionName, d.SurveyIdentifier, + i.LocalCourseCode, i.Namespace, i.SchoolId, i.SchoolYear, i.SectionIdentifier, i.SessionName, i.SurveyIdentifier, + d.Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + FROM deleted d INNER JOIN inserted i ON d.Id = i.Id + WHERE + d.LocalCourseCode <> i.LocalCourseCode OR d.Namespace <> i.Namespace OR d.SchoolId <> i.SchoolId OR d.SchoolYear <> i.SchoolYear OR d.SectionIdentifier <> i.SectionIdentifier OR d.SessionName <> i.SessionName OR d.SurveyIdentifier <> i.SurveyIdentifier; END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveySectionResponse_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_SurveySectionResponse_TR_UpdateChangeVersion] ON [edfi].[SurveySectionResponse] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -973,6 +1503,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveySectionResponseEducationOrganizationTargetAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_SurveySectionResponseEducationOrganizationTargetAssociation_TR_UpdateChangeVersion] ON [edfi].[SurveySectionResponseEducationOrganizationTargetAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; @@ -983,6 +1516,9 @@ BEGIN END GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveySectionResponseStaffTargetAssociation_TR_UpdateChangeVersion] +GO + CREATE TRIGGER [edfi].[edfi_SurveySectionResponseStaffTargetAssociation_TR_UpdateChangeVersion] ON [edfi].[SurveySectionResponseStaffTargetAssociation] AFTER UPDATE AS BEGIN SET NOCOUNT ON; diff --git a/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0060-CreateDeletedForTrackingTriggers.sql b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0220-CreateTriggersForDeleteTracking.sql similarity index 50% rename from Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0060-CreateDeletedForTrackingTriggers.sql rename to Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0220-CreateTriggersForDeleteTracking.sql index 63486cc37b..9f775fb415 100644 --- a/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0060-CreateDeletedForTrackingTriggers.sql +++ b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/0220-CreateTriggersForDeleteTracking.sql @@ -3,6 +3,9 @@ -- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. -- See the LICENSE and NOTICES files in the project root for more information. +DROP TRIGGER IF EXISTS [edfi].[edfi_AbsenceEventCategoryDescriptor_TR_DeleteTracking] +GO + CREATE TRIGGER [edfi].[edfi_AbsenceEventCategoryDescriptor_TR_DeleteTracking] ON [edfi].[AbsenceEventCategoryDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 @@ -10,8 +13,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AbsenceEventCategoryDescriptor](AbsenceEventCategoryDescriptorId, Id, ChangeVersion) - SELECT d.AbsenceEventCategoryDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.AbsenceEventCategoryDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.AbsenceEventCategoryDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.AbsenceEventCategoryDescriptorId = b.DescriptorId END @@ -19,7 +22,8 @@ GO ALTER TABLE [edfi].[AbsenceEventCategoryDescriptor] ENABLE TRIGGER [edfi_AbsenceEventCategoryDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_AcademicHonorCategoryDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_AcademicHonorCategoryDescriptor_TR_DeleteTracking] ON [edfi].[AcademicHonorCategoryDescriptor] AFTER DELETE AS BEGIN @@ -28,8 +32,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AcademicHonorCategoryDescriptor](AcademicHonorCategoryDescriptorId, Id, ChangeVersion) - SELECT d.AcademicHonorCategoryDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.AcademicHonorCategoryDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.AcademicHonorCategoryDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.AcademicHonorCategoryDescriptorId = b.DescriptorId END @@ -37,7 +41,8 @@ GO ALTER TABLE [edfi].[AcademicHonorCategoryDescriptor] ENABLE TRIGGER [edfi_AcademicHonorCategoryDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_AcademicSubjectDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_AcademicSubjectDescriptor_TR_DeleteTracking] ON [edfi].[AcademicSubjectDescriptor] AFTER DELETE AS BEGIN @@ -46,8 +51,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AcademicSubjectDescriptor](AcademicSubjectDescriptorId, Id, ChangeVersion) - SELECT d.AcademicSubjectDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.AcademicSubjectDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.AcademicSubjectDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.AcademicSubjectDescriptorId = b.DescriptorId END @@ -55,7 +60,8 @@ GO ALTER TABLE [edfi].[AcademicSubjectDescriptor] ENABLE TRIGGER [edfi_AcademicSubjectDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_AcademicWeek_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_AcademicWeek_TR_DeleteTracking] ON [edfi].[AcademicWeek] AFTER DELETE AS BEGIN @@ -64,8 +70,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AcademicWeek](SchoolId, WeekIdentifier, Id, ChangeVersion) - SELECT SchoolId, WeekIdentifier, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[AcademicWeek](OldSchoolId, OldWeekIdentifier, Id, Discriminator, ChangeVersion) + SELECT d.SchoolId, d.WeekIdentifier, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO @@ -73,6 +79,8 @@ GO ALTER TABLE [edfi].[AcademicWeek] ENABLE TRIGGER [edfi_AcademicWeek_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_AccommodationDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_AccommodationDescriptor_TR_DeleteTracking] ON [edfi].[AccommodationDescriptor] AFTER DELETE AS BEGIN @@ -81,8 +89,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AccommodationDescriptor](AccommodationDescriptorId, Id, ChangeVersion) - SELECT d.AccommodationDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.AccommodationDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.AccommodationDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.AccommodationDescriptorId = b.DescriptorId END @@ -90,76 +98,86 @@ GO ALTER TABLE [edfi].[AccommodationDescriptor] ENABLE TRIGGER [edfi_AccommodationDescriptor_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Account_TR_DeleteTracking] +GO - -CREATE TRIGGER [edfi].[edfi_AccountClassificationDescriptor_TR_DeleteTracking] ON [edfi].[AccountClassificationDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_Account_TR_DeleteTracking] ON [edfi].[Account] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AccountClassificationDescriptor](AccountClassificationDescriptorId, Id, ChangeVersion) - SELECT d.AccountClassificationDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Account](OldAccountIdentifier, OldEducationOrganizationId, OldFiscalYear, Id, Discriminator, ChangeVersion) + SELECT d.AccountIdentifier, d.EducationOrganizationId, d.FiscalYear, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.AccountClassificationDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[AccountClassificationDescriptor] ENABLE TRIGGER [edfi_AccountClassificationDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[Account] ENABLE TRIGGER [edfi_Account_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_AccountabilityRating_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_AccountCode_TR_DeleteTracking] ON [edfi].[AccountCode] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_AccountabilityRating_TR_DeleteTracking] ON [edfi].[AccountabilityRating] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AccountCode](AccountClassificationDescriptorId, AccountCodeNumber, EducationOrganizationId, FiscalYear, Id, ChangeVersion) - SELECT AccountClassificationDescriptorId, AccountCodeNumber, EducationOrganizationId, FiscalYear, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[AccountabilityRating](OldEducationOrganizationId, OldRatingTitle, OldSchoolYear, Id, Discriminator, ChangeVersion) + SELECT d.EducationOrganizationId, d.RatingTitle, d.SchoolYear, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO -ALTER TABLE [edfi].[AccountCode] ENABLE TRIGGER [edfi_AccountCode_TR_DeleteTracking] +ALTER TABLE [edfi].[AccountabilityRating] ENABLE TRIGGER [edfi_AccountabilityRating_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_AccountClassificationDescriptor_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_Account_TR_DeleteTracking] ON [edfi].[Account] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_AccountClassificationDescriptor_TR_DeleteTracking] ON [edfi].[AccountClassificationDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[Account](AccountIdentifier, EducationOrganizationId, FiscalYear, Id, ChangeVersion) - SELECT AccountIdentifier, EducationOrganizationId, FiscalYear, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.AccountClassificationDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.AccountClassificationDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor b ON d.AccountClassificationDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[Account] ENABLE TRIGGER [edfi_Account_TR_DeleteTracking] +ALTER TABLE [edfi].[AccountClassificationDescriptor] ENABLE TRIGGER [edfi_AccountClassificationDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_AccountCode_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_AccountabilityRating_TR_DeleteTracking] ON [edfi].[AccountabilityRating] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_AccountCode_TR_DeleteTracking] ON [edfi].[AccountCode] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AccountabilityRating](EducationOrganizationId, RatingTitle, SchoolYear, Id, ChangeVersion) - SELECT EducationOrganizationId, RatingTitle, SchoolYear, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[AccountCode](OldAccountClassificationDescriptorId, OldAccountClassificationDescriptorNamespace, OldAccountClassificationDescriptorCodeValue, OldAccountCodeNumber, OldEducationOrganizationId, OldFiscalYear, Id, Discriminator, ChangeVersion) + SELECT d.AccountClassificationDescriptorId, j0.Namespace, j0.CodeValue, d.AccountCodeNumber, d.EducationOrganizationId, d.FiscalYear, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor j0 + ON d.AccountClassificationDescriptorId = j0.DescriptorId END GO -ALTER TABLE [edfi].[AccountabilityRating] ENABLE TRIGGER [edfi_AccountabilityRating_TR_DeleteTracking] +ALTER TABLE [edfi].[AccountCode] ENABLE TRIGGER [edfi_AccountCode_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_AchievementCategoryDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_AchievementCategoryDescriptor_TR_DeleteTracking] ON [edfi].[AchievementCategoryDescriptor] AFTER DELETE AS BEGIN @@ -168,8 +186,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AchievementCategoryDescriptor](AchievementCategoryDescriptorId, Id, ChangeVersion) - SELECT d.AchievementCategoryDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.AchievementCategoryDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.AchievementCategoryDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.AchievementCategoryDescriptorId = b.DescriptorId END @@ -177,7 +195,8 @@ GO ALTER TABLE [edfi].[AchievementCategoryDescriptor] ENABLE TRIGGER [edfi_AchievementCategoryDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_Actual_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_Actual_TR_DeleteTracking] ON [edfi].[Actual] AFTER DELETE AS BEGIN @@ -186,8 +205,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[Actual](AccountIdentifier, AsOfDate, EducationOrganizationId, FiscalYear, Id, ChangeVersion) - SELECT AccountIdentifier, AsOfDate, EducationOrganizationId, FiscalYear, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Actual](OldAccountIdentifier, OldAsOfDate, OldEducationOrganizationId, OldFiscalYear, Id, Discriminator, ChangeVersion) + SELECT d.AccountIdentifier, d.AsOfDate, d.EducationOrganizationId, d.FiscalYear, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO @@ -195,6 +214,8 @@ GO ALTER TABLE [edfi].[Actual] ENABLE TRIGGER [edfi_Actual_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_AdditionalCreditTypeDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_AdditionalCreditTypeDescriptor_TR_DeleteTracking] ON [edfi].[AdditionalCreditTypeDescriptor] AFTER DELETE AS BEGIN @@ -203,8 +224,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AdditionalCreditTypeDescriptor](AdditionalCreditTypeDescriptorId, Id, ChangeVersion) - SELECT d.AdditionalCreditTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.AdditionalCreditTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.AdditionalCreditTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.AdditionalCreditTypeDescriptorId = b.DescriptorId END @@ -212,7 +233,8 @@ GO ALTER TABLE [edfi].[AdditionalCreditTypeDescriptor] ENABLE TRIGGER [edfi_AdditionalCreditTypeDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_AddressTypeDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_AddressTypeDescriptor_TR_DeleteTracking] ON [edfi].[AddressTypeDescriptor] AFTER DELETE AS BEGIN @@ -221,8 +243,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AddressTypeDescriptor](AddressTypeDescriptorId, Id, ChangeVersion) - SELECT d.AddressTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.AddressTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.AddressTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.AddressTypeDescriptorId = b.DescriptorId END @@ -230,7 +252,8 @@ GO ALTER TABLE [edfi].[AddressTypeDescriptor] ENABLE TRIGGER [edfi_AddressTypeDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_AdministrationEnvironmentDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_AdministrationEnvironmentDescriptor_TR_DeleteTracking] ON [edfi].[AdministrationEnvironmentDescriptor] AFTER DELETE AS BEGIN @@ -239,8 +262,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AdministrationEnvironmentDescriptor](AdministrationEnvironmentDescriptorId, Id, ChangeVersion) - SELECT d.AdministrationEnvironmentDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.AdministrationEnvironmentDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.AdministrationEnvironmentDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.AdministrationEnvironmentDescriptorId = b.DescriptorId END @@ -248,7 +271,8 @@ GO ALTER TABLE [edfi].[AdministrationEnvironmentDescriptor] ENABLE TRIGGER [edfi_AdministrationEnvironmentDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_AdministrativeFundingControlDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_AdministrativeFundingControlDescriptor_TR_DeleteTracking] ON [edfi].[AdministrativeFundingControlDescriptor] AFTER DELETE AS BEGIN @@ -257,8 +281,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AdministrativeFundingControlDescriptor](AdministrativeFundingControlDescriptorId, Id, ChangeVersion) - SELECT d.AdministrativeFundingControlDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.AdministrativeFundingControlDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.AdministrativeFundingControlDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.AdministrativeFundingControlDescriptorId = b.DescriptorId END @@ -266,7 +290,8 @@ GO ALTER TABLE [edfi].[AdministrativeFundingControlDescriptor] ENABLE TRIGGER [edfi_AdministrativeFundingControlDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_AncestryEthnicOriginDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_AncestryEthnicOriginDescriptor_TR_DeleteTracking] ON [edfi].[AncestryEthnicOriginDescriptor] AFTER DELETE AS BEGIN @@ -275,8 +300,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AncestryEthnicOriginDescriptor](AncestryEthnicOriginDescriptorId, Id, ChangeVersion) - SELECT d.AncestryEthnicOriginDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.AncestryEthnicOriginDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.AncestryEthnicOriginDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.AncestryEthnicOriginDescriptorId = b.DescriptorId END @@ -284,7 +309,27 @@ GO ALTER TABLE [edfi].[AncestryEthnicOriginDescriptor] ENABLE TRIGGER [edfi_AncestryEthnicOriginDescriptor_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Assessment_TR_DeleteTracking] +GO + +CREATE TRIGGER [edfi].[edfi_Assessment_TR_DeleteTracking] ON [edfi].[Assessment] AFTER DELETE AS +BEGIN + IF @@rowcount = 0 + RETURN + + SET NOCOUNT ON + + INSERT INTO [tracked_changes_edfi].[Assessment](OldAssessmentIdentifier, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.AssessmentIdentifier, d.Namespace, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + FROM deleted d +END +GO + +ALTER TABLE [edfi].[Assessment] ENABLE TRIGGER [edfi_Assessment_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_AssessmentCategoryDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_AssessmentCategoryDescriptor_TR_DeleteTracking] ON [edfi].[AssessmentCategoryDescriptor] AFTER DELETE AS BEGIN @@ -293,8 +338,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AssessmentCategoryDescriptor](AssessmentCategoryDescriptorId, Id, ChangeVersion) - SELECT d.AssessmentCategoryDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.AssessmentCategoryDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.AssessmentCategoryDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.AssessmentCategoryDescriptorId = b.DescriptorId END @@ -302,7 +347,8 @@ GO ALTER TABLE [edfi].[AssessmentCategoryDescriptor] ENABLE TRIGGER [edfi_AssessmentCategoryDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_AssessmentIdentificationSystemDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_AssessmentIdentificationSystemDescriptor_TR_DeleteTracking] ON [edfi].[AssessmentIdentificationSystemDescriptor] AFTER DELETE AS BEGIN @@ -311,8 +357,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AssessmentIdentificationSystemDescriptor](AssessmentIdentificationSystemDescriptorId, Id, ChangeVersion) - SELECT d.AssessmentIdentificationSystemDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.AssessmentIdentificationSystemDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.AssessmentIdentificationSystemDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.AssessmentIdentificationSystemDescriptorId = b.DescriptorId END @@ -320,60 +366,65 @@ GO ALTER TABLE [edfi].[AssessmentIdentificationSystemDescriptor] ENABLE TRIGGER [edfi_AssessmentIdentificationSystemDescriptor_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_AssessmentItem_TR_DeleteTracking] +GO - -CREATE TRIGGER [edfi].[edfi_AssessmentItemCategoryDescriptor_TR_DeleteTracking] ON [edfi].[AssessmentItemCategoryDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_AssessmentItem_TR_DeleteTracking] ON [edfi].[AssessmentItem] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AssessmentItemCategoryDescriptor](AssessmentItemCategoryDescriptorId, Id, ChangeVersion) - SELECT d.AssessmentItemCategoryDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[AssessmentItem](OldAssessmentIdentifier, OldIdentificationCode, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.AssessmentIdentifier, d.IdentificationCode, d.Namespace, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.AssessmentItemCategoryDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[AssessmentItemCategoryDescriptor] ENABLE TRIGGER [edfi_AssessmentItemCategoryDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[AssessmentItem] ENABLE TRIGGER [edfi_AssessmentItem_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_AssessmentItemCategoryDescriptor_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_AssessmentItemResultDescriptor_TR_DeleteTracking] ON [edfi].[AssessmentItemResultDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_AssessmentItemCategoryDescriptor_TR_DeleteTracking] ON [edfi].[AssessmentItemCategoryDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AssessmentItemResultDescriptor](AssessmentItemResultDescriptorId, Id, ChangeVersion) - SELECT d.AssessmentItemResultDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.AssessmentItemCategoryDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.AssessmentItemCategoryDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.AssessmentItemResultDescriptorId = b.DescriptorId + INNER JOIN edfi.Descriptor b ON d.AssessmentItemCategoryDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[AssessmentItemResultDescriptor] ENABLE TRIGGER [edfi_AssessmentItemResultDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[AssessmentItemCategoryDescriptor] ENABLE TRIGGER [edfi_AssessmentItemCategoryDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_AssessmentItemResultDescriptor_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_AssessmentItem_TR_DeleteTracking] ON [edfi].[AssessmentItem] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_AssessmentItemResultDescriptor_TR_DeleteTracking] ON [edfi].[AssessmentItemResultDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AssessmentItem](AssessmentIdentifier, IdentificationCode, Namespace, Id, ChangeVersion) - SELECT AssessmentIdentifier, IdentificationCode, Namespace, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.AssessmentItemResultDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.AssessmentItemResultDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor b ON d.AssessmentItemResultDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[AssessmentItem] ENABLE TRIGGER [edfi_AssessmentItem_TR_DeleteTracking] +ALTER TABLE [edfi].[AssessmentItemResultDescriptor] ENABLE TRIGGER [edfi_AssessmentItemResultDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_AssessmentPeriodDescriptor_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_AssessmentPeriodDescriptor_TR_DeleteTracking] ON [edfi].[AssessmentPeriodDescriptor] AFTER DELETE AS BEGIN @@ -382,8 +433,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AssessmentPeriodDescriptor](AssessmentPeriodDescriptorId, Id, ChangeVersion) - SELECT d.AssessmentPeriodDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.AssessmentPeriodDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.AssessmentPeriodDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.AssessmentPeriodDescriptorId = b.DescriptorId END @@ -391,7 +442,8 @@ GO ALTER TABLE [edfi].[AssessmentPeriodDescriptor] ENABLE TRIGGER [edfi_AssessmentPeriodDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_AssessmentReportingMethodDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_AssessmentReportingMethodDescriptor_TR_DeleteTracking] ON [edfi].[AssessmentReportingMethodDescriptor] AFTER DELETE AS BEGIN @@ -400,8 +452,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AssessmentReportingMethodDescriptor](AssessmentReportingMethodDescriptorId, Id, ChangeVersion) - SELECT d.AssessmentReportingMethodDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.AssessmentReportingMethodDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.AssessmentReportingMethodDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.AssessmentReportingMethodDescriptorId = b.DescriptorId END @@ -409,7 +461,8 @@ GO ALTER TABLE [edfi].[AssessmentReportingMethodDescriptor] ENABLE TRIGGER [edfi_AssessmentReportingMethodDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_AssessmentScoreRangeLearningStandard_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_AssessmentScoreRangeLearningStandard_TR_DeleteTracking] ON [edfi].[AssessmentScoreRangeLearningStandard] AFTER DELETE AS BEGIN @@ -418,8 +471,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AssessmentScoreRangeLearningStandard](AssessmentIdentifier, Namespace, ScoreRangeId, Id, ChangeVersion) - SELECT AssessmentIdentifier, Namespace, ScoreRangeId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[AssessmentScoreRangeLearningStandard](OldAssessmentIdentifier, OldNamespace, OldScoreRangeId, Id, Discriminator, ChangeVersion) + SELECT d.AssessmentIdentifier, d.Namespace, d.ScoreRangeId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO @@ -427,24 +480,9 @@ GO ALTER TABLE [edfi].[AssessmentScoreRangeLearningStandard] ENABLE TRIGGER [edfi_AssessmentScoreRangeLearningStandard_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_Assessment_TR_DeleteTracking] ON [edfi].[Assessment] AFTER DELETE AS -BEGIN - IF @@rowcount = 0 - RETURN - - SET NOCOUNT ON - - INSERT INTO [tracked_deletes_edfi].[Assessment](AssessmentIdentifier, Namespace, Id, ChangeVersion) - SELECT AssessmentIdentifier, Namespace, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) - FROM deleted d -END -GO - -ALTER TABLE [edfi].[Assessment] ENABLE TRIGGER [edfi_Assessment_TR_DeleteTracking] +DROP TRIGGER IF EXISTS [edfi].[edfi_AttemptStatusDescriptor_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_AttemptStatusDescriptor_TR_DeleteTracking] ON [edfi].[AttemptStatusDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 @@ -452,8 +490,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AttemptStatusDescriptor](AttemptStatusDescriptorId, Id, ChangeVersion) - SELECT d.AttemptStatusDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.AttemptStatusDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.AttemptStatusDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.AttemptStatusDescriptorId = b.DescriptorId END @@ -461,7 +499,8 @@ GO ALTER TABLE [edfi].[AttemptStatusDescriptor] ENABLE TRIGGER [edfi_AttemptStatusDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_AttendanceEventCategoryDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_AttendanceEventCategoryDescriptor_TR_DeleteTracking] ON [edfi].[AttendanceEventCategoryDescriptor] AFTER DELETE AS BEGIN @@ -470,8 +509,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[AttendanceEventCategoryDescriptor](AttendanceEventCategoryDescriptorId, Id, ChangeVersion) - SELECT d.AttendanceEventCategoryDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.AttendanceEventCategoryDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.AttendanceEventCategoryDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.AttendanceEventCategoryDescriptorId = b.DescriptorId END @@ -479,7 +518,8 @@ GO ALTER TABLE [edfi].[AttendanceEventCategoryDescriptor] ENABLE TRIGGER [edfi_AttendanceEventCategoryDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_BehaviorDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_BehaviorDescriptor_TR_DeleteTracking] ON [edfi].[BehaviorDescriptor] AFTER DELETE AS BEGIN @@ -488,8 +528,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[BehaviorDescriptor](BehaviorDescriptorId, Id, ChangeVersion) - SELECT d.BehaviorDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.BehaviorDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.BehaviorDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.BehaviorDescriptorId = b.DescriptorId END @@ -497,7 +537,8 @@ GO ALTER TABLE [edfi].[BehaviorDescriptor] ENABLE TRIGGER [edfi_BehaviorDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_BellSchedule_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_BellSchedule_TR_DeleteTracking] ON [edfi].[BellSchedule] AFTER DELETE AS BEGIN @@ -506,8 +547,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[BellSchedule](BellScheduleName, SchoolId, Id, ChangeVersion) - SELECT BellScheduleName, SchoolId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[BellSchedule](OldBellScheduleName, OldSchoolId, Id, Discriminator, ChangeVersion) + SELECT d.BellScheduleName, d.SchoolId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO @@ -515,6 +556,8 @@ GO ALTER TABLE [edfi].[BellSchedule] ENABLE TRIGGER [edfi_BellSchedule_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Budget_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_Budget_TR_DeleteTracking] ON [edfi].[Budget] AFTER DELETE AS BEGIN @@ -523,8 +566,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[Budget](AccountIdentifier, AsOfDate, EducationOrganizationId, FiscalYear, Id, ChangeVersion) - SELECT AccountIdentifier, AsOfDate, EducationOrganizationId, FiscalYear, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Budget](OldAccountIdentifier, OldAsOfDate, OldEducationOrganizationId, OldFiscalYear, Id, Discriminator, ChangeVersion) + SELECT d.AccountIdentifier, d.AsOfDate, d.EducationOrganizationId, d.FiscalYear, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO @@ -532,24 +575,27 @@ GO ALTER TABLE [edfi].[Budget] ENABLE TRIGGER [edfi_Budget_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Calendar_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_CTEProgramServiceDescriptor_TR_DeleteTracking] ON [edfi].[CTEProgramServiceDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_Calendar_TR_DeleteTracking] ON [edfi].[Calendar] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CTEProgramServiceDescriptor](CTEProgramServiceDescriptorId, Id, ChangeVersion) - SELECT d.CTEProgramServiceDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Calendar](OldCalendarCode, OldSchoolId, OldSchoolYear, Id, Discriminator, ChangeVersion) + SELECT d.CalendarCode, d.SchoolId, d.SchoolYear, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.CTEProgramServiceDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[CTEProgramServiceDescriptor] ENABLE TRIGGER [edfi_CTEProgramServiceDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[Calendar] ENABLE TRIGGER [edfi_Calendar_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_CalendarDate_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_CalendarDate_TR_DeleteTracking] ON [edfi].[CalendarDate] AFTER DELETE AS BEGIN @@ -558,8 +604,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CalendarDate](CalendarCode, Date, SchoolId, SchoolYear, Id, ChangeVersion) - SELECT CalendarCode, Date, SchoolId, SchoolYear, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[CalendarDate](OldCalendarCode, OldDate, OldSchoolId, OldSchoolYear, Id, Discriminator, ChangeVersion) + SELECT d.CalendarCode, d.Date, d.SchoolId, d.SchoolYear, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO @@ -567,6 +613,8 @@ GO ALTER TABLE [edfi].[CalendarDate] ENABLE TRIGGER [edfi_CalendarDate_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_CalendarEventDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_CalendarEventDescriptor_TR_DeleteTracking] ON [edfi].[CalendarEventDescriptor] AFTER DELETE AS BEGIN @@ -575,8 +623,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CalendarEventDescriptor](CalendarEventDescriptorId, Id, ChangeVersion) - SELECT d.CalendarEventDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CalendarEventDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CalendarEventDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.CalendarEventDescriptorId = b.DescriptorId END @@ -584,7 +632,8 @@ GO ALTER TABLE [edfi].[CalendarEventDescriptor] ENABLE TRIGGER [edfi_CalendarEventDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_CalendarTypeDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_CalendarTypeDescriptor_TR_DeleteTracking] ON [edfi].[CalendarTypeDescriptor] AFTER DELETE AS BEGIN @@ -593,8 +642,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CalendarTypeDescriptor](CalendarTypeDescriptorId, Id, ChangeVersion) - SELECT d.CalendarTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CalendarTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CalendarTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.CalendarTypeDescriptorId = b.DescriptorId END @@ -602,25 +651,9 @@ GO ALTER TABLE [edfi].[CalendarTypeDescriptor] ENABLE TRIGGER [edfi_CalendarTypeDescriptor_TR_DeleteTracking] GO - - -CREATE TRIGGER [edfi].[edfi_Calendar_TR_DeleteTracking] ON [edfi].[Calendar] AFTER DELETE AS -BEGIN - IF @@rowcount = 0 - RETURN - - SET NOCOUNT ON - - INSERT INTO [tracked_deletes_edfi].[Calendar](CalendarCode, SchoolId, SchoolYear, Id, ChangeVersion) - SELECT CalendarCode, SchoolId, SchoolYear, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) - FROM deleted d -END -GO - -ALTER TABLE [edfi].[Calendar] ENABLE TRIGGER [edfi_Calendar_TR_DeleteTracking] +DROP TRIGGER IF EXISTS [edfi].[edfi_CareerPathwayDescriptor_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_CareerPathwayDescriptor_TR_DeleteTracking] ON [edfi].[CareerPathwayDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 @@ -628,8 +661,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CareerPathwayDescriptor](CareerPathwayDescriptorId, Id, ChangeVersion) - SELECT d.CareerPathwayDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CareerPathwayDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CareerPathwayDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.CareerPathwayDescriptorId = b.DescriptorId END @@ -637,7 +670,8 @@ GO ALTER TABLE [edfi].[CareerPathwayDescriptor] ENABLE TRIGGER [edfi_CareerPathwayDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_CharterApprovalAgencyTypeDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_CharterApprovalAgencyTypeDescriptor_TR_DeleteTracking] ON [edfi].[CharterApprovalAgencyTypeDescriptor] AFTER DELETE AS BEGIN @@ -646,8 +680,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CharterApprovalAgencyTypeDescriptor](CharterApprovalAgencyTypeDescriptorId, Id, ChangeVersion) - SELECT d.CharterApprovalAgencyTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CharterApprovalAgencyTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CharterApprovalAgencyTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.CharterApprovalAgencyTypeDescriptorId = b.DescriptorId END @@ -655,7 +689,8 @@ GO ALTER TABLE [edfi].[CharterApprovalAgencyTypeDescriptor] ENABLE TRIGGER [edfi_CharterApprovalAgencyTypeDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_CharterStatusDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_CharterStatusDescriptor_TR_DeleteTracking] ON [edfi].[CharterStatusDescriptor] AFTER DELETE AS BEGIN @@ -664,8 +699,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CharterStatusDescriptor](CharterStatusDescriptorId, Id, ChangeVersion) - SELECT d.CharterStatusDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CharterStatusDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CharterStatusDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.CharterStatusDescriptorId = b.DescriptorId END @@ -673,7 +708,8 @@ GO ALTER TABLE [edfi].[CharterStatusDescriptor] ENABLE TRIGGER [edfi_CharterStatusDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_CitizenshipStatusDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_CitizenshipStatusDescriptor_TR_DeleteTracking] ON [edfi].[CitizenshipStatusDescriptor] AFTER DELETE AS BEGIN @@ -682,8 +718,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CitizenshipStatusDescriptor](CitizenshipStatusDescriptorId, Id, ChangeVersion) - SELECT d.CitizenshipStatusDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CitizenshipStatusDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CitizenshipStatusDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.CitizenshipStatusDescriptorId = b.DescriptorId END @@ -691,7 +727,8 @@ GO ALTER TABLE [edfi].[CitizenshipStatusDescriptor] ENABLE TRIGGER [edfi_CitizenshipStatusDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_ClassPeriod_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ClassPeriod_TR_DeleteTracking] ON [edfi].[ClassPeriod] AFTER DELETE AS BEGIN @@ -700,8 +737,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ClassPeriod](ClassPeriodName, SchoolId, Id, ChangeVersion) - SELECT ClassPeriodName, SchoolId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[ClassPeriod](OldClassPeriodName, OldSchoolId, Id, Discriminator, ChangeVersion) + SELECT d.ClassPeriodName, d.SchoolId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO @@ -709,6 +746,8 @@ GO ALTER TABLE [edfi].[ClassPeriod] ENABLE TRIGGER [edfi_ClassPeriod_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_ClassroomPositionDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ClassroomPositionDescriptor_TR_DeleteTracking] ON [edfi].[ClassroomPositionDescriptor] AFTER DELETE AS BEGIN @@ -717,8 +756,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ClassroomPositionDescriptor](ClassroomPositionDescriptorId, Id, ChangeVersion) - SELECT d.ClassroomPositionDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ClassroomPositionDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ClassroomPositionDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ClassroomPositionDescriptorId = b.DescriptorId END @@ -726,96 +765,84 @@ GO ALTER TABLE [edfi].[ClassroomPositionDescriptor] ENABLE TRIGGER [edfi_ClassroomPositionDescriptor_TR_DeleteTracking] GO - - -CREATE TRIGGER [edfi].[edfi_CohortScopeDescriptor_TR_DeleteTracking] ON [edfi].[CohortScopeDescriptor] AFTER DELETE AS -BEGIN - IF @@rowcount = 0 - RETURN - - SET NOCOUNT ON - - INSERT INTO [tracked_deletes_edfi].[CohortScopeDescriptor](CohortScopeDescriptorId, Id, ChangeVersion) - SELECT d.CohortScopeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) - FROM deleted d - INNER JOIN edfi.Descriptor b ON d.CohortScopeDescriptorId = b.DescriptorId -END -GO - -ALTER TABLE [edfi].[CohortScopeDescriptor] ENABLE TRIGGER [edfi_CohortScopeDescriptor_TR_DeleteTracking] +DROP TRIGGER IF EXISTS [edfi].[edfi_Cohort_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_CohortTypeDescriptor_TR_DeleteTracking] ON [edfi].[CohortTypeDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_Cohort_TR_DeleteTracking] ON [edfi].[Cohort] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CohortTypeDescriptor](CohortTypeDescriptorId, Id, ChangeVersion) - SELECT d.CohortTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Cohort](OldCohortIdentifier, OldEducationOrganizationId, Id, Discriminator, ChangeVersion) + SELECT d.CohortIdentifier, d.EducationOrganizationId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.CohortTypeDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[CohortTypeDescriptor] ENABLE TRIGGER [edfi_CohortTypeDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[Cohort] ENABLE TRIGGER [edfi_Cohort_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_CohortScopeDescriptor_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_CohortYearTypeDescriptor_TR_DeleteTracking] ON [edfi].[CohortYearTypeDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_CohortScopeDescriptor_TR_DeleteTracking] ON [edfi].[CohortScopeDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CohortYearTypeDescriptor](CohortYearTypeDescriptorId, Id, ChangeVersion) - SELECT d.CohortYearTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CohortScopeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CohortScopeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.CohortYearTypeDescriptorId = b.DescriptorId + INNER JOIN edfi.Descriptor b ON d.CohortScopeDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[CohortYearTypeDescriptor] ENABLE TRIGGER [edfi_CohortYearTypeDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[CohortScopeDescriptor] ENABLE TRIGGER [edfi_CohortScopeDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_CohortTypeDescriptor_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_Cohort_TR_DeleteTracking] ON [edfi].[Cohort] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_CohortTypeDescriptor_TR_DeleteTracking] ON [edfi].[CohortTypeDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[Cohort](CohortIdentifier, EducationOrganizationId, Id, ChangeVersion) - SELECT CohortIdentifier, EducationOrganizationId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CohortTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CohortTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor b ON d.CohortTypeDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[Cohort] ENABLE TRIGGER [edfi_Cohort_TR_DeleteTracking] +ALTER TABLE [edfi].[CohortTypeDescriptor] ENABLE TRIGGER [edfi_CohortTypeDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_CohortYearTypeDescriptor_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_CommunityOrganization_TR_DeleteTracking] ON [edfi].[CommunityOrganization] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_CohortYearTypeDescriptor_TR_DeleteTracking] ON [edfi].[CohortYearTypeDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CommunityOrganization](CommunityOrganizationId, Id, ChangeVersion) - SELECT d.CommunityOrganizationId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CohortYearTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CohortYearTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.EducationOrganization b ON d.CommunityOrganizationId = b.EducationOrganizationId + INNER JOIN edfi.Descriptor b ON d.CohortYearTypeDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[CommunityOrganization] ENABLE TRIGGER [edfi_CommunityOrganization_TR_DeleteTracking] +ALTER TABLE [edfi].[CohortYearTypeDescriptor] ENABLE TRIGGER [edfi_CohortYearTypeDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_CommunityProviderLicense_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_CommunityProviderLicense_TR_DeleteTracking] ON [edfi].[CommunityProviderLicense] AFTER DELETE AS BEGIN @@ -824,8 +851,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CommunityProviderLicense](CommunityProviderId, LicenseIdentifier, LicensingOrganization, Id, ChangeVersion) - SELECT CommunityProviderId, LicenseIdentifier, LicensingOrganization, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[CommunityProviderLicense](OldCommunityProviderId, OldLicenseIdentifier, OldLicensingOrganization, Id, Discriminator, ChangeVersion) + SELECT d.CommunityProviderId, d.LicenseIdentifier, d.LicensingOrganization, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO @@ -833,25 +860,9 @@ GO ALTER TABLE [edfi].[CommunityProviderLicense] ENABLE TRIGGER [edfi_CommunityProviderLicense_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_CommunityProvider_TR_DeleteTracking] ON [edfi].[CommunityProvider] AFTER DELETE AS -BEGIN - IF @@rowcount = 0 - RETURN - - SET NOCOUNT ON - - INSERT INTO [tracked_deletes_edfi].[CommunityProvider](CommunityProviderId, Id, ChangeVersion) - SELECT d.CommunityProviderId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) - FROM deleted d - INNER JOIN edfi.EducationOrganization b ON d.CommunityProviderId = b.EducationOrganizationId -END -GO - -ALTER TABLE [edfi].[CommunityProvider] ENABLE TRIGGER [edfi_CommunityProvider_TR_DeleteTracking] +DROP TRIGGER IF EXISTS [edfi].[edfi_CompetencyLevelDescriptor_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_CompetencyLevelDescriptor_TR_DeleteTracking] ON [edfi].[CompetencyLevelDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 @@ -859,8 +870,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CompetencyLevelDescriptor](CompetencyLevelDescriptorId, Id, ChangeVersion) - SELECT d.CompetencyLevelDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CompetencyLevelDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CompetencyLevelDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.CompetencyLevelDescriptorId = b.DescriptorId END @@ -868,7 +879,8 @@ GO ALTER TABLE [edfi].[CompetencyLevelDescriptor] ENABLE TRIGGER [edfi_CompetencyLevelDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_CompetencyObjective_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_CompetencyObjective_TR_DeleteTracking] ON [edfi].[CompetencyObjective] AFTER DELETE AS BEGIN @@ -877,15 +889,19 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CompetencyObjective](EducationOrganizationId, Objective, ObjectiveGradeLevelDescriptorId, Id, ChangeVersion) - SELECT EducationOrganizationId, Objective, ObjectiveGradeLevelDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[CompetencyObjective](OldEducationOrganizationId, OldObjective, OldObjectiveGradeLevelDescriptorId, OldObjectiveGradeLevelDescriptorNamespace, OldObjectiveGradeLevelDescriptorCodeValue, Id, Discriminator, ChangeVersion) + SELECT d.EducationOrganizationId, d.Objective, d.ObjectiveGradeLevelDescriptorId, j2.Namespace, j2.CodeValue, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor j2 + ON d.ObjectiveGradeLevelDescriptorId = j2.DescriptorId END GO ALTER TABLE [edfi].[CompetencyObjective] ENABLE TRIGGER [edfi_CompetencyObjective_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_ContactTypeDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ContactTypeDescriptor_TR_DeleteTracking] ON [edfi].[ContactTypeDescriptor] AFTER DELETE AS BEGIN @@ -894,8 +910,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ContactTypeDescriptor](ContactTypeDescriptorId, Id, ChangeVersion) - SELECT d.ContactTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ContactTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ContactTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ContactTypeDescriptorId = b.DescriptorId END @@ -903,7 +919,8 @@ GO ALTER TABLE [edfi].[ContactTypeDescriptor] ENABLE TRIGGER [edfi_ContactTypeDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_ContentClassDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ContentClassDescriptor_TR_DeleteTracking] ON [edfi].[ContentClassDescriptor] AFTER DELETE AS BEGIN @@ -912,8 +929,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ContentClassDescriptor](ContentClassDescriptorId, Id, ChangeVersion) - SELECT d.ContentClassDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ContentClassDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ContentClassDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ContentClassDescriptorId = b.DescriptorId END @@ -921,7 +938,8 @@ GO ALTER TABLE [edfi].[ContentClassDescriptor] ENABLE TRIGGER [edfi_ContentClassDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_ContinuationOfServicesReasonDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ContinuationOfServicesReasonDescriptor_TR_DeleteTracking] ON [edfi].[ContinuationOfServicesReasonDescriptor] AFTER DELETE AS BEGIN @@ -930,8 +948,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ContinuationOfServicesReasonDescriptor](ContinuationOfServicesReasonDescriptorId, Id, ChangeVersion) - SELECT d.ContinuationOfServicesReasonDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ContinuationOfServicesReasonDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ContinuationOfServicesReasonDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ContinuationOfServicesReasonDescriptorId = b.DescriptorId END @@ -939,7 +957,8 @@ GO ALTER TABLE [edfi].[ContinuationOfServicesReasonDescriptor] ENABLE TRIGGER [edfi_ContinuationOfServicesReasonDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_ContractedStaff_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ContractedStaff_TR_DeleteTracking] ON [edfi].[ContractedStaff] AFTER DELETE AS BEGIN @@ -948,15 +967,19 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ContractedStaff](AccountIdentifier, AsOfDate, EducationOrganizationId, FiscalYear, StaffUSI, Id, ChangeVersion) - SELECT AccountIdentifier, AsOfDate, EducationOrganizationId, FiscalYear, StaffUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[ContractedStaff](OldAccountIdentifier, OldAsOfDate, OldEducationOrganizationId, OldFiscalYear, OldStaffUSI, OldStaffUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.AccountIdentifier, d.AsOfDate, d.EducationOrganizationId, d.FiscalYear, d.StaffUSI, j4.StaffUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Staff j4 + ON d.StaffUSI = j4.StaffUSI END GO ALTER TABLE [edfi].[ContractedStaff] ENABLE TRIGGER [edfi_ContractedStaff_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_CostRateDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_CostRateDescriptor_TR_DeleteTracking] ON [edfi].[CostRateDescriptor] AFTER DELETE AS BEGIN @@ -965,8 +988,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CostRateDescriptor](CostRateDescriptorId, Id, ChangeVersion) - SELECT d.CostRateDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CostRateDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CostRateDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.CostRateDescriptorId = b.DescriptorId END @@ -974,7 +997,8 @@ GO ALTER TABLE [edfi].[CostRateDescriptor] ENABLE TRIGGER [edfi_CostRateDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_CountryDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_CountryDescriptor_TR_DeleteTracking] ON [edfi].[CountryDescriptor] AFTER DELETE AS BEGIN @@ -983,8 +1007,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CountryDescriptor](CountryDescriptorId, Id, ChangeVersion) - SELECT d.CountryDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CountryDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CountryDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.CountryDescriptorId = b.DescriptorId END @@ -992,7 +1016,27 @@ GO ALTER TABLE [edfi].[CountryDescriptor] ENABLE TRIGGER [edfi_CountryDescriptor_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Course_TR_DeleteTracking] +GO + +CREATE TRIGGER [edfi].[edfi_Course_TR_DeleteTracking] ON [edfi].[Course] AFTER DELETE AS +BEGIN + IF @@rowcount = 0 + RETURN + + SET NOCOUNT ON + + INSERT INTO [tracked_changes_edfi].[Course](OldCourseCode, OldEducationOrganizationId, Id, Discriminator, ChangeVersion) + SELECT d.CourseCode, d.EducationOrganizationId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + FROM deleted d +END +GO + +ALTER TABLE [edfi].[Course] ENABLE TRIGGER [edfi_Course_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_CourseAttemptResultDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_CourseAttemptResultDescriptor_TR_DeleteTracking] ON [edfi].[CourseAttemptResultDescriptor] AFTER DELETE AS BEGIN @@ -1001,8 +1045,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CourseAttemptResultDescriptor](CourseAttemptResultDescriptorId, Id, ChangeVersion) - SELECT d.CourseAttemptResultDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CourseAttemptResultDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CourseAttemptResultDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.CourseAttemptResultDescriptorId = b.DescriptorId END @@ -1010,7 +1054,8 @@ GO ALTER TABLE [edfi].[CourseAttemptResultDescriptor] ENABLE TRIGGER [edfi_CourseAttemptResultDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_CourseDefinedByDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_CourseDefinedByDescriptor_TR_DeleteTracking] ON [edfi].[CourseDefinedByDescriptor] AFTER DELETE AS BEGIN @@ -1019,8 +1064,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CourseDefinedByDescriptor](CourseDefinedByDescriptorId, Id, ChangeVersion) - SELECT d.CourseDefinedByDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CourseDefinedByDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CourseDefinedByDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.CourseDefinedByDescriptorId = b.DescriptorId END @@ -1028,7 +1073,8 @@ GO ALTER TABLE [edfi].[CourseDefinedByDescriptor] ENABLE TRIGGER [edfi_CourseDefinedByDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_CourseGPAApplicabilityDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_CourseGPAApplicabilityDescriptor_TR_DeleteTracking] ON [edfi].[CourseGPAApplicabilityDescriptor] AFTER DELETE AS BEGIN @@ -1037,8 +1083,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CourseGPAApplicabilityDescriptor](CourseGPAApplicabilityDescriptorId, Id, ChangeVersion) - SELECT d.CourseGPAApplicabilityDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CourseGPAApplicabilityDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CourseGPAApplicabilityDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.CourseGPAApplicabilityDescriptorId = b.DescriptorId END @@ -1046,7 +1092,8 @@ GO ALTER TABLE [edfi].[CourseGPAApplicabilityDescriptor] ENABLE TRIGGER [edfi_CourseGPAApplicabilityDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_CourseIdentificationSystemDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_CourseIdentificationSystemDescriptor_TR_DeleteTracking] ON [edfi].[CourseIdentificationSystemDescriptor] AFTER DELETE AS BEGIN @@ -1055,8 +1102,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CourseIdentificationSystemDescriptor](CourseIdentificationSystemDescriptorId, Id, ChangeVersion) - SELECT d.CourseIdentificationSystemDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CourseIdentificationSystemDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CourseIdentificationSystemDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.CourseIdentificationSystemDescriptorId = b.DescriptorId END @@ -1064,7 +1111,8 @@ GO ALTER TABLE [edfi].[CourseIdentificationSystemDescriptor] ENABLE TRIGGER [edfi_CourseIdentificationSystemDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_CourseLevelCharacteristicDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_CourseLevelCharacteristicDescriptor_TR_DeleteTracking] ON [edfi].[CourseLevelCharacteristicDescriptor] AFTER DELETE AS BEGIN @@ -1073,8 +1121,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CourseLevelCharacteristicDescriptor](CourseLevelCharacteristicDescriptorId, Id, ChangeVersion) - SELECT d.CourseLevelCharacteristicDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CourseLevelCharacteristicDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CourseLevelCharacteristicDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.CourseLevelCharacteristicDescriptorId = b.DescriptorId END @@ -1082,7 +1130,8 @@ GO ALTER TABLE [edfi].[CourseLevelCharacteristicDescriptor] ENABLE TRIGGER [edfi_CourseLevelCharacteristicDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_CourseOffering_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_CourseOffering_TR_DeleteTracking] ON [edfi].[CourseOffering] AFTER DELETE AS BEGIN @@ -1091,8 +1140,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CourseOffering](LocalCourseCode, SchoolId, SchoolYear, SessionName, Id, ChangeVersion) - SELECT LocalCourseCode, SchoolId, SchoolYear, SessionName, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[CourseOffering](OldLocalCourseCode, OldSchoolId, OldSchoolYear, OldSessionName, Id, Discriminator, ChangeVersion) + SELECT d.LocalCourseCode, d.SchoolId, d.SchoolYear, d.SessionName, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO @@ -1100,6 +1149,8 @@ GO ALTER TABLE [edfi].[CourseOffering] ENABLE TRIGGER [edfi_CourseOffering_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_CourseRepeatCodeDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_CourseRepeatCodeDescriptor_TR_DeleteTracking] ON [edfi].[CourseRepeatCodeDescriptor] AFTER DELETE AS BEGIN @@ -1108,8 +1159,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CourseRepeatCodeDescriptor](CourseRepeatCodeDescriptorId, Id, ChangeVersion) - SELECT d.CourseRepeatCodeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CourseRepeatCodeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CourseRepeatCodeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.CourseRepeatCodeDescriptorId = b.DescriptorId END @@ -1117,7 +1168,8 @@ GO ALTER TABLE [edfi].[CourseRepeatCodeDescriptor] ENABLE TRIGGER [edfi_CourseRepeatCodeDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_CourseTranscript_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_CourseTranscript_TR_DeleteTracking] ON [edfi].[CourseTranscript] AFTER DELETE AS BEGIN @@ -1126,32 +1178,44 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CourseTranscript](CourseAttemptResultDescriptorId, CourseCode, CourseEducationOrganizationId, EducationOrganizationId, SchoolYear, StudentUSI, TermDescriptorId, Id, ChangeVersion) - SELECT CourseAttemptResultDescriptorId, CourseCode, CourseEducationOrganizationId, EducationOrganizationId, SchoolYear, StudentUSI, TermDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[CourseTranscript](OldCourseAttemptResultDescriptorId, OldCourseAttemptResultDescriptorNamespace, OldCourseAttemptResultDescriptorCodeValue, OldCourseCode, OldCourseEducationOrganizationId, OldEducationOrganizationId, OldSchoolYear, OldStudentUSI, OldStudentUniqueId, OldTermDescriptorId, OldTermDescriptorNamespace, OldTermDescriptorCodeValue, Id, Discriminator, ChangeVersion) + SELECT d.CourseAttemptResultDescriptorId, j0.Namespace, j0.CodeValue, d.CourseCode, d.CourseEducationOrganizationId, d.EducationOrganizationId, d.SchoolYear, d.StudentUSI, j5.StudentUniqueId, d.TermDescriptorId, j6.Namespace, j6.CodeValue, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor j0 + ON d.CourseAttemptResultDescriptorId = j0.DescriptorId + INNER JOIN edfi.Student j5 + ON d.StudentUSI = j5.StudentUSI + INNER JOIN edfi.Descriptor j6 + ON d.TermDescriptorId = j6.DescriptorId END GO ALTER TABLE [edfi].[CourseTranscript] ENABLE TRIGGER [edfi_CourseTranscript_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Credential_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_Course_TR_DeleteTracking] ON [edfi].[Course] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_Credential_TR_DeleteTracking] ON [edfi].[Credential] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[Course](CourseCode, EducationOrganizationId, Id, ChangeVersion) - SELECT CourseCode, EducationOrganizationId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Credential](OldCredentialIdentifier, OldStateOfIssueStateAbbreviationDescriptorId, OldStateOfIssueStateAbbreviationDescriptorNamespace, OldStateOfIssueStateAbbreviationDescriptorCodeValue, Id, Discriminator, ChangeVersion) + SELECT d.CredentialIdentifier, d.StateOfIssueStateAbbreviationDescriptorId, j1.Namespace, j1.CodeValue, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor j1 + ON d.StateOfIssueStateAbbreviationDescriptorId = j1.DescriptorId END GO -ALTER TABLE [edfi].[Course] ENABLE TRIGGER [edfi_Course_TR_DeleteTracking] +ALTER TABLE [edfi].[Credential] ENABLE TRIGGER [edfi_Credential_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_CredentialFieldDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_CredentialFieldDescriptor_TR_DeleteTracking] ON [edfi].[CredentialFieldDescriptor] AFTER DELETE AS BEGIN @@ -1160,8 +1224,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CredentialFieldDescriptor](CredentialFieldDescriptorId, Id, ChangeVersion) - SELECT d.CredentialFieldDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CredentialFieldDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CredentialFieldDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.CredentialFieldDescriptorId = b.DescriptorId END @@ -1169,7 +1233,8 @@ GO ALTER TABLE [edfi].[CredentialFieldDescriptor] ENABLE TRIGGER [edfi_CredentialFieldDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_CredentialTypeDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_CredentialTypeDescriptor_TR_DeleteTracking] ON [edfi].[CredentialTypeDescriptor] AFTER DELETE AS BEGIN @@ -1178,8 +1243,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CredentialTypeDescriptor](CredentialTypeDescriptorId, Id, ChangeVersion) - SELECT d.CredentialTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CredentialTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CredentialTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.CredentialTypeDescriptorId = b.DescriptorId END @@ -1187,60 +1252,65 @@ GO ALTER TABLE [edfi].[CredentialTypeDescriptor] ENABLE TRIGGER [edfi_CredentialTypeDescriptor_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_CreditCategoryDescriptor_TR_DeleteTracking] +GO - -CREATE TRIGGER [edfi].[edfi_Credential_TR_DeleteTracking] ON [edfi].[Credential] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_CreditCategoryDescriptor_TR_DeleteTracking] ON [edfi].[CreditCategoryDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[Credential](CredentialIdentifier, StateOfIssueStateAbbreviationDescriptorId, Id, ChangeVersion) - SELECT CredentialIdentifier, StateOfIssueStateAbbreviationDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CreditCategoryDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CreditCategoryDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor b ON d.CreditCategoryDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[Credential] ENABLE TRIGGER [edfi_Credential_TR_DeleteTracking] +ALTER TABLE [edfi].[CreditCategoryDescriptor] ENABLE TRIGGER [edfi_CreditCategoryDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_CreditTypeDescriptor_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_CreditCategoryDescriptor_TR_DeleteTracking] ON [edfi].[CreditCategoryDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_CreditTypeDescriptor_TR_DeleteTracking] ON [edfi].[CreditTypeDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CreditCategoryDescriptor](CreditCategoryDescriptorId, Id, ChangeVersion) - SELECT d.CreditCategoryDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CreditTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CreditTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.CreditCategoryDescriptorId = b.DescriptorId + INNER JOIN edfi.Descriptor b ON d.CreditTypeDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[CreditCategoryDescriptor] ENABLE TRIGGER [edfi_CreditCategoryDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[CreditTypeDescriptor] ENABLE TRIGGER [edfi_CreditTypeDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_CTEProgramServiceDescriptor_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_CreditTypeDescriptor_TR_DeleteTracking] ON [edfi].[CreditTypeDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_CTEProgramServiceDescriptor_TR_DeleteTracking] ON [edfi].[CTEProgramServiceDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CreditTypeDescriptor](CreditTypeDescriptorId, Id, ChangeVersion) - SELECT d.CreditTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CTEProgramServiceDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CTEProgramServiceDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.CreditTypeDescriptorId = b.DescriptorId + INNER JOIN edfi.Descriptor b ON d.CTEProgramServiceDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[CreditTypeDescriptor] ENABLE TRIGGER [edfi_CreditTypeDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[CTEProgramServiceDescriptor] ENABLE TRIGGER [edfi_CTEProgramServiceDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_CurriculumUsedDescriptor_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_CurriculumUsedDescriptor_TR_DeleteTracking] ON [edfi].[CurriculumUsedDescriptor] AFTER DELETE AS BEGIN @@ -1249,8 +1319,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[CurriculumUsedDescriptor](CurriculumUsedDescriptorId, Id, ChangeVersion) - SELECT d.CurriculumUsedDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.CurriculumUsedDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.CurriculumUsedDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.CurriculumUsedDescriptorId = b.DescriptorId END @@ -1258,7 +1328,8 @@ GO ALTER TABLE [edfi].[CurriculumUsedDescriptor] ENABLE TRIGGER [edfi_CurriculumUsedDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_DeliveryMethodDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_DeliveryMethodDescriptor_TR_DeleteTracking] ON [edfi].[DeliveryMethodDescriptor] AFTER DELETE AS BEGIN @@ -1267,8 +1338,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[DeliveryMethodDescriptor](DeliveryMethodDescriptorId, Id, ChangeVersion) - SELECT d.DeliveryMethodDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.DeliveryMethodDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.DeliveryMethodDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.DeliveryMethodDescriptorId = b.DescriptorId END @@ -1276,25 +1347,9 @@ GO ALTER TABLE [edfi].[DeliveryMethodDescriptor] ENABLE TRIGGER [edfi_DeliveryMethodDescriptor_TR_DeleteTracking] GO - - -CREATE TRIGGER [edfi].[edfi_Descriptor_TR_DeleteTracking] ON [edfi].[Descriptor] AFTER DELETE AS -BEGIN - IF @@rowcount = 0 - RETURN - - SET NOCOUNT ON - - INSERT INTO [tracked_deletes_edfi].[Descriptor](DescriptorId, Id, ChangeVersion) - SELECT DescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) - FROM deleted d -END -GO - -ALTER TABLE [edfi].[Descriptor] ENABLE TRIGGER [edfi_Descriptor_TR_DeleteTracking] +DROP TRIGGER IF EXISTS [edfi].[edfi_DiagnosisDescriptor_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_DiagnosisDescriptor_TR_DeleteTracking] ON [edfi].[DiagnosisDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 @@ -1302,8 +1357,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[DiagnosisDescriptor](DiagnosisDescriptorId, Id, ChangeVersion) - SELECT d.DiagnosisDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.DiagnosisDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.DiagnosisDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.DiagnosisDescriptorId = b.DescriptorId END @@ -1311,7 +1366,8 @@ GO ALTER TABLE [edfi].[DiagnosisDescriptor] ENABLE TRIGGER [edfi_DiagnosisDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_DiplomaLevelDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_DiplomaLevelDescriptor_TR_DeleteTracking] ON [edfi].[DiplomaLevelDescriptor] AFTER DELETE AS BEGIN @@ -1320,8 +1376,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[DiplomaLevelDescriptor](DiplomaLevelDescriptorId, Id, ChangeVersion) - SELECT d.DiplomaLevelDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.DiplomaLevelDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.DiplomaLevelDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.DiplomaLevelDescriptorId = b.DescriptorId END @@ -1329,7 +1385,8 @@ GO ALTER TABLE [edfi].[DiplomaLevelDescriptor] ENABLE TRIGGER [edfi_DiplomaLevelDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_DiplomaTypeDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_DiplomaTypeDescriptor_TR_DeleteTracking] ON [edfi].[DiplomaTypeDescriptor] AFTER DELETE AS BEGIN @@ -1338,8 +1395,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[DiplomaTypeDescriptor](DiplomaTypeDescriptorId, Id, ChangeVersion) - SELECT d.DiplomaTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.DiplomaTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.DiplomaTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.DiplomaTypeDescriptorId = b.DescriptorId END @@ -1347,7 +1404,8 @@ GO ALTER TABLE [edfi].[DiplomaTypeDescriptor] ENABLE TRIGGER [edfi_DiplomaTypeDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_DisabilityDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_DisabilityDescriptor_TR_DeleteTracking] ON [edfi].[DisabilityDescriptor] AFTER DELETE AS BEGIN @@ -1356,8 +1414,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[DisabilityDescriptor](DisabilityDescriptorId, Id, ChangeVersion) - SELECT d.DisabilityDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.DisabilityDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.DisabilityDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.DisabilityDescriptorId = b.DescriptorId END @@ -1365,7 +1423,8 @@ GO ALTER TABLE [edfi].[DisabilityDescriptor] ENABLE TRIGGER [edfi_DisabilityDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_DisabilityDesignationDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_DisabilityDesignationDescriptor_TR_DeleteTracking] ON [edfi].[DisabilityDesignationDescriptor] AFTER DELETE AS BEGIN @@ -1374,8 +1433,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[DisabilityDesignationDescriptor](DisabilityDesignationDescriptorId, Id, ChangeVersion) - SELECT d.DisabilityDesignationDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.DisabilityDesignationDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.DisabilityDesignationDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.DisabilityDesignationDescriptorId = b.DescriptorId END @@ -1383,7 +1442,8 @@ GO ALTER TABLE [edfi].[DisabilityDesignationDescriptor] ENABLE TRIGGER [edfi_DisabilityDesignationDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_DisabilityDeterminationSourceTypeDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_DisabilityDeterminationSourceTypeDescriptor_TR_DeleteTracking] ON [edfi].[DisabilityDeterminationSourceTypeDescriptor] AFTER DELETE AS BEGIN @@ -1392,8 +1452,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[DisabilityDeterminationSourceTypeDescriptor](DisabilityDeterminationSourceTypeDescriptorId, Id, ChangeVersion) - SELECT d.DisabilityDeterminationSourceTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.DisabilityDeterminationSourceTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.DisabilityDeterminationSourceTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.DisabilityDeterminationSourceTypeDescriptorId = b.DescriptorId END @@ -1401,42 +1461,48 @@ GO ALTER TABLE [edfi].[DisabilityDeterminationSourceTypeDescriptor] ENABLE TRIGGER [edfi_DisabilityDeterminationSourceTypeDescriptor_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_DisciplineAction_TR_DeleteTracking] +GO - -CREATE TRIGGER [edfi].[edfi_DisciplineActionLengthDifferenceReasonDescriptor_TR_DeleteTracking] ON [edfi].[DisciplineActionLengthDifferenceReasonDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_DisciplineAction_TR_DeleteTracking] ON [edfi].[DisciplineAction] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[DisciplineActionLengthDifferenceReasonDescriptor](DisciplineActionLengthDifferenceReasonDescriptorId, Id, ChangeVersion) - SELECT d.DisciplineActionLengthDifferenceReasonDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[DisciplineAction](OldDisciplineActionIdentifier, OldDisciplineDate, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.DisciplineActionIdentifier, d.DisciplineDate, d.StudentUSI, j2.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.DisciplineActionLengthDifferenceReasonDescriptorId = b.DescriptorId + INNER JOIN edfi.Student j2 + ON d.StudentUSI = j2.StudentUSI END GO -ALTER TABLE [edfi].[DisciplineActionLengthDifferenceReasonDescriptor] ENABLE TRIGGER [edfi_DisciplineActionLengthDifferenceReasonDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[DisciplineAction] ENABLE TRIGGER [edfi_DisciplineAction_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_DisciplineActionLengthDifferenceReasonDescriptor_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_DisciplineAction_TR_DeleteTracking] ON [edfi].[DisciplineAction] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_DisciplineActionLengthDifferenceReasonDescriptor_TR_DeleteTracking] ON [edfi].[DisciplineActionLengthDifferenceReasonDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[DisciplineAction](DisciplineActionIdentifier, DisciplineDate, StudentUSI, Id, ChangeVersion) - SELECT DisciplineActionIdentifier, DisciplineDate, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.DisciplineActionLengthDifferenceReasonDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.DisciplineActionLengthDifferenceReasonDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor b ON d.DisciplineActionLengthDifferenceReasonDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[DisciplineAction] ENABLE TRIGGER [edfi_DisciplineAction_TR_DeleteTracking] +ALTER TABLE [edfi].[DisciplineActionLengthDifferenceReasonDescriptor] ENABLE TRIGGER [edfi_DisciplineActionLengthDifferenceReasonDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_DisciplineDescriptor_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_DisciplineDescriptor_TR_DeleteTracking] ON [edfi].[DisciplineDescriptor] AFTER DELETE AS BEGIN @@ -1445,8 +1511,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[DisciplineDescriptor](DisciplineDescriptorId, Id, ChangeVersion) - SELECT d.DisciplineDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.DisciplineDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.DisciplineDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.DisciplineDescriptorId = b.DescriptorId END @@ -1454,26 +1520,9 @@ GO ALTER TABLE [edfi].[DisciplineDescriptor] ENABLE TRIGGER [edfi_DisciplineDescriptor_TR_DeleteTracking] GO - - -CREATE TRIGGER [edfi].[edfi_DisciplineIncidentParticipationCodeDescriptor_TR_DeleteTracking] ON [edfi].[DisciplineIncidentParticipationCodeDescriptor] AFTER DELETE AS -BEGIN - IF @@rowcount = 0 - RETURN - - SET NOCOUNT ON - - INSERT INTO [tracked_deletes_edfi].[DisciplineIncidentParticipationCodeDescriptor](DisciplineIncidentParticipationCodeDescriptorId, Id, ChangeVersion) - SELECT d.DisciplineIncidentParticipationCodeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) - FROM deleted d - INNER JOIN edfi.Descriptor b ON d.DisciplineIncidentParticipationCodeDescriptorId = b.DescriptorId -END -GO - -ALTER TABLE [edfi].[DisciplineIncidentParticipationCodeDescriptor] ENABLE TRIGGER [edfi_DisciplineIncidentParticipationCodeDescriptor_TR_DeleteTracking] +DROP TRIGGER IF EXISTS [edfi].[edfi_DisciplineIncident_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_DisciplineIncident_TR_DeleteTracking] ON [edfi].[DisciplineIncident] AFTER DELETE AS BEGIN IF @@rowcount = 0 @@ -1481,8 +1530,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[DisciplineIncident](IncidentIdentifier, SchoolId, Id, ChangeVersion) - SELECT IncidentIdentifier, SchoolId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[DisciplineIncident](OldIncidentIdentifier, OldSchoolId, Id, Discriminator, ChangeVersion) + SELECT d.IncidentIdentifier, d.SchoolId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO @@ -1490,199 +1539,198 @@ GO ALTER TABLE [edfi].[DisciplineIncident] ENABLE TRIGGER [edfi_DisciplineIncident_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_EducationContent_TR_DeleteTracking] ON [edfi].[EducationContent] AFTER DELETE AS -BEGIN - IF @@rowcount = 0 - RETURN - - SET NOCOUNT ON - - INSERT INTO [tracked_deletes_edfi].[EducationContent](ContentIdentifier, Id, ChangeVersion) - SELECT ContentIdentifier, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) - FROM deleted d -END -GO - -ALTER TABLE [edfi].[EducationContent] ENABLE TRIGGER [edfi_EducationContent_TR_DeleteTracking] +DROP TRIGGER IF EXISTS [edfi].[edfi_DisciplineIncidentParticipationCodeDescriptor_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_EducationOrganizationCategoryDescriptor_TR_DeleteTracking] ON [edfi].[EducationOrganizationCategoryDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_DisciplineIncidentParticipationCodeDescriptor_TR_DeleteTracking] ON [edfi].[DisciplineIncidentParticipationCodeDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[EducationOrganizationCategoryDescriptor](EducationOrganizationCategoryDescriptorId, Id, ChangeVersion) - SELECT d.EducationOrganizationCategoryDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.DisciplineIncidentParticipationCodeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.DisciplineIncidentParticipationCodeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.EducationOrganizationCategoryDescriptorId = b.DescriptorId + INNER JOIN edfi.Descriptor b ON d.DisciplineIncidentParticipationCodeDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[EducationOrganizationCategoryDescriptor] ENABLE TRIGGER [edfi_EducationOrganizationCategoryDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[DisciplineIncidentParticipationCodeDescriptor] ENABLE TRIGGER [edfi_DisciplineIncidentParticipationCodeDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_EducationalEnvironmentDescriptor_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_EducationOrganizationIdentificationSystemDescriptor_TR_DeleteTracking] ON [edfi].[EducationOrganizationIdentificationSystemDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_EducationalEnvironmentDescriptor_TR_DeleteTracking] ON [edfi].[EducationalEnvironmentDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[EducationOrganizationIdentificationSystemDescriptor](EducationOrganizationIdentificationSystemDescriptorId, Id, ChangeVersion) - SELECT d.EducationOrganizationIdentificationSystemDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.EducationalEnvironmentDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.EducationalEnvironmentDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.EducationOrganizationIdentificationSystemDescriptorId = b.DescriptorId + INNER JOIN edfi.Descriptor b ON d.EducationalEnvironmentDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[EducationOrganizationIdentificationSystemDescriptor] ENABLE TRIGGER [edfi_EducationOrganizationIdentificationSystemDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[EducationalEnvironmentDescriptor] ENABLE TRIGGER [edfi_EducationalEnvironmentDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_EducationContent_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_EducationOrganizationInterventionPrescriptionAssociation_TR_DeleteTracking] ON [edfi].[EducationOrganizationInterventionPrescriptionAssociation] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_EducationContent_TR_DeleteTracking] ON [edfi].[EducationContent] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[EducationOrganizationInterventionPrescriptionAssociation](EducationOrganizationId, InterventionPrescriptionEducationOrganizationId, InterventionPrescriptionIdentificationCode, Id, ChangeVersion) - SELECT EducationOrganizationId, InterventionPrescriptionEducationOrganizationId, InterventionPrescriptionIdentificationCode, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[EducationContent](OldContentIdentifier, Id, Discriminator, ChangeVersion) + SELECT d.ContentIdentifier, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO -ALTER TABLE [edfi].[EducationOrganizationInterventionPrescriptionAssociation] ENABLE TRIGGER [edfi_EducationOrganizationInterventionPrescriptionAssociation_TR_DeleteTracking] +ALTER TABLE [edfi].[EducationContent] ENABLE TRIGGER [edfi_EducationContent_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_EducationOrganization_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_EducationOrganizationNetworkAssociation_TR_DeleteTracking] ON [edfi].[EducationOrganizationNetworkAssociation] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_EducationOrganization_TR_DeleteTracking] ON [edfi].[EducationOrganization] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[EducationOrganizationNetworkAssociation](EducationOrganizationNetworkId, MemberEducationOrganizationId, Id, ChangeVersion) - SELECT EducationOrganizationNetworkId, MemberEducationOrganizationId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[EducationOrganization](OldEducationOrganizationId, Id, Discriminator, ChangeVersion) + SELECT d.EducationOrganizationId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO -ALTER TABLE [edfi].[EducationOrganizationNetworkAssociation] ENABLE TRIGGER [edfi_EducationOrganizationNetworkAssociation_TR_DeleteTracking] +ALTER TABLE [edfi].[EducationOrganization] ENABLE TRIGGER [edfi_EducationOrganization_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_EducationOrganizationCategoryDescriptor_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_EducationOrganizationNetwork_TR_DeleteTracking] ON [edfi].[EducationOrganizationNetwork] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_EducationOrganizationCategoryDescriptor_TR_DeleteTracking] ON [edfi].[EducationOrganizationCategoryDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[EducationOrganizationNetwork](EducationOrganizationNetworkId, Id, ChangeVersion) - SELECT d.EducationOrganizationNetworkId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.EducationOrganizationCategoryDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.EducationOrganizationCategoryDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.EducationOrganization b ON d.EducationOrganizationNetworkId = b.EducationOrganizationId + INNER JOIN edfi.Descriptor b ON d.EducationOrganizationCategoryDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[EducationOrganizationNetwork] ENABLE TRIGGER [edfi_EducationOrganizationNetwork_TR_DeleteTracking] +ALTER TABLE [edfi].[EducationOrganizationCategoryDescriptor] ENABLE TRIGGER [edfi_EducationOrganizationCategoryDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_EducationOrganizationIdentificationSystemDescriptor_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_EducationOrganizationPeerAssociation_TR_DeleteTracking] ON [edfi].[EducationOrganizationPeerAssociation] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_EducationOrganizationIdentificationSystemDescriptor_TR_DeleteTracking] ON [edfi].[EducationOrganizationIdentificationSystemDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[EducationOrganizationPeerAssociation](EducationOrganizationId, PeerEducationOrganizationId, Id, ChangeVersion) - SELECT EducationOrganizationId, PeerEducationOrganizationId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.EducationOrganizationIdentificationSystemDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.EducationOrganizationIdentificationSystemDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor b ON d.EducationOrganizationIdentificationSystemDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[EducationOrganizationPeerAssociation] ENABLE TRIGGER [edfi_EducationOrganizationPeerAssociation_TR_DeleteTracking] +ALTER TABLE [edfi].[EducationOrganizationIdentificationSystemDescriptor] ENABLE TRIGGER [edfi_EducationOrganizationIdentificationSystemDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_EducationOrganizationInterventionPrescriptionAssociation_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_EducationOrganization_TR_DeleteTracking] ON [edfi].[EducationOrganization] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_EducationOrganizationInterventionPrescriptionAssociation_TR_DeleteTracking] ON [edfi].[EducationOrganizationInterventionPrescriptionAssociation] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[EducationOrganization](EducationOrganizationId, Id, ChangeVersion) - SELECT EducationOrganizationId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[EducationOrganizationInterventionPrescriptionAssociation](OldEducationOrganizationId, OldInterventionPrescriptionEducationOrganizationId, OldInterventionPrescriptionIdentificationCode, Id, Discriminator, ChangeVersion) + SELECT d.EducationOrganizationId, d.InterventionPrescriptionEducationOrganizationId, d.InterventionPrescriptionIdentificationCode, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO -ALTER TABLE [edfi].[EducationOrganization] ENABLE TRIGGER [edfi_EducationOrganization_TR_DeleteTracking] +ALTER TABLE [edfi].[EducationOrganizationInterventionPrescriptionAssociation] ENABLE TRIGGER [edfi_EducationOrganizationInterventionPrescriptionAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_EducationOrganizationNetworkAssociation_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_EducationPlanDescriptor_TR_DeleteTracking] ON [edfi].[EducationPlanDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_EducationOrganizationNetworkAssociation_TR_DeleteTracking] ON [edfi].[EducationOrganizationNetworkAssociation] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[EducationPlanDescriptor](EducationPlanDescriptorId, Id, ChangeVersion) - SELECT d.EducationPlanDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[EducationOrganizationNetworkAssociation](OldEducationOrganizationNetworkId, OldMemberEducationOrganizationId, Id, Discriminator, ChangeVersion) + SELECT d.EducationOrganizationNetworkId, d.MemberEducationOrganizationId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.EducationPlanDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[EducationPlanDescriptor] ENABLE TRIGGER [edfi_EducationPlanDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[EducationOrganizationNetworkAssociation] ENABLE TRIGGER [edfi_EducationOrganizationNetworkAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_EducationOrganizationPeerAssociation_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_EducationServiceCenter_TR_DeleteTracking] ON [edfi].[EducationServiceCenter] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_EducationOrganizationPeerAssociation_TR_DeleteTracking] ON [edfi].[EducationOrganizationPeerAssociation] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[EducationServiceCenter](EducationServiceCenterId, Id, ChangeVersion) - SELECT d.EducationServiceCenterId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[EducationOrganizationPeerAssociation](OldEducationOrganizationId, OldPeerEducationOrganizationId, Id, Discriminator, ChangeVersion) + SELECT d.EducationOrganizationId, d.PeerEducationOrganizationId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.EducationOrganization b ON d.EducationServiceCenterId = b.EducationOrganizationId END GO -ALTER TABLE [edfi].[EducationServiceCenter] ENABLE TRIGGER [edfi_EducationServiceCenter_TR_DeleteTracking] +ALTER TABLE [edfi].[EducationOrganizationPeerAssociation] ENABLE TRIGGER [edfi_EducationOrganizationPeerAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_EducationPlanDescriptor_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_EducationalEnvironmentDescriptor_TR_DeleteTracking] ON [edfi].[EducationalEnvironmentDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_EducationPlanDescriptor_TR_DeleteTracking] ON [edfi].[EducationPlanDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[EducationalEnvironmentDescriptor](EducationalEnvironmentDescriptorId, Id, ChangeVersion) - SELECT d.EducationalEnvironmentDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.EducationPlanDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.EducationPlanDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.EducationalEnvironmentDescriptorId = b.DescriptorId + INNER JOIN edfi.Descriptor b ON d.EducationPlanDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[EducationalEnvironmentDescriptor] ENABLE TRIGGER [edfi_EducationalEnvironmentDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[EducationPlanDescriptor] ENABLE TRIGGER [edfi_EducationPlanDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_ElectronicMailTypeDescriptor_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_ElectronicMailTypeDescriptor_TR_DeleteTracking] ON [edfi].[ElectronicMailTypeDescriptor] AFTER DELETE AS BEGIN @@ -1691,8 +1739,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ElectronicMailTypeDescriptor](ElectronicMailTypeDescriptorId, Id, ChangeVersion) - SELECT d.ElectronicMailTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ElectronicMailTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ElectronicMailTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ElectronicMailTypeDescriptorId = b.DescriptorId END @@ -1700,7 +1748,8 @@ GO ALTER TABLE [edfi].[ElectronicMailTypeDescriptor] ENABLE TRIGGER [edfi_ElectronicMailTypeDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_EmploymentStatusDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_EmploymentStatusDescriptor_TR_DeleteTracking] ON [edfi].[EmploymentStatusDescriptor] AFTER DELETE AS BEGIN @@ -1709,8 +1758,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[EmploymentStatusDescriptor](EmploymentStatusDescriptorId, Id, ChangeVersion) - SELECT d.EmploymentStatusDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.EmploymentStatusDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.EmploymentStatusDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.EmploymentStatusDescriptorId = b.DescriptorId END @@ -1718,7 +1767,8 @@ GO ALTER TABLE [edfi].[EmploymentStatusDescriptor] ENABLE TRIGGER [edfi_EmploymentStatusDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_EntryGradeLevelReasonDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_EntryGradeLevelReasonDescriptor_TR_DeleteTracking] ON [edfi].[EntryGradeLevelReasonDescriptor] AFTER DELETE AS BEGIN @@ -1727,8 +1777,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[EntryGradeLevelReasonDescriptor](EntryGradeLevelReasonDescriptorId, Id, ChangeVersion) - SELECT d.EntryGradeLevelReasonDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.EntryGradeLevelReasonDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.EntryGradeLevelReasonDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.EntryGradeLevelReasonDescriptorId = b.DescriptorId END @@ -1736,7 +1786,8 @@ GO ALTER TABLE [edfi].[EntryGradeLevelReasonDescriptor] ENABLE TRIGGER [edfi_EntryGradeLevelReasonDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_EntryTypeDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_EntryTypeDescriptor_TR_DeleteTracking] ON [edfi].[EntryTypeDescriptor] AFTER DELETE AS BEGIN @@ -1745,8 +1796,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[EntryTypeDescriptor](EntryTypeDescriptorId, Id, ChangeVersion) - SELECT d.EntryTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.EntryTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.EntryTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.EntryTypeDescriptorId = b.DescriptorId END @@ -1754,7 +1805,8 @@ GO ALTER TABLE [edfi].[EntryTypeDescriptor] ENABLE TRIGGER [edfi_EntryTypeDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_EventCircumstanceDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_EventCircumstanceDescriptor_TR_DeleteTracking] ON [edfi].[EventCircumstanceDescriptor] AFTER DELETE AS BEGIN @@ -1763,8 +1815,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[EventCircumstanceDescriptor](EventCircumstanceDescriptorId, Id, ChangeVersion) - SELECT d.EventCircumstanceDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.EventCircumstanceDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.EventCircumstanceDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.EventCircumstanceDescriptorId = b.DescriptorId END @@ -1772,7 +1824,8 @@ GO ALTER TABLE [edfi].[EventCircumstanceDescriptor] ENABLE TRIGGER [edfi_EventCircumstanceDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_ExitWithdrawTypeDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ExitWithdrawTypeDescriptor_TR_DeleteTracking] ON [edfi].[ExitWithdrawTypeDescriptor] AFTER DELETE AS BEGIN @@ -1781,8 +1834,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ExitWithdrawTypeDescriptor](ExitWithdrawTypeDescriptorId, Id, ChangeVersion) - SELECT d.ExitWithdrawTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ExitWithdrawTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ExitWithdrawTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ExitWithdrawTypeDescriptorId = b.DescriptorId END @@ -1790,7 +1843,8 @@ GO ALTER TABLE [edfi].[ExitWithdrawTypeDescriptor] ENABLE TRIGGER [edfi_ExitWithdrawTypeDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_FeederSchoolAssociation_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_FeederSchoolAssociation_TR_DeleteTracking] ON [edfi].[FeederSchoolAssociation] AFTER DELETE AS BEGIN @@ -1799,8 +1853,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[FeederSchoolAssociation](BeginDate, FeederSchoolId, SchoolId, Id, ChangeVersion) - SELECT BeginDate, FeederSchoolId, SchoolId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[FeederSchoolAssociation](OldBeginDate, OldFeederSchoolId, OldSchoolId, Id, Discriminator, ChangeVersion) + SELECT d.BeginDate, d.FeederSchoolId, d.SchoolId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO @@ -1808,6 +1862,8 @@ GO ALTER TABLE [edfi].[FeederSchoolAssociation] ENABLE TRIGGER [edfi_FeederSchoolAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_GeneralStudentProgramAssociation_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_GeneralStudentProgramAssociation_TR_DeleteTracking] ON [edfi].[GeneralStudentProgramAssociation] AFTER DELETE AS BEGIN @@ -1816,191 +1872,221 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[GeneralStudentProgramAssociation](BeginDate, EducationOrganizationId, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, ChangeVersion) - SELECT BeginDate, EducationOrganizationId, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[GeneralStudentProgramAssociation](OldBeginDate, OldEducationOrganizationId, OldProgramEducationOrganizationId, OldProgramName, OldProgramTypeDescriptorId, OldProgramTypeDescriptorNamespace, OldProgramTypeDescriptorCodeValue, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.BeginDate, d.EducationOrganizationId, d.ProgramEducationOrganizationId, d.ProgramName, d.ProgramTypeDescriptorId, j4.Namespace, j4.CodeValue, d.StudentUSI, j5.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor j4 + ON d.ProgramTypeDescriptorId = j4.DescriptorId + INNER JOIN edfi.Student j5 + ON d.StudentUSI = j5.StudentUSI END GO ALTER TABLE [edfi].[GeneralStudentProgramAssociation] ENABLE TRIGGER [edfi_GeneralStudentProgramAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Grade_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_GradeLevelDescriptor_TR_DeleteTracking] ON [edfi].[GradeLevelDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_Grade_TR_DeleteTracking] ON [edfi].[Grade] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[GradeLevelDescriptor](GradeLevelDescriptorId, Id, ChangeVersion) - SELECT d.GradeLevelDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Grade](OldBeginDate, OldGradeTypeDescriptorId, OldGradeTypeDescriptorNamespace, OldGradeTypeDescriptorCodeValue, OldGradingPeriodDescriptorId, OldGradingPeriodDescriptorNamespace, OldGradingPeriodDescriptorCodeValue, OldGradingPeriodSchoolYear, OldGradingPeriodSequence, OldLocalCourseCode, OldSchoolId, OldSchoolYear, OldSectionIdentifier, OldSessionName, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.BeginDate, d.GradeTypeDescriptorId, j1.Namespace, j1.CodeValue, d.GradingPeriodDescriptorId, j2.Namespace, j2.CodeValue, d.GradingPeriodSchoolYear, d.GradingPeriodSequence, d.LocalCourseCode, d.SchoolId, d.SchoolYear, d.SectionIdentifier, d.SessionName, d.StudentUSI, j10.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.GradeLevelDescriptorId = b.DescriptorId + INNER JOIN edfi.Descriptor j1 + ON d.GradeTypeDescriptorId = j1.DescriptorId + INNER JOIN edfi.Descriptor j2 + ON d.GradingPeriodDescriptorId = j2.DescriptorId + INNER JOIN edfi.Student j10 + ON d.StudentUSI = j10.StudentUSI END GO -ALTER TABLE [edfi].[GradeLevelDescriptor] ENABLE TRIGGER [edfi_GradeLevelDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[Grade] ENABLE TRIGGER [edfi_Grade_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_GradebookEntry_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_GradePointAverageTypeDescriptor_TR_DeleteTracking] ON [edfi].[GradePointAverageTypeDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_GradebookEntry_TR_DeleteTracking] ON [edfi].[GradebookEntry] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[GradePointAverageTypeDescriptor](GradePointAverageTypeDescriptorId, Id, ChangeVersion) - SELECT d.GradePointAverageTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[GradebookEntry](OldDateAssigned, OldGradebookEntryTitle, OldLocalCourseCode, OldSchoolId, OldSchoolYear, OldSectionIdentifier, OldSessionName, Id, Discriminator, ChangeVersion) + SELECT d.DateAssigned, d.GradebookEntryTitle, d.LocalCourseCode, d.SchoolId, d.SchoolYear, d.SectionIdentifier, d.SessionName, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.GradePointAverageTypeDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[GradePointAverageTypeDescriptor] ENABLE TRIGGER [edfi_GradePointAverageTypeDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[GradebookEntry] ENABLE TRIGGER [edfi_GradebookEntry_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_GradebookEntryTypeDescriptor_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_GradeTypeDescriptor_TR_DeleteTracking] ON [edfi].[GradeTypeDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_GradebookEntryTypeDescriptor_TR_DeleteTracking] ON [edfi].[GradebookEntryTypeDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[GradeTypeDescriptor](GradeTypeDescriptorId, Id, ChangeVersion) - SELECT d.GradeTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.GradebookEntryTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.GradebookEntryTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.GradeTypeDescriptorId = b.DescriptorId + INNER JOIN edfi.Descriptor b ON d.GradebookEntryTypeDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[GradeTypeDescriptor] ENABLE TRIGGER [edfi_GradeTypeDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[GradebookEntryTypeDescriptor] ENABLE TRIGGER [edfi_GradebookEntryTypeDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_GradeLevelDescriptor_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_Grade_TR_DeleteTracking] ON [edfi].[Grade] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_GradeLevelDescriptor_TR_DeleteTracking] ON [edfi].[GradeLevelDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[Grade](BeginDate, GradeTypeDescriptorId, GradingPeriodDescriptorId, GradingPeriodSchoolYear, GradingPeriodSequence, LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, StudentUSI, Id, ChangeVersion) - SELECT BeginDate, GradeTypeDescriptorId, GradingPeriodDescriptorId, GradingPeriodSchoolYear, GradingPeriodSequence, LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.GradeLevelDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.GradeLevelDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor b ON d.GradeLevelDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[Grade] ENABLE TRIGGER [edfi_Grade_TR_DeleteTracking] +ALTER TABLE [edfi].[GradeLevelDescriptor] ENABLE TRIGGER [edfi_GradeLevelDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_GradePointAverageTypeDescriptor_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_GradebookEntryTypeDescriptor_TR_DeleteTracking] ON [edfi].[GradebookEntryTypeDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_GradePointAverageTypeDescriptor_TR_DeleteTracking] ON [edfi].[GradePointAverageTypeDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[GradebookEntryTypeDescriptor](GradebookEntryTypeDescriptorId, Id, ChangeVersion) - SELECT d.GradebookEntryTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.GradePointAverageTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.GradePointAverageTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.GradebookEntryTypeDescriptorId = b.DescriptorId + INNER JOIN edfi.Descriptor b ON d.GradePointAverageTypeDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[GradebookEntryTypeDescriptor] ENABLE TRIGGER [edfi_GradebookEntryTypeDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[GradePointAverageTypeDescriptor] ENABLE TRIGGER [edfi_GradePointAverageTypeDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_GradeTypeDescriptor_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_GradebookEntry_TR_DeleteTracking] ON [edfi].[GradebookEntry] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_GradeTypeDescriptor_TR_DeleteTracking] ON [edfi].[GradeTypeDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[GradebookEntry](DateAssigned, GradebookEntryTitle, LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, Id, ChangeVersion) - SELECT DateAssigned, GradebookEntryTitle, LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.GradeTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.GradeTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor b ON d.GradeTypeDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[GradebookEntry] ENABLE TRIGGER [edfi_GradebookEntry_TR_DeleteTracking] +ALTER TABLE [edfi].[GradeTypeDescriptor] ENABLE TRIGGER [edfi_GradeTypeDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_GradingPeriod_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_GradingPeriodDescriptor_TR_DeleteTracking] ON [edfi].[GradingPeriodDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_GradingPeriod_TR_DeleteTracking] ON [edfi].[GradingPeriod] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[GradingPeriodDescriptor](GradingPeriodDescriptorId, Id, ChangeVersion) - SELECT d.GradingPeriodDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[GradingPeriod](OldGradingPeriodDescriptorId, OldGradingPeriodDescriptorNamespace, OldGradingPeriodDescriptorCodeValue, OldPeriodSequence, OldSchoolId, OldSchoolYear, Id, Discriminator, ChangeVersion) + SELECT d.GradingPeriodDescriptorId, j0.Namespace, j0.CodeValue, d.PeriodSequence, d.SchoolId, d.SchoolYear, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.GradingPeriodDescriptorId = b.DescriptorId + INNER JOIN edfi.Descriptor j0 + ON d.GradingPeriodDescriptorId = j0.DescriptorId END GO -ALTER TABLE [edfi].[GradingPeriodDescriptor] ENABLE TRIGGER [edfi_GradingPeriodDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[GradingPeriod] ENABLE TRIGGER [edfi_GradingPeriod_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_GradingPeriodDescriptor_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_GradingPeriod_TR_DeleteTracking] ON [edfi].[GradingPeriod] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_GradingPeriodDescriptor_TR_DeleteTracking] ON [edfi].[GradingPeriodDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[GradingPeriod](GradingPeriodDescriptorId, PeriodSequence, SchoolId, SchoolYear, Id, ChangeVersion) - SELECT GradingPeriodDescriptorId, PeriodSequence, SchoolId, SchoolYear, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.GradingPeriodDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.GradingPeriodDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor b ON d.GradingPeriodDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[GradingPeriod] ENABLE TRIGGER [edfi_GradingPeriod_TR_DeleteTracking] +ALTER TABLE [edfi].[GradingPeriodDescriptor] ENABLE TRIGGER [edfi_GradingPeriodDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_GraduationPlan_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_GraduationPlanTypeDescriptor_TR_DeleteTracking] ON [edfi].[GraduationPlanTypeDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_GraduationPlan_TR_DeleteTracking] ON [edfi].[GraduationPlan] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[GraduationPlanTypeDescriptor](GraduationPlanTypeDescriptorId, Id, ChangeVersion) - SELECT d.GraduationPlanTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[GraduationPlan](OldEducationOrganizationId, OldGraduationPlanTypeDescriptorId, OldGraduationPlanTypeDescriptorNamespace, OldGraduationPlanTypeDescriptorCodeValue, OldGraduationSchoolYear, Id, Discriminator, ChangeVersion) + SELECT d.EducationOrganizationId, d.GraduationPlanTypeDescriptorId, j1.Namespace, j1.CodeValue, d.GraduationSchoolYear, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.GraduationPlanTypeDescriptorId = b.DescriptorId + INNER JOIN edfi.Descriptor j1 + ON d.GraduationPlanTypeDescriptorId = j1.DescriptorId END GO -ALTER TABLE [edfi].[GraduationPlanTypeDescriptor] ENABLE TRIGGER [edfi_GraduationPlanTypeDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[GraduationPlan] ENABLE TRIGGER [edfi_GraduationPlan_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_GraduationPlanTypeDescriptor_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_GraduationPlan_TR_DeleteTracking] ON [edfi].[GraduationPlan] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_GraduationPlanTypeDescriptor_TR_DeleteTracking] ON [edfi].[GraduationPlanTypeDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[GraduationPlan](EducationOrganizationId, GraduationPlanTypeDescriptorId, GraduationSchoolYear, Id, ChangeVersion) - SELECT EducationOrganizationId, GraduationPlanTypeDescriptorId, GraduationSchoolYear, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.GraduationPlanTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.GraduationPlanTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor b ON d.GraduationPlanTypeDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[GraduationPlan] ENABLE TRIGGER [edfi_GraduationPlan_TR_DeleteTracking] +ALTER TABLE [edfi].[GraduationPlanTypeDescriptor] ENABLE TRIGGER [edfi_GraduationPlanTypeDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_GunFreeSchoolsActReportingStatusDescriptor_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_GunFreeSchoolsActReportingStatusDescriptor_TR_DeleteTracking] ON [edfi].[GunFreeSchoolsActReportingStatusDescriptor] AFTER DELETE AS BEGIN @@ -2009,8 +2095,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[GunFreeSchoolsActReportingStatusDescriptor](GunFreeSchoolsActReportingStatusDescriptorId, Id, ChangeVersion) - SELECT d.GunFreeSchoolsActReportingStatusDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.GunFreeSchoolsActReportingStatusDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.GunFreeSchoolsActReportingStatusDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.GunFreeSchoolsActReportingStatusDescriptorId = b.DescriptorId END @@ -2018,7 +2104,8 @@ GO ALTER TABLE [edfi].[GunFreeSchoolsActReportingStatusDescriptor] ENABLE TRIGGER [edfi_GunFreeSchoolsActReportingStatusDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_HomelessPrimaryNighttimeResidenceDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_HomelessPrimaryNighttimeResidenceDescriptor_TR_DeleteTracking] ON [edfi].[HomelessPrimaryNighttimeResidenceDescriptor] AFTER DELETE AS BEGIN @@ -2027,8 +2114,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[HomelessPrimaryNighttimeResidenceDescriptor](HomelessPrimaryNighttimeResidenceDescriptorId, Id, ChangeVersion) - SELECT d.HomelessPrimaryNighttimeResidenceDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.HomelessPrimaryNighttimeResidenceDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.HomelessPrimaryNighttimeResidenceDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.HomelessPrimaryNighttimeResidenceDescriptorId = b.DescriptorId END @@ -2036,7 +2123,8 @@ GO ALTER TABLE [edfi].[HomelessPrimaryNighttimeResidenceDescriptor] ENABLE TRIGGER [edfi_HomelessPrimaryNighttimeResidenceDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_HomelessProgramServiceDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_HomelessProgramServiceDescriptor_TR_DeleteTracking] ON [edfi].[HomelessProgramServiceDescriptor] AFTER DELETE AS BEGIN @@ -2045,8 +2133,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[HomelessProgramServiceDescriptor](HomelessProgramServiceDescriptorId, Id, ChangeVersion) - SELECT d.HomelessProgramServiceDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.HomelessProgramServiceDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.HomelessProgramServiceDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.HomelessProgramServiceDescriptorId = b.DescriptorId END @@ -2054,7 +2142,8 @@ GO ALTER TABLE [edfi].[HomelessProgramServiceDescriptor] ENABLE TRIGGER [edfi_HomelessProgramServiceDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_IdentificationDocumentUseDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_IdentificationDocumentUseDescriptor_TR_DeleteTracking] ON [edfi].[IdentificationDocumentUseDescriptor] AFTER DELETE AS BEGIN @@ -2063,8 +2152,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[IdentificationDocumentUseDescriptor](IdentificationDocumentUseDescriptorId, Id, ChangeVersion) - SELECT d.IdentificationDocumentUseDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.IdentificationDocumentUseDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.IdentificationDocumentUseDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.IdentificationDocumentUseDescriptorId = b.DescriptorId END @@ -2072,7 +2161,8 @@ GO ALTER TABLE [edfi].[IdentificationDocumentUseDescriptor] ENABLE TRIGGER [edfi_IdentificationDocumentUseDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_IncidentLocationDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_IncidentLocationDescriptor_TR_DeleteTracking] ON [edfi].[IncidentLocationDescriptor] AFTER DELETE AS BEGIN @@ -2081,8 +2171,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[IncidentLocationDescriptor](IncidentLocationDescriptorId, Id, ChangeVersion) - SELECT d.IncidentLocationDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.IncidentLocationDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.IncidentLocationDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.IncidentLocationDescriptorId = b.DescriptorId END @@ -2090,7 +2180,8 @@ GO ALTER TABLE [edfi].[IncidentLocationDescriptor] ENABLE TRIGGER [edfi_IncidentLocationDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_IndicatorDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_IndicatorDescriptor_TR_DeleteTracking] ON [edfi].[IndicatorDescriptor] AFTER DELETE AS BEGIN @@ -2099,8 +2190,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[IndicatorDescriptor](IndicatorDescriptorId, Id, ChangeVersion) - SELECT d.IndicatorDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.IndicatorDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.IndicatorDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.IndicatorDescriptorId = b.DescriptorId END @@ -2108,7 +2199,8 @@ GO ALTER TABLE [edfi].[IndicatorDescriptor] ENABLE TRIGGER [edfi_IndicatorDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_IndicatorGroupDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_IndicatorGroupDescriptor_TR_DeleteTracking] ON [edfi].[IndicatorGroupDescriptor] AFTER DELETE AS BEGIN @@ -2117,8 +2209,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[IndicatorGroupDescriptor](IndicatorGroupDescriptorId, Id, ChangeVersion) - SELECT d.IndicatorGroupDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.IndicatorGroupDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.IndicatorGroupDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.IndicatorGroupDescriptorId = b.DescriptorId END @@ -2126,7 +2218,8 @@ GO ALTER TABLE [edfi].[IndicatorGroupDescriptor] ENABLE TRIGGER [edfi_IndicatorGroupDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_IndicatorLevelDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_IndicatorLevelDescriptor_TR_DeleteTracking] ON [edfi].[IndicatorLevelDescriptor] AFTER DELETE AS BEGIN @@ -2135,8 +2228,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[IndicatorLevelDescriptor](IndicatorLevelDescriptorId, Id, ChangeVersion) - SELECT d.IndicatorLevelDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.IndicatorLevelDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.IndicatorLevelDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.IndicatorLevelDescriptorId = b.DescriptorId END @@ -2144,7 +2237,8 @@ GO ALTER TABLE [edfi].[IndicatorLevelDescriptor] ENABLE TRIGGER [edfi_IndicatorLevelDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_InstitutionTelephoneNumberTypeDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_InstitutionTelephoneNumberTypeDescriptor_TR_DeleteTracking] ON [edfi].[InstitutionTelephoneNumberTypeDescriptor] AFTER DELETE AS BEGIN @@ -2153,8 +2247,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[InstitutionTelephoneNumberTypeDescriptor](InstitutionTelephoneNumberTypeDescriptorId, Id, ChangeVersion) - SELECT d.InstitutionTelephoneNumberTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.InstitutionTelephoneNumberTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.InstitutionTelephoneNumberTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.InstitutionTelephoneNumberTypeDescriptorId = b.DescriptorId END @@ -2162,7 +2256,8 @@ GO ALTER TABLE [edfi].[InstitutionTelephoneNumberTypeDescriptor] ENABLE TRIGGER [edfi_InstitutionTelephoneNumberTypeDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_InteractivityStyleDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_InteractivityStyleDescriptor_TR_DeleteTracking] ON [edfi].[InteractivityStyleDescriptor] AFTER DELETE AS BEGIN @@ -2171,8 +2266,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[InteractivityStyleDescriptor](InteractivityStyleDescriptorId, Id, ChangeVersion) - SELECT d.InteractivityStyleDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.InteractivityStyleDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.InteractivityStyleDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.InteractivityStyleDescriptorId = b.DescriptorId END @@ -2180,7 +2275,8 @@ GO ALTER TABLE [edfi].[InteractivityStyleDescriptor] ENABLE TRIGGER [edfi_InteractivityStyleDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_InternetAccessDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_InternetAccessDescriptor_TR_DeleteTracking] ON [edfi].[InternetAccessDescriptor] AFTER DELETE AS BEGIN @@ -2189,8 +2285,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[InternetAccessDescriptor](InternetAccessDescriptorId, Id, ChangeVersion) - SELECT d.InternetAccessDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.InternetAccessDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.InternetAccessDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.InternetAccessDescriptorId = b.DescriptorId END @@ -2198,94 +2294,103 @@ GO ALTER TABLE [edfi].[InternetAccessDescriptor] ENABLE TRIGGER [edfi_InternetAccessDescriptor_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Intervention_TR_DeleteTracking] +GO - -CREATE TRIGGER [edfi].[edfi_InterventionClassDescriptor_TR_DeleteTracking] ON [edfi].[InterventionClassDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_Intervention_TR_DeleteTracking] ON [edfi].[Intervention] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[InterventionClassDescriptor](InterventionClassDescriptorId, Id, ChangeVersion) - SELECT d.InterventionClassDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Intervention](OldEducationOrganizationId, OldInterventionIdentificationCode, Id, Discriminator, ChangeVersion) + SELECT d.EducationOrganizationId, d.InterventionIdentificationCode, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.InterventionClassDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[InterventionClassDescriptor] ENABLE TRIGGER [edfi_InterventionClassDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[Intervention] ENABLE TRIGGER [edfi_Intervention_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_InterventionClassDescriptor_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_InterventionEffectivenessRatingDescriptor_TR_DeleteTracking] ON [edfi].[InterventionEffectivenessRatingDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_InterventionClassDescriptor_TR_DeleteTracking] ON [edfi].[InterventionClassDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[InterventionEffectivenessRatingDescriptor](InterventionEffectivenessRatingDescriptorId, Id, ChangeVersion) - SELECT d.InterventionEffectivenessRatingDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.InterventionClassDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.InterventionClassDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.InterventionEffectivenessRatingDescriptorId = b.DescriptorId + INNER JOIN edfi.Descriptor b ON d.InterventionClassDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[InterventionEffectivenessRatingDescriptor] ENABLE TRIGGER [edfi_InterventionEffectivenessRatingDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[InterventionClassDescriptor] ENABLE TRIGGER [edfi_InterventionClassDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_InterventionEffectivenessRatingDescriptor_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_InterventionPrescription_TR_DeleteTracking] ON [edfi].[InterventionPrescription] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_InterventionEffectivenessRatingDescriptor_TR_DeleteTracking] ON [edfi].[InterventionEffectivenessRatingDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[InterventionPrescription](EducationOrganizationId, InterventionPrescriptionIdentificationCode, Id, ChangeVersion) - SELECT EducationOrganizationId, InterventionPrescriptionIdentificationCode, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.InterventionEffectivenessRatingDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.InterventionEffectivenessRatingDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor b ON d.InterventionEffectivenessRatingDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[InterventionPrescription] ENABLE TRIGGER [edfi_InterventionPrescription_TR_DeleteTracking] +ALTER TABLE [edfi].[InterventionEffectivenessRatingDescriptor] ENABLE TRIGGER [edfi_InterventionEffectivenessRatingDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_InterventionPrescription_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_InterventionStudy_TR_DeleteTracking] ON [edfi].[InterventionStudy] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_InterventionPrescription_TR_DeleteTracking] ON [edfi].[InterventionPrescription] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[InterventionStudy](EducationOrganizationId, InterventionStudyIdentificationCode, Id, ChangeVersion) - SELECT EducationOrganizationId, InterventionStudyIdentificationCode, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[InterventionPrescription](OldEducationOrganizationId, OldInterventionPrescriptionIdentificationCode, Id, Discriminator, ChangeVersion) + SELECT d.EducationOrganizationId, d.InterventionPrescriptionIdentificationCode, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO -ALTER TABLE [edfi].[InterventionStudy] ENABLE TRIGGER [edfi_InterventionStudy_TR_DeleteTracking] +ALTER TABLE [edfi].[InterventionPrescription] ENABLE TRIGGER [edfi_InterventionPrescription_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_InterventionStudy_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_Intervention_TR_DeleteTracking] ON [edfi].[Intervention] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_InterventionStudy_TR_DeleteTracking] ON [edfi].[InterventionStudy] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[Intervention](EducationOrganizationId, InterventionIdentificationCode, Id, ChangeVersion) - SELECT EducationOrganizationId, InterventionIdentificationCode, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[InterventionStudy](OldEducationOrganizationId, OldInterventionStudyIdentificationCode, Id, Discriminator, ChangeVersion) + SELECT d.EducationOrganizationId, d.InterventionStudyIdentificationCode, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO -ALTER TABLE [edfi].[Intervention] ENABLE TRIGGER [edfi_Intervention_TR_DeleteTracking] +ALTER TABLE [edfi].[InterventionStudy] ENABLE TRIGGER [edfi_InterventionStudy_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_LanguageDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_LanguageDescriptor_TR_DeleteTracking] ON [edfi].[LanguageDescriptor] AFTER DELETE AS BEGIN @@ -2294,8 +2399,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[LanguageDescriptor](LanguageDescriptorId, Id, ChangeVersion) - SELECT d.LanguageDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.LanguageDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.LanguageDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.LanguageDescriptorId = b.DescriptorId END @@ -2303,7 +2408,8 @@ GO ALTER TABLE [edfi].[LanguageDescriptor] ENABLE TRIGGER [edfi_LanguageDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_LanguageInstructionProgramServiceDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_LanguageInstructionProgramServiceDescriptor_TR_DeleteTracking] ON [edfi].[LanguageInstructionProgramServiceDescriptor] AFTER DELETE AS BEGIN @@ -2312,8 +2418,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[LanguageInstructionProgramServiceDescriptor](LanguageInstructionProgramServiceDescriptorId, Id, ChangeVersion) - SELECT d.LanguageInstructionProgramServiceDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.LanguageInstructionProgramServiceDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.LanguageInstructionProgramServiceDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.LanguageInstructionProgramServiceDescriptorId = b.DescriptorId END @@ -2321,7 +2427,8 @@ GO ALTER TABLE [edfi].[LanguageInstructionProgramServiceDescriptor] ENABLE TRIGGER [edfi_LanguageInstructionProgramServiceDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_LanguageUseDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_LanguageUseDescriptor_TR_DeleteTracking] ON [edfi].[LanguageUseDescriptor] AFTER DELETE AS BEGIN @@ -2330,8 +2437,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[LanguageUseDescriptor](LanguageUseDescriptorId, Id, ChangeVersion) - SELECT d.LanguageUseDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.LanguageUseDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.LanguageUseDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.LanguageUseDescriptorId = b.DescriptorId END @@ -2339,7 +2446,8 @@ GO ALTER TABLE [edfi].[LanguageUseDescriptor] ENABLE TRIGGER [edfi_LanguageUseDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_LearningObjective_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_LearningObjective_TR_DeleteTracking] ON [edfi].[LearningObjective] AFTER DELETE AS BEGIN @@ -2348,8 +2456,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[LearningObjective](LearningObjectiveId, Namespace, Id, ChangeVersion) - SELECT LearningObjectiveId, Namespace, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[LearningObjective](OldLearningObjectiveId, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.LearningObjectiveId, d.Namespace, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO @@ -2357,95 +2465,104 @@ GO ALTER TABLE [edfi].[LearningObjective] ENABLE TRIGGER [edfi_LearningObjective_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_LearningStandard_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_LearningStandardCategoryDescriptor_TR_DeleteTracking] ON [edfi].[LearningStandardCategoryDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_LearningStandard_TR_DeleteTracking] ON [edfi].[LearningStandard] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[LearningStandardCategoryDescriptor](LearningStandardCategoryDescriptorId, Id, ChangeVersion) - SELECT d.LearningStandardCategoryDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[LearningStandard](OldLearningStandardId, Id, Discriminator, ChangeVersion) + SELECT d.LearningStandardId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.LearningStandardCategoryDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[LearningStandardCategoryDescriptor] ENABLE TRIGGER [edfi_LearningStandardCategoryDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[LearningStandard] ENABLE TRIGGER [edfi_LearningStandard_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_LearningStandardCategoryDescriptor_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_LearningStandardEquivalenceAssociation_TR_DeleteTracking] ON [edfi].[LearningStandardEquivalenceAssociation] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_LearningStandardCategoryDescriptor_TR_DeleteTracking] ON [edfi].[LearningStandardCategoryDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[LearningStandardEquivalenceAssociation](Namespace, SourceLearningStandardId, TargetLearningStandardId, Id, ChangeVersion) - SELECT Namespace, SourceLearningStandardId, TargetLearningStandardId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.LearningStandardCategoryDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.LearningStandardCategoryDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor b ON d.LearningStandardCategoryDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[LearningStandardEquivalenceAssociation] ENABLE TRIGGER [edfi_LearningStandardEquivalenceAssociation_TR_DeleteTracking] +ALTER TABLE [edfi].[LearningStandardCategoryDescriptor] ENABLE TRIGGER [edfi_LearningStandardCategoryDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_LearningStandardEquivalenceAssociation_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_LearningStandardEquivalenceStrengthDescriptor_TR_DeleteTracking] ON [edfi].[LearningStandardEquivalenceStrengthDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_LearningStandardEquivalenceAssociation_TR_DeleteTracking] ON [edfi].[LearningStandardEquivalenceAssociation] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[LearningStandardEquivalenceStrengthDescriptor](LearningStandardEquivalenceStrengthDescriptorId, Id, ChangeVersion) - SELECT d.LearningStandardEquivalenceStrengthDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[LearningStandardEquivalenceAssociation](OldNamespace, OldSourceLearningStandardId, OldTargetLearningStandardId, Id, Discriminator, ChangeVersion) + SELECT d.Namespace, d.SourceLearningStandardId, d.TargetLearningStandardId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.LearningStandardEquivalenceStrengthDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[LearningStandardEquivalenceStrengthDescriptor] ENABLE TRIGGER [edfi_LearningStandardEquivalenceStrengthDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[LearningStandardEquivalenceAssociation] ENABLE TRIGGER [edfi_LearningStandardEquivalenceAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_LearningStandardEquivalenceStrengthDescriptor_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_LearningStandardScopeDescriptor_TR_DeleteTracking] ON [edfi].[LearningStandardScopeDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_LearningStandardEquivalenceStrengthDescriptor_TR_DeleteTracking] ON [edfi].[LearningStandardEquivalenceStrengthDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[LearningStandardScopeDescriptor](LearningStandardScopeDescriptorId, Id, ChangeVersion) - SELECT d.LearningStandardScopeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.LearningStandardEquivalenceStrengthDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.LearningStandardEquivalenceStrengthDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.LearningStandardScopeDescriptorId = b.DescriptorId + INNER JOIN edfi.Descriptor b ON d.LearningStandardEquivalenceStrengthDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[LearningStandardScopeDescriptor] ENABLE TRIGGER [edfi_LearningStandardScopeDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[LearningStandardEquivalenceStrengthDescriptor] ENABLE TRIGGER [edfi_LearningStandardEquivalenceStrengthDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_LearningStandardScopeDescriptor_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_LearningStandard_TR_DeleteTracking] ON [edfi].[LearningStandard] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_LearningStandardScopeDescriptor_TR_DeleteTracking] ON [edfi].[LearningStandardScopeDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[LearningStandard](LearningStandardId, Id, ChangeVersion) - SELECT LearningStandardId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.LearningStandardScopeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.LearningStandardScopeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor b ON d.LearningStandardScopeDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[LearningStandard] ENABLE TRIGGER [edfi_LearningStandard_TR_DeleteTracking] +ALTER TABLE [edfi].[LearningStandardScopeDescriptor] ENABLE TRIGGER [edfi_LearningStandardScopeDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_LevelOfEducationDescriptor_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_LevelOfEducationDescriptor_TR_DeleteTracking] ON [edfi].[LevelOfEducationDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 @@ -2453,8 +2570,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[LevelOfEducationDescriptor](LevelOfEducationDescriptorId, Id, ChangeVersion) - SELECT d.LevelOfEducationDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.LevelOfEducationDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.LevelOfEducationDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.LevelOfEducationDescriptorId = b.DescriptorId END @@ -2462,7 +2579,8 @@ GO ALTER TABLE [edfi].[LevelOfEducationDescriptor] ENABLE TRIGGER [edfi_LevelOfEducationDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_LicenseStatusDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_LicenseStatusDescriptor_TR_DeleteTracking] ON [edfi].[LicenseStatusDescriptor] AFTER DELETE AS BEGIN @@ -2471,8 +2589,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[LicenseStatusDescriptor](LicenseStatusDescriptorId, Id, ChangeVersion) - SELECT d.LicenseStatusDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.LicenseStatusDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.LicenseStatusDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.LicenseStatusDescriptorId = b.DescriptorId END @@ -2480,7 +2598,8 @@ GO ALTER TABLE [edfi].[LicenseStatusDescriptor] ENABLE TRIGGER [edfi_LicenseStatusDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_LicenseTypeDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_LicenseTypeDescriptor_TR_DeleteTracking] ON [edfi].[LicenseTypeDescriptor] AFTER DELETE AS BEGIN @@ -2489,8 +2608,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[LicenseTypeDescriptor](LicenseTypeDescriptorId, Id, ChangeVersion) - SELECT d.LicenseTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.LicenseTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.LicenseTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.LicenseTypeDescriptorId = b.DescriptorId END @@ -2498,7 +2617,8 @@ GO ALTER TABLE [edfi].[LicenseTypeDescriptor] ENABLE TRIGGER [edfi_LicenseTypeDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_LimitedEnglishProficiencyDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_LimitedEnglishProficiencyDescriptor_TR_DeleteTracking] ON [edfi].[LimitedEnglishProficiencyDescriptor] AFTER DELETE AS BEGIN @@ -2507,8 +2627,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[LimitedEnglishProficiencyDescriptor](LimitedEnglishProficiencyDescriptorId, Id, ChangeVersion) - SELECT d.LimitedEnglishProficiencyDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.LimitedEnglishProficiencyDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.LimitedEnglishProficiencyDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.LimitedEnglishProficiencyDescriptorId = b.DescriptorId END @@ -2516,61 +2636,46 @@ GO ALTER TABLE [edfi].[LimitedEnglishProficiencyDescriptor] ENABLE TRIGGER [edfi_LimitedEnglishProficiencyDescriptor_TR_DeleteTracking] GO - - -CREATE TRIGGER [edfi].[edfi_LocalEducationAgencyCategoryDescriptor_TR_DeleteTracking] ON [edfi].[LocalEducationAgencyCategoryDescriptor] AFTER DELETE AS -BEGIN - IF @@rowcount = 0 - RETURN - - SET NOCOUNT ON - - INSERT INTO [tracked_deletes_edfi].[LocalEducationAgencyCategoryDescriptor](LocalEducationAgencyCategoryDescriptorId, Id, ChangeVersion) - SELECT d.LocalEducationAgencyCategoryDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) - FROM deleted d - INNER JOIN edfi.Descriptor b ON d.LocalEducationAgencyCategoryDescriptorId = b.DescriptorId -END -GO - -ALTER TABLE [edfi].[LocalEducationAgencyCategoryDescriptor] ENABLE TRIGGER [edfi_LocalEducationAgencyCategoryDescriptor_TR_DeleteTracking] +DROP TRIGGER IF EXISTS [edfi].[edfi_LocaleDescriptor_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_LocalEducationAgency_TR_DeleteTracking] ON [edfi].[LocalEducationAgency] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_LocaleDescriptor_TR_DeleteTracking] ON [edfi].[LocaleDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[LocalEducationAgency](LocalEducationAgencyId, Id, ChangeVersion) - SELECT d.LocalEducationAgencyId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.LocaleDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.LocaleDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.EducationOrganization b ON d.LocalEducationAgencyId = b.EducationOrganizationId + INNER JOIN edfi.Descriptor b ON d.LocaleDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[LocalEducationAgency] ENABLE TRIGGER [edfi_LocalEducationAgency_TR_DeleteTracking] +ALTER TABLE [edfi].[LocaleDescriptor] ENABLE TRIGGER [edfi_LocaleDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_LocalEducationAgencyCategoryDescriptor_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_LocaleDescriptor_TR_DeleteTracking] ON [edfi].[LocaleDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_LocalEducationAgencyCategoryDescriptor_TR_DeleteTracking] ON [edfi].[LocalEducationAgencyCategoryDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[LocaleDescriptor](LocaleDescriptorId, Id, ChangeVersion) - SELECT d.LocaleDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.LocalEducationAgencyCategoryDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.LocalEducationAgencyCategoryDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.LocaleDescriptorId = b.DescriptorId + INNER JOIN edfi.Descriptor b ON d.LocalEducationAgencyCategoryDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[LocaleDescriptor] ENABLE TRIGGER [edfi_LocaleDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[LocalEducationAgencyCategoryDescriptor] ENABLE TRIGGER [edfi_LocalEducationAgencyCategoryDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Location_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_Location_TR_DeleteTracking] ON [edfi].[Location] AFTER DELETE AS BEGIN @@ -2579,8 +2684,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[Location](ClassroomIdentificationCode, SchoolId, Id, ChangeVersion) - SELECT ClassroomIdentificationCode, SchoolId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Location](OldClassroomIdentificationCode, OldSchoolId, Id, Discriminator, ChangeVersion) + SELECT d.ClassroomIdentificationCode, d.SchoolId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO @@ -2588,6 +2693,8 @@ GO ALTER TABLE [edfi].[Location] ENABLE TRIGGER [edfi_Location_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_MagnetSpecialProgramEmphasisSchoolDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_MagnetSpecialProgramEmphasisSchoolDescriptor_TR_DeleteTracking] ON [edfi].[MagnetSpecialProgramEmphasisSchoolDescriptor] AFTER DELETE AS BEGIN @@ -2596,8 +2703,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[MagnetSpecialProgramEmphasisSchoolDescriptor](MagnetSpecialProgramEmphasisSchoolDescriptorId, Id, ChangeVersion) - SELECT d.MagnetSpecialProgramEmphasisSchoolDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.MagnetSpecialProgramEmphasisSchoolDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.MagnetSpecialProgramEmphasisSchoolDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.MagnetSpecialProgramEmphasisSchoolDescriptorId = b.DescriptorId END @@ -2605,7 +2712,8 @@ GO ALTER TABLE [edfi].[MagnetSpecialProgramEmphasisSchoolDescriptor] ENABLE TRIGGER [edfi_MagnetSpecialProgramEmphasisSchoolDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_MediumOfInstructionDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_MediumOfInstructionDescriptor_TR_DeleteTracking] ON [edfi].[MediumOfInstructionDescriptor] AFTER DELETE AS BEGIN @@ -2614,8 +2722,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[MediumOfInstructionDescriptor](MediumOfInstructionDescriptorId, Id, ChangeVersion) - SELECT d.MediumOfInstructionDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.MediumOfInstructionDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.MediumOfInstructionDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.MediumOfInstructionDescriptorId = b.DescriptorId END @@ -2623,7 +2731,8 @@ GO ALTER TABLE [edfi].[MediumOfInstructionDescriptor] ENABLE TRIGGER [edfi_MediumOfInstructionDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_MethodCreditEarnedDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_MethodCreditEarnedDescriptor_TR_DeleteTracking] ON [edfi].[MethodCreditEarnedDescriptor] AFTER DELETE AS BEGIN @@ -2632,8 +2741,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[MethodCreditEarnedDescriptor](MethodCreditEarnedDescriptorId, Id, ChangeVersion) - SELECT d.MethodCreditEarnedDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.MethodCreditEarnedDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.MethodCreditEarnedDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.MethodCreditEarnedDescriptorId = b.DescriptorId END @@ -2641,7 +2750,8 @@ GO ALTER TABLE [edfi].[MethodCreditEarnedDescriptor] ENABLE TRIGGER [edfi_MethodCreditEarnedDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_MigrantEducationProgramServiceDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_MigrantEducationProgramServiceDescriptor_TR_DeleteTracking] ON [edfi].[MigrantEducationProgramServiceDescriptor] AFTER DELETE AS BEGIN @@ -2650,8 +2760,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[MigrantEducationProgramServiceDescriptor](MigrantEducationProgramServiceDescriptorId, Id, ChangeVersion) - SELECT d.MigrantEducationProgramServiceDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.MigrantEducationProgramServiceDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.MigrantEducationProgramServiceDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.MigrantEducationProgramServiceDescriptorId = b.DescriptorId END @@ -2659,7 +2769,8 @@ GO ALTER TABLE [edfi].[MigrantEducationProgramServiceDescriptor] ENABLE TRIGGER [edfi_MigrantEducationProgramServiceDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_MonitoredDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_MonitoredDescriptor_TR_DeleteTracking] ON [edfi].[MonitoredDescriptor] AFTER DELETE AS BEGIN @@ -2668,8 +2779,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[MonitoredDescriptor](MonitoredDescriptorId, Id, ChangeVersion) - SELECT d.MonitoredDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.MonitoredDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.MonitoredDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.MonitoredDescriptorId = b.DescriptorId END @@ -2677,7 +2788,8 @@ GO ALTER TABLE [edfi].[MonitoredDescriptor] ENABLE TRIGGER [edfi_MonitoredDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_NeglectedOrDelinquentProgramDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_NeglectedOrDelinquentProgramDescriptor_TR_DeleteTracking] ON [edfi].[NeglectedOrDelinquentProgramDescriptor] AFTER DELETE AS BEGIN @@ -2686,8 +2798,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[NeglectedOrDelinquentProgramDescriptor](NeglectedOrDelinquentProgramDescriptorId, Id, ChangeVersion) - SELECT d.NeglectedOrDelinquentProgramDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.NeglectedOrDelinquentProgramDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.NeglectedOrDelinquentProgramDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.NeglectedOrDelinquentProgramDescriptorId = b.DescriptorId END @@ -2695,7 +2807,8 @@ GO ALTER TABLE [edfi].[NeglectedOrDelinquentProgramDescriptor] ENABLE TRIGGER [edfi_NeglectedOrDelinquentProgramDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_NeglectedOrDelinquentProgramServiceDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_NeglectedOrDelinquentProgramServiceDescriptor_TR_DeleteTracking] ON [edfi].[NeglectedOrDelinquentProgramServiceDescriptor] AFTER DELETE AS BEGIN @@ -2704,8 +2817,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[NeglectedOrDelinquentProgramServiceDescriptor](NeglectedOrDelinquentProgramServiceDescriptorId, Id, ChangeVersion) - SELECT d.NeglectedOrDelinquentProgramServiceDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.NeglectedOrDelinquentProgramServiceDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.NeglectedOrDelinquentProgramServiceDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.NeglectedOrDelinquentProgramServiceDescriptorId = b.DescriptorId END @@ -2713,7 +2826,8 @@ GO ALTER TABLE [edfi].[NeglectedOrDelinquentProgramServiceDescriptor] ENABLE TRIGGER [edfi_NeglectedOrDelinquentProgramServiceDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_NetworkPurposeDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_NetworkPurposeDescriptor_TR_DeleteTracking] ON [edfi].[NetworkPurposeDescriptor] AFTER DELETE AS BEGIN @@ -2722,8 +2836,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[NetworkPurposeDescriptor](NetworkPurposeDescriptorId, Id, ChangeVersion) - SELECT d.NetworkPurposeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.NetworkPurposeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.NetworkPurposeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.NetworkPurposeDescriptorId = b.DescriptorId END @@ -2731,7 +2845,8 @@ GO ALTER TABLE [edfi].[NetworkPurposeDescriptor] ENABLE TRIGGER [edfi_NetworkPurposeDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_ObjectiveAssessment_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ObjectiveAssessment_TR_DeleteTracking] ON [edfi].[ObjectiveAssessment] AFTER DELETE AS BEGIN @@ -2740,8 +2855,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ObjectiveAssessment](AssessmentIdentifier, IdentificationCode, Namespace, Id, ChangeVersion) - SELECT AssessmentIdentifier, IdentificationCode, Namespace, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[ObjectiveAssessment](OldAssessmentIdentifier, OldIdentificationCode, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.AssessmentIdentifier, d.IdentificationCode, d.Namespace, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO @@ -2749,6 +2864,8 @@ GO ALTER TABLE [edfi].[ObjectiveAssessment] ENABLE TRIGGER [edfi_ObjectiveAssessment_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_OldEthnicityDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_OldEthnicityDescriptor_TR_DeleteTracking] ON [edfi].[OldEthnicityDescriptor] AFTER DELETE AS BEGIN @@ -2757,8 +2874,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[OldEthnicityDescriptor](OldEthnicityDescriptorId, Id, ChangeVersion) - SELECT d.OldEthnicityDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.OldEthnicityDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.OldEthnicityDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.OldEthnicityDescriptorId = b.DescriptorId END @@ -2766,7 +2883,8 @@ GO ALTER TABLE [edfi].[OldEthnicityDescriptor] ENABLE TRIGGER [edfi_OldEthnicityDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_OpenStaffPosition_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_OpenStaffPosition_TR_DeleteTracking] ON [edfi].[OpenStaffPosition] AFTER DELETE AS BEGIN @@ -2775,8 +2893,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[OpenStaffPosition](EducationOrganizationId, RequisitionNumber, Id, ChangeVersion) - SELECT EducationOrganizationId, RequisitionNumber, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[OpenStaffPosition](OldEducationOrganizationId, OldRequisitionNumber, Id, Discriminator, ChangeVersion) + SELECT d.EducationOrganizationId, d.RequisitionNumber, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO @@ -2784,6 +2902,8 @@ GO ALTER TABLE [edfi].[OpenStaffPosition] ENABLE TRIGGER [edfi_OpenStaffPosition_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_OperationalStatusDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_OperationalStatusDescriptor_TR_DeleteTracking] ON [edfi].[OperationalStatusDescriptor] AFTER DELETE AS BEGIN @@ -2792,8 +2912,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[OperationalStatusDescriptor](OperationalStatusDescriptorId, Id, ChangeVersion) - SELECT d.OperationalStatusDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.OperationalStatusDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.OperationalStatusDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.OperationalStatusDescriptorId = b.DescriptorId END @@ -2801,26 +2921,9 @@ GO ALTER TABLE [edfi].[OperationalStatusDescriptor] ENABLE TRIGGER [edfi_OperationalStatusDescriptor_TR_DeleteTracking] GO - - -CREATE TRIGGER [edfi].[edfi_OrganizationDepartment_TR_DeleteTracking] ON [edfi].[OrganizationDepartment] AFTER DELETE AS -BEGIN - IF @@rowcount = 0 - RETURN - - SET NOCOUNT ON - - INSERT INTO [tracked_deletes_edfi].[OrganizationDepartment](OrganizationDepartmentId, Id, ChangeVersion) - SELECT d.OrganizationDepartmentId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) - FROM deleted d - INNER JOIN edfi.EducationOrganization b ON d.OrganizationDepartmentId = b.EducationOrganizationId -END -GO - -ALTER TABLE [edfi].[OrganizationDepartment] ENABLE TRIGGER [edfi_OrganizationDepartment_TR_DeleteTracking] +DROP TRIGGER IF EXISTS [edfi].[edfi_OtherNameTypeDescriptor_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_OtherNameTypeDescriptor_TR_DeleteTracking] ON [edfi].[OtherNameTypeDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 @@ -2828,8 +2931,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[OtherNameTypeDescriptor](OtherNameTypeDescriptorId, Id, ChangeVersion) - SELECT d.OtherNameTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.OtherNameTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.OtherNameTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.OtherNameTypeDescriptorId = b.DescriptorId END @@ -2837,7 +2940,8 @@ GO ALTER TABLE [edfi].[OtherNameTypeDescriptor] ENABLE TRIGGER [edfi_OtherNameTypeDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_Parent_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_Parent_TR_DeleteTracking] ON [edfi].[Parent] AFTER DELETE AS BEGIN @@ -2846,8 +2950,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[Parent](ParentUSI, Id, ChangeVersion) - SELECT ParentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Parent](OldParentUSI, OldParentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.ParentUSI, d.ParentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO @@ -2855,6 +2959,8 @@ GO ALTER TABLE [edfi].[Parent] ENABLE TRIGGER [edfi_Parent_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_ParticipationDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ParticipationDescriptor_TR_DeleteTracking] ON [edfi].[ParticipationDescriptor] AFTER DELETE AS BEGIN @@ -2863,8 +2969,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ParticipationDescriptor](ParticipationDescriptorId, Id, ChangeVersion) - SELECT d.ParticipationDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ParticipationDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ParticipationDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ParticipationDescriptorId = b.DescriptorId END @@ -2872,7 +2978,8 @@ GO ALTER TABLE [edfi].[ParticipationDescriptor] ENABLE TRIGGER [edfi_ParticipationDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_ParticipationStatusDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ParticipationStatusDescriptor_TR_DeleteTracking] ON [edfi].[ParticipationStatusDescriptor] AFTER DELETE AS BEGIN @@ -2881,8 +2988,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ParticipationStatusDescriptor](ParticipationStatusDescriptorId, Id, ChangeVersion) - SELECT d.ParticipationStatusDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ParticipationStatusDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ParticipationStatusDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ParticipationStatusDescriptorId = b.DescriptorId END @@ -2890,7 +2997,8 @@ GO ALTER TABLE [edfi].[ParticipationStatusDescriptor] ENABLE TRIGGER [edfi_ParticipationStatusDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_Payroll_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_Payroll_TR_DeleteTracking] ON [edfi].[Payroll] AFTER DELETE AS BEGIN @@ -2899,15 +3007,19 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[Payroll](AccountIdentifier, AsOfDate, EducationOrganizationId, FiscalYear, StaffUSI, Id, ChangeVersion) - SELECT AccountIdentifier, AsOfDate, EducationOrganizationId, FiscalYear, StaffUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Payroll](OldAccountIdentifier, OldAsOfDate, OldEducationOrganizationId, OldFiscalYear, OldStaffUSI, OldStaffUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.AccountIdentifier, d.AsOfDate, d.EducationOrganizationId, d.FiscalYear, d.StaffUSI, j4.StaffUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Staff j4 + ON d.StaffUSI = j4.StaffUSI END GO ALTER TABLE [edfi].[Payroll] ENABLE TRIGGER [edfi_Payroll_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_PerformanceBaseConversionDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_PerformanceBaseConversionDescriptor_TR_DeleteTracking] ON [edfi].[PerformanceBaseConversionDescriptor] AFTER DELETE AS BEGIN @@ -2916,8 +3028,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[PerformanceBaseConversionDescriptor](PerformanceBaseConversionDescriptorId, Id, ChangeVersion) - SELECT d.PerformanceBaseConversionDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.PerformanceBaseConversionDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.PerformanceBaseConversionDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.PerformanceBaseConversionDescriptorId = b.DescriptorId END @@ -2925,7 +3037,8 @@ GO ALTER TABLE [edfi].[PerformanceBaseConversionDescriptor] ENABLE TRIGGER [edfi_PerformanceBaseConversionDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_PerformanceLevelDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_PerformanceLevelDescriptor_TR_DeleteTracking] ON [edfi].[PerformanceLevelDescriptor] AFTER DELETE AS BEGIN @@ -2934,8 +3047,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[PerformanceLevelDescriptor](PerformanceLevelDescriptorId, Id, ChangeVersion) - SELECT d.PerformanceLevelDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.PerformanceLevelDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.PerformanceLevelDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.PerformanceLevelDescriptorId = b.DescriptorId END @@ -2943,7 +3056,8 @@ GO ALTER TABLE [edfi].[PerformanceLevelDescriptor] ENABLE TRIGGER [edfi_PerformanceLevelDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_Person_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_Person_TR_DeleteTracking] ON [edfi].[Person] AFTER DELETE AS BEGIN @@ -2952,15 +3066,19 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[Person](PersonId, SourceSystemDescriptorId, Id, ChangeVersion) - SELECT PersonId, SourceSystemDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Person](OldPersonId, OldSourceSystemDescriptorId, OldSourceSystemDescriptorNamespace, OldSourceSystemDescriptorCodeValue, Id, Discriminator, ChangeVersion) + SELECT d.PersonId, d.SourceSystemDescriptorId, j1.Namespace, j1.CodeValue, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor j1 + ON d.SourceSystemDescriptorId = j1.DescriptorId END GO ALTER TABLE [edfi].[Person] ENABLE TRIGGER [edfi_Person_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_PersonalInformationVerificationDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_PersonalInformationVerificationDescriptor_TR_DeleteTracking] ON [edfi].[PersonalInformationVerificationDescriptor] AFTER DELETE AS BEGIN @@ -2969,8 +3087,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[PersonalInformationVerificationDescriptor](PersonalInformationVerificationDescriptorId, Id, ChangeVersion) - SELECT d.PersonalInformationVerificationDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.PersonalInformationVerificationDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.PersonalInformationVerificationDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.PersonalInformationVerificationDescriptorId = b.DescriptorId END @@ -2978,7 +3096,8 @@ GO ALTER TABLE [edfi].[PersonalInformationVerificationDescriptor] ENABLE TRIGGER [edfi_PersonalInformationVerificationDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_PlatformTypeDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_PlatformTypeDescriptor_TR_DeleteTracking] ON [edfi].[PlatformTypeDescriptor] AFTER DELETE AS BEGIN @@ -2987,8 +3106,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[PlatformTypeDescriptor](PlatformTypeDescriptorId, Id, ChangeVersion) - SELECT d.PlatformTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.PlatformTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.PlatformTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.PlatformTypeDescriptorId = b.DescriptorId END @@ -2996,7 +3115,8 @@ GO ALTER TABLE [edfi].[PlatformTypeDescriptor] ENABLE TRIGGER [edfi_PlatformTypeDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_PopulationServedDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_PopulationServedDescriptor_TR_DeleteTracking] ON [edfi].[PopulationServedDescriptor] AFTER DELETE AS BEGIN @@ -3005,8 +3125,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[PopulationServedDescriptor](PopulationServedDescriptorId, Id, ChangeVersion) - SELECT d.PopulationServedDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.PopulationServedDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.PopulationServedDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.PopulationServedDescriptorId = b.DescriptorId END @@ -3014,25 +3134,27 @@ GO ALTER TABLE [edfi].[PopulationServedDescriptor] ENABLE TRIGGER [edfi_PopulationServedDescriptor_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_PostingResultDescriptor_TR_DeleteTracking] +GO - -CREATE TRIGGER [edfi].[edfi_PostSecondaryEventCategoryDescriptor_TR_DeleteTracking] ON [edfi].[PostSecondaryEventCategoryDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_PostingResultDescriptor_TR_DeleteTracking] ON [edfi].[PostingResultDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[PostSecondaryEventCategoryDescriptor](PostSecondaryEventCategoryDescriptorId, Id, ChangeVersion) - SELECT d.PostSecondaryEventCategoryDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.PostingResultDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.PostingResultDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.PostSecondaryEventCategoryDescriptorId = b.DescriptorId + INNER JOIN edfi.Descriptor b ON d.PostingResultDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[PostSecondaryEventCategoryDescriptor] ENABLE TRIGGER [edfi_PostSecondaryEventCategoryDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[PostingResultDescriptor] ENABLE TRIGGER [edfi_PostingResultDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_PostSecondaryEvent_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_PostSecondaryEvent_TR_DeleteTracking] ON [edfi].[PostSecondaryEvent] AFTER DELETE AS BEGIN @@ -3041,87 +3163,99 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[PostSecondaryEvent](EventDate, PostSecondaryEventCategoryDescriptorId, StudentUSI, Id, ChangeVersion) - SELECT EventDate, PostSecondaryEventCategoryDescriptorId, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[PostSecondaryEvent](OldEventDate, OldPostSecondaryEventCategoryDescriptorId, OldPostSecondaryEventCategoryDescriptorNamespace, OldPostSecondaryEventCategoryDescriptorCodeValue, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.EventDate, d.PostSecondaryEventCategoryDescriptorId, j1.Namespace, j1.CodeValue, d.StudentUSI, j2.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor j1 + ON d.PostSecondaryEventCategoryDescriptorId = j1.DescriptorId + INNER JOIN edfi.Student j2 + ON d.StudentUSI = j2.StudentUSI END GO ALTER TABLE [edfi].[PostSecondaryEvent] ENABLE TRIGGER [edfi_PostSecondaryEvent_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_PostSecondaryEventCategoryDescriptor_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_PostSecondaryInstitutionLevelDescriptor_TR_DeleteTracking] ON [edfi].[PostSecondaryInstitutionLevelDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_PostSecondaryEventCategoryDescriptor_TR_DeleteTracking] ON [edfi].[PostSecondaryEventCategoryDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[PostSecondaryInstitutionLevelDescriptor](PostSecondaryInstitutionLevelDescriptorId, Id, ChangeVersion) - SELECT d.PostSecondaryInstitutionLevelDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.PostSecondaryEventCategoryDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.PostSecondaryEventCategoryDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.PostSecondaryInstitutionLevelDescriptorId = b.DescriptorId + INNER JOIN edfi.Descriptor b ON d.PostSecondaryEventCategoryDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[PostSecondaryInstitutionLevelDescriptor] ENABLE TRIGGER [edfi_PostSecondaryInstitutionLevelDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[PostSecondaryEventCategoryDescriptor] ENABLE TRIGGER [edfi_PostSecondaryEventCategoryDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_PostSecondaryInstitutionLevelDescriptor_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_PostSecondaryInstitution_TR_DeleteTracking] ON [edfi].[PostSecondaryInstitution] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_PostSecondaryInstitutionLevelDescriptor_TR_DeleteTracking] ON [edfi].[PostSecondaryInstitutionLevelDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[PostSecondaryInstitution](PostSecondaryInstitutionId, Id, ChangeVersion) - SELECT d.PostSecondaryInstitutionId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.PostSecondaryInstitutionLevelDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.PostSecondaryInstitutionLevelDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.EducationOrganization b ON d.PostSecondaryInstitutionId = b.EducationOrganizationId + INNER JOIN edfi.Descriptor b ON d.PostSecondaryInstitutionLevelDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[PostSecondaryInstitution] ENABLE TRIGGER [edfi_PostSecondaryInstitution_TR_DeleteTracking] +ALTER TABLE [edfi].[PostSecondaryInstitutionLevelDescriptor] ENABLE TRIGGER [edfi_PostSecondaryInstitutionLevelDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_ProficiencyDescriptor_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_PostingResultDescriptor_TR_DeleteTracking] ON [edfi].[PostingResultDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_ProficiencyDescriptor_TR_DeleteTracking] ON [edfi].[ProficiencyDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[PostingResultDescriptor](PostingResultDescriptorId, Id, ChangeVersion) - SELECT d.PostingResultDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ProficiencyDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ProficiencyDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.PostingResultDescriptorId = b.DescriptorId + INNER JOIN edfi.Descriptor b ON d.ProficiencyDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[PostingResultDescriptor] ENABLE TRIGGER [edfi_PostingResultDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[ProficiencyDescriptor] ENABLE TRIGGER [edfi_ProficiencyDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Program_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_ProficiencyDescriptor_TR_DeleteTracking] ON [edfi].[ProficiencyDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_Program_TR_DeleteTracking] ON [edfi].[Program] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ProficiencyDescriptor](ProficiencyDescriptorId, Id, ChangeVersion) - SELECT d.ProficiencyDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Program](OldEducationOrganizationId, OldProgramName, OldProgramTypeDescriptorId, OldProgramTypeDescriptorNamespace, OldProgramTypeDescriptorCodeValue, Id, Discriminator, ChangeVersion) + SELECT d.EducationOrganizationId, d.ProgramName, d.ProgramTypeDescriptorId, j2.Namespace, j2.CodeValue, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.ProficiencyDescriptorId = b.DescriptorId + INNER JOIN edfi.Descriptor j2 + ON d.ProgramTypeDescriptorId = j2.DescriptorId END GO -ALTER TABLE [edfi].[ProficiencyDescriptor] ENABLE TRIGGER [edfi_ProficiencyDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[Program] ENABLE TRIGGER [edfi_Program_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_ProgramAssignmentDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ProgramAssignmentDescriptor_TR_DeleteTracking] ON [edfi].[ProgramAssignmentDescriptor] AFTER DELETE AS BEGIN @@ -3130,8 +3264,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ProgramAssignmentDescriptor](ProgramAssignmentDescriptorId, Id, ChangeVersion) - SELECT d.ProgramAssignmentDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ProgramAssignmentDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ProgramAssignmentDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ProgramAssignmentDescriptorId = b.DescriptorId END @@ -3139,7 +3273,8 @@ GO ALTER TABLE [edfi].[ProgramAssignmentDescriptor] ENABLE TRIGGER [edfi_ProgramAssignmentDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_ProgramCharacteristicDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ProgramCharacteristicDescriptor_TR_DeleteTracking] ON [edfi].[ProgramCharacteristicDescriptor] AFTER DELETE AS BEGIN @@ -3148,8 +3283,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ProgramCharacteristicDescriptor](ProgramCharacteristicDescriptorId, Id, ChangeVersion) - SELECT d.ProgramCharacteristicDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ProgramCharacteristicDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ProgramCharacteristicDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ProgramCharacteristicDescriptorId = b.DescriptorId END @@ -3157,7 +3292,8 @@ GO ALTER TABLE [edfi].[ProgramCharacteristicDescriptor] ENABLE TRIGGER [edfi_ProgramCharacteristicDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_ProgramSponsorDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ProgramSponsorDescriptor_TR_DeleteTracking] ON [edfi].[ProgramSponsorDescriptor] AFTER DELETE AS BEGIN @@ -3166,8 +3302,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ProgramSponsorDescriptor](ProgramSponsorDescriptorId, Id, ChangeVersion) - SELECT d.ProgramSponsorDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ProgramSponsorDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ProgramSponsorDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ProgramSponsorDescriptorId = b.DescriptorId END @@ -3175,7 +3311,8 @@ GO ALTER TABLE [edfi].[ProgramSponsorDescriptor] ENABLE TRIGGER [edfi_ProgramSponsorDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_ProgramTypeDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ProgramTypeDescriptor_TR_DeleteTracking] ON [edfi].[ProgramTypeDescriptor] AFTER DELETE AS BEGIN @@ -3184,8 +3321,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ProgramTypeDescriptor](ProgramTypeDescriptorId, Id, ChangeVersion) - SELECT d.ProgramTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ProgramTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ProgramTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ProgramTypeDescriptorId = b.DescriptorId END @@ -3193,25 +3330,9 @@ GO ALTER TABLE [edfi].[ProgramTypeDescriptor] ENABLE TRIGGER [edfi_ProgramTypeDescriptor_TR_DeleteTracking] GO - - -CREATE TRIGGER [edfi].[edfi_Program_TR_DeleteTracking] ON [edfi].[Program] AFTER DELETE AS -BEGIN - IF @@rowcount = 0 - RETURN - - SET NOCOUNT ON - - INSERT INTO [tracked_deletes_edfi].[Program](EducationOrganizationId, ProgramName, ProgramTypeDescriptorId, Id, ChangeVersion) - SELECT EducationOrganizationId, ProgramName, ProgramTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) - FROM deleted d -END -GO - -ALTER TABLE [edfi].[Program] ENABLE TRIGGER [edfi_Program_TR_DeleteTracking] +DROP TRIGGER IF EXISTS [edfi].[edfi_ProgressDescriptor_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_ProgressDescriptor_TR_DeleteTracking] ON [edfi].[ProgressDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 @@ -3219,8 +3340,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ProgressDescriptor](ProgressDescriptorId, Id, ChangeVersion) - SELECT d.ProgressDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ProgressDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ProgressDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ProgressDescriptorId = b.DescriptorId END @@ -3228,7 +3349,8 @@ GO ALTER TABLE [edfi].[ProgressDescriptor] ENABLE TRIGGER [edfi_ProgressDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_ProgressLevelDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ProgressLevelDescriptor_TR_DeleteTracking] ON [edfi].[ProgressLevelDescriptor] AFTER DELETE AS BEGIN @@ -3237,8 +3359,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ProgressLevelDescriptor](ProgressLevelDescriptorId, Id, ChangeVersion) - SELECT d.ProgressLevelDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ProgressLevelDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ProgressLevelDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ProgressLevelDescriptorId = b.DescriptorId END @@ -3246,7 +3368,8 @@ GO ALTER TABLE [edfi].[ProgressLevelDescriptor] ENABLE TRIGGER [edfi_ProgressLevelDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_ProviderCategoryDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ProviderCategoryDescriptor_TR_DeleteTracking] ON [edfi].[ProviderCategoryDescriptor] AFTER DELETE AS BEGIN @@ -3255,8 +3378,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ProviderCategoryDescriptor](ProviderCategoryDescriptorId, Id, ChangeVersion) - SELECT d.ProviderCategoryDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ProviderCategoryDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ProviderCategoryDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ProviderCategoryDescriptorId = b.DescriptorId END @@ -3264,7 +3387,8 @@ GO ALTER TABLE [edfi].[ProviderCategoryDescriptor] ENABLE TRIGGER [edfi_ProviderCategoryDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_ProviderProfitabilityDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ProviderProfitabilityDescriptor_TR_DeleteTracking] ON [edfi].[ProviderProfitabilityDescriptor] AFTER DELETE AS BEGIN @@ -3273,8 +3397,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ProviderProfitabilityDescriptor](ProviderProfitabilityDescriptorId, Id, ChangeVersion) - SELECT d.ProviderProfitabilityDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ProviderProfitabilityDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ProviderProfitabilityDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ProviderProfitabilityDescriptorId = b.DescriptorId END @@ -3282,7 +3406,8 @@ GO ALTER TABLE [edfi].[ProviderProfitabilityDescriptor] ENABLE TRIGGER [edfi_ProviderProfitabilityDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_ProviderStatusDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ProviderStatusDescriptor_TR_DeleteTracking] ON [edfi].[ProviderStatusDescriptor] AFTER DELETE AS BEGIN @@ -3291,8 +3416,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ProviderStatusDescriptor](ProviderStatusDescriptorId, Id, ChangeVersion) - SELECT d.ProviderStatusDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ProviderStatusDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ProviderStatusDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ProviderStatusDescriptorId = b.DescriptorId END @@ -3300,7 +3425,8 @@ GO ALTER TABLE [edfi].[ProviderStatusDescriptor] ENABLE TRIGGER [edfi_ProviderStatusDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_PublicationStatusDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_PublicationStatusDescriptor_TR_DeleteTracking] ON [edfi].[PublicationStatusDescriptor] AFTER DELETE AS BEGIN @@ -3309,8 +3435,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[PublicationStatusDescriptor](PublicationStatusDescriptorId, Id, ChangeVersion) - SELECT d.PublicationStatusDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.PublicationStatusDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.PublicationStatusDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.PublicationStatusDescriptorId = b.DescriptorId END @@ -3318,7 +3444,8 @@ GO ALTER TABLE [edfi].[PublicationStatusDescriptor] ENABLE TRIGGER [edfi_PublicationStatusDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_QuestionFormDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_QuestionFormDescriptor_TR_DeleteTracking] ON [edfi].[QuestionFormDescriptor] AFTER DELETE AS BEGIN @@ -3327,8 +3454,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[QuestionFormDescriptor](QuestionFormDescriptorId, Id, ChangeVersion) - SELECT d.QuestionFormDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.QuestionFormDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.QuestionFormDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.QuestionFormDescriptorId = b.DescriptorId END @@ -3336,7 +3463,8 @@ GO ALTER TABLE [edfi].[QuestionFormDescriptor] ENABLE TRIGGER [edfi_QuestionFormDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_RaceDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_RaceDescriptor_TR_DeleteTracking] ON [edfi].[RaceDescriptor] AFTER DELETE AS BEGIN @@ -3345,8 +3473,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[RaceDescriptor](RaceDescriptorId, Id, ChangeVersion) - SELECT d.RaceDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.RaceDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.RaceDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.RaceDescriptorId = b.DescriptorId END @@ -3354,7 +3482,8 @@ GO ALTER TABLE [edfi].[RaceDescriptor] ENABLE TRIGGER [edfi_RaceDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_ReasonExitedDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ReasonExitedDescriptor_TR_DeleteTracking] ON [edfi].[ReasonExitedDescriptor] AFTER DELETE AS BEGIN @@ -3363,8 +3492,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ReasonExitedDescriptor](ReasonExitedDescriptorId, Id, ChangeVersion) - SELECT d.ReasonExitedDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ReasonExitedDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ReasonExitedDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ReasonExitedDescriptorId = b.DescriptorId END @@ -3372,7 +3501,8 @@ GO ALTER TABLE [edfi].[ReasonExitedDescriptor] ENABLE TRIGGER [edfi_ReasonExitedDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_ReasonNotTestedDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ReasonNotTestedDescriptor_TR_DeleteTracking] ON [edfi].[ReasonNotTestedDescriptor] AFTER DELETE AS BEGIN @@ -3381,8 +3511,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ReasonNotTestedDescriptor](ReasonNotTestedDescriptorId, Id, ChangeVersion) - SELECT d.ReasonNotTestedDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ReasonNotTestedDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ReasonNotTestedDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ReasonNotTestedDescriptorId = b.DescriptorId END @@ -3390,7 +3520,8 @@ GO ALTER TABLE [edfi].[ReasonNotTestedDescriptor] ENABLE TRIGGER [edfi_ReasonNotTestedDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_RecognitionTypeDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_RecognitionTypeDescriptor_TR_DeleteTracking] ON [edfi].[RecognitionTypeDescriptor] AFTER DELETE AS BEGIN @@ -3399,8 +3530,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[RecognitionTypeDescriptor](RecognitionTypeDescriptorId, Id, ChangeVersion) - SELECT d.RecognitionTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.RecognitionTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.RecognitionTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.RecognitionTypeDescriptorId = b.DescriptorId END @@ -3408,7 +3539,8 @@ GO ALTER TABLE [edfi].[RecognitionTypeDescriptor] ENABLE TRIGGER [edfi_RecognitionTypeDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_RelationDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_RelationDescriptor_TR_DeleteTracking] ON [edfi].[RelationDescriptor] AFTER DELETE AS BEGIN @@ -3417,8 +3549,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[RelationDescriptor](RelationDescriptorId, Id, ChangeVersion) - SELECT d.RelationDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.RelationDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.RelationDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.RelationDescriptorId = b.DescriptorId END @@ -3426,7 +3558,8 @@ GO ALTER TABLE [edfi].[RelationDescriptor] ENABLE TRIGGER [edfi_RelationDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_RepeatIdentifierDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_RepeatIdentifierDescriptor_TR_DeleteTracking] ON [edfi].[RepeatIdentifierDescriptor] AFTER DELETE AS BEGIN @@ -3435,8 +3568,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[RepeatIdentifierDescriptor](RepeatIdentifierDescriptorId, Id, ChangeVersion) - SELECT d.RepeatIdentifierDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.RepeatIdentifierDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.RepeatIdentifierDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.RepeatIdentifierDescriptorId = b.DescriptorId END @@ -3444,7 +3577,8 @@ GO ALTER TABLE [edfi].[RepeatIdentifierDescriptor] ENABLE TRIGGER [edfi_RepeatIdentifierDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_ReportCard_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ReportCard_TR_DeleteTracking] ON [edfi].[ReportCard] AFTER DELETE AS BEGIN @@ -3453,15 +3587,21 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ReportCard](EducationOrganizationId, GradingPeriodDescriptorId, GradingPeriodSchoolId, GradingPeriodSchoolYear, GradingPeriodSequence, StudentUSI, Id, ChangeVersion) - SELECT EducationOrganizationId, GradingPeriodDescriptorId, GradingPeriodSchoolId, GradingPeriodSchoolYear, GradingPeriodSequence, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[ReportCard](OldEducationOrganizationId, OldGradingPeriodDescriptorId, OldGradingPeriodDescriptorNamespace, OldGradingPeriodDescriptorCodeValue, OldGradingPeriodSchoolId, OldGradingPeriodSchoolYear, OldGradingPeriodSequence, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.EducationOrganizationId, d.GradingPeriodDescriptorId, j1.Namespace, j1.CodeValue, d.GradingPeriodSchoolId, d.GradingPeriodSchoolYear, d.GradingPeriodSequence, d.StudentUSI, j5.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor j1 + ON d.GradingPeriodDescriptorId = j1.DescriptorId + INNER JOIN edfi.Student j5 + ON d.StudentUSI = j5.StudentUSI END GO ALTER TABLE [edfi].[ReportCard] ENABLE TRIGGER [edfi_ReportCard_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_ReporterDescriptionDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ReporterDescriptionDescriptor_TR_DeleteTracking] ON [edfi].[ReporterDescriptionDescriptor] AFTER DELETE AS BEGIN @@ -3470,8 +3610,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ReporterDescriptionDescriptor](ReporterDescriptionDescriptorId, Id, ChangeVersion) - SELECT d.ReporterDescriptionDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ReporterDescriptionDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ReporterDescriptionDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ReporterDescriptionDescriptorId = b.DescriptorId END @@ -3479,7 +3619,8 @@ GO ALTER TABLE [edfi].[ReporterDescriptionDescriptor] ENABLE TRIGGER [edfi_ReporterDescriptionDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_ResidencyStatusDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ResidencyStatusDescriptor_TR_DeleteTracking] ON [edfi].[ResidencyStatusDescriptor] AFTER DELETE AS BEGIN @@ -3488,8 +3629,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ResidencyStatusDescriptor](ResidencyStatusDescriptorId, Id, ChangeVersion) - SELECT d.ResidencyStatusDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ResidencyStatusDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ResidencyStatusDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ResidencyStatusDescriptorId = b.DescriptorId END @@ -3497,7 +3638,8 @@ GO ALTER TABLE [edfi].[ResidencyStatusDescriptor] ENABLE TRIGGER [edfi_ResidencyStatusDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_ResponseIndicatorDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ResponseIndicatorDescriptor_TR_DeleteTracking] ON [edfi].[ResponseIndicatorDescriptor] AFTER DELETE AS BEGIN @@ -3506,8 +3648,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ResponseIndicatorDescriptor](ResponseIndicatorDescriptorId, Id, ChangeVersion) - SELECT d.ResponseIndicatorDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ResponseIndicatorDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ResponseIndicatorDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ResponseIndicatorDescriptorId = b.DescriptorId END @@ -3515,7 +3657,8 @@ GO ALTER TABLE [edfi].[ResponseIndicatorDescriptor] ENABLE TRIGGER [edfi_ResponseIndicatorDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_ResponsibilityDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ResponsibilityDescriptor_TR_DeleteTracking] ON [edfi].[ResponsibilityDescriptor] AFTER DELETE AS BEGIN @@ -3524,8 +3667,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ResponsibilityDescriptor](ResponsibilityDescriptorId, Id, ChangeVersion) - SELECT d.ResponsibilityDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ResponsibilityDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ResponsibilityDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ResponsibilityDescriptorId = b.DescriptorId END @@ -3533,42 +3676,48 @@ GO ALTER TABLE [edfi].[ResponsibilityDescriptor] ENABLE TRIGGER [edfi_ResponsibilityDescriptor_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_RestraintEvent_TR_DeleteTracking] +GO - -CREATE TRIGGER [edfi].[edfi_RestraintEventReasonDescriptor_TR_DeleteTracking] ON [edfi].[RestraintEventReasonDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_RestraintEvent_TR_DeleteTracking] ON [edfi].[RestraintEvent] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[RestraintEventReasonDescriptor](RestraintEventReasonDescriptorId, Id, ChangeVersion) - SELECT d.RestraintEventReasonDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[RestraintEvent](OldRestraintEventIdentifier, OldSchoolId, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.RestraintEventIdentifier, d.SchoolId, d.StudentUSI, j2.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.RestraintEventReasonDescriptorId = b.DescriptorId + INNER JOIN edfi.Student j2 + ON d.StudentUSI = j2.StudentUSI END GO -ALTER TABLE [edfi].[RestraintEventReasonDescriptor] ENABLE TRIGGER [edfi_RestraintEventReasonDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[RestraintEvent] ENABLE TRIGGER [edfi_RestraintEvent_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_RestraintEventReasonDescriptor_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_RestraintEvent_TR_DeleteTracking] ON [edfi].[RestraintEvent] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_RestraintEventReasonDescriptor_TR_DeleteTracking] ON [edfi].[RestraintEventReasonDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[RestraintEvent](RestraintEventIdentifier, SchoolId, StudentUSI, Id, ChangeVersion) - SELECT RestraintEventIdentifier, SchoolId, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.RestraintEventReasonDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.RestraintEventReasonDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor b ON d.RestraintEventReasonDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[RestraintEvent] ENABLE TRIGGER [edfi_RestraintEvent_TR_DeleteTracking] +ALTER TABLE [edfi].[RestraintEventReasonDescriptor] ENABLE TRIGGER [edfi_RestraintEventReasonDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_ResultDatatypeTypeDescriptor_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_ResultDatatypeTypeDescriptor_TR_DeleteTracking] ON [edfi].[ResultDatatypeTypeDescriptor] AFTER DELETE AS BEGIN @@ -3577,8 +3726,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ResultDatatypeTypeDescriptor](ResultDatatypeTypeDescriptorId, Id, ChangeVersion) - SELECT d.ResultDatatypeTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ResultDatatypeTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ResultDatatypeTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ResultDatatypeTypeDescriptorId = b.DescriptorId END @@ -3586,7 +3735,8 @@ GO ALTER TABLE [edfi].[ResultDatatypeTypeDescriptor] ENABLE TRIGGER [edfi_ResultDatatypeTypeDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_RetestIndicatorDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_RetestIndicatorDescriptor_TR_DeleteTracking] ON [edfi].[RetestIndicatorDescriptor] AFTER DELETE AS BEGIN @@ -3595,8 +3745,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[RetestIndicatorDescriptor](RetestIndicatorDescriptorId, Id, ChangeVersion) - SELECT d.RetestIndicatorDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.RetestIndicatorDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.RetestIndicatorDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.RetestIndicatorDescriptorId = b.DescriptorId END @@ -3604,7 +3754,8 @@ GO ALTER TABLE [edfi].[RetestIndicatorDescriptor] ENABLE TRIGGER [edfi_RetestIndicatorDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_SchoolCategoryDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_SchoolCategoryDescriptor_TR_DeleteTracking] ON [edfi].[SchoolCategoryDescriptor] AFTER DELETE AS BEGIN @@ -3613,8 +3764,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SchoolCategoryDescriptor](SchoolCategoryDescriptorId, Id, ChangeVersion) - SELECT d.SchoolCategoryDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.SchoolCategoryDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.SchoolCategoryDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.SchoolCategoryDescriptorId = b.DescriptorId END @@ -3622,7 +3773,8 @@ GO ALTER TABLE [edfi].[SchoolCategoryDescriptor] ENABLE TRIGGER [edfi_SchoolCategoryDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_SchoolChoiceImplementStatusDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_SchoolChoiceImplementStatusDescriptor_TR_DeleteTracking] ON [edfi].[SchoolChoiceImplementStatusDescriptor] AFTER DELETE AS BEGIN @@ -3631,8 +3783,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SchoolChoiceImplementStatusDescriptor](SchoolChoiceImplementStatusDescriptorId, Id, ChangeVersion) - SELECT d.SchoolChoiceImplementStatusDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.SchoolChoiceImplementStatusDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.SchoolChoiceImplementStatusDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.SchoolChoiceImplementStatusDescriptorId = b.DescriptorId END @@ -3640,7 +3792,8 @@ GO ALTER TABLE [edfi].[SchoolChoiceImplementStatusDescriptor] ENABLE TRIGGER [edfi_SchoolChoiceImplementStatusDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_SchoolFoodServiceProgramServiceDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_SchoolFoodServiceProgramServiceDescriptor_TR_DeleteTracking] ON [edfi].[SchoolFoodServiceProgramServiceDescriptor] AFTER DELETE AS BEGIN @@ -3649,8 +3802,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SchoolFoodServiceProgramServiceDescriptor](SchoolFoodServiceProgramServiceDescriptorId, Id, ChangeVersion) - SELECT d.SchoolFoodServiceProgramServiceDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.SchoolFoodServiceProgramServiceDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.SchoolFoodServiceProgramServiceDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.SchoolFoodServiceProgramServiceDescriptorId = b.DescriptorId END @@ -3658,7 +3811,8 @@ GO ALTER TABLE [edfi].[SchoolFoodServiceProgramServiceDescriptor] ENABLE TRIGGER [edfi_SchoolFoodServiceProgramServiceDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_SchoolTypeDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_SchoolTypeDescriptor_TR_DeleteTracking] ON [edfi].[SchoolTypeDescriptor] AFTER DELETE AS BEGIN @@ -3667,8 +3821,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SchoolTypeDescriptor](SchoolTypeDescriptorId, Id, ChangeVersion) - SELECT d.SchoolTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.SchoolTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.SchoolTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.SchoolTypeDescriptorId = b.DescriptorId END @@ -3676,77 +3830,84 @@ GO ALTER TABLE [edfi].[SchoolTypeDescriptor] ENABLE TRIGGER [edfi_SchoolTypeDescriptor_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SchoolYearType_TR_DeleteTracking] +GO - -CREATE TRIGGER [edfi].[edfi_School_TR_DeleteTracking] ON [edfi].[School] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_SchoolYearType_TR_DeleteTracking] ON [edfi].[SchoolYearType] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[School](SchoolId, Id, ChangeVersion) - SELECT d.SchoolId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[SchoolYearType](OldSchoolYear, Id, ChangeVersion) + SELECT d.SchoolYear, d.Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.EducationOrganization b ON d.SchoolId = b.EducationOrganizationId END GO -ALTER TABLE [edfi].[School] ENABLE TRIGGER [edfi_School_TR_DeleteTracking] +ALTER TABLE [edfi].[SchoolYearType] ENABLE TRIGGER [edfi_SchoolYearType_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Section_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_SectionAttendanceTakenEvent_TR_DeleteTracking] ON [edfi].[SectionAttendanceTakenEvent] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_Section_TR_DeleteTracking] ON [edfi].[Section] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SectionAttendanceTakenEvent](CalendarCode, Date, LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, Id, ChangeVersion) - SELECT CalendarCode, Date, LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Section](OldLocalCourseCode, OldSchoolId, OldSchoolYear, OldSectionIdentifier, OldSessionName, Id, Discriminator, ChangeVersion) + SELECT d.LocalCourseCode, d.SchoolId, d.SchoolYear, d.SectionIdentifier, d.SessionName, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO -ALTER TABLE [edfi].[SectionAttendanceTakenEvent] ENABLE TRIGGER [edfi_SectionAttendanceTakenEvent_TR_DeleteTracking] +ALTER TABLE [edfi].[Section] ENABLE TRIGGER [edfi_Section_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SectionAttendanceTakenEvent_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_SectionCharacteristicDescriptor_TR_DeleteTracking] ON [edfi].[SectionCharacteristicDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_SectionAttendanceTakenEvent_TR_DeleteTracking] ON [edfi].[SectionAttendanceTakenEvent] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SectionCharacteristicDescriptor](SectionCharacteristicDescriptorId, Id, ChangeVersion) - SELECT d.SectionCharacteristicDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[SectionAttendanceTakenEvent](OldCalendarCode, OldDate, OldLocalCourseCode, OldSchoolId, OldSchoolYear, OldSectionIdentifier, OldSessionName, Id, Discriminator, ChangeVersion) + SELECT d.CalendarCode, d.Date, d.LocalCourseCode, d.SchoolId, d.SchoolYear, d.SectionIdentifier, d.SessionName, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.SectionCharacteristicDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[SectionCharacteristicDescriptor] ENABLE TRIGGER [edfi_SectionCharacteristicDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[SectionAttendanceTakenEvent] ENABLE TRIGGER [edfi_SectionAttendanceTakenEvent_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SectionCharacteristicDescriptor_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_Section_TR_DeleteTracking] ON [edfi].[Section] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_SectionCharacteristicDescriptor_TR_DeleteTracking] ON [edfi].[SectionCharacteristicDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[Section](LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, Id, ChangeVersion) - SELECT LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.SectionCharacteristicDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.SectionCharacteristicDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor b ON d.SectionCharacteristicDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[Section] ENABLE TRIGGER [edfi_Section_TR_DeleteTracking] +ALTER TABLE [edfi].[SectionCharacteristicDescriptor] ENABLE TRIGGER [edfi_SectionCharacteristicDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SeparationDescriptor_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_SeparationDescriptor_TR_DeleteTracking] ON [edfi].[SeparationDescriptor] AFTER DELETE AS BEGIN @@ -3755,8 +3916,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SeparationDescriptor](SeparationDescriptorId, Id, ChangeVersion) - SELECT d.SeparationDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.SeparationDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.SeparationDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.SeparationDescriptorId = b.DescriptorId END @@ -3764,7 +3925,8 @@ GO ALTER TABLE [edfi].[SeparationDescriptor] ENABLE TRIGGER [edfi_SeparationDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_SeparationReasonDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_SeparationReasonDescriptor_TR_DeleteTracking] ON [edfi].[SeparationReasonDescriptor] AFTER DELETE AS BEGIN @@ -3773,8 +3935,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SeparationReasonDescriptor](SeparationReasonDescriptorId, Id, ChangeVersion) - SELECT d.SeparationReasonDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.SeparationReasonDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.SeparationReasonDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.SeparationReasonDescriptorId = b.DescriptorId END @@ -3782,7 +3944,8 @@ GO ALTER TABLE [edfi].[SeparationReasonDescriptor] ENABLE TRIGGER [edfi_SeparationReasonDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_ServiceDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_ServiceDescriptor_TR_DeleteTracking] ON [edfi].[ServiceDescriptor] AFTER DELETE AS BEGIN @@ -3791,8 +3954,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[ServiceDescriptor](ServiceDescriptorId, Id, ChangeVersion) - SELECT d.ServiceDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.ServiceDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.ServiceDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.ServiceDescriptorId = b.DescriptorId END @@ -3800,7 +3963,8 @@ GO ALTER TABLE [edfi].[ServiceDescriptor] ENABLE TRIGGER [edfi_ServiceDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_Session_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_Session_TR_DeleteTracking] ON [edfi].[Session] AFTER DELETE AS BEGIN @@ -3809,8 +3973,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[Session](SchoolId, SchoolYear, SessionName, Id, ChangeVersion) - SELECT SchoolId, SchoolYear, SessionName, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Session](OldSchoolId, OldSchoolYear, OldSessionName, Id, Discriminator, ChangeVersion) + SELECT d.SchoolId, d.SchoolYear, d.SessionName, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO @@ -3818,6 +3982,8 @@ GO ALTER TABLE [edfi].[Session] ENABLE TRIGGER [edfi_Session_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SexDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_SexDescriptor_TR_DeleteTracking] ON [edfi].[SexDescriptor] AFTER DELETE AS BEGIN @@ -3826,8 +3992,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SexDescriptor](SexDescriptorId, Id, ChangeVersion) - SELECT d.SexDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.SexDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.SexDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.SexDescriptorId = b.DescriptorId END @@ -3835,7 +4001,8 @@ GO ALTER TABLE [edfi].[SexDescriptor] ENABLE TRIGGER [edfi_SexDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_SourceSystemDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_SourceSystemDescriptor_TR_DeleteTracking] ON [edfi].[SourceSystemDescriptor] AFTER DELETE AS BEGIN @@ -3844,8 +4011,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SourceSystemDescriptor](SourceSystemDescriptorId, Id, ChangeVersion) - SELECT d.SourceSystemDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.SourceSystemDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.SourceSystemDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.SourceSystemDescriptorId = b.DescriptorId END @@ -3853,7 +4020,8 @@ GO ALTER TABLE [edfi].[SourceSystemDescriptor] ENABLE TRIGGER [edfi_SourceSystemDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_SpecialEducationProgramServiceDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_SpecialEducationProgramServiceDescriptor_TR_DeleteTracking] ON [edfi].[SpecialEducationProgramServiceDescriptor] AFTER DELETE AS BEGIN @@ -3862,8 +4030,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SpecialEducationProgramServiceDescriptor](SpecialEducationProgramServiceDescriptorId, Id, ChangeVersion) - SELECT d.SpecialEducationProgramServiceDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.SpecialEducationProgramServiceDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.SpecialEducationProgramServiceDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.SpecialEducationProgramServiceDescriptorId = b.DescriptorId END @@ -3871,7 +4039,8 @@ GO ALTER TABLE [edfi].[SpecialEducationProgramServiceDescriptor] ENABLE TRIGGER [edfi_SpecialEducationProgramServiceDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_SpecialEducationSettingDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_SpecialEducationSettingDescriptor_TR_DeleteTracking] ON [edfi].[SpecialEducationSettingDescriptor] AFTER DELETE AS BEGIN @@ -3880,8 +4049,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SpecialEducationSettingDescriptor](SpecialEducationSettingDescriptorId, Id, ChangeVersion) - SELECT d.SpecialEducationSettingDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.SpecialEducationSettingDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.SpecialEducationSettingDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.SpecialEducationSettingDescriptorId = b.DescriptorId END @@ -3889,7 +4058,27 @@ GO ALTER TABLE [edfi].[SpecialEducationSettingDescriptor] ENABLE TRIGGER [edfi_SpecialEducationSettingDescriptor_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Staff_TR_DeleteTracking] +GO + +CREATE TRIGGER [edfi].[edfi_Staff_TR_DeleteTracking] ON [edfi].[Staff] AFTER DELETE AS +BEGIN + IF @@rowcount = 0 + RETURN + + SET NOCOUNT ON + + INSERT INTO [tracked_changes_edfi].[Staff](OldStaffUSI, OldStaffUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.StaffUSI, d.StaffUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + FROM deleted d +END +GO + +ALTER TABLE [edfi].[Staff] ENABLE TRIGGER [edfi_Staff_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StaffAbsenceEvent_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StaffAbsenceEvent_TR_DeleteTracking] ON [edfi].[StaffAbsenceEvent] AFTER DELETE AS BEGIN @@ -3898,15 +4087,21 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StaffAbsenceEvent](AbsenceEventCategoryDescriptorId, EventDate, StaffUSI, Id, ChangeVersion) - SELECT AbsenceEventCategoryDescriptorId, EventDate, StaffUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StaffAbsenceEvent](OldAbsenceEventCategoryDescriptorId, OldAbsenceEventCategoryDescriptorNamespace, OldAbsenceEventCategoryDescriptorCodeValue, OldEventDate, OldStaffUSI, OldStaffUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.AbsenceEventCategoryDescriptorId, j0.Namespace, j0.CodeValue, d.EventDate, d.StaffUSI, j2.StaffUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor j0 + ON d.AbsenceEventCategoryDescriptorId = j0.DescriptorId + INNER JOIN edfi.Staff j2 + ON d.StaffUSI = j2.StaffUSI END GO ALTER TABLE [edfi].[StaffAbsenceEvent] ENABLE TRIGGER [edfi_StaffAbsenceEvent_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StaffClassificationDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StaffClassificationDescriptor_TR_DeleteTracking] ON [edfi].[StaffClassificationDescriptor] AFTER DELETE AS BEGIN @@ -3915,8 +4110,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StaffClassificationDescriptor](StaffClassificationDescriptorId, Id, ChangeVersion) - SELECT d.StaffClassificationDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.StaffClassificationDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.StaffClassificationDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.StaffClassificationDescriptorId = b.DescriptorId END @@ -3924,8 +4119,9 @@ GO ALTER TABLE [edfi].[StaffClassificationDescriptor] ENABLE TRIGGER [edfi_StaffClassificationDescriptor_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StaffCohortAssociation_TR_DeleteTracking] +GO - CREATE TRIGGER [edfi].[edfi_StaffCohortAssociation_TR_DeleteTracking] ON [edfi].[StaffCohortAssociation] AFTER DELETE AS BEGIN IF @@rowcount = 0 @@ -3933,15 +4129,19 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StaffCohortAssociation](BeginDate, CohortIdentifier, EducationOrganizationId, StaffUSI, Id, ChangeVersion) - SELECT BeginDate, CohortIdentifier, EducationOrganizationId, StaffUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StaffCohortAssociation](OldBeginDate, OldCohortIdentifier, OldEducationOrganizationId, OldStaffUSI, OldStaffUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.BeginDate, d.CohortIdentifier, d.EducationOrganizationId, d.StaffUSI, j3.StaffUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Staff j3 + ON d.StaffUSI = j3.StaffUSI END GO ALTER TABLE [edfi].[StaffCohortAssociation] ENABLE TRIGGER [edfi_StaffCohortAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StaffDisciplineIncidentAssociation_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StaffDisciplineIncidentAssociation_TR_DeleteTracking] ON [edfi].[StaffDisciplineIncidentAssociation] AFTER DELETE AS BEGIN @@ -3950,15 +4150,19 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StaffDisciplineIncidentAssociation](IncidentIdentifier, SchoolId, StaffUSI, Id, ChangeVersion) - SELECT IncidentIdentifier, SchoolId, StaffUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StaffDisciplineIncidentAssociation](OldIncidentIdentifier, OldSchoolId, OldStaffUSI, OldStaffUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.IncidentIdentifier, d.SchoolId, d.StaffUSI, j2.StaffUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Staff j2 + ON d.StaffUSI = j2.StaffUSI END GO ALTER TABLE [edfi].[StaffDisciplineIncidentAssociation] ENABLE TRIGGER [edfi_StaffDisciplineIncidentAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StaffEducationOrganizationAssignmentAssociation_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StaffEducationOrganizationAssignmentAssociation_TR_DeleteTracking] ON [edfi].[StaffEducationOrganizationAssignmentAssociation] AFTER DELETE AS BEGIN @@ -3967,15 +4171,21 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StaffEducationOrganizationAssignmentAssociation](BeginDate, EducationOrganizationId, StaffClassificationDescriptorId, StaffUSI, Id, ChangeVersion) - SELECT BeginDate, EducationOrganizationId, StaffClassificationDescriptorId, StaffUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StaffEducationOrganizationAssignmentAssociation](OldBeginDate, OldEducationOrganizationId, OldStaffClassificationDescriptorId, OldStaffClassificationDescriptorNamespace, OldStaffClassificationDescriptorCodeValue, OldStaffUSI, OldStaffUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.BeginDate, d.EducationOrganizationId, d.StaffClassificationDescriptorId, j2.Namespace, j2.CodeValue, d.StaffUSI, j3.StaffUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor j2 + ON d.StaffClassificationDescriptorId = j2.DescriptorId + INNER JOIN edfi.Staff j3 + ON d.StaffUSI = j3.StaffUSI END GO ALTER TABLE [edfi].[StaffEducationOrganizationAssignmentAssociation] ENABLE TRIGGER [edfi_StaffEducationOrganizationAssignmentAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StaffEducationOrganizationContactAssociation_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StaffEducationOrganizationContactAssociation_TR_DeleteTracking] ON [edfi].[StaffEducationOrganizationContactAssociation] AFTER DELETE AS BEGIN @@ -3984,15 +4194,19 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StaffEducationOrganizationContactAssociation](ContactTitle, EducationOrganizationId, StaffUSI, Id, ChangeVersion) - SELECT ContactTitle, EducationOrganizationId, StaffUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StaffEducationOrganizationContactAssociation](OldContactTitle, OldEducationOrganizationId, OldStaffUSI, OldStaffUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.ContactTitle, d.EducationOrganizationId, d.StaffUSI, j2.StaffUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Staff j2 + ON d.StaffUSI = j2.StaffUSI END GO ALTER TABLE [edfi].[StaffEducationOrganizationContactAssociation] ENABLE TRIGGER [edfi_StaffEducationOrganizationContactAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StaffEducationOrganizationEmploymentAssociation_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StaffEducationOrganizationEmploymentAssociation_TR_DeleteTracking] ON [edfi].[StaffEducationOrganizationEmploymentAssociation] AFTER DELETE AS BEGIN @@ -4001,15 +4215,21 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StaffEducationOrganizationEmploymentAssociation](EducationOrganizationId, EmploymentStatusDescriptorId, HireDate, StaffUSI, Id, ChangeVersion) - SELECT EducationOrganizationId, EmploymentStatusDescriptorId, HireDate, StaffUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StaffEducationOrganizationEmploymentAssociation](OldEducationOrganizationId, OldEmploymentStatusDescriptorId, OldEmploymentStatusDescriptorNamespace, OldEmploymentStatusDescriptorCodeValue, OldHireDate, OldStaffUSI, OldStaffUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.EducationOrganizationId, d.EmploymentStatusDescriptorId, j1.Namespace, j1.CodeValue, d.HireDate, d.StaffUSI, j3.StaffUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor j1 + ON d.EmploymentStatusDescriptorId = j1.DescriptorId + INNER JOIN edfi.Staff j3 + ON d.StaffUSI = j3.StaffUSI END GO ALTER TABLE [edfi].[StaffEducationOrganizationEmploymentAssociation] ENABLE TRIGGER [edfi_StaffEducationOrganizationEmploymentAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StaffIdentificationSystemDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StaffIdentificationSystemDescriptor_TR_DeleteTracking] ON [edfi].[StaffIdentificationSystemDescriptor] AFTER DELETE AS BEGIN @@ -4018,8 +4238,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StaffIdentificationSystemDescriptor](StaffIdentificationSystemDescriptorId, Id, ChangeVersion) - SELECT d.StaffIdentificationSystemDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.StaffIdentificationSystemDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.StaffIdentificationSystemDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.StaffIdentificationSystemDescriptorId = b.DescriptorId END @@ -4027,42 +4247,50 @@ GO ALTER TABLE [edfi].[StaffIdentificationSystemDescriptor] ENABLE TRIGGER [edfi_StaffIdentificationSystemDescriptor_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StaffLeave_TR_DeleteTracking] +GO - -CREATE TRIGGER [edfi].[edfi_StaffLeaveEventCategoryDescriptor_TR_DeleteTracking] ON [edfi].[StaffLeaveEventCategoryDescriptor] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_StaffLeave_TR_DeleteTracking] ON [edfi].[StaffLeave] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StaffLeaveEventCategoryDescriptor](StaffLeaveEventCategoryDescriptorId, Id, ChangeVersion) - SELECT d.StaffLeaveEventCategoryDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StaffLeave](OldBeginDate, OldStaffLeaveEventCategoryDescriptorId, OldStaffLeaveEventCategoryDescriptorNamespace, OldStaffLeaveEventCategoryDescriptorCodeValue, OldStaffUSI, OldStaffUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.BeginDate, d.StaffLeaveEventCategoryDescriptorId, j1.Namespace, j1.CodeValue, d.StaffUSI, j2.StaffUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.Descriptor b ON d.StaffLeaveEventCategoryDescriptorId = b.DescriptorId + INNER JOIN edfi.Descriptor j1 + ON d.StaffLeaveEventCategoryDescriptorId = j1.DescriptorId + INNER JOIN edfi.Staff j2 + ON d.StaffUSI = j2.StaffUSI END GO -ALTER TABLE [edfi].[StaffLeaveEventCategoryDescriptor] ENABLE TRIGGER [edfi_StaffLeaveEventCategoryDescriptor_TR_DeleteTracking] +ALTER TABLE [edfi].[StaffLeave] ENABLE TRIGGER [edfi_StaffLeave_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StaffLeaveEventCategoryDescriptor_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_StaffLeave_TR_DeleteTracking] ON [edfi].[StaffLeave] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_StaffLeaveEventCategoryDescriptor_TR_DeleteTracking] ON [edfi].[StaffLeaveEventCategoryDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StaffLeave](BeginDate, StaffLeaveEventCategoryDescriptorId, StaffUSI, Id, ChangeVersion) - SELECT BeginDate, StaffLeaveEventCategoryDescriptorId, StaffUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.StaffLeaveEventCategoryDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.StaffLeaveEventCategoryDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor b ON d.StaffLeaveEventCategoryDescriptorId = b.DescriptorId END GO -ALTER TABLE [edfi].[StaffLeave] ENABLE TRIGGER [edfi_StaffLeave_TR_DeleteTracking] +ALTER TABLE [edfi].[StaffLeaveEventCategoryDescriptor] ENABLE TRIGGER [edfi_StaffLeaveEventCategoryDescriptor_TR_DeleteTracking] +GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StaffProgramAssociation_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_StaffProgramAssociation_TR_DeleteTracking] ON [edfi].[StaffProgramAssociation] AFTER DELETE AS BEGIN @@ -4071,15 +4299,21 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StaffProgramAssociation](BeginDate, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StaffUSI, Id, ChangeVersion) - SELECT BeginDate, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StaffUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StaffProgramAssociation](OldBeginDate, OldProgramEducationOrganizationId, OldProgramName, OldProgramTypeDescriptorId, OldProgramTypeDescriptorNamespace, OldProgramTypeDescriptorCodeValue, OldStaffUSI, OldStaffUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.BeginDate, d.ProgramEducationOrganizationId, d.ProgramName, d.ProgramTypeDescriptorId, j3.Namespace, j3.CodeValue, d.StaffUSI, j4.StaffUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor j3 + ON d.ProgramTypeDescriptorId = j3.DescriptorId + INNER JOIN edfi.Staff j4 + ON d.StaffUSI = j4.StaffUSI END GO ALTER TABLE [edfi].[StaffProgramAssociation] ENABLE TRIGGER [edfi_StaffProgramAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StaffSchoolAssociation_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StaffSchoolAssociation_TR_DeleteTracking] ON [edfi].[StaffSchoolAssociation] AFTER DELETE AS BEGIN @@ -4088,15 +4322,21 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StaffSchoolAssociation](ProgramAssignmentDescriptorId, SchoolId, StaffUSI, Id, ChangeVersion) - SELECT ProgramAssignmentDescriptorId, SchoolId, StaffUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StaffSchoolAssociation](OldProgramAssignmentDescriptorId, OldProgramAssignmentDescriptorNamespace, OldProgramAssignmentDescriptorCodeValue, OldSchoolId, OldStaffUSI, OldStaffUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.ProgramAssignmentDescriptorId, j0.Namespace, j0.CodeValue, d.SchoolId, d.StaffUSI, j2.StaffUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor j0 + ON d.ProgramAssignmentDescriptorId = j0.DescriptorId + INNER JOIN edfi.Staff j2 + ON d.StaffUSI = j2.StaffUSI END GO ALTER TABLE [edfi].[StaffSchoolAssociation] ENABLE TRIGGER [edfi_StaffSchoolAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StaffSectionAssociation_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StaffSectionAssociation_TR_DeleteTracking] ON [edfi].[StaffSectionAssociation] AFTER DELETE AS BEGIN @@ -4105,33 +4345,20 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StaffSectionAssociation](LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, StaffUSI, Id, ChangeVersion) - SELECT LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, StaffUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StaffSectionAssociation](OldLocalCourseCode, OldSchoolId, OldSchoolYear, OldSectionIdentifier, OldSessionName, OldStaffUSI, OldStaffUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.LocalCourseCode, d.SchoolId, d.SchoolYear, d.SectionIdentifier, d.SessionName, d.StaffUSI, j5.StaffUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Staff j5 + ON d.StaffUSI = j5.StaffUSI END GO ALTER TABLE [edfi].[StaffSectionAssociation] ENABLE TRIGGER [edfi_StaffSectionAssociation_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_Staff_TR_DeleteTracking] ON [edfi].[Staff] AFTER DELETE AS -BEGIN - IF @@rowcount = 0 - RETURN - - SET NOCOUNT ON - - INSERT INTO [tracked_deletes_edfi].[Staff](StaffUSI, Id, ChangeVersion) - SELECT StaffUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) - FROM deleted d -END -GO - -ALTER TABLE [edfi].[Staff] ENABLE TRIGGER [edfi_Staff_TR_DeleteTracking] +DROP TRIGGER IF EXISTS [edfi].[edfi_StateAbbreviationDescriptor_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_StateAbbreviationDescriptor_TR_DeleteTracking] ON [edfi].[StateAbbreviationDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 @@ -4139,8 +4366,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StateAbbreviationDescriptor](StateAbbreviationDescriptorId, Id, ChangeVersion) - SELECT d.StateAbbreviationDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.StateAbbreviationDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.StateAbbreviationDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.StateAbbreviationDescriptorId = b.DescriptorId END @@ -4148,25 +4375,27 @@ GO ALTER TABLE [edfi].[StateAbbreviationDescriptor] ENABLE TRIGGER [edfi_StateAbbreviationDescriptor_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_Student_TR_DeleteTracking] +GO - -CREATE TRIGGER [edfi].[edfi_StateEducationAgency_TR_DeleteTracking] ON [edfi].[StateEducationAgency] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_Student_TR_DeleteTracking] ON [edfi].[Student] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StateEducationAgency](StateEducationAgencyId, Id, ChangeVersion) - SELECT d.StateEducationAgencyId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Student](OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.StudentUSI, d.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.EducationOrganization b ON d.StateEducationAgencyId = b.EducationOrganizationId END GO -ALTER TABLE [edfi].[StateEducationAgency] ENABLE TRIGGER [edfi_StateEducationAgency_TR_DeleteTracking] +ALTER TABLE [edfi].[Student] ENABLE TRIGGER [edfi_Student_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentAcademicRecord_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StudentAcademicRecord_TR_DeleteTracking] ON [edfi].[StudentAcademicRecord] AFTER DELETE AS BEGIN @@ -4175,15 +4404,21 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StudentAcademicRecord](EducationOrganizationId, SchoolYear, StudentUSI, TermDescriptorId, Id, ChangeVersion) - SELECT EducationOrganizationId, SchoolYear, StudentUSI, TermDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StudentAcademicRecord](OldEducationOrganizationId, OldSchoolYear, OldStudentUSI, OldStudentUniqueId, OldTermDescriptorId, OldTermDescriptorNamespace, OldTermDescriptorCodeValue, Id, Discriminator, ChangeVersion) + SELECT d.EducationOrganizationId, d.SchoolYear, d.StudentUSI, j2.StudentUniqueId, d.TermDescriptorId, j3.Namespace, j3.CodeValue, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Student j2 + ON d.StudentUSI = j2.StudentUSI + INNER JOIN edfi.Descriptor j3 + ON d.TermDescriptorId = j3.DescriptorId END GO ALTER TABLE [edfi].[StudentAcademicRecord] ENABLE TRIGGER [edfi_StudentAcademicRecord_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentAssessment_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StudentAssessment_TR_DeleteTracking] ON [edfi].[StudentAssessment] AFTER DELETE AS BEGIN @@ -4192,34 +4427,20 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StudentAssessment](AssessmentIdentifier, Namespace, StudentAssessmentIdentifier, StudentUSI, Id, ChangeVersion) - SELECT AssessmentIdentifier, Namespace, StudentAssessmentIdentifier, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StudentAssessment](OldAssessmentIdentifier, OldNamespace, OldStudentAssessmentIdentifier, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.AssessmentIdentifier, d.Namespace, d.StudentAssessmentIdentifier, d.StudentUSI, j3.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Student j3 + ON d.StudentUSI = j3.StudentUSI END GO ALTER TABLE [edfi].[StudentAssessment] ENABLE TRIGGER [edfi_StudentAssessment_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_StudentCTEProgramAssociation_TR_DeleteTracking] ON [edfi].[StudentCTEProgramAssociation] AFTER DELETE AS -BEGIN - IF @@rowcount = 0 - RETURN - - SET NOCOUNT ON - - INSERT INTO [tracked_deletes_edfi].[StudentCTEProgramAssociation](BeginDate, EducationOrganizationId, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, ChangeVersion) - SELECT d.BeginDate, d.EducationOrganizationId, d.ProgramEducationOrganizationId, d.ProgramName, d.ProgramTypeDescriptorId, d.StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) - FROM deleted d - INNER JOIN edfi.GeneralStudentProgramAssociation b ON d.BeginDate = b.BeginDate AND d.EducationOrganizationId = b.EducationOrganizationId AND d.ProgramEducationOrganizationId = b.ProgramEducationOrganizationId AND d.ProgramName = b.ProgramName AND d.ProgramTypeDescriptorId = b.ProgramTypeDescriptorId AND d.StudentUSI = b.StudentUSI -END -GO - -ALTER TABLE [edfi].[StudentCTEProgramAssociation] ENABLE TRIGGER [edfi_StudentCTEProgramAssociation_TR_DeleteTracking] +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentCharacteristicDescriptor_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_StudentCharacteristicDescriptor_TR_DeleteTracking] ON [edfi].[StudentCharacteristicDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 @@ -4227,8 +4448,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StudentCharacteristicDescriptor](StudentCharacteristicDescriptorId, Id, ChangeVersion) - SELECT d.StudentCharacteristicDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.StudentCharacteristicDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.StudentCharacteristicDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.StudentCharacteristicDescriptorId = b.DescriptorId END @@ -4236,7 +4457,8 @@ GO ALTER TABLE [edfi].[StudentCharacteristicDescriptor] ENABLE TRIGGER [edfi_StudentCharacteristicDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentCohortAssociation_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StudentCohortAssociation_TR_DeleteTracking] ON [edfi].[StudentCohortAssociation] AFTER DELETE AS BEGIN @@ -4245,15 +4467,19 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StudentCohortAssociation](BeginDate, CohortIdentifier, EducationOrganizationId, StudentUSI, Id, ChangeVersion) - SELECT BeginDate, CohortIdentifier, EducationOrganizationId, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StudentCohortAssociation](OldBeginDate, OldCohortIdentifier, OldEducationOrganizationId, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.BeginDate, d.CohortIdentifier, d.EducationOrganizationId, d.StudentUSI, j3.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Student j3 + ON d.StudentUSI = j3.StudentUSI END GO ALTER TABLE [edfi].[StudentCohortAssociation] ENABLE TRIGGER [edfi_StudentCohortAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentCompetencyObjective_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StudentCompetencyObjective_TR_DeleteTracking] ON [edfi].[StudentCompetencyObjective] AFTER DELETE AS BEGIN @@ -4262,15 +4488,23 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StudentCompetencyObjective](GradingPeriodDescriptorId, GradingPeriodSchoolId, GradingPeriodSchoolYear, GradingPeriodSequence, Objective, ObjectiveEducationOrganizationId, ObjectiveGradeLevelDescriptorId, StudentUSI, Id, ChangeVersion) - SELECT GradingPeriodDescriptorId, GradingPeriodSchoolId, GradingPeriodSchoolYear, GradingPeriodSequence, Objective, ObjectiveEducationOrganizationId, ObjectiveGradeLevelDescriptorId, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StudentCompetencyObjective](OldGradingPeriodDescriptorId, OldGradingPeriodDescriptorNamespace, OldGradingPeriodDescriptorCodeValue, OldGradingPeriodSchoolId, OldGradingPeriodSchoolYear, OldGradingPeriodSequence, OldObjective, OldObjectiveEducationOrganizationId, OldObjectiveGradeLevelDescriptorId, OldObjectiveGradeLevelDescriptorNamespace, OldObjectiveGradeLevelDescriptorCodeValue, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.GradingPeriodDescriptorId, j0.Namespace, j0.CodeValue, d.GradingPeriodSchoolId, d.GradingPeriodSchoolYear, d.GradingPeriodSequence, d.Objective, d.ObjectiveEducationOrganizationId, d.ObjectiveGradeLevelDescriptorId, j6.Namespace, j6.CodeValue, d.StudentUSI, j7.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor j0 + ON d.GradingPeriodDescriptorId = j0.DescriptorId + INNER JOIN edfi.Descriptor j6 + ON d.ObjectiveGradeLevelDescriptorId = j6.DescriptorId + INNER JOIN edfi.Student j7 + ON d.StudentUSI = j7.StudentUSI END GO ALTER TABLE [edfi].[StudentCompetencyObjective] ENABLE TRIGGER [edfi_StudentCompetencyObjective_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentDisciplineIncidentAssociation_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StudentDisciplineIncidentAssociation_TR_DeleteTracking] ON [edfi].[StudentDisciplineIncidentAssociation] AFTER DELETE AS BEGIN @@ -4279,15 +4513,19 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StudentDisciplineIncidentAssociation](IncidentIdentifier, SchoolId, StudentUSI, Id, ChangeVersion) - SELECT IncidentIdentifier, SchoolId, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StudentDisciplineIncidentAssociation](OldIncidentIdentifier, OldSchoolId, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.IncidentIdentifier, d.SchoolId, d.StudentUSI, j2.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Student j2 + ON d.StudentUSI = j2.StudentUSI END GO ALTER TABLE [edfi].[StudentDisciplineIncidentAssociation] ENABLE TRIGGER [edfi_StudentDisciplineIncidentAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentDisciplineIncidentBehaviorAssociation_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StudentDisciplineIncidentBehaviorAssociation_TR_DeleteTracking] ON [edfi].[StudentDisciplineIncidentBehaviorAssociation] AFTER DELETE AS BEGIN @@ -4296,15 +4534,21 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StudentDisciplineIncidentBehaviorAssociation](BehaviorDescriptorId, IncidentIdentifier, SchoolId, StudentUSI, Id, ChangeVersion) - SELECT BehaviorDescriptorId, IncidentIdentifier, SchoolId, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StudentDisciplineIncidentBehaviorAssociation](OldBehaviorDescriptorId, OldBehaviorDescriptorNamespace, OldBehaviorDescriptorCodeValue, OldIncidentIdentifier, OldSchoolId, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.BehaviorDescriptorId, j0.Namespace, j0.CodeValue, d.IncidentIdentifier, d.SchoolId, d.StudentUSI, j3.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor j0 + ON d.BehaviorDescriptorId = j0.DescriptorId + INNER JOIN edfi.Student j3 + ON d.StudentUSI = j3.StudentUSI END GO ALTER TABLE [edfi].[StudentDisciplineIncidentBehaviorAssociation] ENABLE TRIGGER [edfi_StudentDisciplineIncidentBehaviorAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentDisciplineIncidentNonOffenderAssociation_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StudentDisciplineIncidentNonOffenderAssociation_TR_DeleteTracking] ON [edfi].[StudentDisciplineIncidentNonOffenderAssociation] AFTER DELETE AS BEGIN @@ -4313,15 +4557,19 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StudentDisciplineIncidentNonOffenderAssociation](IncidentIdentifier, SchoolId, StudentUSI, Id, ChangeVersion) - SELECT IncidentIdentifier, SchoolId, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StudentDisciplineIncidentNonOffenderAssociation](OldIncidentIdentifier, OldSchoolId, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.IncidentIdentifier, d.SchoolId, d.StudentUSI, j2.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Student j2 + ON d.StudentUSI = j2.StudentUSI END GO ALTER TABLE [edfi].[StudentDisciplineIncidentNonOffenderAssociation] ENABLE TRIGGER [edfi_StudentDisciplineIncidentNonOffenderAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentEducationOrganizationAssociation_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StudentEducationOrganizationAssociation_TR_DeleteTracking] ON [edfi].[StudentEducationOrganizationAssociation] AFTER DELETE AS BEGIN @@ -4330,15 +4578,19 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StudentEducationOrganizationAssociation](EducationOrganizationId, StudentUSI, Id, ChangeVersion) - SELECT EducationOrganizationId, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StudentEducationOrganizationAssociation](OldEducationOrganizationId, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.EducationOrganizationId, d.StudentUSI, j1.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Student j1 + ON d.StudentUSI = j1.StudentUSI END GO ALTER TABLE [edfi].[StudentEducationOrganizationAssociation] ENABLE TRIGGER [edfi_StudentEducationOrganizationAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentEducationOrganizationResponsibilityAssociation_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StudentEducationOrganizationResponsibilityAssociation_TR_DeleteTracking] ON [edfi].[StudentEducationOrganizationResponsibilityAssociation] AFTER DELETE AS BEGIN @@ -4347,15 +4599,21 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StudentEducationOrganizationResponsibilityAssociation](BeginDate, EducationOrganizationId, ResponsibilityDescriptorId, StudentUSI, Id, ChangeVersion) - SELECT BeginDate, EducationOrganizationId, ResponsibilityDescriptorId, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StudentEducationOrganizationResponsibilityAssociation](OldBeginDate, OldEducationOrganizationId, OldResponsibilityDescriptorId, OldResponsibilityDescriptorNamespace, OldResponsibilityDescriptorCodeValue, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.BeginDate, d.EducationOrganizationId, d.ResponsibilityDescriptorId, j2.Namespace, j2.CodeValue, d.StudentUSI, j3.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor j2 + ON d.ResponsibilityDescriptorId = j2.DescriptorId + INNER JOIN edfi.Student j3 + ON d.StudentUSI = j3.StudentUSI END GO ALTER TABLE [edfi].[StudentEducationOrganizationResponsibilityAssociation] ENABLE TRIGGER [edfi_StudentEducationOrganizationResponsibilityAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentGradebookEntry_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StudentGradebookEntry_TR_DeleteTracking] ON [edfi].[StudentGradebookEntry] AFTER DELETE AS BEGIN @@ -4364,34 +4622,20 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StudentGradebookEntry](BeginDate, DateAssigned, GradebookEntryTitle, LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, StudentUSI, Id, ChangeVersion) - SELECT BeginDate, DateAssigned, GradebookEntryTitle, LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StudentGradebookEntry](OldBeginDate, OldDateAssigned, OldGradebookEntryTitle, OldLocalCourseCode, OldSchoolId, OldSchoolYear, OldSectionIdentifier, OldSessionName, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.BeginDate, d.DateAssigned, d.GradebookEntryTitle, d.LocalCourseCode, d.SchoolId, d.SchoolYear, d.SectionIdentifier, d.SessionName, d.StudentUSI, j8.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Student j8 + ON d.StudentUSI = j8.StudentUSI END GO ALTER TABLE [edfi].[StudentGradebookEntry] ENABLE TRIGGER [edfi_StudentGradebookEntry_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_StudentHomelessProgramAssociation_TR_DeleteTracking] ON [edfi].[StudentHomelessProgramAssociation] AFTER DELETE AS -BEGIN - IF @@rowcount = 0 - RETURN - - SET NOCOUNT ON - - INSERT INTO [tracked_deletes_edfi].[StudentHomelessProgramAssociation](BeginDate, EducationOrganizationId, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, ChangeVersion) - SELECT d.BeginDate, d.EducationOrganizationId, d.ProgramEducationOrganizationId, d.ProgramName, d.ProgramTypeDescriptorId, d.StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) - FROM deleted d - INNER JOIN edfi.GeneralStudentProgramAssociation b ON d.BeginDate = b.BeginDate AND d.EducationOrganizationId = b.EducationOrganizationId AND d.ProgramEducationOrganizationId = b.ProgramEducationOrganizationId AND d.ProgramName = b.ProgramName AND d.ProgramTypeDescriptorId = b.ProgramTypeDescriptorId AND d.StudentUSI = b.StudentUSI -END -GO - -ALTER TABLE [edfi].[StudentHomelessProgramAssociation] ENABLE TRIGGER [edfi_StudentHomelessProgramAssociation_TR_DeleteTracking] +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentIdentificationSystemDescriptor_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_StudentIdentificationSystemDescriptor_TR_DeleteTracking] ON [edfi].[StudentIdentificationSystemDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 @@ -4399,8 +4643,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StudentIdentificationSystemDescriptor](StudentIdentificationSystemDescriptorId, Id, ChangeVersion) - SELECT d.StudentIdentificationSystemDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.StudentIdentificationSystemDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.StudentIdentificationSystemDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.StudentIdentificationSystemDescriptorId = b.DescriptorId END @@ -4408,7 +4652,8 @@ GO ALTER TABLE [edfi].[StudentIdentificationSystemDescriptor] ENABLE TRIGGER [edfi_StudentIdentificationSystemDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentInterventionAssociation_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StudentInterventionAssociation_TR_DeleteTracking] ON [edfi].[StudentInterventionAssociation] AFTER DELETE AS BEGIN @@ -4417,15 +4662,19 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StudentInterventionAssociation](EducationOrganizationId, InterventionIdentificationCode, StudentUSI, Id, ChangeVersion) - SELECT EducationOrganizationId, InterventionIdentificationCode, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StudentInterventionAssociation](OldEducationOrganizationId, OldInterventionIdentificationCode, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.EducationOrganizationId, d.InterventionIdentificationCode, d.StudentUSI, j2.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Student j2 + ON d.StudentUSI = j2.StudentUSI END GO ALTER TABLE [edfi].[StudentInterventionAssociation] ENABLE TRIGGER [edfi_StudentInterventionAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentInterventionAttendanceEvent_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StudentInterventionAttendanceEvent_TR_DeleteTracking] ON [edfi].[StudentInterventionAttendanceEvent] AFTER DELETE AS BEGIN @@ -4434,34 +4683,22 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StudentInterventionAttendanceEvent](AttendanceEventCategoryDescriptorId, EducationOrganizationId, EventDate, InterventionIdentificationCode, StudentUSI, Id, ChangeVersion) - SELECT AttendanceEventCategoryDescriptorId, EducationOrganizationId, EventDate, InterventionIdentificationCode, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StudentInterventionAttendanceEvent](OldAttendanceEventCategoryDescriptorId, OldAttendanceEventCategoryDescriptorNamespace, OldAttendanceEventCategoryDescriptorCodeValue, OldEducationOrganizationId, OldEventDate, OldInterventionIdentificationCode, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.AttendanceEventCategoryDescriptorId, j0.Namespace, j0.CodeValue, d.EducationOrganizationId, d.EventDate, d.InterventionIdentificationCode, d.StudentUSI, j4.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor j0 + ON d.AttendanceEventCategoryDescriptorId = j0.DescriptorId + INNER JOIN edfi.Student j4 + ON d.StudentUSI = j4.StudentUSI END GO ALTER TABLE [edfi].[StudentInterventionAttendanceEvent] ENABLE TRIGGER [edfi_StudentInterventionAttendanceEvent_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_StudentLanguageInstructionProgramAssociation_TR_DeleteTracking] ON [edfi].[StudentLanguageInstructionProgramAssociation] AFTER DELETE AS -BEGIN - IF @@rowcount = 0 - RETURN - - SET NOCOUNT ON - - INSERT INTO [tracked_deletes_edfi].[StudentLanguageInstructionProgramAssociation](BeginDate, EducationOrganizationId, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, ChangeVersion) - SELECT d.BeginDate, d.EducationOrganizationId, d.ProgramEducationOrganizationId, d.ProgramName, d.ProgramTypeDescriptorId, d.StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) - FROM deleted d - INNER JOIN edfi.GeneralStudentProgramAssociation b ON d.BeginDate = b.BeginDate AND d.EducationOrganizationId = b.EducationOrganizationId AND d.ProgramEducationOrganizationId = b.ProgramEducationOrganizationId AND d.ProgramName = b.ProgramName AND d.ProgramTypeDescriptorId = b.ProgramTypeDescriptorId AND d.StudentUSI = b.StudentUSI -END -GO - -ALTER TABLE [edfi].[StudentLanguageInstructionProgramAssociation] ENABLE TRIGGER [edfi_StudentLanguageInstructionProgramAssociation_TR_DeleteTracking] +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentLearningObjective_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_StudentLearningObjective_TR_DeleteTracking] ON [edfi].[StudentLearningObjective] AFTER DELETE AS BEGIN IF @@rowcount = 0 @@ -4469,52 +4706,22 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StudentLearningObjective](GradingPeriodDescriptorId, GradingPeriodSchoolId, GradingPeriodSchoolYear, GradingPeriodSequence, LearningObjectiveId, Namespace, StudentUSI, Id, ChangeVersion) - SELECT GradingPeriodDescriptorId, GradingPeriodSchoolId, GradingPeriodSchoolYear, GradingPeriodSequence, LearningObjectiveId, Namespace, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StudentLearningObjective](OldGradingPeriodDescriptorId, OldGradingPeriodDescriptorNamespace, OldGradingPeriodDescriptorCodeValue, OldGradingPeriodSchoolId, OldGradingPeriodSchoolYear, OldGradingPeriodSequence, OldLearningObjectiveId, OldNamespace, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.GradingPeriodDescriptorId, j0.Namespace, j0.CodeValue, d.GradingPeriodSchoolId, d.GradingPeriodSchoolYear, d.GradingPeriodSequence, d.LearningObjectiveId, d.Namespace, d.StudentUSI, j6.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor j0 + ON d.GradingPeriodDescriptorId = j0.DescriptorId + INNER JOIN edfi.Student j6 + ON d.StudentUSI = j6.StudentUSI END GO ALTER TABLE [edfi].[StudentLearningObjective] ENABLE TRIGGER [edfi_StudentLearningObjective_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_StudentMigrantEducationProgramAssociation_TR_DeleteTracking] ON [edfi].[StudentMigrantEducationProgramAssociation] AFTER DELETE AS -BEGIN - IF @@rowcount = 0 - RETURN - - SET NOCOUNT ON - - INSERT INTO [tracked_deletes_edfi].[StudentMigrantEducationProgramAssociation](BeginDate, EducationOrganizationId, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, ChangeVersion) - SELECT d.BeginDate, d.EducationOrganizationId, d.ProgramEducationOrganizationId, d.ProgramName, d.ProgramTypeDescriptorId, d.StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) - FROM deleted d - INNER JOIN edfi.GeneralStudentProgramAssociation b ON d.BeginDate = b.BeginDate AND d.EducationOrganizationId = b.EducationOrganizationId AND d.ProgramEducationOrganizationId = b.ProgramEducationOrganizationId AND d.ProgramName = b.ProgramName AND d.ProgramTypeDescriptorId = b.ProgramTypeDescriptorId AND d.StudentUSI = b.StudentUSI -END -GO - -ALTER TABLE [edfi].[StudentMigrantEducationProgramAssociation] ENABLE TRIGGER [edfi_StudentMigrantEducationProgramAssociation_TR_DeleteTracking] -GO - - -CREATE TRIGGER [edfi].[edfi_StudentNeglectedOrDelinquentProgramAssociation_TR_DeleteTracking] ON [edfi].[StudentNeglectedOrDelinquentProgramAssociation] AFTER DELETE AS -BEGIN - IF @@rowcount = 0 - RETURN - - SET NOCOUNT ON - - INSERT INTO [tracked_deletes_edfi].[StudentNeglectedOrDelinquentProgramAssociation](BeginDate, EducationOrganizationId, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, ChangeVersion) - SELECT d.BeginDate, d.EducationOrganizationId, d.ProgramEducationOrganizationId, d.ProgramName, d.ProgramTypeDescriptorId, d.StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) - FROM deleted d - INNER JOIN edfi.GeneralStudentProgramAssociation b ON d.BeginDate = b.BeginDate AND d.EducationOrganizationId = b.EducationOrganizationId AND d.ProgramEducationOrganizationId = b.ProgramEducationOrganizationId AND d.ProgramName = b.ProgramName AND d.ProgramTypeDescriptorId = b.ProgramTypeDescriptorId AND d.StudentUSI = b.StudentUSI -END -GO - -ALTER TABLE [edfi].[StudentNeglectedOrDelinquentProgramAssociation] ENABLE TRIGGER [edfi_StudentNeglectedOrDelinquentProgramAssociation_TR_DeleteTracking] +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentParentAssociation_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_StudentParentAssociation_TR_DeleteTracking] ON [edfi].[StudentParentAssociation] AFTER DELETE AS BEGIN IF @@rowcount = 0 @@ -4522,15 +4729,21 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StudentParentAssociation](ParentUSI, StudentUSI, Id, ChangeVersion) - SELECT ParentUSI, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StudentParentAssociation](OldParentUSI, OldParentUniqueId, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.ParentUSI, j0.ParentUniqueId, d.StudentUSI, j1.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Parent j0 + ON d.ParentUSI = j0.ParentUSI + INNER JOIN edfi.Student j1 + ON d.StudentUSI = j1.StudentUSI END GO ALTER TABLE [edfi].[StudentParentAssociation] ENABLE TRIGGER [edfi_StudentParentAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentParticipationCodeDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StudentParticipationCodeDescriptor_TR_DeleteTracking] ON [edfi].[StudentParticipationCodeDescriptor] AFTER DELETE AS BEGIN @@ -4539,8 +4752,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StudentParticipationCodeDescriptor](StudentParticipationCodeDescriptorId, Id, ChangeVersion) - SELECT d.StudentParticipationCodeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.StudentParticipationCodeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.StudentParticipationCodeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.StudentParticipationCodeDescriptorId = b.DescriptorId END @@ -4548,26 +4761,9 @@ GO ALTER TABLE [edfi].[StudentParticipationCodeDescriptor] ENABLE TRIGGER [edfi_StudentParticipationCodeDescriptor_TR_DeleteTracking] GO - - -CREATE TRIGGER [edfi].[edfi_StudentProgramAssociation_TR_DeleteTracking] ON [edfi].[StudentProgramAssociation] AFTER DELETE AS -BEGIN - IF @@rowcount = 0 - RETURN - - SET NOCOUNT ON - - INSERT INTO [tracked_deletes_edfi].[StudentProgramAssociation](BeginDate, EducationOrganizationId, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, ChangeVersion) - SELECT d.BeginDate, d.EducationOrganizationId, d.ProgramEducationOrganizationId, d.ProgramName, d.ProgramTypeDescriptorId, d.StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) - FROM deleted d - INNER JOIN edfi.GeneralStudentProgramAssociation b ON d.BeginDate = b.BeginDate AND d.EducationOrganizationId = b.EducationOrganizationId AND d.ProgramEducationOrganizationId = b.ProgramEducationOrganizationId AND d.ProgramName = b.ProgramName AND d.ProgramTypeDescriptorId = b.ProgramTypeDescriptorId AND d.StudentUSI = b.StudentUSI -END -GO - -ALTER TABLE [edfi].[StudentProgramAssociation] ENABLE TRIGGER [edfi_StudentProgramAssociation_TR_DeleteTracking] +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentProgramAttendanceEvent_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_StudentProgramAttendanceEvent_TR_DeleteTracking] ON [edfi].[StudentProgramAttendanceEvent] AFTER DELETE AS BEGIN IF @@rowcount = 0 @@ -4575,15 +4771,23 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StudentProgramAttendanceEvent](AttendanceEventCategoryDescriptorId, EducationOrganizationId, EventDate, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, ChangeVersion) - SELECT AttendanceEventCategoryDescriptorId, EducationOrganizationId, EventDate, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StudentProgramAttendanceEvent](OldAttendanceEventCategoryDescriptorId, OldAttendanceEventCategoryDescriptorNamespace, OldAttendanceEventCategoryDescriptorCodeValue, OldEducationOrganizationId, OldEventDate, OldProgramEducationOrganizationId, OldProgramName, OldProgramTypeDescriptorId, OldProgramTypeDescriptorNamespace, OldProgramTypeDescriptorCodeValue, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.AttendanceEventCategoryDescriptorId, j0.Namespace, j0.CodeValue, d.EducationOrganizationId, d.EventDate, d.ProgramEducationOrganizationId, d.ProgramName, d.ProgramTypeDescriptorId, j5.Namespace, j5.CodeValue, d.StudentUSI, j6.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor j0 + ON d.AttendanceEventCategoryDescriptorId = j0.DescriptorId + INNER JOIN edfi.Descriptor j5 + ON d.ProgramTypeDescriptorId = j5.DescriptorId + INNER JOIN edfi.Student j6 + ON d.StudentUSI = j6.StudentUSI END GO ALTER TABLE [edfi].[StudentProgramAttendanceEvent] ENABLE TRIGGER [edfi_StudentProgramAttendanceEvent_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentSchoolAssociation_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StudentSchoolAssociation_TR_DeleteTracking] ON [edfi].[StudentSchoolAssociation] AFTER DELETE AS BEGIN @@ -4592,15 +4796,19 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StudentSchoolAssociation](EntryDate, SchoolId, StudentUSI, Id, ChangeVersion) - SELECT EntryDate, SchoolId, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StudentSchoolAssociation](OldEntryDate, OldSchoolId, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.EntryDate, d.SchoolId, d.StudentUSI, j2.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Student j2 + ON d.StudentUSI = j2.StudentUSI END GO ALTER TABLE [edfi].[StudentSchoolAssociation] ENABLE TRIGGER [edfi_StudentSchoolAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentSchoolAttendanceEvent_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StudentSchoolAttendanceEvent_TR_DeleteTracking] ON [edfi].[StudentSchoolAttendanceEvent] AFTER DELETE AS BEGIN @@ -4609,34 +4817,22 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StudentSchoolAttendanceEvent](AttendanceEventCategoryDescriptorId, EventDate, SchoolId, SchoolYear, SessionName, StudentUSI, Id, ChangeVersion) - SELECT AttendanceEventCategoryDescriptorId, EventDate, SchoolId, SchoolYear, SessionName, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StudentSchoolAttendanceEvent](OldAttendanceEventCategoryDescriptorId, OldAttendanceEventCategoryDescriptorNamespace, OldAttendanceEventCategoryDescriptorCodeValue, OldEventDate, OldSchoolId, OldSchoolYear, OldSessionName, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.AttendanceEventCategoryDescriptorId, j0.Namespace, j0.CodeValue, d.EventDate, d.SchoolId, d.SchoolYear, d.SessionName, d.StudentUSI, j5.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor j0 + ON d.AttendanceEventCategoryDescriptorId = j0.DescriptorId + INNER JOIN edfi.Student j5 + ON d.StudentUSI = j5.StudentUSI END GO ALTER TABLE [edfi].[StudentSchoolAttendanceEvent] ENABLE TRIGGER [edfi_StudentSchoolAttendanceEvent_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_StudentSchoolFoodServiceProgramAssociation_TR_DeleteTracking] ON [edfi].[StudentSchoolFoodServiceProgramAssociation] AFTER DELETE AS -BEGIN - IF @@rowcount = 0 - RETURN - - SET NOCOUNT ON - - INSERT INTO [tracked_deletes_edfi].[StudentSchoolFoodServiceProgramAssociation](BeginDate, EducationOrganizationId, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, ChangeVersion) - SELECT d.BeginDate, d.EducationOrganizationId, d.ProgramEducationOrganizationId, d.ProgramName, d.ProgramTypeDescriptorId, d.StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) - FROM deleted d - INNER JOIN edfi.GeneralStudentProgramAssociation b ON d.BeginDate = b.BeginDate AND d.EducationOrganizationId = b.EducationOrganizationId AND d.ProgramEducationOrganizationId = b.ProgramEducationOrganizationId AND d.ProgramName = b.ProgramName AND d.ProgramTypeDescriptorId = b.ProgramTypeDescriptorId AND d.StudentUSI = b.StudentUSI -END -GO - -ALTER TABLE [edfi].[StudentSchoolFoodServiceProgramAssociation] ENABLE TRIGGER [edfi_StudentSchoolFoodServiceProgramAssociation_TR_DeleteTracking] +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentSectionAssociation_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_StudentSectionAssociation_TR_DeleteTracking] ON [edfi].[StudentSectionAssociation] AFTER DELETE AS BEGIN IF @@rowcount = 0 @@ -4644,15 +4840,19 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StudentSectionAssociation](BeginDate, LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, StudentUSI, Id, ChangeVersion) - SELECT BeginDate, LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StudentSectionAssociation](OldBeginDate, OldLocalCourseCode, OldSchoolId, OldSchoolYear, OldSectionIdentifier, OldSessionName, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.BeginDate, d.LocalCourseCode, d.SchoolId, d.SchoolYear, d.SectionIdentifier, d.SessionName, d.StudentUSI, j6.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Student j6 + ON d.StudentUSI = j6.StudentUSI END GO ALTER TABLE [edfi].[StudentSectionAssociation] ENABLE TRIGGER [edfi_StudentSectionAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_StudentSectionAttendanceEvent_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_StudentSectionAttendanceEvent_TR_DeleteTracking] ON [edfi].[StudentSectionAttendanceEvent] AFTER DELETE AS BEGIN @@ -4661,69 +4861,41 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StudentSectionAttendanceEvent](AttendanceEventCategoryDescriptorId, EventDate, LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, StudentUSI, Id, ChangeVersion) - SELECT AttendanceEventCategoryDescriptorId, EventDate, LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[StudentSectionAttendanceEvent](OldAttendanceEventCategoryDescriptorId, OldAttendanceEventCategoryDescriptorNamespace, OldAttendanceEventCategoryDescriptorCodeValue, OldEventDate, OldLocalCourseCode, OldSchoolId, OldSchoolYear, OldSectionIdentifier, OldSessionName, OldStudentUSI, OldStudentUniqueId, Id, Discriminator, ChangeVersion) + SELECT d.AttendanceEventCategoryDescriptorId, j0.Namespace, j0.CodeValue, d.EventDate, d.LocalCourseCode, d.SchoolId, d.SchoolYear, d.SectionIdentifier, d.SessionName, d.StudentUSI, j7.StudentUniqueId, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor j0 + ON d.AttendanceEventCategoryDescriptorId = j0.DescriptorId + INNER JOIN edfi.Student j7 + ON d.StudentUSI = j7.StudentUSI END GO ALTER TABLE [edfi].[StudentSectionAttendanceEvent] ENABLE TRIGGER [edfi_StudentSectionAttendanceEvent_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_StudentSpecialEducationProgramAssociation_TR_DeleteTracking] ON [edfi].[StudentSpecialEducationProgramAssociation] AFTER DELETE AS -BEGIN - IF @@rowcount = 0 - RETURN - - SET NOCOUNT ON - - INSERT INTO [tracked_deletes_edfi].[StudentSpecialEducationProgramAssociation](BeginDate, EducationOrganizationId, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, ChangeVersion) - SELECT d.BeginDate, d.EducationOrganizationId, d.ProgramEducationOrganizationId, d.ProgramName, d.ProgramTypeDescriptorId, d.StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) - FROM deleted d - INNER JOIN edfi.GeneralStudentProgramAssociation b ON d.BeginDate = b.BeginDate AND d.EducationOrganizationId = b.EducationOrganizationId AND d.ProgramEducationOrganizationId = b.ProgramEducationOrganizationId AND d.ProgramName = b.ProgramName AND d.ProgramTypeDescriptorId = b.ProgramTypeDescriptorId AND d.StudentUSI = b.StudentUSI -END -GO - -ALTER TABLE [edfi].[StudentSpecialEducationProgramAssociation] ENABLE TRIGGER [edfi_StudentSpecialEducationProgramAssociation_TR_DeleteTracking] +DROP TRIGGER IF EXISTS [edfi].[edfi_Survey_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_StudentTitleIPartAProgramAssociation_TR_DeleteTracking] ON [edfi].[StudentTitleIPartAProgramAssociation] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_Survey_TR_DeleteTracking] ON [edfi].[Survey] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[StudentTitleIPartAProgramAssociation](BeginDate, EducationOrganizationId, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, ChangeVersion) - SELECT d.BeginDate, d.EducationOrganizationId, d.ProgramEducationOrganizationId, d.ProgramName, d.ProgramTypeDescriptorId, d.StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Survey](OldNamespace, OldSurveyIdentifier, Id, Discriminator, ChangeVersion) + SELECT d.Namespace, d.SurveyIdentifier, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d - INNER JOIN edfi.GeneralStudentProgramAssociation b ON d.BeginDate = b.BeginDate AND d.EducationOrganizationId = b.EducationOrganizationId AND d.ProgramEducationOrganizationId = b.ProgramEducationOrganizationId AND d.ProgramName = b.ProgramName AND d.ProgramTypeDescriptorId = b.ProgramTypeDescriptorId AND d.StudentUSI = b.StudentUSI END GO -ALTER TABLE [edfi].[StudentTitleIPartAProgramAssociation] ENABLE TRIGGER [edfi_StudentTitleIPartAProgramAssociation_TR_DeleteTracking] -GO - - -CREATE TRIGGER [edfi].[edfi_Student_TR_DeleteTracking] ON [edfi].[Student] AFTER DELETE AS -BEGIN - IF @@rowcount = 0 - RETURN - - SET NOCOUNT ON - - INSERT INTO [tracked_deletes_edfi].[Student](StudentUSI, Id, ChangeVersion) - SELECT StudentUSI, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) - FROM deleted d -END +ALTER TABLE [edfi].[Survey] ENABLE TRIGGER [edfi_Survey_TR_DeleteTracking] GO -ALTER TABLE [edfi].[Student] ENABLE TRIGGER [edfi_Student_TR_DeleteTracking] +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveyCategoryDescriptor_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_SurveyCategoryDescriptor_TR_DeleteTracking] ON [edfi].[SurveyCategoryDescriptor] AFTER DELETE AS BEGIN IF @@rowcount = 0 @@ -4731,8 +4903,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SurveyCategoryDescriptor](SurveyCategoryDescriptorId, Id, ChangeVersion) - SELECT d.SurveyCategoryDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.SurveyCategoryDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.SurveyCategoryDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.SurveyCategoryDescriptorId = b.DescriptorId END @@ -4740,7 +4912,8 @@ GO ALTER TABLE [edfi].[SurveyCategoryDescriptor] ENABLE TRIGGER [edfi_SurveyCategoryDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveyCourseAssociation_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_SurveyCourseAssociation_TR_DeleteTracking] ON [edfi].[SurveyCourseAssociation] AFTER DELETE AS BEGIN @@ -4749,8 +4922,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SurveyCourseAssociation](CourseCode, EducationOrganizationId, Namespace, SurveyIdentifier, Id, ChangeVersion) - SELECT CourseCode, EducationOrganizationId, Namespace, SurveyIdentifier, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[SurveyCourseAssociation](OldCourseCode, OldEducationOrganizationId, OldNamespace, OldSurveyIdentifier, Id, Discriminator, ChangeVersion) + SELECT d.CourseCode, d.EducationOrganizationId, d.Namespace, d.SurveyIdentifier, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO @@ -4758,6 +4931,8 @@ GO ALTER TABLE [edfi].[SurveyCourseAssociation] ENABLE TRIGGER [edfi_SurveyCourseAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveyLevelDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_SurveyLevelDescriptor_TR_DeleteTracking] ON [edfi].[SurveyLevelDescriptor] AFTER DELETE AS BEGIN @@ -4766,8 +4941,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SurveyLevelDescriptor](SurveyLevelDescriptorId, Id, ChangeVersion) - SELECT d.SurveyLevelDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.SurveyLevelDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.SurveyLevelDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.SurveyLevelDescriptorId = b.DescriptorId END @@ -4775,7 +4950,8 @@ GO ALTER TABLE [edfi].[SurveyLevelDescriptor] ENABLE TRIGGER [edfi_SurveyLevelDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveyProgramAssociation_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_SurveyProgramAssociation_TR_DeleteTracking] ON [edfi].[SurveyProgramAssociation] AFTER DELETE AS BEGIN @@ -4784,33 +4960,20 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SurveyProgramAssociation](EducationOrganizationId, Namespace, ProgramName, ProgramTypeDescriptorId, SurveyIdentifier, Id, ChangeVersion) - SELECT EducationOrganizationId, Namespace, ProgramName, ProgramTypeDescriptorId, SurveyIdentifier, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[SurveyProgramAssociation](OldEducationOrganizationId, OldNamespace, OldProgramName, OldProgramTypeDescriptorId, OldProgramTypeDescriptorNamespace, OldProgramTypeDescriptorCodeValue, OldSurveyIdentifier, Id, Discriminator, ChangeVersion) + SELECT d.EducationOrganizationId, d.Namespace, d.ProgramName, d.ProgramTypeDescriptorId, j3.Namespace, j3.CodeValue, d.SurveyIdentifier, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Descriptor j3 + ON d.ProgramTypeDescriptorId = j3.DescriptorId END GO ALTER TABLE [edfi].[SurveyProgramAssociation] ENABLE TRIGGER [edfi_SurveyProgramAssociation_TR_DeleteTracking] GO - -CREATE TRIGGER [edfi].[edfi_SurveyQuestionResponse_TR_DeleteTracking] ON [edfi].[SurveyQuestionResponse] AFTER DELETE AS -BEGIN - IF @@rowcount = 0 - RETURN - - SET NOCOUNT ON - - INSERT INTO [tracked_deletes_edfi].[SurveyQuestionResponse](Namespace, QuestionCode, SurveyIdentifier, SurveyResponseIdentifier, Id, ChangeVersion) - SELECT Namespace, QuestionCode, SurveyIdentifier, SurveyResponseIdentifier, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) - FROM deleted d -END -GO - -ALTER TABLE [edfi].[SurveyQuestionResponse] ENABLE TRIGGER [edfi_SurveyQuestionResponse_TR_DeleteTracking] +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveyQuestion_TR_DeleteTracking] GO - CREATE TRIGGER [edfi].[edfi_SurveyQuestion_TR_DeleteTracking] ON [edfi].[SurveyQuestion] AFTER DELETE AS BEGIN IF @@rowcount = 0 @@ -4818,8 +4981,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SurveyQuestion](Namespace, QuestionCode, SurveyIdentifier, Id, ChangeVersion) - SELECT Namespace, QuestionCode, SurveyIdentifier, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[SurveyQuestion](OldNamespace, OldQuestionCode, OldSurveyIdentifier, Id, Discriminator, ChangeVersion) + SELECT d.Namespace, d.QuestionCode, d.SurveyIdentifier, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO @@ -4827,108 +4990,124 @@ GO ALTER TABLE [edfi].[SurveyQuestion] ENABLE TRIGGER [edfi_SurveyQuestion_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveyQuestionResponse_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_SurveyResponseEducationOrganizationTargetAssociation_TR_DeleteTracking] ON [edfi].[SurveyResponseEducationOrganizationTargetAssociation] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_SurveyQuestionResponse_TR_DeleteTracking] ON [edfi].[SurveyQuestionResponse] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SurveyResponseEducationOrganizationTargetAssociation](EducationOrganizationId, Namespace, SurveyIdentifier, SurveyResponseIdentifier, Id, ChangeVersion) - SELECT EducationOrganizationId, Namespace, SurveyIdentifier, SurveyResponseIdentifier, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[SurveyQuestionResponse](OldNamespace, OldQuestionCode, OldSurveyIdentifier, OldSurveyResponseIdentifier, Id, Discriminator, ChangeVersion) + SELECT d.Namespace, d.QuestionCode, d.SurveyIdentifier, d.SurveyResponseIdentifier, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO -ALTER TABLE [edfi].[SurveyResponseEducationOrganizationTargetAssociation] ENABLE TRIGGER [edfi_SurveyResponseEducationOrganizationTargetAssociation_TR_DeleteTracking] +ALTER TABLE [edfi].[SurveyQuestionResponse] ENABLE TRIGGER [edfi_SurveyQuestionResponse_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveyResponse_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_SurveyResponseStaffTargetAssociation_TR_DeleteTracking] ON [edfi].[SurveyResponseStaffTargetAssociation] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_SurveyResponse_TR_DeleteTracking] ON [edfi].[SurveyResponse] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SurveyResponseStaffTargetAssociation](Namespace, StaffUSI, SurveyIdentifier, SurveyResponseIdentifier, Id, ChangeVersion) - SELECT Namespace, StaffUSI, SurveyIdentifier, SurveyResponseIdentifier, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[SurveyResponse](OldNamespace, OldSurveyIdentifier, OldSurveyResponseIdentifier, Id, Discriminator, ChangeVersion) + SELECT d.Namespace, d.SurveyIdentifier, d.SurveyResponseIdentifier, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO -ALTER TABLE [edfi].[SurveyResponseStaffTargetAssociation] ENABLE TRIGGER [edfi_SurveyResponseStaffTargetAssociation_TR_DeleteTracking] +ALTER TABLE [edfi].[SurveyResponse] ENABLE TRIGGER [edfi_SurveyResponse_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveyResponseEducationOrganizationTargetAssociation_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_SurveyResponse_TR_DeleteTracking] ON [edfi].[SurveyResponse] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_SurveyResponseEducationOrganizationTargetAssociation_TR_DeleteTracking] ON [edfi].[SurveyResponseEducationOrganizationTargetAssociation] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SurveyResponse](Namespace, SurveyIdentifier, SurveyResponseIdentifier, Id, ChangeVersion) - SELECT Namespace, SurveyIdentifier, SurveyResponseIdentifier, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[SurveyResponseEducationOrganizationTargetAssociation](OldEducationOrganizationId, OldNamespace, OldSurveyIdentifier, OldSurveyResponseIdentifier, Id, Discriminator, ChangeVersion) + SELECT d.EducationOrganizationId, d.Namespace, d.SurveyIdentifier, d.SurveyResponseIdentifier, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO -ALTER TABLE [edfi].[SurveyResponse] ENABLE TRIGGER [edfi_SurveyResponse_TR_DeleteTracking] +ALTER TABLE [edfi].[SurveyResponseEducationOrganizationTargetAssociation] ENABLE TRIGGER [edfi_SurveyResponseEducationOrganizationTargetAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveyResponseStaffTargetAssociation_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_SurveySectionAssociation_TR_DeleteTracking] ON [edfi].[SurveySectionAssociation] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_SurveyResponseStaffTargetAssociation_TR_DeleteTracking] ON [edfi].[SurveyResponseStaffTargetAssociation] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SurveySectionAssociation](LocalCourseCode, Namespace, SchoolId, SchoolYear, SectionIdentifier, SessionName, SurveyIdentifier, Id, ChangeVersion) - SELECT LocalCourseCode, Namespace, SchoolId, SchoolYear, SectionIdentifier, SessionName, SurveyIdentifier, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[SurveyResponseStaffTargetAssociation](OldNamespace, OldStaffUSI, OldStaffUniqueId, OldSurveyIdentifier, OldSurveyResponseIdentifier, Id, Discriminator, ChangeVersion) + SELECT d.Namespace, d.StaffUSI, j1.StaffUniqueId, d.SurveyIdentifier, d.SurveyResponseIdentifier, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Staff j1 + ON d.StaffUSI = j1.StaffUSI END GO -ALTER TABLE [edfi].[SurveySectionAssociation] ENABLE TRIGGER [edfi_SurveySectionAssociation_TR_DeleteTracking] +ALTER TABLE [edfi].[SurveyResponseStaffTargetAssociation] ENABLE TRIGGER [edfi_SurveyResponseStaffTargetAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveySection_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_SurveySectionResponseEducationOrganizationTargetAssociation_TR_DeleteTracking] ON [edfi].[SurveySectionResponseEducationOrganizationTargetAssociation] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_SurveySection_TR_DeleteTracking] ON [edfi].[SurveySection] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SurveySectionResponseEducationOrganizationTargetAssociation](EducationOrganizationId, Namespace, SurveyIdentifier, SurveyResponseIdentifier, SurveySectionTitle, Id, ChangeVersion) - SELECT EducationOrganizationId, Namespace, SurveyIdentifier, SurveyResponseIdentifier, SurveySectionTitle, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[SurveySection](OldNamespace, OldSurveyIdentifier, OldSurveySectionTitle, Id, Discriminator, ChangeVersion) + SELECT d.Namespace, d.SurveyIdentifier, d.SurveySectionTitle, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO -ALTER TABLE [edfi].[SurveySectionResponseEducationOrganizationTargetAssociation] ENABLE TRIGGER [edfi_SurveySectionResponseEducationOrganizationTargetAssociation_TR_DeleteTracking] +ALTER TABLE [edfi].[SurveySection] ENABLE TRIGGER [edfi_SurveySection_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveySectionAssociation_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_SurveySectionResponseStaffTargetAssociation_TR_DeleteTracking] ON [edfi].[SurveySectionResponseStaffTargetAssociation] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_SurveySectionAssociation_TR_DeleteTracking] ON [edfi].[SurveySectionAssociation] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SurveySectionResponseStaffTargetAssociation](Namespace, StaffUSI, SurveyIdentifier, SurveyResponseIdentifier, SurveySectionTitle, Id, ChangeVersion) - SELECT Namespace, StaffUSI, SurveyIdentifier, SurveyResponseIdentifier, SurveySectionTitle, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[SurveySectionAssociation](OldLocalCourseCode, OldNamespace, OldSchoolId, OldSchoolYear, OldSectionIdentifier, OldSessionName, OldSurveyIdentifier, Id, Discriminator, ChangeVersion) + SELECT d.LocalCourseCode, d.Namespace, d.SchoolId, d.SchoolYear, d.SectionIdentifier, d.SessionName, d.SurveyIdentifier, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO -ALTER TABLE [edfi].[SurveySectionResponseStaffTargetAssociation] ENABLE TRIGGER [edfi_SurveySectionResponseStaffTargetAssociation_TR_DeleteTracking] +ALTER TABLE [edfi].[SurveySectionAssociation] ENABLE TRIGGER [edfi_SurveySectionAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveySectionResponse_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_SurveySectionResponse_TR_DeleteTracking] ON [edfi].[SurveySectionResponse] AFTER DELETE AS BEGIN @@ -4937,8 +5116,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SurveySectionResponse](Namespace, SurveyIdentifier, SurveyResponseIdentifier, SurveySectionTitle, Id, ChangeVersion) - SELECT Namespace, SurveyIdentifier, SurveyResponseIdentifier, SurveySectionTitle, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[SurveySectionResponse](OldNamespace, OldSurveyIdentifier, OldSurveyResponseIdentifier, OldSurveySectionTitle, Id, Discriminator, ChangeVersion) + SELECT d.Namespace, d.SurveyIdentifier, d.SurveyResponseIdentifier, d.SurveySectionTitle, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO @@ -4946,40 +5125,48 @@ GO ALTER TABLE [edfi].[SurveySectionResponse] ENABLE TRIGGER [edfi_SurveySectionResponse_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveySectionResponseEducationOrganizationTargetAssociation_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_SurveySection_TR_DeleteTracking] ON [edfi].[SurveySection] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_SurveySectionResponseEducationOrganizationTargetAssociation_TR_DeleteTracking] ON [edfi].[SurveySectionResponseEducationOrganizationTargetAssociation] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[SurveySection](Namespace, SurveyIdentifier, SurveySectionTitle, Id, ChangeVersion) - SELECT Namespace, SurveyIdentifier, SurveySectionTitle, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[SurveySectionResponseEducationOrganizationTargetAssociation](OldEducationOrganizationId, OldNamespace, OldSurveyIdentifier, OldSurveyResponseIdentifier, OldSurveySectionTitle, Id, Discriminator, ChangeVersion) + SELECT d.EducationOrganizationId, d.Namespace, d.SurveyIdentifier, d.SurveyResponseIdentifier, d.SurveySectionTitle, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d END GO -ALTER TABLE [edfi].[SurveySection] ENABLE TRIGGER [edfi_SurveySection_TR_DeleteTracking] +ALTER TABLE [edfi].[SurveySectionResponseEducationOrganizationTargetAssociation] ENABLE TRIGGER [edfi_SurveySectionResponseEducationOrganizationTargetAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_SurveySectionResponseStaffTargetAssociation_TR_DeleteTracking] +GO -CREATE TRIGGER [edfi].[edfi_Survey_TR_DeleteTracking] ON [edfi].[Survey] AFTER DELETE AS +CREATE TRIGGER [edfi].[edfi_SurveySectionResponseStaffTargetAssociation_TR_DeleteTracking] ON [edfi].[SurveySectionResponseStaffTargetAssociation] AFTER DELETE AS BEGIN IF @@rowcount = 0 RETURN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[Survey](Namespace, SurveyIdentifier, Id, ChangeVersion) - SELECT Namespace, SurveyIdentifier, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[SurveySectionResponseStaffTargetAssociation](OldNamespace, OldStaffUSI, OldStaffUniqueId, OldSurveyIdentifier, OldSurveyResponseIdentifier, OldSurveySectionTitle, Id, Discriminator, ChangeVersion) + SELECT d.Namespace, d.StaffUSI, j1.StaffUniqueId, d.SurveyIdentifier, d.SurveyResponseIdentifier, d.SurveySectionTitle, d.Id, d.Discriminator, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d + INNER JOIN edfi.Staff j1 + ON d.StaffUSI = j1.StaffUSI END GO -ALTER TABLE [edfi].[Survey] ENABLE TRIGGER [edfi_Survey_TR_DeleteTracking] +ALTER TABLE [edfi].[SurveySectionResponseStaffTargetAssociation] ENABLE TRIGGER [edfi_SurveySectionResponseStaffTargetAssociation_TR_DeleteTracking] GO +DROP TRIGGER IF EXISTS [edfi].[edfi_TeachingCredentialBasisDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_TeachingCredentialBasisDescriptor_TR_DeleteTracking] ON [edfi].[TeachingCredentialBasisDescriptor] AFTER DELETE AS BEGIN @@ -4988,8 +5175,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[TeachingCredentialBasisDescriptor](TeachingCredentialBasisDescriptorId, Id, ChangeVersion) - SELECT d.TeachingCredentialBasisDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.TeachingCredentialBasisDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.TeachingCredentialBasisDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.TeachingCredentialBasisDescriptorId = b.DescriptorId END @@ -4997,7 +5184,8 @@ GO ALTER TABLE [edfi].[TeachingCredentialBasisDescriptor] ENABLE TRIGGER [edfi_TeachingCredentialBasisDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_TeachingCredentialDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_TeachingCredentialDescriptor_TR_DeleteTracking] ON [edfi].[TeachingCredentialDescriptor] AFTER DELETE AS BEGIN @@ -5006,8 +5194,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[TeachingCredentialDescriptor](TeachingCredentialDescriptorId, Id, ChangeVersion) - SELECT d.TeachingCredentialDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.TeachingCredentialDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.TeachingCredentialDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.TeachingCredentialDescriptorId = b.DescriptorId END @@ -5015,7 +5203,8 @@ GO ALTER TABLE [edfi].[TeachingCredentialDescriptor] ENABLE TRIGGER [edfi_TeachingCredentialDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_TechnicalSkillsAssessmentDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_TechnicalSkillsAssessmentDescriptor_TR_DeleteTracking] ON [edfi].[TechnicalSkillsAssessmentDescriptor] AFTER DELETE AS BEGIN @@ -5024,8 +5213,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[TechnicalSkillsAssessmentDescriptor](TechnicalSkillsAssessmentDescriptorId, Id, ChangeVersion) - SELECT d.TechnicalSkillsAssessmentDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.TechnicalSkillsAssessmentDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.TechnicalSkillsAssessmentDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.TechnicalSkillsAssessmentDescriptorId = b.DescriptorId END @@ -5033,7 +5222,8 @@ GO ALTER TABLE [edfi].[TechnicalSkillsAssessmentDescriptor] ENABLE TRIGGER [edfi_TechnicalSkillsAssessmentDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_TelephoneNumberTypeDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_TelephoneNumberTypeDescriptor_TR_DeleteTracking] ON [edfi].[TelephoneNumberTypeDescriptor] AFTER DELETE AS BEGIN @@ -5042,8 +5232,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[TelephoneNumberTypeDescriptor](TelephoneNumberTypeDescriptorId, Id, ChangeVersion) - SELECT d.TelephoneNumberTypeDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.TelephoneNumberTypeDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.TelephoneNumberTypeDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.TelephoneNumberTypeDescriptorId = b.DescriptorId END @@ -5051,7 +5241,8 @@ GO ALTER TABLE [edfi].[TelephoneNumberTypeDescriptor] ENABLE TRIGGER [edfi_TelephoneNumberTypeDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_TermDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_TermDescriptor_TR_DeleteTracking] ON [edfi].[TermDescriptor] AFTER DELETE AS BEGIN @@ -5060,8 +5251,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[TermDescriptor](TermDescriptorId, Id, ChangeVersion) - SELECT d.TermDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.TermDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.TermDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.TermDescriptorId = b.DescriptorId END @@ -5069,7 +5260,8 @@ GO ALTER TABLE [edfi].[TermDescriptor] ENABLE TRIGGER [edfi_TermDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_TitleIPartAParticipantDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_TitleIPartAParticipantDescriptor_TR_DeleteTracking] ON [edfi].[TitleIPartAParticipantDescriptor] AFTER DELETE AS BEGIN @@ -5078,8 +5270,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[TitleIPartAParticipantDescriptor](TitleIPartAParticipantDescriptorId, Id, ChangeVersion) - SELECT d.TitleIPartAParticipantDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.TitleIPartAParticipantDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.TitleIPartAParticipantDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.TitleIPartAParticipantDescriptorId = b.DescriptorId END @@ -5087,7 +5279,8 @@ GO ALTER TABLE [edfi].[TitleIPartAParticipantDescriptor] ENABLE TRIGGER [edfi_TitleIPartAParticipantDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_TitleIPartAProgramServiceDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_TitleIPartAProgramServiceDescriptor_TR_DeleteTracking] ON [edfi].[TitleIPartAProgramServiceDescriptor] AFTER DELETE AS BEGIN @@ -5096,8 +5289,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[TitleIPartAProgramServiceDescriptor](TitleIPartAProgramServiceDescriptorId, Id, ChangeVersion) - SELECT d.TitleIPartAProgramServiceDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.TitleIPartAProgramServiceDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.TitleIPartAProgramServiceDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.TitleIPartAProgramServiceDescriptorId = b.DescriptorId END @@ -5105,7 +5298,8 @@ GO ALTER TABLE [edfi].[TitleIPartAProgramServiceDescriptor] ENABLE TRIGGER [edfi_TitleIPartAProgramServiceDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_TitleIPartASchoolDesignationDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_TitleIPartASchoolDesignationDescriptor_TR_DeleteTracking] ON [edfi].[TitleIPartASchoolDesignationDescriptor] AFTER DELETE AS BEGIN @@ -5114,8 +5308,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[TitleIPartASchoolDesignationDescriptor](TitleIPartASchoolDesignationDescriptorId, Id, ChangeVersion) - SELECT d.TitleIPartASchoolDesignationDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.TitleIPartASchoolDesignationDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.TitleIPartASchoolDesignationDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.TitleIPartASchoolDesignationDescriptorId = b.DescriptorId END @@ -5123,7 +5317,8 @@ GO ALTER TABLE [edfi].[TitleIPartASchoolDesignationDescriptor] ENABLE TRIGGER [edfi_TitleIPartASchoolDesignationDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_TribalAffiliationDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_TribalAffiliationDescriptor_TR_DeleteTracking] ON [edfi].[TribalAffiliationDescriptor] AFTER DELETE AS BEGIN @@ -5132,8 +5327,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[TribalAffiliationDescriptor](TribalAffiliationDescriptorId, Id, ChangeVersion) - SELECT d.TribalAffiliationDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.TribalAffiliationDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.TribalAffiliationDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.TribalAffiliationDescriptorId = b.DescriptorId END @@ -5141,7 +5336,8 @@ GO ALTER TABLE [edfi].[TribalAffiliationDescriptor] ENABLE TRIGGER [edfi_TribalAffiliationDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_VisaDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_VisaDescriptor_TR_DeleteTracking] ON [edfi].[VisaDescriptor] AFTER DELETE AS BEGIN @@ -5150,8 +5346,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[VisaDescriptor](VisaDescriptorId, Id, ChangeVersion) - SELECT d.VisaDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.VisaDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.VisaDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.VisaDescriptorId = b.DescriptorId END @@ -5159,7 +5355,8 @@ GO ALTER TABLE [edfi].[VisaDescriptor] ENABLE TRIGGER [edfi_VisaDescriptor_TR_DeleteTracking] GO - +DROP TRIGGER IF EXISTS [edfi].[edfi_WeaponDescriptor_TR_DeleteTracking] +GO CREATE TRIGGER [edfi].[edfi_WeaponDescriptor_TR_DeleteTracking] ON [edfi].[WeaponDescriptor] AFTER DELETE AS BEGIN @@ -5168,8 +5365,8 @@ BEGIN SET NOCOUNT ON - INSERT INTO [tracked_deletes_edfi].[WeaponDescriptor](WeaponDescriptorId, Id, ChangeVersion) - SELECT d.WeaponDescriptorId, Id, (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + INSERT INTO [tracked_changes_edfi].[Descriptor](OldDescriptorId, OldCodeValue, OldNamespace, Id, Discriminator, ChangeVersion) + SELECT d.WeaponDescriptorId, b.CodeValue, b.Namespace, b.Id, 'edfi.WeaponDescriptor', (NEXT VALUE FOR [changes].[ChangeVersionSequence]) FROM deleted d INNER JOIN edfi.Descriptor b ON d.WeaponDescriptorId = b.DescriptorId END @@ -5177,5 +5374,3 @@ GO ALTER TABLE [edfi].[WeaponDescriptor] ENABLE TRIGGER [edfi_WeaponDescriptor_TR_DeleteTracking] GO - - diff --git a/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/1010-CreateGetMaxChangeVersionFunction.sql b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/1010-CreateGetMaxChangeVersionFunction.sql index 41fa5bce16..4a43accc65 100644 --- a/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/1010-CreateGetMaxChangeVersionFunction.sql +++ b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/1010-CreateGetMaxChangeVersionFunction.sql @@ -3,12 +3,7 @@ -- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. -- See the LICENSE and NOTICES files in the project root for more information. -SET ANSI_NULLS ON -GO -SET QUOTED_IDENTIFIER ON -GO - -CREATE FUNCTION [changes].GetMaxChangeVersion() +CREATE OR ALTER FUNCTION [changes].GetMaxChangeVersion() RETURNS bigint AS BEGIN diff --git a/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/1020-AuthViewsIncludingDeletes.sql b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/1020-AuthViewsIncludingDeletes.sql new file mode 100644 index 0000000000..90bb91cf4d --- /dev/null +++ b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/1020-AuthViewsIncludingDeletes.sql @@ -0,0 +1,201 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +DROP VIEW IF EXISTS auth.LocalEducationAgencyIdToStudentUSIIncludingDeletes; +GO + +CREATE VIEW auth.LocalEducationAgencyIdToStudentUSIIncludingDeletes AS + SELECT sch.LocalEducationAgencyId, ssa.StudentUSI + FROM edfi.School sch + JOIN edfi.StudentSchoolAssociation ssa ON sch.SchoolId = ssa.SchoolId + + UNION + + SELECT sch.LocalEducationAgencyId, ssa_tc.OldStudentUSI as StudentUSI + FROM edfi.School sch + JOIN tracked_changes_edfi.StudentSchoolAssociation ssa_tc ON sch.SchoolId = ssa_tc.OldSchoolId; +GO + +DROP VIEW IF EXISTS auth.LocalEducationAgencyIdToStaffUSIIncludingDeletes; +GO + +CREATE VIEW auth.LocalEducationAgencyIdToStaffUSIIncludingDeletes AS + -- LEA employment + SELECT lea.LocalEducationAgencyId, emp.StaffUSI + FROM edfi.LocalEducationAgency lea + JOIN edfi.StaffEducationOrganizationEmploymentAssociation emp + ON lea.LocalEducationAgencyId = emp.EducationOrganizationId + + UNION + + -- LEA employment (deleted employment) + SELECT lea.LocalEducationAgencyId, emp_tc.OldStaffUSI as StaffUSI + FROM edfi.LocalEducationAgency lea + JOIN tracked_changes_edfi.StaffEducationOrganizationEmploymentAssociation emp_tc + ON lea.LocalEducationAgencyId = emp_tc.OldEducationOrganizationId + + UNION + + -- LEA-level organization department employment + SELECT lea.LocalEducationAgencyId, emp.StaffUSI + FROM edfi.LocalEducationAgency lea + JOIN edfi.OrganizationDepartment od + ON lea.LocalEducationAgencyId = od.ParentEducationOrganizationId + JOIN edfi.StaffEducationOrganizationEmploymentAssociation emp + ON od.OrganizationDepartmentId = emp.EducationOrganizationId + + UNION + + -- LEA-level organization department employment (deleted employment) + SELECT lea.LocalEducationAgencyId, emp_tc.OldStaffUSI as StaffUSI + FROM edfi.LocalEducationAgency lea + JOIN edfi.OrganizationDepartment od + ON lea.LocalEducationAgencyId = od.ParentEducationOrganizationId + JOIN tracked_changes_edfi.StaffEducationOrganizationEmploymentAssociation emp_tc + ON od.OrganizationDepartmentId = emp_tc.OldEducationOrganizationId + + UNION + + -- LEA assignment + SELECT lea.LocalEducationAgencyId, assgn.StaffUSI + FROM edfi.LocalEducationAgency lea + JOIN edfi.StaffEducationOrganizationAssignmentAssociation assgn + ON lea.LocalEducationAgencyId = assgn.EducationOrganizationId + + UNION + + -- LEA assignment (deleted assignment) + SELECT lea.LocalEducationAgencyId, assgn_tc.OldStaffUSI as StaffUSI + FROM edfi.LocalEducationAgency lea + JOIN tracked_changes_edfi.StaffEducationOrganizationAssignmentAssociation assgn_tc + ON lea.LocalEducationAgencyId = assgn_tc.OldEducationOrganizationId + + UNION + + -- LEA-level organization department assignment + SELECT lea.LocalEducationAgencyId, assgn.StaffUSI + FROM edfi.LocalEducationAgency lea + JOIN edfi.OrganizationDepartment od + ON lea.LocalEducationAgencyId = od.ParentEducationOrganizationId + JOIN edfi.StaffEducationOrganizationAssignmentAssociation assgn + ON od.OrganizationDepartmentId = assgn.EducationOrganizationId + + UNION + + -- LEA-level organization department assignment (deleted assignment) + SELECT lea.LocalEducationAgencyId, assgn_tc.OldStaffUSI as StaffUSI + FROM edfi.LocalEducationAgency lea + JOIN edfi.OrganizationDepartment od + ON lea.LocalEducationAgencyId = od.ParentEducationOrganizationId + JOIN tracked_changes_edfi.StaffEducationOrganizationAssignmentAssociation assgn_tc + ON od.OrganizationDepartmentId = assgn_tc.OldEducationOrganizationId + + UNION + + -- School employment + SELECT sch.LocalEducationAgencyId, emp.StaffUSI + FROM edfi.School sch + JOIN edfi.StaffEducationOrganizationEmploymentAssociation emp + ON sch.SchoolId = emp.EducationOrganizationId + + UNION + + -- School employment (deleted employment) + SELECT sch.LocalEducationAgencyId, emp_tc.OldStaffUSI as StaffUSI + FROM edfi.School sch + JOIN tracked_changes_edfi.StaffEducationOrganizationEmploymentAssociation emp_tc + ON sch.SchoolId = emp_tc.OldEducationOrganizationId + + UNION + + -- School-level organization department employment + SELECT sch.LocalEducationAgencyId, emp.StaffUSI + FROM edfi.School sch + JOIN edfi.OrganizationDepartment od + ON sch.SchoolId = od.ParentEducationOrganizationId + JOIN edfi.StaffEducationOrganizationEmploymentAssociation emp + ON od.OrganizationDepartmentId = emp.EducationOrganizationId + + UNION + + -- School-level organization department employment (deleted employment) + SELECT sch.LocalEducationAgencyId, emp_tc.OldStaffUSI as StaffUSI + FROM edfi.School sch + JOIN edfi.OrganizationDepartment od + ON sch.SchoolId = od.ParentEducationOrganizationId + JOIN tracked_changes_edfi.StaffEducationOrganizationEmploymentAssociation emp_tc + ON od.OrganizationDepartmentId = emp_tc.OldEducationOrganizationId + + UNION + + -- School assignment + SELECT sch.LocalEducationAgencyId, assgn.StaffUSI + FROM edfi.School sch + JOIN edfi.StaffEducationOrganizationAssignmentAssociation assgn + ON sch.SchoolId = assgn.EducationOrganizationId + + UNION + + -- School assignment (deleted assignment) + SELECT sch.LocalEducationAgencyId, assgn_tc.OldStaffUSI as StaffUSI + FROM edfi.School sch + JOIN tracked_changes_edfi.StaffEducationOrganizationAssignmentAssociation assgn_tc + ON sch.SchoolId = assgn_tc.OldEducationOrganizationId + + UNION + + -- School-level organization department assignment + SELECT sch.LocalEducationAgencyId, assgn.StaffUSI + FROM edfi.School sch + JOIN edfi.OrganizationDepartment od + ON sch.SchoolId = od.ParentEducationOrganizationId + JOIN edfi.StaffEducationOrganizationAssignmentAssociation assgn + ON od.OrganizationDepartmentId = assgn.EducationOrganizationId + + UNION + + SELECT sch.LocalEducationAgencyId, assgn_tc.OldStaffUSI as StaffUSI + FROM edfi.School sch + JOIN edfi.OrganizationDepartment od + ON sch.SchoolId = od.ParentEducationOrganizationId + JOIN tracked_changes_edfi.StaffEducationOrganizationAssignmentAssociation assgn_tc + ON od.OrganizationDepartmentId = assgn_tc.OldEducationOrganizationId; +GO + +DROP VIEW IF EXISTS auth.LocalEducationAgencyIdToParentUSIIncludingDeletes; +GO + +CREATE VIEW auth.LocalEducationAgencyIdToParentUSIIncludingDeletes AS + -- Intact StudentSchoolAssociation and intact StudentParentAssociation + SELECT sch.LocalEducationAgencyId, spa.ParentUSI + FROM edfi.School sch + JOIN edfi.StudentSchoolAssociation ssa ON sch.SchoolId = ssa.SchoolId + JOIN edfi.Student s ON ssa.StudentUSI = s.StudentUSI + JOIN edfi.StudentParentAssociation spa ON ssa.StudentUSI = spa.StudentUSI + + UNION + + -- Intact StudentSchoolAssociation and deleted StudentParentAssociation + SELECT sch.LocalEducationAgencyId, spa_tc.OldParentUSI as ParentUSI + FROM edfi.School sch + JOIN edfi.StudentSchoolAssociation ssa ON sch.SchoolId = ssa.SchoolId + JOIN tracked_changes_edfi.StudentParentAssociation spa_tc ON ssa.StudentUSI = spa_tc.OldStudentUSI + + UNION + + -- Deleted StudentSchoolAssociation and intact StudentParentAssociation + SELECT sch.LocalEducationAgencyId, spa.ParentUSI + FROM edfi.School sch + JOIN tracked_changes_edfi.StudentSchoolAssociation ssa_tc ON sch.SchoolId = ssa_tc.OldSchoolId + JOIN edfi.StudentParentAssociation spa ON ssa_tc.OldStudentUSI = spa.StudentUSI + + UNION + + -- Deleted StudentSchoolAssociation and StudentParentAssociation + SELECT sch.LocalEducationAgencyId, spa_tc.OldParentUSI as ParentUSI + FROM edfi.School sch + JOIN tracked_changes_edfi.StudentSchoolAssociation ssa_tc ON sch.SchoolId = ssa_tc.OldSchoolId + JOIN tracked_changes_edfi.StudentParentAssociation spa_tc ON ssa_tc.OldStudentUSI = spa_tc.OldStudentUSI; +GO diff --git a/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/1030-AuthViewsIncludingDeletes-SchoolClient.sql b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/1030-AuthViewsIncludingDeletes-SchoolClient.sql new file mode 100644 index 0000000000..d5324cf833 --- /dev/null +++ b/Application/EdFi.Ods.Standard/Artifacts/MsSql/Structure/Ods/Changes/1030-AuthViewsIncludingDeletes-SchoolClient.sql @@ -0,0 +1,116 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +CREATE OR ALTER VIEW [auth].[SchoolIdToStudentUSIIncludingDeletes] +AS + -- School to Student + SELECT ssa.SchoolId, ssa.StudentUSI + FROM edfi.StudentSchoolAssociation ssa + + UNION + + -- School to Student (deleted) + SELECT sch.SchoolId, ssa_tc.OldStudentUSI as StudentUSI + FROM edfi.School sch + INNER JOIN tracked_changes_edfi.StudentSchoolAssociation ssa_tc + ON sch.SchoolId = ssa_tc.OldSchoolId +GO + +CREATE OR ALTER VIEW [auth].[SchoolIdToStaffUSIIncludingDeletes] +AS + -- School to Staff (through School employment) + SELECT sch.SchoolId + ,seo_empl.StaffUSI + FROM edfi.School sch + INNER JOIN edfi.StaffEducationOrganizationEmploymentAssociation seo_empl + ON sch.SchoolId = seo_empl.EducationOrganizationId + + UNION + + -- School to Staff (through deleted School employment) + SELECT sch.SchoolId + ,seo_empl_tc.OldStaffUSI AS StaffUSI + FROM edfi.School sch + INNER JOIN tracked_changes_edfi.StaffEducationOrganizationEmploymentAssociation seo_empl_tc + ON sch.SchoolId = seo_empl_tc.OldEducationOrganizationId + + UNION + + -- School to Staff (through School-level department employment) + SELECT sch.SchoolId + ,seo_empl.StaffUSI + FROM edfi.School sch + INNER JOIN edfi.OrganizationDepartment od + ON sch.SchoolId = od.ParentEducationOrganizationId + INNER JOIN edfi.StaffEducationOrganizationEmploymentAssociation seo_empl + ON od.OrganizationDepartmentId = seo_empl.EducationOrganizationId + + UNION + + -- School to Staff (through deleted School-level department employment) + SELECT sch.SchoolId + ,seo_empl_tc.OldStaffUSI AS StaffUSI + FROM edfi.School sch + INNER JOIN edfi.OrganizationDepartment od + ON sch.SchoolId = od.ParentEducationOrganizationId + INNER JOIN tracked_changes_edfi.StaffEducationOrganizationEmploymentAssociation seo_empl_tc + ON od.OrganizationDepartmentId = seo_empl_tc.OldEducationOrganizationId + + UNION + + -- School to Staff (through School assignment) + SELECT sch.SchoolId + ,seo_assgn.StaffUSI + FROM edfi.School sch + INNER JOIN edfi.StaffEducationOrganizationAssignmentAssociation seo_assgn + ON sch.SchoolId = seo_assgn.EducationOrganizationId + + UNION + + -- School to Staff (through deleted School assignment) + SELECT sch.SchoolId + ,seo_assgn_tc.OldStaffUSI AS StaffUSI + FROM edfi.School sch + INNER JOIN tracked_changes_edfi.StaffEducationOrganizationAssignmentAssociation seo_assgn_tc + ON sch.SchoolId = seo_assgn_tc.OldEducationOrganizationId + + UNION + + -- School to Staff (through School-level department assignment) + SELECT sch.SchoolId + ,seo_assgn.StaffUSI + FROM edfi.School sch + INNER JOIN edfi.OrganizationDepartment od + ON sch.SchoolId = od.ParentEducationOrganizationId + INNER JOIN edfi.StaffEducationOrganizationAssignmentAssociation seo_assgn + ON od.OrganizationDepartmentId = seo_assgn.EducationOrganizationId + + UNION + + -- School to Staff (through deleted School-level department assignment) + SELECT sch.SchoolId + ,seo_assgn_tc.OldStaffUSI AS StaffUSI + FROM edfi.School sch + INNER JOIN edfi.OrganizationDepartment od + ON sch.SchoolId = od.ParentEducationOrganizationId + INNER JOIN tracked_changes_edfi.StaffEducationOrganizationAssignmentAssociation seo_assgn_tc + ON od.OrganizationDepartmentId = seo_assgn_tc.OldEducationOrganizationId; +GO + +CREATE VIEW [auth].[ParentUSIToSchoolIdIncludingDeletes] +AS + -- School to Parent USI + SELECT ssa.SchoolId, spa.ParentUSI + FROM edfi.StudentSchoolAssociation ssa + INNER JOIN edfi.StudentParentAssociation spa + ON ssa.StudentUSI = spa.StudentUSI + + UNION + + SELECT ssa.SchoolId, spa_tc.OldParentUSI AS ParentUSI + FROM edfi.StudentSchoolAssociation ssa + INNER JOIN tracked_changes_edfi.StudentParentAssociation spa_tc + ON ssa.StudentUSI = spa_tc.OldStudentUSI +GO diff --git a/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0030-AddColumnChangeVersionForTables.sql b/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0030-AddColumnChangeVersionForTables.sql index 9520ffda19..52a5173a23 100644 --- a/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0030-AddColumnChangeVersionForTables.sql +++ b/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0030-AddColumnChangeVersionForTables.sql @@ -3,300 +3,502 @@ -- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. -- See the LICENSE and NOTICES files in the project root for more information. -ALTER TABLE edfi.AcademicWeek -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.Account -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.AccountCode -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.AccountabilityRating -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.Actual -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.Assessment -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.AssessmentItem -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.AssessmentScoreRangeLearningStandard -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.BellSchedule -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.Budget -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.Calendar -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.CalendarDate -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.ClassPeriod -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.Cohort -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.CommunityProviderLicense -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.CompetencyObjective -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.ContractedStaff -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.Course -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.CourseOffering -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.CourseTranscript -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.Credential -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.Descriptor -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.DisciplineAction -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.DisciplineIncident -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.EducationContent -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.EducationOrganization -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.EducationOrganizationInterventionPrescriptionAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.EducationOrganizationNetworkAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.EducationOrganizationPeerAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.FeederSchoolAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.GeneralStudentProgramAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.Grade -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.GradebookEntry -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.GradingPeriod -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.GraduationPlan -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.Intervention -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.InterventionPrescription -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.InterventionStudy -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.LearningObjective -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.LearningStandard -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.LearningStandardEquivalenceAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.Location -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.ObjectiveAssessment -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.OpenStaffPosition -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.Parent -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.Payroll -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.Person -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.PostSecondaryEvent -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.Program -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.ReportCard -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.RestraintEvent -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.SchoolYearType -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.Section -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.SectionAttendanceTakenEvent -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.Session -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.Staff -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StaffAbsenceEvent -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StaffCohortAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StaffDisciplineIncidentAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StaffEducationOrganizationAssignmentAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StaffEducationOrganizationContactAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StaffEducationOrganizationEmploymentAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StaffLeave -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StaffProgramAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StaffSchoolAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StaffSectionAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.Student -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StudentAcademicRecord -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StudentAssessment -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StudentCohortAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StudentCompetencyObjective -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StudentDisciplineIncidentAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StudentDisciplineIncidentBehaviorAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StudentDisciplineIncidentNonOffenderAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StudentEducationOrganizationAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StudentEducationOrganizationResponsibilityAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StudentGradebookEntry -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StudentInterventionAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StudentInterventionAttendanceEvent -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StudentLearningObjective -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StudentParentAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StudentProgramAttendanceEvent -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StudentSchoolAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StudentSchoolAttendanceEvent -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StudentSectionAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.StudentSectionAttendanceEvent -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.Survey -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.SurveyCourseAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.SurveyProgramAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.SurveyQuestion -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.SurveyQuestionResponse -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.SurveyResponse -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.SurveyResponseEducationOrganizationTargetAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.SurveyResponseStaffTargetAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.SurveySection -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.SurveySectionAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.SurveySectionResponse -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.SurveySectionResponseEducationOrganizationTargetAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - -ALTER TABLE edfi.SurveySectionResponseStaffTargetAssociation -ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; - +DO $$ +BEGIN +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='academicweek' AND column_name='changeversion') THEN + ALTER TABLE edfi.academicweek + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='account' AND column_name='changeversion') THEN + ALTER TABLE edfi.account + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='accountabilityrating' AND column_name='changeversion') THEN + ALTER TABLE edfi.accountabilityrating + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='accountcode' AND column_name='changeversion') THEN + ALTER TABLE edfi.accountcode + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='actual' AND column_name='changeversion') THEN + ALTER TABLE edfi.actual + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='assessment' AND column_name='changeversion') THEN + ALTER TABLE edfi.assessment + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='assessmentitem' AND column_name='changeversion') THEN + ALTER TABLE edfi.assessmentitem + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='assessmentscorerangelearningstandard' AND column_name='changeversion') THEN + ALTER TABLE edfi.assessmentscorerangelearningstandard + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='bellschedule' AND column_name='changeversion') THEN + ALTER TABLE edfi.bellschedule + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='budget' AND column_name='changeversion') THEN + ALTER TABLE edfi.budget + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='calendar' AND column_name='changeversion') THEN + ALTER TABLE edfi.calendar + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='calendardate' AND column_name='changeversion') THEN + ALTER TABLE edfi.calendardate + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='classperiod' AND column_name='changeversion') THEN + ALTER TABLE edfi.classperiod + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='cohort' AND column_name='changeversion') THEN + ALTER TABLE edfi.cohort + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='communityproviderlicense' AND column_name='changeversion') THEN + ALTER TABLE edfi.communityproviderlicense + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='competencyobjective' AND column_name='changeversion') THEN + ALTER TABLE edfi.competencyobjective + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='contractedstaff' AND column_name='changeversion') THEN + ALTER TABLE edfi.contractedstaff + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='course' AND column_name='changeversion') THEN + ALTER TABLE edfi.course + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='courseoffering' AND column_name='changeversion') THEN + ALTER TABLE edfi.courseoffering + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='coursetranscript' AND column_name='changeversion') THEN + ALTER TABLE edfi.coursetranscript + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='credential' AND column_name='changeversion') THEN + ALTER TABLE edfi.credential + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='descriptor' AND column_name='changeversion') THEN + ALTER TABLE edfi.descriptor + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='disciplineaction' AND column_name='changeversion') THEN + ALTER TABLE edfi.disciplineaction + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='disciplineincident' AND column_name='changeversion') THEN + ALTER TABLE edfi.disciplineincident + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='educationcontent' AND column_name='changeversion') THEN + ALTER TABLE edfi.educationcontent + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='educationorganization' AND column_name='changeversion') THEN + ALTER TABLE edfi.educationorganization + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='educationorganizationinterventionprescriptionassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.educationorganizationinterventionprescriptionassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='educationorganizationnetworkassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.educationorganizationnetworkassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='educationorganizationpeerassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.educationorganizationpeerassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='feederschoolassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.feederschoolassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='generalstudentprogramassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.generalstudentprogramassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='grade' AND column_name='changeversion') THEN + ALTER TABLE edfi.grade + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='gradebookentry' AND column_name='changeversion') THEN + ALTER TABLE edfi.gradebookentry + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='gradingperiod' AND column_name='changeversion') THEN + ALTER TABLE edfi.gradingperiod + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='graduationplan' AND column_name='changeversion') THEN + ALTER TABLE edfi.graduationplan + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='intervention' AND column_name='changeversion') THEN + ALTER TABLE edfi.intervention + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='interventionprescription' AND column_name='changeversion') THEN + ALTER TABLE edfi.interventionprescription + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='interventionstudy' AND column_name='changeversion') THEN + ALTER TABLE edfi.interventionstudy + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='learningobjective' AND column_name='changeversion') THEN + ALTER TABLE edfi.learningobjective + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='learningstandard' AND column_name='changeversion') THEN + ALTER TABLE edfi.learningstandard + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='learningstandardequivalenceassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.learningstandardequivalenceassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='location' AND column_name='changeversion') THEN + ALTER TABLE edfi.location + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='objectiveassessment' AND column_name='changeversion') THEN + ALTER TABLE edfi.objectiveassessment + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='openstaffposition' AND column_name='changeversion') THEN + ALTER TABLE edfi.openstaffposition + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='parent' AND column_name='changeversion') THEN + ALTER TABLE edfi.parent + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='payroll' AND column_name='changeversion') THEN + ALTER TABLE edfi.payroll + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='person' AND column_name='changeversion') THEN + ALTER TABLE edfi.person + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='postsecondaryevent' AND column_name='changeversion') THEN + ALTER TABLE edfi.postsecondaryevent + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='program' AND column_name='changeversion') THEN + ALTER TABLE edfi.program + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='reportcard' AND column_name='changeversion') THEN + ALTER TABLE edfi.reportcard + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='restraintevent' AND column_name='changeversion') THEN + ALTER TABLE edfi.restraintevent + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='schoolyeartype' AND column_name='changeversion') THEN + ALTER TABLE edfi.schoolyeartype + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='section' AND column_name='changeversion') THEN + ALTER TABLE edfi.section + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='sectionattendancetakenevent' AND column_name='changeversion') THEN + ALTER TABLE edfi.sectionattendancetakenevent + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='session' AND column_name='changeversion') THEN + ALTER TABLE edfi.session + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='staff' AND column_name='changeversion') THEN + ALTER TABLE edfi.staff + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='staffabsenceevent' AND column_name='changeversion') THEN + ALTER TABLE edfi.staffabsenceevent + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='staffcohortassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.staffcohortassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='staffdisciplineincidentassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.staffdisciplineincidentassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='staffeducationorganizationassignmentassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.staffeducationorganizationassignmentassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='staffeducationorganizationcontactassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.staffeducationorganizationcontactassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='staffeducationorganizationemploymentassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.staffeducationorganizationemploymentassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='staffleave' AND column_name='changeversion') THEN + ALTER TABLE edfi.staffleave + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='staffprogramassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.staffprogramassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='staffschoolassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.staffschoolassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='staffsectionassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.staffsectionassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='student' AND column_name='changeversion') THEN + ALTER TABLE edfi.student + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='studentacademicrecord' AND column_name='changeversion') THEN + ALTER TABLE edfi.studentacademicrecord + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='studentassessment' AND column_name='changeversion') THEN + ALTER TABLE edfi.studentassessment + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='studentcohortassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.studentcohortassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='studentcompetencyobjective' AND column_name='changeversion') THEN + ALTER TABLE edfi.studentcompetencyobjective + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='studentdisciplineincidentassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.studentdisciplineincidentassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='studentdisciplineincidentbehaviorassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.studentdisciplineincidentbehaviorassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='studentdisciplineincidentnonoffenderassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.studentdisciplineincidentnonoffenderassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='studenteducationorganizationassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.studenteducationorganizationassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='studenteducationorganizationresponsibilityassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.studenteducationorganizationresponsibilityassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='studentgradebookentry' AND column_name='changeversion') THEN + ALTER TABLE edfi.studentgradebookentry + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='studentinterventionassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.studentinterventionassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='studentinterventionattendanceevent' AND column_name='changeversion') THEN + ALTER TABLE edfi.studentinterventionattendanceevent + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='studentlearningobjective' AND column_name='changeversion') THEN + ALTER TABLE edfi.studentlearningobjective + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='studentparentassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.studentparentassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='studentprogramattendanceevent' AND column_name='changeversion') THEN + ALTER TABLE edfi.studentprogramattendanceevent + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='studentschoolassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.studentschoolassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='studentschoolattendanceevent' AND column_name='changeversion') THEN + ALTER TABLE edfi.studentschoolattendanceevent + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='studentsectionassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.studentsectionassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='studentsectionattendanceevent' AND column_name='changeversion') THEN + ALTER TABLE edfi.studentsectionattendanceevent + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='survey' AND column_name='changeversion') THEN + ALTER TABLE edfi.survey + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='surveycourseassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.surveycourseassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='surveyprogramassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.surveyprogramassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='surveyquestion' AND column_name='changeversion') THEN + ALTER TABLE edfi.surveyquestion + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='surveyquestionresponse' AND column_name='changeversion') THEN + ALTER TABLE edfi.surveyquestionresponse + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='surveyresponse' AND column_name='changeversion') THEN + ALTER TABLE edfi.surveyresponse + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='surveyresponseeducationorganizationtargetassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.surveyresponseeducationorganizationtargetassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='surveyresponsestafftargetassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.surveyresponsestafftargetassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='surveysection' AND column_name='changeversion') THEN + ALTER TABLE edfi.surveysection + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='surveysectionassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.surveysectionassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='surveysectionresponse' AND column_name='changeversion') THEN + ALTER TABLE edfi.surveysectionresponse + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='surveysectionresponseeducationorganizationtargetassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.surveysectionresponseeducationorganizationtargetassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='edfi' AND table_name='surveysectionresponsestafftargetassociation' AND column_name='changeversion') THEN + ALTER TABLE edfi.surveysectionresponsestafftargetassociation + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + +END +$$; \ No newline at end of file diff --git a/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0040-CreateTriggerUpdateChangeVersionGenerator.sql b/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0040-CreateTriggerUpdateChangeVersionGenerator.sql deleted file mode 100644 index 16e52b62f2..0000000000 --- a/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0040-CreateTriggerUpdateChangeVersionGenerator.sql +++ /dev/null @@ -1,297 +0,0 @@ -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.AcademicWeek - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.Account - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.AccountCode - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.AccountabilityRating - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.Actual - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.Assessment - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.AssessmentItem - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.AssessmentScoreRangeLearningStandard - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.BellSchedule - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.Budget - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.Calendar - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.CalendarDate - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.ClassPeriod - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.Cohort - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.CommunityProviderLicense - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.CompetencyObjective - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.ContractedStaff - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.Course - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.CourseOffering - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.CourseTranscript - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.Credential - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.Descriptor - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.DisciplineAction - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.DisciplineIncident - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.EducationContent - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.EducationOrganization - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.EducationOrganizationInterventionPrescriptionAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.EducationOrganizationNetworkAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.EducationOrganizationPeerAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.FeederSchoolAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.GeneralStudentProgramAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.Grade - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.GradebookEntry - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.GradingPeriod - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.GraduationPlan - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.Intervention - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.InterventionPrescription - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.InterventionStudy - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.LearningObjective - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.LearningStandard - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.LearningStandardEquivalenceAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.Location - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.ObjectiveAssessment - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.OpenStaffPosition - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.Parent - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.Payroll - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.Person - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.PostSecondaryEvent - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.Program - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.ReportCard - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.RestraintEvent - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.SchoolYearType - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.Section - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.SectionAttendanceTakenEvent - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.Session - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.Staff - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StaffAbsenceEvent - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StaffCohortAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StaffDisciplineIncidentAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StaffEducationOrganizationAssignmentAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StaffEducationOrganizationContactAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StaffEducationOrganizationEmploymentAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StaffLeave - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StaffProgramAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StaffSchoolAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StaffSectionAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.Student - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StudentAcademicRecord - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StudentAssessment - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StudentCohortAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StudentCompetencyObjective - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StudentDisciplineIncidentAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StudentDisciplineIncidentBehaviorAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StudentDisciplineIncidentNonOffenderAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StudentEducationOrganizationAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StudentEducationOrganizationResponsibilityAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StudentGradebookEntry - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StudentInterventionAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StudentInterventionAttendanceEvent - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StudentLearningObjective - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StudentParentAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StudentProgramAttendanceEvent - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StudentSchoolAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StudentSchoolAttendanceEvent - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StudentSectionAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.StudentSectionAttendanceEvent - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.Survey - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.SurveyCourseAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.SurveyProgramAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.SurveyQuestion - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.SurveyQuestionResponse - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.SurveyResponse - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.SurveyResponseEducationOrganizationTargetAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.SurveyResponseStaffTargetAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.SurveySection - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.SurveySectionAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.SurveySectionResponse - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.SurveySectionResponseEducationOrganizationTargetAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - -CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.SurveySectionResponseStaffTargetAssociation - FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); - diff --git a/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0050-CreateTrackedDeleteTables.sql b/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0050-CreateTrackedDeleteTables.sql deleted file mode 100644 index 1e4db213a8..0000000000 --- a/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0050-CreateTrackedDeleteTables.sql +++ /dev/null @@ -1,2655 +0,0 @@ --- SPDX-License-Identifier: Apache-2.0 --- Licensed to the Ed-Fi Alliance under one or more agreements. --- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. --- See the LICENSE and NOTICES files in the project root for more information. - -CREATE TABLE tracked_deletes_edfi.AbsenceEventCategoryDescriptor -( - AbsenceEventCategoryDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AbsenceEventCategoryDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.AcademicHonorCategoryDescriptor -( - AcademicHonorCategoryDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AcademicHonorCategoryDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.AcademicSubjectDescriptor -( - AcademicSubjectDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AcademicSubjectDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.AcademicWeek -( - SchoolId INT NOT NULL, - WeekIdentifier VARCHAR(80) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AcademicWeek_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.AccommodationDescriptor -( - AccommodationDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AccommodationDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.Account -( - AccountIdentifier VARCHAR(50) NOT NULL, - EducationOrganizationId INT NOT NULL, - FiscalYear INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT Account_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.AccountClassificationDescriptor -( - AccountClassificationDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AccountClassificationDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.AccountCode -( - AccountClassificationDescriptorId INT NOT NULL, - AccountCodeNumber VARCHAR(50) NOT NULL, - EducationOrganizationId INT NOT NULL, - FiscalYear INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AccountCode_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.AccountabilityRating -( - EducationOrganizationId INT NOT NULL, - RatingTitle VARCHAR(60) NOT NULL, - SchoolYear SMALLINT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AccountabilityRating_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.AchievementCategoryDescriptor -( - AchievementCategoryDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AchievementCategoryDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.Actual -( - AccountIdentifier VARCHAR(50) NOT NULL, - AsOfDate DATE NOT NULL, - EducationOrganizationId INT NOT NULL, - FiscalYear INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT Actual_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.AdditionalCreditTypeDescriptor -( - AdditionalCreditTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AdditionalCreditTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.AddressTypeDescriptor -( - AddressTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AddressTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.AdministrationEnvironmentDescriptor -( - AdministrationEnvironmentDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AdministrationEnvironmentDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.AdministrativeFundingControlDescriptor -( - AdministrativeFundingControlDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AdministrativeFundingControlDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.AncestryEthnicOriginDescriptor -( - AncestryEthnicOriginDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AncestryEthnicOriginDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.Assessment -( - AssessmentIdentifier VARCHAR(60) NOT NULL, - Namespace VARCHAR(255) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT Assessment_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.AssessmentCategoryDescriptor -( - AssessmentCategoryDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AssessmentCategoryDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.AssessmentIdentificationSystemDescriptor -( - AssessmentIdentificationSystemDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AssessmentIdentificationSystemDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.AssessmentItem -( - AssessmentIdentifier VARCHAR(60) NOT NULL, - IdentificationCode VARCHAR(60) NOT NULL, - Namespace VARCHAR(255) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AssessmentItem_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.AssessmentItemCategoryDescriptor -( - AssessmentItemCategoryDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AssessmentItemCategoryDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.AssessmentItemResultDescriptor -( - AssessmentItemResultDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AssessmentItemResultDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.AssessmentPeriodDescriptor -( - AssessmentPeriodDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AssessmentPeriodDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.AssessmentReportingMethodDescriptor -( - AssessmentReportingMethodDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AssessmentReportingMethodDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.AssessmentScoreRangeLearningStandard -( - AssessmentIdentifier VARCHAR(60) NOT NULL, - Namespace VARCHAR(255) NOT NULL, - ScoreRangeId VARCHAR(60) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AssessmentScoreRangeLearningStandard_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.AttemptStatusDescriptor -( - AttemptStatusDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AttemptStatusDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.AttendanceEventCategoryDescriptor -( - AttendanceEventCategoryDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT AttendanceEventCategoryDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.BehaviorDescriptor -( - BehaviorDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT BehaviorDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.BellSchedule -( - BellScheduleName VARCHAR(60) NOT NULL, - SchoolId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT BellSchedule_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.Budget -( - AccountIdentifier VARCHAR(50) NOT NULL, - AsOfDate DATE NOT NULL, - EducationOrganizationId INT NOT NULL, - FiscalYear INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT Budget_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CTEProgramServiceDescriptor -( - CTEProgramServiceDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CTEProgramServiceDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.Calendar -( - CalendarCode VARCHAR(60) NOT NULL, - SchoolId INT NOT NULL, - SchoolYear SMALLINT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT Calendar_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CalendarDate -( - CalendarCode VARCHAR(60) NOT NULL, - Date DATE NOT NULL, - SchoolId INT NOT NULL, - SchoolYear SMALLINT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CalendarDate_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CalendarEventDescriptor -( - CalendarEventDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CalendarEventDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CalendarTypeDescriptor -( - CalendarTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CalendarTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CareerPathwayDescriptor -( - CareerPathwayDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CareerPathwayDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CharterApprovalAgencyTypeDescriptor -( - CharterApprovalAgencyTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CharterApprovalAgencyTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CharterStatusDescriptor -( - CharterStatusDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CharterStatusDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CitizenshipStatusDescriptor -( - CitizenshipStatusDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CitizenshipStatusDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ClassPeriod -( - ClassPeriodName VARCHAR(60) NOT NULL, - SchoolId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ClassPeriod_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ClassroomPositionDescriptor -( - ClassroomPositionDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ClassroomPositionDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.Cohort -( - CohortIdentifier VARCHAR(20) NOT NULL, - EducationOrganizationId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT Cohort_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CohortScopeDescriptor -( - CohortScopeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CohortScopeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CohortTypeDescriptor -( - CohortTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CohortTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CohortYearTypeDescriptor -( - CohortYearTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CohortYearTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CommunityOrganization -( - CommunityOrganizationId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CommunityOrganization_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CommunityProvider -( - CommunityProviderId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CommunityProvider_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CommunityProviderLicense -( - CommunityProviderId INT NOT NULL, - LicenseIdentifier VARCHAR(20) NOT NULL, - LicensingOrganization VARCHAR(75) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CommunityProviderLicense_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CompetencyLevelDescriptor -( - CompetencyLevelDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CompetencyLevelDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CompetencyObjective -( - EducationOrganizationId INT NOT NULL, - Objective VARCHAR(60) NOT NULL, - ObjectiveGradeLevelDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CompetencyObjective_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ContactTypeDescriptor -( - ContactTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ContactTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ContentClassDescriptor -( - ContentClassDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ContentClassDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ContinuationOfServicesReasonDescriptor -( - ContinuationOfServicesReasonDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ContinuationOfServicesReasonDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ContractedStaff -( - AccountIdentifier VARCHAR(50) NOT NULL, - AsOfDate DATE NOT NULL, - EducationOrganizationId INT NOT NULL, - FiscalYear INT NOT NULL, - StaffUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ContractedStaff_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CostRateDescriptor -( - CostRateDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CostRateDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CountryDescriptor -( - CountryDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CountryDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.Course -( - CourseCode VARCHAR(60) NOT NULL, - EducationOrganizationId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT Course_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CourseAttemptResultDescriptor -( - CourseAttemptResultDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CourseAttemptResultDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CourseDefinedByDescriptor -( - CourseDefinedByDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CourseDefinedByDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CourseGPAApplicabilityDescriptor -( - CourseGPAApplicabilityDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CourseGPAApplicabilityDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CourseIdentificationSystemDescriptor -( - CourseIdentificationSystemDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CourseIdentificationSystemDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CourseLevelCharacteristicDescriptor -( - CourseLevelCharacteristicDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CourseLevelCharacteristicDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CourseOffering -( - LocalCourseCode VARCHAR(60) NOT NULL, - SchoolId INT NOT NULL, - SchoolYear SMALLINT NOT NULL, - SessionName VARCHAR(60) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CourseOffering_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CourseRepeatCodeDescriptor -( - CourseRepeatCodeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CourseRepeatCodeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CourseTranscript -( - CourseAttemptResultDescriptorId INT NOT NULL, - CourseCode VARCHAR(60) NOT NULL, - CourseEducationOrganizationId INT NOT NULL, - EducationOrganizationId INT NOT NULL, - SchoolYear SMALLINT NOT NULL, - StudentUSI INT NOT NULL, - TermDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CourseTranscript_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.Credential -( - CredentialIdentifier VARCHAR(60) NOT NULL, - StateOfIssueStateAbbreviationDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT Credential_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CredentialFieldDescriptor -( - CredentialFieldDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CredentialFieldDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CredentialTypeDescriptor -( - CredentialTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CredentialTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CreditCategoryDescriptor -( - CreditCategoryDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CreditCategoryDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CreditTypeDescriptor -( - CreditTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CreditTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.CurriculumUsedDescriptor -( - CurriculumUsedDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT CurriculumUsedDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.DeliveryMethodDescriptor -( - DeliveryMethodDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT DeliveryMethodDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.Descriptor -( - DescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT Descriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.DiagnosisDescriptor -( - DiagnosisDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT DiagnosisDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.DiplomaLevelDescriptor -( - DiplomaLevelDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT DiplomaLevelDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.DiplomaTypeDescriptor -( - DiplomaTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT DiplomaTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.DisabilityDescriptor -( - DisabilityDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT DisabilityDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.DisabilityDesignationDescriptor -( - DisabilityDesignationDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT DisabilityDesignationDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.DisabilityDeterminationSourceTypeDescriptor -( - DisabilityDeterminationSourceTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT DisabilityDeterminationSourceTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.DisciplineAction -( - DisciplineActionIdentifier VARCHAR(20) NOT NULL, - DisciplineDate DATE NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT DisciplineAction_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.DisciplineActionLengthDifferenceReasonDescriptor -( - DisciplineActionLengthDifferenceReasonDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT DisciplineActionLengthDifferenceReasonDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.DisciplineDescriptor -( - DisciplineDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT DisciplineDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.DisciplineIncident -( - IncidentIdentifier VARCHAR(20) NOT NULL, - SchoolId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT DisciplineIncident_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.DisciplineIncidentParticipationCodeDescriptor -( - DisciplineIncidentParticipationCodeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT DisciplineIncidentParticipationCodeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.EducationContent -( - ContentIdentifier VARCHAR(225) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT EducationContent_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.EducationOrganization -( - EducationOrganizationId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT EducationOrganization_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.EducationOrganizationCategoryDescriptor -( - EducationOrganizationCategoryDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT EducationOrganizationCategoryDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.EducationOrganizationIdentificationSystemDescriptor -( - EducationOrganizationIdentificationSystemDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT EducationOrganizationIdentificationSystemDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.EducationOrganizationInterventionPrescriptionAssociation -( - EducationOrganizationId INT NOT NULL, - InterventionPrescriptionEducationOrganizationId INT NOT NULL, - InterventionPrescriptionIdentificationCode VARCHAR(60) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT EducationOrganizationInterventionPrescriptionAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.EducationOrganizationNetwork -( - EducationOrganizationNetworkId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT EducationOrganizationNetwork_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.EducationOrganizationNetworkAssociation -( - EducationOrganizationNetworkId INT NOT NULL, - MemberEducationOrganizationId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT EducationOrganizationNetworkAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.EducationOrganizationPeerAssociation -( - EducationOrganizationId INT NOT NULL, - PeerEducationOrganizationId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT EducationOrganizationPeerAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.EducationPlanDescriptor -( - EducationPlanDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT EducationPlanDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.EducationServiceCenter -( - EducationServiceCenterId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT EducationServiceCenter_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.EducationalEnvironmentDescriptor -( - EducationalEnvironmentDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT EducationalEnvironmentDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ElectronicMailTypeDescriptor -( - ElectronicMailTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ElectronicMailTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.EmploymentStatusDescriptor -( - EmploymentStatusDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT EmploymentStatusDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.EntryGradeLevelReasonDescriptor -( - EntryGradeLevelReasonDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT EntryGradeLevelReasonDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.EntryTypeDescriptor -( - EntryTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT EntryTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.EventCircumstanceDescriptor -( - EventCircumstanceDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT EventCircumstanceDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ExitWithdrawTypeDescriptor -( - ExitWithdrawTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ExitWithdrawTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.FeederSchoolAssociation -( - BeginDate DATE NOT NULL, - FeederSchoolId INT NOT NULL, - SchoolId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT FeederSchoolAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.GeneralStudentProgramAssociation -( - BeginDate DATE NOT NULL, - EducationOrganizationId INT NOT NULL, - ProgramEducationOrganizationId INT NOT NULL, - ProgramName VARCHAR(60) NOT NULL, - ProgramTypeDescriptorId INT NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT GeneralStudentProgramAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.Grade -( - BeginDate DATE NOT NULL, - GradeTypeDescriptorId INT NOT NULL, - GradingPeriodDescriptorId INT NOT NULL, - GradingPeriodSchoolYear SMALLINT NOT NULL, - GradingPeriodSequence INT NOT NULL, - LocalCourseCode VARCHAR(60) NOT NULL, - SchoolId INT NOT NULL, - SchoolYear SMALLINT NOT NULL, - SectionIdentifier VARCHAR(255) NOT NULL, - SessionName VARCHAR(60) NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT Grade_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.GradeLevelDescriptor -( - GradeLevelDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT GradeLevelDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.GradePointAverageTypeDescriptor -( - GradePointAverageTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT GradePointAverageTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.GradeTypeDescriptor -( - GradeTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT GradeTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.GradebookEntry -( - DateAssigned DATE NOT NULL, - GradebookEntryTitle VARCHAR(60) NOT NULL, - LocalCourseCode VARCHAR(60) NOT NULL, - SchoolId INT NOT NULL, - SchoolYear SMALLINT NOT NULL, - SectionIdentifier VARCHAR(255) NOT NULL, - SessionName VARCHAR(60) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT GradebookEntry_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.GradebookEntryTypeDescriptor -( - GradebookEntryTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT GradebookEntryTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.GradingPeriod -( - GradingPeriodDescriptorId INT NOT NULL, - PeriodSequence INT NOT NULL, - SchoolId INT NOT NULL, - SchoolYear SMALLINT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT GradingPeriod_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.GradingPeriodDescriptor -( - GradingPeriodDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT GradingPeriodDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.GraduationPlan -( - EducationOrganizationId INT NOT NULL, - GraduationPlanTypeDescriptorId INT NOT NULL, - GraduationSchoolYear SMALLINT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT GraduationPlan_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.GraduationPlanTypeDescriptor -( - GraduationPlanTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT GraduationPlanTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.GunFreeSchoolsActReportingStatusDescriptor -( - GunFreeSchoolsActReportingStatusDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT GunFreeSchoolsActReportingStatusDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.HomelessPrimaryNighttimeResidenceDescriptor -( - HomelessPrimaryNighttimeResidenceDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT HomelessPrimaryNighttimeResidenceDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.HomelessProgramServiceDescriptor -( - HomelessProgramServiceDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT HomelessProgramServiceDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.IdentificationDocumentUseDescriptor -( - IdentificationDocumentUseDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT IdentificationDocumentUseDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.IncidentLocationDescriptor -( - IncidentLocationDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT IncidentLocationDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.IndicatorDescriptor -( - IndicatorDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT IndicatorDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.IndicatorGroupDescriptor -( - IndicatorGroupDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT IndicatorGroupDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.IndicatorLevelDescriptor -( - IndicatorLevelDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT IndicatorLevelDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.InstitutionTelephoneNumberTypeDescriptor -( - InstitutionTelephoneNumberTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT InstitutionTelephoneNumberTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.InteractivityStyleDescriptor -( - InteractivityStyleDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT InteractivityStyleDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.InternetAccessDescriptor -( - InternetAccessDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT InternetAccessDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.Intervention -( - EducationOrganizationId INT NOT NULL, - InterventionIdentificationCode VARCHAR(60) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT Intervention_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.InterventionClassDescriptor -( - InterventionClassDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT InterventionClassDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.InterventionEffectivenessRatingDescriptor -( - InterventionEffectivenessRatingDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT InterventionEffectivenessRatingDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.InterventionPrescription -( - EducationOrganizationId INT NOT NULL, - InterventionPrescriptionIdentificationCode VARCHAR(60) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT InterventionPrescription_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.InterventionStudy -( - EducationOrganizationId INT NOT NULL, - InterventionStudyIdentificationCode VARCHAR(60) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT InterventionStudy_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.LanguageDescriptor -( - LanguageDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT LanguageDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.LanguageInstructionProgramServiceDescriptor -( - LanguageInstructionProgramServiceDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT LanguageInstructionProgramServiceDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.LanguageUseDescriptor -( - LanguageUseDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT LanguageUseDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.LearningObjective -( - LearningObjectiveId VARCHAR(60) NOT NULL, - Namespace VARCHAR(255) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT LearningObjective_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.LearningStandard -( - LearningStandardId VARCHAR(60) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT LearningStandard_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.LearningStandardCategoryDescriptor -( - LearningStandardCategoryDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT LearningStandardCategoryDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.LearningStandardEquivalenceAssociation -( - Namespace VARCHAR(255) NOT NULL, - SourceLearningStandardId VARCHAR(60) NOT NULL, - TargetLearningStandardId VARCHAR(60) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT LearningStandardEquivalenceAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.LearningStandardEquivalenceStrengthDescriptor -( - LearningStandardEquivalenceStrengthDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT LearningStandardEquivalenceStrengthDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.LearningStandardScopeDescriptor -( - LearningStandardScopeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT LearningStandardScopeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.LevelOfEducationDescriptor -( - LevelOfEducationDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT LevelOfEducationDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.LicenseStatusDescriptor -( - LicenseStatusDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT LicenseStatusDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.LicenseTypeDescriptor -( - LicenseTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT LicenseTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.LimitedEnglishProficiencyDescriptor -( - LimitedEnglishProficiencyDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT LimitedEnglishProficiencyDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.LocalEducationAgency -( - LocalEducationAgencyId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT LocalEducationAgency_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.LocalEducationAgencyCategoryDescriptor -( - LocalEducationAgencyCategoryDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT LocalEducationAgencyCategoryDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.LocaleDescriptor -( - LocaleDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT LocaleDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.Location -( - ClassroomIdentificationCode VARCHAR(60) NOT NULL, - SchoolId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT Location_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.MagnetSpecialProgramEmphasisSchoolDescriptor -( - MagnetSpecialProgramEmphasisSchoolDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT MagnetSpecialProgramEmphasisSchoolDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.MediumOfInstructionDescriptor -( - MediumOfInstructionDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT MediumOfInstructionDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.MethodCreditEarnedDescriptor -( - MethodCreditEarnedDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT MethodCreditEarnedDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.MigrantEducationProgramServiceDescriptor -( - MigrantEducationProgramServiceDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT MigrantEducationProgramServiceDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.MonitoredDescriptor -( - MonitoredDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT MonitoredDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.NeglectedOrDelinquentProgramDescriptor -( - NeglectedOrDelinquentProgramDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT NeglectedOrDelinquentProgramDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.NeglectedOrDelinquentProgramServiceDescriptor -( - NeglectedOrDelinquentProgramServiceDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT NeglectedOrDelinquentProgramServiceDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.NetworkPurposeDescriptor -( - NetworkPurposeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT NetworkPurposeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ObjectiveAssessment -( - AssessmentIdentifier VARCHAR(60) NOT NULL, - IdentificationCode VARCHAR(60) NOT NULL, - Namespace VARCHAR(255) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ObjectiveAssessment_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.OldEthnicityDescriptor -( - OldEthnicityDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT OldEthnicityDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.OpenStaffPosition -( - EducationOrganizationId INT NOT NULL, - RequisitionNumber VARCHAR(20) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT OpenStaffPosition_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.OperationalStatusDescriptor -( - OperationalStatusDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT OperationalStatusDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.OrganizationDepartment -( - OrganizationDepartmentId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT OrganizationDepartment_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.OtherNameTypeDescriptor -( - OtherNameTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT OtherNameTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.Parent -( - ParentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT Parent_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ParticipationDescriptor -( - ParticipationDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ParticipationDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ParticipationStatusDescriptor -( - ParticipationStatusDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ParticipationStatusDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.Payroll -( - AccountIdentifier VARCHAR(50) NOT NULL, - AsOfDate DATE NOT NULL, - EducationOrganizationId INT NOT NULL, - FiscalYear INT NOT NULL, - StaffUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT Payroll_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.PerformanceBaseConversionDescriptor -( - PerformanceBaseConversionDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT PerformanceBaseConversionDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.PerformanceLevelDescriptor -( - PerformanceLevelDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT PerformanceLevelDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.Person -( - PersonId VARCHAR(32) NOT NULL, - SourceSystemDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT Person_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.PersonalInformationVerificationDescriptor -( - PersonalInformationVerificationDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT PersonalInformationVerificationDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.PlatformTypeDescriptor -( - PlatformTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT PlatformTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.PopulationServedDescriptor -( - PopulationServedDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT PopulationServedDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.PostSecondaryEvent -( - EventDate DATE NOT NULL, - PostSecondaryEventCategoryDescriptorId INT NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT PostSecondaryEvent_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.PostSecondaryEventCategoryDescriptor -( - PostSecondaryEventCategoryDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT PostSecondaryEventCategoryDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.PostSecondaryInstitution -( - PostSecondaryInstitutionId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT PostSecondaryInstitution_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.PostSecondaryInstitutionLevelDescriptor -( - PostSecondaryInstitutionLevelDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT PostSecondaryInstitutionLevelDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.PostingResultDescriptor -( - PostingResultDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT PostingResultDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ProficiencyDescriptor -( - ProficiencyDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ProficiencyDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.Program -( - EducationOrganizationId INT NOT NULL, - ProgramName VARCHAR(60) NOT NULL, - ProgramTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT Program_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ProgramAssignmentDescriptor -( - ProgramAssignmentDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ProgramAssignmentDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ProgramCharacteristicDescriptor -( - ProgramCharacteristicDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ProgramCharacteristicDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ProgramSponsorDescriptor -( - ProgramSponsorDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ProgramSponsorDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ProgramTypeDescriptor -( - ProgramTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ProgramTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ProgressDescriptor -( - ProgressDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ProgressDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ProgressLevelDescriptor -( - ProgressLevelDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ProgressLevelDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ProviderCategoryDescriptor -( - ProviderCategoryDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ProviderCategoryDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ProviderProfitabilityDescriptor -( - ProviderProfitabilityDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ProviderProfitabilityDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ProviderStatusDescriptor -( - ProviderStatusDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ProviderStatusDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.PublicationStatusDescriptor -( - PublicationStatusDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT PublicationStatusDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.QuestionFormDescriptor -( - QuestionFormDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT QuestionFormDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.RaceDescriptor -( - RaceDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT RaceDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ReasonExitedDescriptor -( - ReasonExitedDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ReasonExitedDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ReasonNotTestedDescriptor -( - ReasonNotTestedDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ReasonNotTestedDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.RecognitionTypeDescriptor -( - RecognitionTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT RecognitionTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.RelationDescriptor -( - RelationDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT RelationDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.RepeatIdentifierDescriptor -( - RepeatIdentifierDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT RepeatIdentifierDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ReportCard -( - EducationOrganizationId INT NOT NULL, - GradingPeriodDescriptorId INT NOT NULL, - GradingPeriodSchoolId INT NOT NULL, - GradingPeriodSchoolYear SMALLINT NOT NULL, - GradingPeriodSequence INT NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ReportCard_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ReporterDescriptionDescriptor -( - ReporterDescriptionDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ReporterDescriptionDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ResidencyStatusDescriptor -( - ResidencyStatusDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ResidencyStatusDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ResponseIndicatorDescriptor -( - ResponseIndicatorDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ResponseIndicatorDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ResponsibilityDescriptor -( - ResponsibilityDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ResponsibilityDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.RestraintEvent -( - RestraintEventIdentifier VARCHAR(20) NOT NULL, - SchoolId INT NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT RestraintEvent_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.RestraintEventReasonDescriptor -( - RestraintEventReasonDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT RestraintEventReasonDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ResultDatatypeTypeDescriptor -( - ResultDatatypeTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ResultDatatypeTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.RetestIndicatorDescriptor -( - RetestIndicatorDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT RetestIndicatorDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.School -( - SchoolId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT School_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SchoolCategoryDescriptor -( - SchoolCategoryDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SchoolCategoryDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SchoolChoiceImplementStatusDescriptor -( - SchoolChoiceImplementStatusDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SchoolChoiceImplementStatusDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SchoolFoodServiceProgramServiceDescriptor -( - SchoolFoodServiceProgramServiceDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SchoolFoodServiceProgramServiceDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SchoolTypeDescriptor -( - SchoolTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SchoolTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.Section -( - LocalCourseCode VARCHAR(60) NOT NULL, - SchoolId INT NOT NULL, - SchoolYear SMALLINT NOT NULL, - SectionIdentifier VARCHAR(255) NOT NULL, - SessionName VARCHAR(60) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT Section_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SectionAttendanceTakenEvent -( - CalendarCode VARCHAR(60) NOT NULL, - Date DATE NOT NULL, - LocalCourseCode VARCHAR(60) NOT NULL, - SchoolId INT NOT NULL, - SchoolYear SMALLINT NOT NULL, - SectionIdentifier VARCHAR(255) NOT NULL, - SessionName VARCHAR(60) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SectionAttendanceTakenEvent_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SectionCharacteristicDescriptor -( - SectionCharacteristicDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SectionCharacteristicDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SeparationDescriptor -( - SeparationDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SeparationDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SeparationReasonDescriptor -( - SeparationReasonDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SeparationReasonDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.ServiceDescriptor -( - ServiceDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT ServiceDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.Session -( - SchoolId INT NOT NULL, - SchoolYear SMALLINT NOT NULL, - SessionName VARCHAR(60) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT Session_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SexDescriptor -( - SexDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SexDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SourceSystemDescriptor -( - SourceSystemDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SourceSystemDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SpecialEducationProgramServiceDescriptor -( - SpecialEducationProgramServiceDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SpecialEducationProgramServiceDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SpecialEducationSettingDescriptor -( - SpecialEducationSettingDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SpecialEducationSettingDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.Staff -( - StaffUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT Staff_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StaffAbsenceEvent -( - AbsenceEventCategoryDescriptorId INT NOT NULL, - EventDate DATE NOT NULL, - StaffUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StaffAbsenceEvent_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StaffClassificationDescriptor -( - StaffClassificationDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StaffClassificationDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StaffCohortAssociation -( - BeginDate DATE NOT NULL, - CohortIdentifier VARCHAR(20) NOT NULL, - EducationOrganizationId INT NOT NULL, - StaffUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StaffCohortAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StaffDisciplineIncidentAssociation -( - IncidentIdentifier VARCHAR(20) NOT NULL, - SchoolId INT NOT NULL, - StaffUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StaffDisciplineIncidentAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StaffEducationOrganizationAssignmentAssociation -( - BeginDate DATE NOT NULL, - EducationOrganizationId INT NOT NULL, - StaffClassificationDescriptorId INT NOT NULL, - StaffUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StaffEducationOrganizationAssignmentAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StaffEducationOrganizationContactAssociation -( - ContactTitle VARCHAR(75) NOT NULL, - EducationOrganizationId INT NOT NULL, - StaffUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StaffEducationOrganizationContactAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StaffEducationOrganizationEmploymentAssociation -( - EducationOrganizationId INT NOT NULL, - EmploymentStatusDescriptorId INT NOT NULL, - HireDate DATE NOT NULL, - StaffUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StaffEducationOrganizationEmploymentAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StaffIdentificationSystemDescriptor -( - StaffIdentificationSystemDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StaffIdentificationSystemDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StaffLeave -( - BeginDate DATE NOT NULL, - StaffLeaveEventCategoryDescriptorId INT NOT NULL, - StaffUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StaffLeave_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StaffLeaveEventCategoryDescriptor -( - StaffLeaveEventCategoryDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StaffLeaveEventCategoryDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StaffProgramAssociation -( - BeginDate DATE NOT NULL, - ProgramEducationOrganizationId INT NOT NULL, - ProgramName VARCHAR(60) NOT NULL, - ProgramTypeDescriptorId INT NOT NULL, - StaffUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StaffProgramAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StaffSchoolAssociation -( - ProgramAssignmentDescriptorId INT NOT NULL, - SchoolId INT NOT NULL, - StaffUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StaffSchoolAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StaffSectionAssociation -( - LocalCourseCode VARCHAR(60) NOT NULL, - SchoolId INT NOT NULL, - SchoolYear SMALLINT NOT NULL, - SectionIdentifier VARCHAR(255) NOT NULL, - SessionName VARCHAR(60) NOT NULL, - StaffUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StaffSectionAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StateAbbreviationDescriptor -( - StateAbbreviationDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StateAbbreviationDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StateEducationAgency -( - StateEducationAgencyId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StateEducationAgency_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.Student -( - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT Student_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentAcademicRecord -( - EducationOrganizationId INT NOT NULL, - SchoolYear SMALLINT NOT NULL, - StudentUSI INT NOT NULL, - TermDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentAcademicRecord_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentAssessment -( - AssessmentIdentifier VARCHAR(60) NOT NULL, - Namespace VARCHAR(255) NOT NULL, - StudentAssessmentIdentifier VARCHAR(60) NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentAssessment_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentCTEProgramAssociation -( - BeginDate DATE NOT NULL, - EducationOrganizationId INT NOT NULL, - ProgramEducationOrganizationId INT NOT NULL, - ProgramName VARCHAR(60) NOT NULL, - ProgramTypeDescriptorId INT NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentCTEProgramAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentCharacteristicDescriptor -( - StudentCharacteristicDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentCharacteristicDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentCohortAssociation -( - BeginDate DATE NOT NULL, - CohortIdentifier VARCHAR(20) NOT NULL, - EducationOrganizationId INT NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentCohortAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentCompetencyObjective -( - GradingPeriodDescriptorId INT NOT NULL, - GradingPeriodSchoolId INT NOT NULL, - GradingPeriodSchoolYear SMALLINT NOT NULL, - GradingPeriodSequence INT NOT NULL, - Objective VARCHAR(60) NOT NULL, - ObjectiveEducationOrganizationId INT NOT NULL, - ObjectiveGradeLevelDescriptorId INT NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentCompetencyObjective_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentDisciplineIncidentAssociation -( - IncidentIdentifier VARCHAR(20) NOT NULL, - SchoolId INT NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentDisciplineIncidentAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentDisciplineIncidentBehaviorAssociation -( - BehaviorDescriptorId INT NOT NULL, - IncidentIdentifier VARCHAR(20) NOT NULL, - SchoolId INT NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentDisciplineIncidentBehaviorAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentDisciplineIncidentNonOffenderAssociation -( - IncidentIdentifier VARCHAR(20) NOT NULL, - SchoolId INT NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentDisciplineIncidentNonOffenderAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentEducationOrganizationAssociation -( - EducationOrganizationId INT NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentEducationOrganizationAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentEducationOrganizationResponsibilityAssociation -( - BeginDate DATE NOT NULL, - EducationOrganizationId INT NOT NULL, - ResponsibilityDescriptorId INT NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentEducationOrganizationResponsibilityAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentGradebookEntry -( - BeginDate DATE NOT NULL, - DateAssigned DATE NOT NULL, - GradebookEntryTitle VARCHAR(60) NOT NULL, - LocalCourseCode VARCHAR(60) NOT NULL, - SchoolId INT NOT NULL, - SchoolYear SMALLINT NOT NULL, - SectionIdentifier VARCHAR(255) NOT NULL, - SessionName VARCHAR(60) NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentGradebookEntry_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentHomelessProgramAssociation -( - BeginDate DATE NOT NULL, - EducationOrganizationId INT NOT NULL, - ProgramEducationOrganizationId INT NOT NULL, - ProgramName VARCHAR(60) NOT NULL, - ProgramTypeDescriptorId INT NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentHomelessProgramAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentIdentificationSystemDescriptor -( - StudentIdentificationSystemDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentIdentificationSystemDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentInterventionAssociation -( - EducationOrganizationId INT NOT NULL, - InterventionIdentificationCode VARCHAR(60) NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentInterventionAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentInterventionAttendanceEvent -( - AttendanceEventCategoryDescriptorId INT NOT NULL, - EducationOrganizationId INT NOT NULL, - EventDate DATE NOT NULL, - InterventionIdentificationCode VARCHAR(60) NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentInterventionAttendanceEvent_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentLanguageInstructionProgramAssociation -( - BeginDate DATE NOT NULL, - EducationOrganizationId INT NOT NULL, - ProgramEducationOrganizationId INT NOT NULL, - ProgramName VARCHAR(60) NOT NULL, - ProgramTypeDescriptorId INT NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentLanguageInstructionProgramAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentLearningObjective -( - GradingPeriodDescriptorId INT NOT NULL, - GradingPeriodSchoolId INT NOT NULL, - GradingPeriodSchoolYear SMALLINT NOT NULL, - GradingPeriodSequence INT NOT NULL, - LearningObjectiveId VARCHAR(60) NOT NULL, - Namespace VARCHAR(255) NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentLearningObjective_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentMigrantEducationProgramAssociation -( - BeginDate DATE NOT NULL, - EducationOrganizationId INT NOT NULL, - ProgramEducationOrganizationId INT NOT NULL, - ProgramName VARCHAR(60) NOT NULL, - ProgramTypeDescriptorId INT NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentMigrantEducationProgramAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentNeglectedOrDelinquentProgramAssociation -( - BeginDate DATE NOT NULL, - EducationOrganizationId INT NOT NULL, - ProgramEducationOrganizationId INT NOT NULL, - ProgramName VARCHAR(60) NOT NULL, - ProgramTypeDescriptorId INT NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentNeglectedOrDelinquentProgramAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentParentAssociation -( - ParentUSI INT NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentParentAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentParticipationCodeDescriptor -( - StudentParticipationCodeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentParticipationCodeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentProgramAssociation -( - BeginDate DATE NOT NULL, - EducationOrganizationId INT NOT NULL, - ProgramEducationOrganizationId INT NOT NULL, - ProgramName VARCHAR(60) NOT NULL, - ProgramTypeDescriptorId INT NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentProgramAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentProgramAttendanceEvent -( - AttendanceEventCategoryDescriptorId INT NOT NULL, - EducationOrganizationId INT NOT NULL, - EventDate DATE NOT NULL, - ProgramEducationOrganizationId INT NOT NULL, - ProgramName VARCHAR(60) NOT NULL, - ProgramTypeDescriptorId INT NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentProgramAttendanceEvent_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentSchoolAssociation -( - EntryDate DATE NOT NULL, - SchoolId INT NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentSchoolAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentSchoolAttendanceEvent -( - AttendanceEventCategoryDescriptorId INT NOT NULL, - EventDate DATE NOT NULL, - SchoolId INT NOT NULL, - SchoolYear SMALLINT NOT NULL, - SessionName VARCHAR(60) NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentSchoolAttendanceEvent_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentSchoolFoodServiceProgramAssociation -( - BeginDate DATE NOT NULL, - EducationOrganizationId INT NOT NULL, - ProgramEducationOrganizationId INT NOT NULL, - ProgramName VARCHAR(60) NOT NULL, - ProgramTypeDescriptorId INT NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentSchoolFoodServiceProgramAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentSectionAssociation -( - BeginDate DATE NOT NULL, - LocalCourseCode VARCHAR(60) NOT NULL, - SchoolId INT NOT NULL, - SchoolYear SMALLINT NOT NULL, - SectionIdentifier VARCHAR(255) NOT NULL, - SessionName VARCHAR(60) NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentSectionAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentSectionAttendanceEvent -( - AttendanceEventCategoryDescriptorId INT NOT NULL, - EventDate DATE NOT NULL, - LocalCourseCode VARCHAR(60) NOT NULL, - SchoolId INT NOT NULL, - SchoolYear SMALLINT NOT NULL, - SectionIdentifier VARCHAR(255) NOT NULL, - SessionName VARCHAR(60) NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentSectionAttendanceEvent_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentSpecialEducationProgramAssociation -( - BeginDate DATE NOT NULL, - EducationOrganizationId INT NOT NULL, - ProgramEducationOrganizationId INT NOT NULL, - ProgramName VARCHAR(60) NOT NULL, - ProgramTypeDescriptorId INT NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentSpecialEducationProgramAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.StudentTitleIPartAProgramAssociation -( - BeginDate DATE NOT NULL, - EducationOrganizationId INT NOT NULL, - ProgramEducationOrganizationId INT NOT NULL, - ProgramName VARCHAR(60) NOT NULL, - ProgramTypeDescriptorId INT NOT NULL, - StudentUSI INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT StudentTitleIPartAProgramAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.Survey -( - Namespace VARCHAR(255) NOT NULL, - SurveyIdentifier VARCHAR(60) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT Survey_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SurveyCategoryDescriptor -( - SurveyCategoryDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SurveyCategoryDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SurveyCourseAssociation -( - CourseCode VARCHAR(60) NOT NULL, - EducationOrganizationId INT NOT NULL, - Namespace VARCHAR(255) NOT NULL, - SurveyIdentifier VARCHAR(60) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SurveyCourseAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SurveyLevelDescriptor -( - SurveyLevelDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SurveyLevelDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SurveyProgramAssociation -( - EducationOrganizationId INT NOT NULL, - Namespace VARCHAR(255) NOT NULL, - ProgramName VARCHAR(60) NOT NULL, - ProgramTypeDescriptorId INT NOT NULL, - SurveyIdentifier VARCHAR(60) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SurveyProgramAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SurveyQuestion -( - Namespace VARCHAR(255) NOT NULL, - QuestionCode VARCHAR(60) NOT NULL, - SurveyIdentifier VARCHAR(60) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SurveyQuestion_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SurveyQuestionResponse -( - Namespace VARCHAR(255) NOT NULL, - QuestionCode VARCHAR(60) NOT NULL, - SurveyIdentifier VARCHAR(60) NOT NULL, - SurveyResponseIdentifier VARCHAR(60) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SurveyQuestionResponse_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SurveyResponse -( - Namespace VARCHAR(255) NOT NULL, - SurveyIdentifier VARCHAR(60) NOT NULL, - SurveyResponseIdentifier VARCHAR(60) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SurveyResponse_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SurveyResponseEducationOrganizationTargetAssociation -( - EducationOrganizationId INT NOT NULL, - Namespace VARCHAR(255) NOT NULL, - SurveyIdentifier VARCHAR(60) NOT NULL, - SurveyResponseIdentifier VARCHAR(60) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SurveyResponseEducationOrganizationTargetAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SurveyResponseStaffTargetAssociation -( - Namespace VARCHAR(255) NOT NULL, - StaffUSI INT NOT NULL, - SurveyIdentifier VARCHAR(60) NOT NULL, - SurveyResponseIdentifier VARCHAR(60) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SurveyResponseStaffTargetAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SurveySection -( - Namespace VARCHAR(255) NOT NULL, - SurveyIdentifier VARCHAR(60) NOT NULL, - SurveySectionTitle VARCHAR(255) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SurveySection_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SurveySectionAssociation -( - LocalCourseCode VARCHAR(60) NOT NULL, - Namespace VARCHAR(255) NOT NULL, - SchoolId INT NOT NULL, - SchoolYear SMALLINT NOT NULL, - SectionIdentifier VARCHAR(255) NOT NULL, - SessionName VARCHAR(60) NOT NULL, - SurveyIdentifier VARCHAR(60) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SurveySectionAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SurveySectionResponse -( - Namespace VARCHAR(255) NOT NULL, - SurveyIdentifier VARCHAR(60) NOT NULL, - SurveyResponseIdentifier VARCHAR(60) NOT NULL, - SurveySectionTitle VARCHAR(255) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SurveySectionResponse_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SurveySectionResponseEducationOrganizationTargetAssociation -( - EducationOrganizationId INT NOT NULL, - Namespace VARCHAR(255) NOT NULL, - SurveyIdentifier VARCHAR(60) NOT NULL, - SurveyResponseIdentifier VARCHAR(60) NOT NULL, - SurveySectionTitle VARCHAR(255) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SurveySectionResponseEducationOrganizationTargetAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.SurveySectionResponseStaffTargetAssociation -( - Namespace VARCHAR(255) NOT NULL, - StaffUSI INT NOT NULL, - SurveyIdentifier VARCHAR(60) NOT NULL, - SurveyResponseIdentifier VARCHAR(60) NOT NULL, - SurveySectionTitle VARCHAR(255) NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT SurveySectionResponseStaffTargetAssociation_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.TeachingCredentialBasisDescriptor -( - TeachingCredentialBasisDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT TeachingCredentialBasisDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.TeachingCredentialDescriptor -( - TeachingCredentialDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT TeachingCredentialDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.TechnicalSkillsAssessmentDescriptor -( - TechnicalSkillsAssessmentDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT TechnicalSkillsAssessmentDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.TelephoneNumberTypeDescriptor -( - TelephoneNumberTypeDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT TelephoneNumberTypeDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.TermDescriptor -( - TermDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT TermDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.TitleIPartAParticipantDescriptor -( - TitleIPartAParticipantDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT TitleIPartAParticipantDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.TitleIPartAProgramServiceDescriptor -( - TitleIPartAProgramServiceDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT TitleIPartAProgramServiceDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.TitleIPartASchoolDesignationDescriptor -( - TitleIPartASchoolDesignationDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT TitleIPartASchoolDesignationDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.TribalAffiliationDescriptor -( - TribalAffiliationDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT TribalAffiliationDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.VisaDescriptor -( - VisaDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT VisaDescriptor_PK PRIMARY KEY (ChangeVersion) -); - -CREATE TABLE tracked_deletes_edfi.WeaponDescriptor -( - WeaponDescriptorId INT NOT NULL, - Id UUID NOT NULL, - ChangeVersion BIGINT NOT NULL, - CONSTRAINT WeaponDescriptor_PK PRIMARY KEY (ChangeVersion) -); - diff --git a/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0054-DropTrackedDeleteTables.sql b/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0054-DropTrackedDeleteTables.sql new file mode 100644 index 0000000000..b4c5faf87a --- /dev/null +++ b/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0054-DropTrackedDeleteTables.sql @@ -0,0 +1,593 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +DROP TABLE IF EXISTS tracked_deletes_edfi.absenceeventcategorydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.absenceeventcategorydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.academichonorcategorydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.academichonorcategorydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.academicsubjectdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.academicsubjectdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.academicweek; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.academicweek_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.accommodationdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.accommodationdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.account; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.account_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.accountabilityrating; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.accountabilityrating_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.accountclassificationdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.accountclassificationdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.accountcode; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.accountcode_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.achievementcategorydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.achievementcategorydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.actual; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.actual_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.additionalcredittypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.additionalcredittypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.addresstypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.addresstypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.administrationenvironmentdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.administrationenvironmentdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.administrativefundingcontroldescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.administrativefundingcontroldescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.ancestryethnicorigindescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.ancestryethnicorigindescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.assessment; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.assessment_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.assessmentcategorydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.assessmentcategorydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.assessmentidentificationsystemdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.assessmentidentificationsystemdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.assessmentitem; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.assessmentitem_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.assessmentitemcategorydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.assessmentitemcategorydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.assessmentitemresultdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.assessmentitemresultdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.assessmentperioddescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.assessmentperioddescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.assessmentreportingmethoddescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.assessmentreportingmethoddescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.assessmentscorerangelearningstandard; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.assessmentscorerangelearningstandard_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.attemptstatusdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.attemptstatusdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.attendanceeventcategorydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.attendanceeventcategorydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.behaviordescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.behaviordescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.bellschedule; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.bellschedule_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.budget; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.budget_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.calendar; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.calendar_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.calendardate; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.calendardate_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.calendareventdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.calendareventdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.calendartypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.calendartypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.careerpathwaydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.careerpathwaydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.charterapprovalagencytypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.charterapprovalagencytypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.charterstatusdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.charterstatusdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.citizenshipstatusdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.citizenshipstatusdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.classperiod; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.classperiod_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.classroompositiondescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.classroompositiondescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.cohort; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.cohort_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.cohortscopedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.cohortscopedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.cohorttypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.cohorttypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.cohortyeartypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.cohortyeartypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.communityorganization; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.communityorganization_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.communityprovider; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.communityprovider_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.communityproviderlicense; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.communityproviderlicense_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.competencyleveldescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.competencyleveldescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.competencyobjective; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.competencyobjective_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.contacttypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.contacttypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.contentclassdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.contentclassdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.continuationofservicesreasondescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.continuationofservicesreasondescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.contractedstaff; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.contractedstaff_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.costratedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.costratedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.countrydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.countrydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.course; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.course_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.courseattemptresultdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.courseattemptresultdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.coursedefinedbydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.coursedefinedbydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.coursegpaapplicabilitydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.coursegpaapplicabilitydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.courseidentificationsystemdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.courseidentificationsystemdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.courselevelcharacteristicdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.courselevelcharacteristicdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.courseoffering; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.courseoffering_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.courserepeatcodedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.courserepeatcodedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.coursetranscript; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.coursetranscript_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.credential; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.credential_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.credentialfielddescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.credentialfielddescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.credentialtypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.credentialtypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.creditcategorydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.creditcategorydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.credittypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.credittypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.cteprogramservicedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.cteprogramservicedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.curriculumuseddescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.curriculumuseddescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.deliverymethoddescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.deliverymethoddescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.descriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.descriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.diagnosisdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.diagnosisdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.diplomaleveldescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.diplomaleveldescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.diplomatypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.diplomatypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.disabilitydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.disabilitydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.disabilitydesignationdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.disabilitydesignationdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.disabilitydeterminationsourcetypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.disabilitydeterminationsourcetypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.disciplineaction; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.disciplineaction_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.disciplineactionlengthdifferencereasondescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.disciplineactionlengthdifferencereasondescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.disciplinedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.disciplinedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.disciplineincident; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.disciplineincident_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.disciplineincidentparticipationcodedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.disciplineincidentparticipationcodedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.educationalenvironmentdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.educationalenvironmentdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.educationcontent; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.educationcontent_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.educationorganization; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.educationorganization_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.educationorganizationcategorydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.educationorganizationcategorydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.educationorganizationidentificationsystemdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.educationorganizationidentificationsystemdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.educationorganizationinterventionprescriptionassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.educationorganizationinterventionprescription_e670ae_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.educationorganizationnetwork; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.educationorganizationnetwork_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.educationorganizationnetworkassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.educationorganizationnetworkassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.educationorganizationpeerassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.educationorganizationpeerassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.educationplandescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.educationplandescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.educationservicecenter; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.educationservicecenter_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.electronicmailtypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.electronicmailtypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.employmentstatusdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.employmentstatusdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.entrygradelevelreasondescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.entrygradelevelreasondescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.entrytypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.entrytypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.eventcircumstancedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.eventcircumstancedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.exitwithdrawtypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.exitwithdrawtypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.feederschoolassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.feederschoolassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.generalstudentprogramassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.generalstudentprogramassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.grade; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.grade_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.gradebookentry; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.gradebookentry_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.gradebookentrytypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.gradebookentrytypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.gradeleveldescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.gradeleveldescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.gradepointaveragetypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.gradepointaveragetypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.gradetypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.gradetypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.gradingperiod; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.gradingperiod_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.gradingperioddescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.gradingperioddescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.graduationplan; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.graduationplan_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.graduationplantypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.graduationplantypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.gunfreeschoolsactreportingstatusdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.gunfreeschoolsactreportingstatusdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.homelessprimarynighttimeresidencedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.homelessprimarynighttimeresidencedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.homelessprogramservicedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.homelessprogramservicedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.identificationdocumentusedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.identificationdocumentusedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.incidentlocationdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.incidentlocationdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.indicatordescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.indicatordescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.indicatorgroupdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.indicatorgroupdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.indicatorleveldescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.indicatorleveldescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.institutiontelephonenumbertypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.institutiontelephonenumbertypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.interactivitystyledescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.interactivitystyledescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.internetaccessdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.internetaccessdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.intervention; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.intervention_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.interventionclassdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.interventionclassdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.interventioneffectivenessratingdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.interventioneffectivenessratingdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.interventionprescription; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.interventionprescription_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.interventionstudy; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.interventionstudy_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.languagedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.languagedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.languageinstructionprogramservicedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.languageinstructionprogramservicedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.languageusedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.languageusedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.learningobjective; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.learningobjective_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.learningstandard; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.learningstandard_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.learningstandardcategorydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.learningstandardcategorydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.learningstandardequivalenceassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.learningstandardequivalenceassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.learningstandardequivalencestrengthdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.learningstandardequivalencestrengthdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.learningstandardscopedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.learningstandardscopedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.levelofeducationdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.levelofeducationdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.licensestatusdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.licensestatusdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.licensetypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.licensetypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.limitedenglishproficiencydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.limitedenglishproficiencydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.localedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.localedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.localeducationagency; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.localeducationagency_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.localeducationagencycategorydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.localeducationagencycategorydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.location; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.location_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.magnetspecialprogramemphasisschooldescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.magnetspecialprogramemphasisschooldescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.mediumofinstructiondescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.mediumofinstructiondescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.methodcreditearneddescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.methodcreditearneddescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.migranteducationprogramservicedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.migranteducationprogramservicedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.monitoreddescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.monitoreddescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.neglectedordelinquentprogramdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.neglectedordelinquentprogramdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.neglectedordelinquentprogramservicedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.neglectedordelinquentprogramservicedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.networkpurposedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.networkpurposedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.objectiveassessment; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.objectiveassessment_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.oldethnicitydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.oldethnicitydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.openstaffposition; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.openstaffposition_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.operationalstatusdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.operationalstatusdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.organizationdepartment; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.organizationdepartment_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.othernametypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.othernametypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.parent; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.parent_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.participationdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.participationdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.participationstatusdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.participationstatusdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.payroll; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.payroll_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.performancebaseconversiondescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.performancebaseconversiondescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.performanceleveldescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.performanceleveldescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.person; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.person_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.personalinformationverificationdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.personalinformationverificationdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.platformtypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.platformtypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.populationserveddescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.populationserveddescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.postingresultdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.postingresultdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.postsecondaryevent; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.postsecondaryevent_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.postsecondaryeventcategorydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.postsecondaryeventcategorydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.postsecondaryinstitution; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.postsecondaryinstitution_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.postsecondaryinstitutionleveldescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.postsecondaryinstitutionleveldescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.proficiencydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.proficiencydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.program; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.program_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.programassignmentdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.programassignmentdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.programcharacteristicdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.programcharacteristicdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.programsponsordescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.programsponsordescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.programtypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.programtypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.progressdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.progressdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.progressleveldescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.progressleveldescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.providercategorydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.providercategorydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.providerprofitabilitydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.providerprofitabilitydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.providerstatusdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.providerstatusdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.publicationstatusdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.publicationstatusdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.questionformdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.questionformdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.racedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.racedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.reasonexiteddescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.reasonexiteddescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.reasonnottesteddescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.reasonnottesteddescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.recognitiontypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.recognitiontypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.relationdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.relationdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.repeatidentifierdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.repeatidentifierdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.reportcard; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.reportcard_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.reporterdescriptiondescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.reporterdescriptiondescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.residencystatusdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.residencystatusdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.responseindicatordescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.responseindicatordescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.responsibilitydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.responsibilitydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.restraintevent; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.restraintevent_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.restrainteventreasondescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.restrainteventreasondescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.resultdatatypetypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.resultdatatypetypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.retestindicatordescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.retestindicatordescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.school; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.school_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.schoolcategorydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.schoolcategorydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.schoolchoiceimplementstatusdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.schoolchoiceimplementstatusdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.schoolfoodserviceprogramservicedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.schoolfoodserviceprogramservicedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.schooltypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.schooltypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.schoolyeartype; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.schoolyeartype_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.section; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.section_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.sectionattendancetakenevent; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.sectionattendancetakenevent_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.sectioncharacteristicdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.sectioncharacteristicdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.separationdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.separationdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.separationreasondescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.separationreasondescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.servicedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.servicedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.session; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.session_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.sexdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.sexdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.sourcesystemdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.sourcesystemdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.specialeducationprogramservicedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.specialeducationprogramservicedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.specialeducationsettingdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.specialeducationsettingdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.staff; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.staff_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.staffabsenceevent; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.staffabsenceevent_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.staffclassificationdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.staffclassificationdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.staffcohortassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.staffcohortassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.staffdisciplineincidentassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.staffdisciplineincidentassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.staffeducationorganizationassignmentassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.staffeducationorganizationassignmentassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.staffeducationorganizationcontactassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.staffeducationorganizationcontactassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.staffeducationorganizationemploymentassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.staffeducationorganizationemploymentassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.staffidentificationsystemdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.staffidentificationsystemdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.staffleave; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.staffleave_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.staffleaveeventcategorydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.staffleaveeventcategorydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.staffprogramassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.staffprogramassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.staffschoolassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.staffschoolassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.staffsectionassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.staffsectionassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.stateabbreviationdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.stateabbreviationdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.stateeducationagency; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.stateeducationagency_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.student; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.student_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentacademicrecord; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentacademicrecord_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentassessment; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentassessment_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentcharacteristicdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentcharacteristicdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentcohortassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentcohortassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentcompetencyobjective; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentcompetencyobjective_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentcteprogramassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentcteprogramassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentdisciplineincidentassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentdisciplineincidentassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentdisciplineincidentbehaviorassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentdisciplineincidentbehaviorassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentdisciplineincidentnonoffenderassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentdisciplineincidentnonoffenderassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studenteducationorganizationassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studenteducationorganizationassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studenteducationorganizationresponsibilityassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studenteducationorganizationresponsibilityass_42aa64_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentgradebookentry; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentgradebookentry_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studenthomelessprogramassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studenthomelessprogramassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentidentificationsystemdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentidentificationsystemdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentinterventionassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentinterventionassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentinterventionattendanceevent; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentinterventionattendanceevent_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentlanguageinstructionprogramassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentlanguageinstructionprogramassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentlearningobjective; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentlearningobjective_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentmigranteducationprogramassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentmigranteducationprogramassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentneglectedordelinquentprogramassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentneglectedordelinquentprogramassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentparentassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentparentassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentparticipationcodedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentparticipationcodedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentprogramassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentprogramassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentprogramattendanceevent; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentprogramattendanceevent_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentschoolassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentschoolassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentschoolattendanceevent; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentschoolattendanceevent_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentschoolfoodserviceprogramassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentschoolfoodserviceprogramassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentsectionassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentsectionassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentsectionattendanceevent; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentsectionattendanceevent_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studentspecialeducationprogramassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studentspecialeducationprogramassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.studenttitleipartaprogramassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.studenttitleipartaprogramassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.survey; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.survey_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.surveycategorydescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.surveycategorydescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.surveycourseassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.surveycourseassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.surveyleveldescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.surveyleveldescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.surveyprogramassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.surveyprogramassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.surveyquestion; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.surveyquestion_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.surveyquestionresponse; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.surveyquestionresponse_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.surveyresponse; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.surveyresponse_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.surveyresponseeducationorganizationtargetassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.surveyresponseeducationorganizationtargetassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.surveyresponsestafftargetassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.surveyresponsestafftargetassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.surveysection; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.surveysection_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.surveysectionassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.surveysectionassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.surveysectionresponse; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.surveysectionresponse_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.surveysectionresponseeducationorganizationtargetassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.surveysectionresponseeducationorganizationtar_730be1_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.surveysectionresponsestafftargetassociation; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.surveysectionresponsestafftargetassociation_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.teachingcredentialbasisdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.teachingcredentialbasisdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.teachingcredentialdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.teachingcredentialdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.technicalskillsassessmentdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.technicalskillsassessmentdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.telephonenumbertypedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.telephonenumbertypedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.termdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.termdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.titleipartaparticipantdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.titleipartaparticipantdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.titleipartaprogramservicedescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.titleipartaprogramservicedescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.titleipartaschooldesignationdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.titleipartaschooldesignationdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.tribalaffiliationdescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.tribalaffiliationdescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.visadescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.visadescriptor_tr_deltrkg() CASCADE; +DROP TABLE IF EXISTS tracked_deletes_edfi.weapondescriptor; +DROP FUNCTION IF EXISTS tracked_deletes_edfi.weapondescriptor_tr_deltrkg() CASCADE; diff --git a/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0056-DropTrackedDeleteSchema.sql b/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0056-DropTrackedDeleteSchema.sql new file mode 100644 index 0000000000..a647d24f20 --- /dev/null +++ b/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0056-DropTrackedDeleteSchema.sql @@ -0,0 +1,6 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +DROP SCHEMA IF EXISTS tracked_deletes_edfi; diff --git a/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0060-CreateDeletedForTrackingTriggers.sql b/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0060-CreateDeletedForTrackingTriggers.sql deleted file mode 100644 index ff90e4cab7..0000000000 --- a/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0060-CreateDeletedForTrackingTriggers.sql +++ /dev/null @@ -1,4009 +0,0 @@ --- SPDX-License-Identifier: Apache-2.0 --- Licensed to the Ed-Fi Alliance under one or more agreements. --- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. --- See the LICENSE and NOTICES files in the project root for more information. - -CREATE FUNCTION tracked_deletes_edfi.AbsenceEventCategoryDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AbsenceEventCategoryDescriptor(AbsenceEventCategoryDescriptorId, Id, ChangeVersion) - SELECT OLD.AbsenceEventCategoryDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.AbsenceEventCategoryDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AbsenceEventCategoryDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AbsenceEventCategoryDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.AcademicHonorCategoryDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AcademicHonorCategoryDescriptor(AcademicHonorCategoryDescriptorId, Id, ChangeVersion) - SELECT OLD.AcademicHonorCategoryDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.AcademicHonorCategoryDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AcademicHonorCategoryDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AcademicHonorCategoryDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.AcademicSubjectDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AcademicSubjectDescriptor(AcademicSubjectDescriptorId, Id, ChangeVersion) - SELECT OLD.AcademicSubjectDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.AcademicSubjectDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AcademicSubjectDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AcademicSubjectDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.AcademicWeek_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AcademicWeek(SchoolId, WeekIdentifier, Id, ChangeVersion) - VALUES (OLD.SchoolId, OLD.WeekIdentifier, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AcademicWeek - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AcademicWeek_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.AccommodationDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AccommodationDescriptor(AccommodationDescriptorId, Id, ChangeVersion) - SELECT OLD.AccommodationDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.AccommodationDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AccommodationDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AccommodationDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.AccountClassificationDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AccountClassificationDescriptor(AccountClassificationDescriptorId, Id, ChangeVersion) - SELECT OLD.AccountClassificationDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.AccountClassificationDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AccountClassificationDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AccountClassificationDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.AccountCode_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AccountCode(AccountClassificationDescriptorId, AccountCodeNumber, EducationOrganizationId, FiscalYear, Id, ChangeVersion) - VALUES (OLD.AccountClassificationDescriptorId, OLD.AccountCodeNumber, OLD.EducationOrganizationId, OLD.FiscalYear, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AccountCode - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AccountCode_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.Account_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.Account(AccountIdentifier, EducationOrganizationId, FiscalYear, Id, ChangeVersion) - VALUES (OLD.AccountIdentifier, OLD.EducationOrganizationId, OLD.FiscalYear, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.Account - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.Account_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.AccountabilityRating_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AccountabilityRating(EducationOrganizationId, RatingTitle, SchoolYear, Id, ChangeVersion) - VALUES (OLD.EducationOrganizationId, OLD.RatingTitle, OLD.SchoolYear, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AccountabilityRating - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AccountabilityRating_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.AchievementCategoryDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AchievementCategoryDescriptor(AchievementCategoryDescriptorId, Id, ChangeVersion) - SELECT OLD.AchievementCategoryDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.AchievementCategoryDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AchievementCategoryDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AchievementCategoryDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.Actual_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.Actual(AccountIdentifier, AsOfDate, EducationOrganizationId, FiscalYear, Id, ChangeVersion) - VALUES (OLD.AccountIdentifier, OLD.AsOfDate, OLD.EducationOrganizationId, OLD.FiscalYear, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.Actual - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.Actual_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.AdditionalCreditTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AdditionalCreditTypeDescriptor(AdditionalCreditTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.AdditionalCreditTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.AdditionalCreditTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AdditionalCreditTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AdditionalCreditTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.AddressTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AddressTypeDescriptor(AddressTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.AddressTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.AddressTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AddressTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AddressTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.AdministrationEnvironmentDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AdministrationEnvironmentDescriptor(AdministrationEnvironmentDescriptorId, Id, ChangeVersion) - SELECT OLD.AdministrationEnvironmentDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.AdministrationEnvironmentDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AdministrationEnvironmentDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AdministrationEnvironmentDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.AdministrativeFundingControlDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AdministrativeFundingControlDescriptor(AdministrativeFundingControlDescriptorId, Id, ChangeVersion) - SELECT OLD.AdministrativeFundingControlDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.AdministrativeFundingControlDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AdministrativeFundingControlDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AdministrativeFundingControlDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.AncestryEthnicOriginDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AncestryEthnicOriginDescriptor(AncestryEthnicOriginDescriptorId, Id, ChangeVersion) - SELECT OLD.AncestryEthnicOriginDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.AncestryEthnicOriginDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AncestryEthnicOriginDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AncestryEthnicOriginDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.AssessmentCategoryDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AssessmentCategoryDescriptor(AssessmentCategoryDescriptorId, Id, ChangeVersion) - SELECT OLD.AssessmentCategoryDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.AssessmentCategoryDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AssessmentCategoryDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AssessmentCategoryDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.AssessmentIdentificationSystemDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AssessmentIdentificationSystemDescriptor(AssessmentIdentificationSystemDescriptorId, Id, ChangeVersion) - SELECT OLD.AssessmentIdentificationSystemDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.AssessmentIdentificationSystemDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AssessmentIdentificationSystemDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AssessmentIdentificationSystemDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.AssessmentItemCategoryDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AssessmentItemCategoryDescriptor(AssessmentItemCategoryDescriptorId, Id, ChangeVersion) - SELECT OLD.AssessmentItemCategoryDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.AssessmentItemCategoryDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AssessmentItemCategoryDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AssessmentItemCategoryDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.AssessmentItemResultDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AssessmentItemResultDescriptor(AssessmentItemResultDescriptorId, Id, ChangeVersion) - SELECT OLD.AssessmentItemResultDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.AssessmentItemResultDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AssessmentItemResultDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AssessmentItemResultDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.AssessmentItem_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AssessmentItem(AssessmentIdentifier, IdentificationCode, Namespace, Id, ChangeVersion) - VALUES (OLD.AssessmentIdentifier, OLD.IdentificationCode, OLD.Namespace, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AssessmentItem - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AssessmentItem_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.AssessmentPeriodDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AssessmentPeriodDescriptor(AssessmentPeriodDescriptorId, Id, ChangeVersion) - SELECT OLD.AssessmentPeriodDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.AssessmentPeriodDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AssessmentPeriodDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AssessmentPeriodDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.AssessmentReportingMethodDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AssessmentReportingMethodDescriptor(AssessmentReportingMethodDescriptorId, Id, ChangeVersion) - SELECT OLD.AssessmentReportingMethodDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.AssessmentReportingMethodDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AssessmentReportingMethodDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AssessmentReportingMethodDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.AssessmentScoreRangeLearningStandard_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AssessmentScoreRangeLearningStandard(AssessmentIdentifier, Namespace, ScoreRangeId, Id, ChangeVersion) - VALUES (OLD.AssessmentIdentifier, OLD.Namespace, OLD.ScoreRangeId, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AssessmentScoreRangeLearningStandard - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AssessmentScoreRangeLearningStandard_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.Assessment_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.Assessment(AssessmentIdentifier, Namespace, Id, ChangeVersion) - VALUES (OLD.AssessmentIdentifier, OLD.Namespace, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.Assessment - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.Assessment_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.AttemptStatusDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AttemptStatusDescriptor(AttemptStatusDescriptorId, Id, ChangeVersion) - SELECT OLD.AttemptStatusDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.AttemptStatusDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AttemptStatusDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AttemptStatusDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.AttendanceEventCategoryDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.AttendanceEventCategoryDescriptor(AttendanceEventCategoryDescriptorId, Id, ChangeVersion) - SELECT OLD.AttendanceEventCategoryDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.AttendanceEventCategoryDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.AttendanceEventCategoryDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.AttendanceEventCategoryDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.BehaviorDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.BehaviorDescriptor(BehaviorDescriptorId, Id, ChangeVersion) - SELECT OLD.BehaviorDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.BehaviorDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.BehaviorDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.BehaviorDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.BellSchedule_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.BellSchedule(BellScheduleName, SchoolId, Id, ChangeVersion) - VALUES (OLD.BellScheduleName, OLD.SchoolId, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.BellSchedule - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.BellSchedule_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.Budget_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.Budget(AccountIdentifier, AsOfDate, EducationOrganizationId, FiscalYear, Id, ChangeVersion) - VALUES (OLD.AccountIdentifier, OLD.AsOfDate, OLD.EducationOrganizationId, OLD.FiscalYear, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.Budget - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.Budget_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CTEProgramServiceDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CTEProgramServiceDescriptor(CTEProgramServiceDescriptorId, Id, ChangeVersion) - SELECT OLD.CTEProgramServiceDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CTEProgramServiceDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CTEProgramServiceDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CTEProgramServiceDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CalendarDate_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CalendarDate(CalendarCode, Date, SchoolId, SchoolYear, Id, ChangeVersion) - VALUES (OLD.CalendarCode, OLD.Date, OLD.SchoolId, OLD.SchoolYear, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CalendarDate - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CalendarDate_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CalendarEventDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CalendarEventDescriptor(CalendarEventDescriptorId, Id, ChangeVersion) - SELECT OLD.CalendarEventDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CalendarEventDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CalendarEventDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CalendarEventDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CalendarTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CalendarTypeDescriptor(CalendarTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.CalendarTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CalendarTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CalendarTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CalendarTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.Calendar_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.Calendar(CalendarCode, SchoolId, SchoolYear, Id, ChangeVersion) - VALUES (OLD.CalendarCode, OLD.SchoolId, OLD.SchoolYear, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.Calendar - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.Calendar_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CareerPathwayDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CareerPathwayDescriptor(CareerPathwayDescriptorId, Id, ChangeVersion) - SELECT OLD.CareerPathwayDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CareerPathwayDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CareerPathwayDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CareerPathwayDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CharterApprovalAgencyTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CharterApprovalAgencyTypeDescriptor(CharterApprovalAgencyTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.CharterApprovalAgencyTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CharterApprovalAgencyTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CharterApprovalAgencyTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CharterApprovalAgencyTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CharterStatusDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CharterStatusDescriptor(CharterStatusDescriptorId, Id, ChangeVersion) - SELECT OLD.CharterStatusDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CharterStatusDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CharterStatusDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CharterStatusDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CitizenshipStatusDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CitizenshipStatusDescriptor(CitizenshipStatusDescriptorId, Id, ChangeVersion) - SELECT OLD.CitizenshipStatusDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CitizenshipStatusDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CitizenshipStatusDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CitizenshipStatusDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ClassPeriod_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ClassPeriod(ClassPeriodName, SchoolId, Id, ChangeVersion) - VALUES (OLD.ClassPeriodName, OLD.SchoolId, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ClassPeriod - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ClassPeriod_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ClassroomPositionDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ClassroomPositionDescriptor(ClassroomPositionDescriptorId, Id, ChangeVersion) - SELECT OLD.ClassroomPositionDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ClassroomPositionDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ClassroomPositionDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ClassroomPositionDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CohortScopeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CohortScopeDescriptor(CohortScopeDescriptorId, Id, ChangeVersion) - SELECT OLD.CohortScopeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CohortScopeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CohortScopeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CohortScopeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CohortTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CohortTypeDescriptor(CohortTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.CohortTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CohortTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CohortTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CohortTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CohortYearTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CohortYearTypeDescriptor(CohortYearTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.CohortYearTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CohortYearTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CohortYearTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CohortYearTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.Cohort_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.Cohort(CohortIdentifier, EducationOrganizationId, Id, ChangeVersion) - VALUES (OLD.CohortIdentifier, OLD.EducationOrganizationId, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.Cohort - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.Cohort_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CommunityOrganization_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CommunityOrganization(CommunityOrganizationId, Id, ChangeVersion) - SELECT OLD.CommunityOrganizationId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.EducationOrganization WHERE EducationOrganizationId = OLD.CommunityOrganizationId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CommunityOrganization - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CommunityOrganization_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CommunityProviderLicense_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CommunityProviderLicense(CommunityProviderId, LicenseIdentifier, LicensingOrganization, Id, ChangeVersion) - VALUES (OLD.CommunityProviderId, OLD.LicenseIdentifier, OLD.LicensingOrganization, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CommunityProviderLicense - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CommunityProviderLicense_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CommunityProvider_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CommunityProvider(CommunityProviderId, Id, ChangeVersion) - SELECT OLD.CommunityProviderId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.EducationOrganization WHERE EducationOrganizationId = OLD.CommunityProviderId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CommunityProvider - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CommunityProvider_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CompetencyLevelDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CompetencyLevelDescriptor(CompetencyLevelDescriptorId, Id, ChangeVersion) - SELECT OLD.CompetencyLevelDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CompetencyLevelDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CompetencyLevelDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CompetencyLevelDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CompetencyObjective_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CompetencyObjective(EducationOrganizationId, Objective, ObjectiveGradeLevelDescriptorId, Id, ChangeVersion) - VALUES (OLD.EducationOrganizationId, OLD.Objective, OLD.ObjectiveGradeLevelDescriptorId, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CompetencyObjective - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CompetencyObjective_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ContactTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ContactTypeDescriptor(ContactTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.ContactTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ContactTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ContactTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ContactTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ContentClassDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ContentClassDescriptor(ContentClassDescriptorId, Id, ChangeVersion) - SELECT OLD.ContentClassDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ContentClassDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ContentClassDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ContentClassDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ContinuationOfServicesReasonDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ContinuationOfServicesReasonDescriptor(ContinuationOfServicesReasonDescriptorId, Id, ChangeVersion) - SELECT OLD.ContinuationOfServicesReasonDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ContinuationOfServicesReasonDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ContinuationOfServicesReasonDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ContinuationOfServicesReasonDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ContractedStaff_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ContractedStaff(AccountIdentifier, AsOfDate, EducationOrganizationId, FiscalYear, StaffUSI, Id, ChangeVersion) - VALUES (OLD.AccountIdentifier, OLD.AsOfDate, OLD.EducationOrganizationId, OLD.FiscalYear, OLD.StaffUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ContractedStaff - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ContractedStaff_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CostRateDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CostRateDescriptor(CostRateDescriptorId, Id, ChangeVersion) - SELECT OLD.CostRateDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CostRateDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CostRateDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CostRateDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CountryDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CountryDescriptor(CountryDescriptorId, Id, ChangeVersion) - SELECT OLD.CountryDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CountryDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CountryDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CountryDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CourseAttemptResultDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CourseAttemptResultDescriptor(CourseAttemptResultDescriptorId, Id, ChangeVersion) - SELECT OLD.CourseAttemptResultDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CourseAttemptResultDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CourseAttemptResultDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CourseAttemptResultDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CourseDefinedByDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CourseDefinedByDescriptor(CourseDefinedByDescriptorId, Id, ChangeVersion) - SELECT OLD.CourseDefinedByDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CourseDefinedByDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CourseDefinedByDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CourseDefinedByDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CourseGPAApplicabilityDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CourseGPAApplicabilityDescriptor(CourseGPAApplicabilityDescriptorId, Id, ChangeVersion) - SELECT OLD.CourseGPAApplicabilityDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CourseGPAApplicabilityDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CourseGPAApplicabilityDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CourseGPAApplicabilityDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CourseIdentificationSystemDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CourseIdentificationSystemDescriptor(CourseIdentificationSystemDescriptorId, Id, ChangeVersion) - SELECT OLD.CourseIdentificationSystemDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CourseIdentificationSystemDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CourseIdentificationSystemDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CourseIdentificationSystemDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CourseLevelCharacteristicDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CourseLevelCharacteristicDescriptor(CourseLevelCharacteristicDescriptorId, Id, ChangeVersion) - SELECT OLD.CourseLevelCharacteristicDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CourseLevelCharacteristicDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CourseLevelCharacteristicDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CourseLevelCharacteristicDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CourseOffering_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CourseOffering(LocalCourseCode, SchoolId, SchoolYear, SessionName, Id, ChangeVersion) - VALUES (OLD.LocalCourseCode, OLD.SchoolId, OLD.SchoolYear, OLD.SessionName, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CourseOffering - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CourseOffering_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CourseRepeatCodeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CourseRepeatCodeDescriptor(CourseRepeatCodeDescriptorId, Id, ChangeVersion) - SELECT OLD.CourseRepeatCodeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CourseRepeatCodeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CourseRepeatCodeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CourseRepeatCodeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CourseTranscript_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CourseTranscript(CourseAttemptResultDescriptorId, CourseCode, CourseEducationOrganizationId, EducationOrganizationId, SchoolYear, StudentUSI, TermDescriptorId, Id, ChangeVersion) - VALUES (OLD.CourseAttemptResultDescriptorId, OLD.CourseCode, OLD.CourseEducationOrganizationId, OLD.EducationOrganizationId, OLD.SchoolYear, OLD.StudentUSI, OLD.TermDescriptorId, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CourseTranscript - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CourseTranscript_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.Course_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.Course(CourseCode, EducationOrganizationId, Id, ChangeVersion) - VALUES (OLD.CourseCode, OLD.EducationOrganizationId, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.Course - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.Course_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CredentialFieldDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CredentialFieldDescriptor(CredentialFieldDescriptorId, Id, ChangeVersion) - SELECT OLD.CredentialFieldDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CredentialFieldDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CredentialFieldDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CredentialFieldDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CredentialTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CredentialTypeDescriptor(CredentialTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.CredentialTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CredentialTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CredentialTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CredentialTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.Credential_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.Credential(CredentialIdentifier, StateOfIssueStateAbbreviationDescriptorId, Id, ChangeVersion) - VALUES (OLD.CredentialIdentifier, OLD.StateOfIssueStateAbbreviationDescriptorId, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.Credential - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.Credential_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CreditCategoryDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CreditCategoryDescriptor(CreditCategoryDescriptorId, Id, ChangeVersion) - SELECT OLD.CreditCategoryDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CreditCategoryDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CreditCategoryDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CreditCategoryDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CreditTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CreditTypeDescriptor(CreditTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.CreditTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CreditTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CreditTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CreditTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.CurriculumUsedDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.CurriculumUsedDescriptor(CurriculumUsedDescriptorId, Id, ChangeVersion) - SELECT OLD.CurriculumUsedDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.CurriculumUsedDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.CurriculumUsedDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.CurriculumUsedDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.DeliveryMethodDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.DeliveryMethodDescriptor(DeliveryMethodDescriptorId, Id, ChangeVersion) - SELECT OLD.DeliveryMethodDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.DeliveryMethodDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.DeliveryMethodDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.DeliveryMethodDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.Descriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.Descriptor(DescriptorId, Id, ChangeVersion) - VALUES (OLD.DescriptorId, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.Descriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.Descriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.DiagnosisDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.DiagnosisDescriptor(DiagnosisDescriptorId, Id, ChangeVersion) - SELECT OLD.DiagnosisDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.DiagnosisDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.DiagnosisDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.DiagnosisDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.DiplomaLevelDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.DiplomaLevelDescriptor(DiplomaLevelDescriptorId, Id, ChangeVersion) - SELECT OLD.DiplomaLevelDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.DiplomaLevelDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.DiplomaLevelDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.DiplomaLevelDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.DiplomaTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.DiplomaTypeDescriptor(DiplomaTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.DiplomaTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.DiplomaTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.DiplomaTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.DiplomaTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.DisabilityDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.DisabilityDescriptor(DisabilityDescriptorId, Id, ChangeVersion) - SELECT OLD.DisabilityDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.DisabilityDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.DisabilityDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.DisabilityDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.DisabilityDesignationDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.DisabilityDesignationDescriptor(DisabilityDesignationDescriptorId, Id, ChangeVersion) - SELECT OLD.DisabilityDesignationDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.DisabilityDesignationDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.DisabilityDesignationDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.DisabilityDesignationDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.DisabilityDeterminationSourceTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.DisabilityDeterminationSourceTypeDescriptor(DisabilityDeterminationSourceTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.DisabilityDeterminationSourceTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.DisabilityDeterminationSourceTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.DisabilityDeterminationSourceTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.DisabilityDeterminationSourceTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.DisciplineActionLengthDifferenceReasonDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.DisciplineActionLengthDifferenceReasonDescriptor(DisciplineActionLengthDifferenceReasonDescriptorId, Id, ChangeVersion) - SELECT OLD.DisciplineActionLengthDifferenceReasonDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.DisciplineActionLengthDifferenceReasonDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.DisciplineActionLengthDifferenceReasonDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.DisciplineActionLengthDifferenceReasonDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.DisciplineAction_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.DisciplineAction(DisciplineActionIdentifier, DisciplineDate, StudentUSI, Id, ChangeVersion) - VALUES (OLD.DisciplineActionIdentifier, OLD.DisciplineDate, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.DisciplineAction - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.DisciplineAction_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.DisciplineDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.DisciplineDescriptor(DisciplineDescriptorId, Id, ChangeVersion) - SELECT OLD.DisciplineDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.DisciplineDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.DisciplineDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.DisciplineDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.DisciplineIncidentParticipationCodeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.DisciplineIncidentParticipationCodeDescriptor(DisciplineIncidentParticipationCodeDescriptorId, Id, ChangeVersion) - SELECT OLD.DisciplineIncidentParticipationCodeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.DisciplineIncidentParticipationCodeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.DisciplineIncidentParticipationCodeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.DisciplineIncidentParticipationCodeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.DisciplineIncident_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.DisciplineIncident(IncidentIdentifier, SchoolId, Id, ChangeVersion) - VALUES (OLD.IncidentIdentifier, OLD.SchoolId, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.DisciplineIncident - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.DisciplineIncident_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.EducationContent_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.EducationContent(ContentIdentifier, Id, ChangeVersion) - VALUES (OLD.ContentIdentifier, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.EducationContent - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.EducationContent_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.EducationOrganizationCategoryDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.EducationOrganizationCategoryDescriptor(EducationOrganizationCategoryDescriptorId, Id, ChangeVersion) - SELECT OLD.EducationOrganizationCategoryDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.EducationOrganizationCategoryDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.EducationOrganizationCategoryDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.EducationOrganizationCategoryDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.EducationOrganizationIdentificationSystemDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.EducationOrganizationIdentificationSystemDescriptor(EducationOrganizationIdentificationSystemDescriptorId, Id, ChangeVersion) - SELECT OLD.EducationOrganizationIdentificationSystemDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.EducationOrganizationIdentificationSystemDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.EducationOrganizationIdentificationSystemDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.EducationOrganizationIdentificationSystemDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.EducationOrganizationInterventionPrescription_e670ae_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.EducationOrganizationInterventionPrescriptionAssociation(EducationOrganizationId, InterventionPrescriptionEducationOrganizationId, InterventionPrescriptionIdentificationCode, Id, ChangeVersion) - VALUES (OLD.EducationOrganizationId, OLD.InterventionPrescriptionEducationOrganizationId, OLD.InterventionPrescriptionIdentificationCode, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.EducationOrganizationInterventionPrescriptionAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.EducationOrganizationInterventionPrescription_e670ae_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.EducationOrganizationNetworkAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.EducationOrganizationNetworkAssociation(EducationOrganizationNetworkId, MemberEducationOrganizationId, Id, ChangeVersion) - VALUES (OLD.EducationOrganizationNetworkId, OLD.MemberEducationOrganizationId, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.EducationOrganizationNetworkAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.EducationOrganizationNetworkAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.EducationOrganizationNetwork_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.EducationOrganizationNetwork(EducationOrganizationNetworkId, Id, ChangeVersion) - SELECT OLD.EducationOrganizationNetworkId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.EducationOrganization WHERE EducationOrganizationId = OLD.EducationOrganizationNetworkId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.EducationOrganizationNetwork - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.EducationOrganizationNetwork_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.EducationOrganizationPeerAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.EducationOrganizationPeerAssociation(EducationOrganizationId, PeerEducationOrganizationId, Id, ChangeVersion) - VALUES (OLD.EducationOrganizationId, OLD.PeerEducationOrganizationId, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.EducationOrganizationPeerAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.EducationOrganizationPeerAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.EducationOrganization_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.EducationOrganization(EducationOrganizationId, Id, ChangeVersion) - VALUES (OLD.EducationOrganizationId, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.EducationOrganization - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.EducationOrganization_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.EducationPlanDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.EducationPlanDescriptor(EducationPlanDescriptorId, Id, ChangeVersion) - SELECT OLD.EducationPlanDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.EducationPlanDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.EducationPlanDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.EducationPlanDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.EducationServiceCenter_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.EducationServiceCenter(EducationServiceCenterId, Id, ChangeVersion) - SELECT OLD.EducationServiceCenterId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.EducationOrganization WHERE EducationOrganizationId = OLD.EducationServiceCenterId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.EducationServiceCenter - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.EducationServiceCenter_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.EducationalEnvironmentDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.EducationalEnvironmentDescriptor(EducationalEnvironmentDescriptorId, Id, ChangeVersion) - SELECT OLD.EducationalEnvironmentDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.EducationalEnvironmentDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.EducationalEnvironmentDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.EducationalEnvironmentDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ElectronicMailTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ElectronicMailTypeDescriptor(ElectronicMailTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.ElectronicMailTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ElectronicMailTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ElectronicMailTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ElectronicMailTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.EmploymentStatusDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.EmploymentStatusDescriptor(EmploymentStatusDescriptorId, Id, ChangeVersion) - SELECT OLD.EmploymentStatusDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.EmploymentStatusDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.EmploymentStatusDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.EmploymentStatusDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.EntryGradeLevelReasonDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.EntryGradeLevelReasonDescriptor(EntryGradeLevelReasonDescriptorId, Id, ChangeVersion) - SELECT OLD.EntryGradeLevelReasonDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.EntryGradeLevelReasonDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.EntryGradeLevelReasonDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.EntryGradeLevelReasonDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.EntryTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.EntryTypeDescriptor(EntryTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.EntryTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.EntryTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.EntryTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.EntryTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.EventCircumstanceDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.EventCircumstanceDescriptor(EventCircumstanceDescriptorId, Id, ChangeVersion) - SELECT OLD.EventCircumstanceDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.EventCircumstanceDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.EventCircumstanceDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.EventCircumstanceDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ExitWithdrawTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ExitWithdrawTypeDescriptor(ExitWithdrawTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.ExitWithdrawTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ExitWithdrawTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ExitWithdrawTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ExitWithdrawTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.FeederSchoolAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.FeederSchoolAssociation(BeginDate, FeederSchoolId, SchoolId, Id, ChangeVersion) - VALUES (OLD.BeginDate, OLD.FeederSchoolId, OLD.SchoolId, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.FeederSchoolAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.FeederSchoolAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.GeneralStudentProgramAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.GeneralStudentProgramAssociation(BeginDate, EducationOrganizationId, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, ChangeVersion) - VALUES (OLD.BeginDate, OLD.EducationOrganizationId, OLD.ProgramEducationOrganizationId, OLD.ProgramName, OLD.ProgramTypeDescriptorId, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.GeneralStudentProgramAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.GeneralStudentProgramAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.GradeLevelDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.GradeLevelDescriptor(GradeLevelDescriptorId, Id, ChangeVersion) - SELECT OLD.GradeLevelDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.GradeLevelDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.GradeLevelDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.GradeLevelDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.GradePointAverageTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.GradePointAverageTypeDescriptor(GradePointAverageTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.GradePointAverageTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.GradePointAverageTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.GradePointAverageTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.GradePointAverageTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.GradeTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.GradeTypeDescriptor(GradeTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.GradeTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.GradeTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.GradeTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.GradeTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.Grade_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.Grade(BeginDate, GradeTypeDescriptorId, GradingPeriodDescriptorId, GradingPeriodSchoolYear, GradingPeriodSequence, LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, StudentUSI, Id, ChangeVersion) - VALUES (OLD.BeginDate, OLD.GradeTypeDescriptorId, OLD.GradingPeriodDescriptorId, OLD.GradingPeriodSchoolYear, OLD.GradingPeriodSequence, OLD.LocalCourseCode, OLD.SchoolId, OLD.SchoolYear, OLD.SectionIdentifier, OLD.SessionName, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.Grade - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.Grade_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.GradebookEntryTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.GradebookEntryTypeDescriptor(GradebookEntryTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.GradebookEntryTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.GradebookEntryTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.GradebookEntryTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.GradebookEntryTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.GradebookEntry_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.GradebookEntry(DateAssigned, GradebookEntryTitle, LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, Id, ChangeVersion) - VALUES (OLD.DateAssigned, OLD.GradebookEntryTitle, OLD.LocalCourseCode, OLD.SchoolId, OLD.SchoolYear, OLD.SectionIdentifier, OLD.SessionName, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.GradebookEntry - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.GradebookEntry_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.GradingPeriodDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.GradingPeriodDescriptor(GradingPeriodDescriptorId, Id, ChangeVersion) - SELECT OLD.GradingPeriodDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.GradingPeriodDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.GradingPeriodDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.GradingPeriodDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.GradingPeriod_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.GradingPeriod(GradingPeriodDescriptorId, PeriodSequence, SchoolId, SchoolYear, Id, ChangeVersion) - VALUES (OLD.GradingPeriodDescriptorId, OLD.PeriodSequence, OLD.SchoolId, OLD.SchoolYear, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.GradingPeriod - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.GradingPeriod_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.GraduationPlanTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.GraduationPlanTypeDescriptor(GraduationPlanTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.GraduationPlanTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.GraduationPlanTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.GraduationPlanTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.GraduationPlanTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.GraduationPlan_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.GraduationPlan(EducationOrganizationId, GraduationPlanTypeDescriptorId, GraduationSchoolYear, Id, ChangeVersion) - VALUES (OLD.EducationOrganizationId, OLD.GraduationPlanTypeDescriptorId, OLD.GraduationSchoolYear, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.GraduationPlan - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.GraduationPlan_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.GunFreeSchoolsActReportingStatusDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.GunFreeSchoolsActReportingStatusDescriptor(GunFreeSchoolsActReportingStatusDescriptorId, Id, ChangeVersion) - SELECT OLD.GunFreeSchoolsActReportingStatusDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.GunFreeSchoolsActReportingStatusDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.GunFreeSchoolsActReportingStatusDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.GunFreeSchoolsActReportingStatusDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.HomelessPrimaryNighttimeResidenceDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.HomelessPrimaryNighttimeResidenceDescriptor(HomelessPrimaryNighttimeResidenceDescriptorId, Id, ChangeVersion) - SELECT OLD.HomelessPrimaryNighttimeResidenceDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.HomelessPrimaryNighttimeResidenceDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.HomelessPrimaryNighttimeResidenceDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.HomelessPrimaryNighttimeResidenceDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.HomelessProgramServiceDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.HomelessProgramServiceDescriptor(HomelessProgramServiceDescriptorId, Id, ChangeVersion) - SELECT OLD.HomelessProgramServiceDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.HomelessProgramServiceDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.HomelessProgramServiceDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.HomelessProgramServiceDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.IdentificationDocumentUseDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.IdentificationDocumentUseDescriptor(IdentificationDocumentUseDescriptorId, Id, ChangeVersion) - SELECT OLD.IdentificationDocumentUseDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.IdentificationDocumentUseDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.IdentificationDocumentUseDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.IdentificationDocumentUseDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.IncidentLocationDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.IncidentLocationDescriptor(IncidentLocationDescriptorId, Id, ChangeVersion) - SELECT OLD.IncidentLocationDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.IncidentLocationDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.IncidentLocationDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.IncidentLocationDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.IndicatorDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.IndicatorDescriptor(IndicatorDescriptorId, Id, ChangeVersion) - SELECT OLD.IndicatorDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.IndicatorDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.IndicatorDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.IndicatorDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.IndicatorGroupDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.IndicatorGroupDescriptor(IndicatorGroupDescriptorId, Id, ChangeVersion) - SELECT OLD.IndicatorGroupDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.IndicatorGroupDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.IndicatorGroupDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.IndicatorGroupDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.IndicatorLevelDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.IndicatorLevelDescriptor(IndicatorLevelDescriptorId, Id, ChangeVersion) - SELECT OLD.IndicatorLevelDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.IndicatorLevelDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.IndicatorLevelDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.IndicatorLevelDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.InstitutionTelephoneNumberTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.InstitutionTelephoneNumberTypeDescriptor(InstitutionTelephoneNumberTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.InstitutionTelephoneNumberTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.InstitutionTelephoneNumberTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.InstitutionTelephoneNumberTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.InstitutionTelephoneNumberTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.InteractivityStyleDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.InteractivityStyleDescriptor(InteractivityStyleDescriptorId, Id, ChangeVersion) - SELECT OLD.InteractivityStyleDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.InteractivityStyleDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.InteractivityStyleDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.InteractivityStyleDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.InternetAccessDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.InternetAccessDescriptor(InternetAccessDescriptorId, Id, ChangeVersion) - SELECT OLD.InternetAccessDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.InternetAccessDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.InternetAccessDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.InternetAccessDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.InterventionClassDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.InterventionClassDescriptor(InterventionClassDescriptorId, Id, ChangeVersion) - SELECT OLD.InterventionClassDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.InterventionClassDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.InterventionClassDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.InterventionClassDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.InterventionEffectivenessRatingDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.InterventionEffectivenessRatingDescriptor(InterventionEffectivenessRatingDescriptorId, Id, ChangeVersion) - SELECT OLD.InterventionEffectivenessRatingDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.InterventionEffectivenessRatingDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.InterventionEffectivenessRatingDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.InterventionEffectivenessRatingDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.InterventionPrescription_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.InterventionPrescription(EducationOrganizationId, InterventionPrescriptionIdentificationCode, Id, ChangeVersion) - VALUES (OLD.EducationOrganizationId, OLD.InterventionPrescriptionIdentificationCode, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.InterventionPrescription - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.InterventionPrescription_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.InterventionStudy_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.InterventionStudy(EducationOrganizationId, InterventionStudyIdentificationCode, Id, ChangeVersion) - VALUES (OLD.EducationOrganizationId, OLD.InterventionStudyIdentificationCode, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.InterventionStudy - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.InterventionStudy_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.Intervention_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.Intervention(EducationOrganizationId, InterventionIdentificationCode, Id, ChangeVersion) - VALUES (OLD.EducationOrganizationId, OLD.InterventionIdentificationCode, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.Intervention - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.Intervention_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.LanguageDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.LanguageDescriptor(LanguageDescriptorId, Id, ChangeVersion) - SELECT OLD.LanguageDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.LanguageDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.LanguageDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.LanguageDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.LanguageInstructionProgramServiceDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.LanguageInstructionProgramServiceDescriptor(LanguageInstructionProgramServiceDescriptorId, Id, ChangeVersion) - SELECT OLD.LanguageInstructionProgramServiceDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.LanguageInstructionProgramServiceDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.LanguageInstructionProgramServiceDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.LanguageInstructionProgramServiceDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.LanguageUseDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.LanguageUseDescriptor(LanguageUseDescriptorId, Id, ChangeVersion) - SELECT OLD.LanguageUseDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.LanguageUseDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.LanguageUseDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.LanguageUseDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.LearningObjective_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.LearningObjective(LearningObjectiveId, Namespace, Id, ChangeVersion) - VALUES (OLD.LearningObjectiveId, OLD.Namespace, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.LearningObjective - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.LearningObjective_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.LearningStandardCategoryDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.LearningStandardCategoryDescriptor(LearningStandardCategoryDescriptorId, Id, ChangeVersion) - SELECT OLD.LearningStandardCategoryDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.LearningStandardCategoryDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.LearningStandardCategoryDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.LearningStandardCategoryDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.LearningStandardEquivalenceAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.LearningStandardEquivalenceAssociation(Namespace, SourceLearningStandardId, TargetLearningStandardId, Id, ChangeVersion) - VALUES (OLD.Namespace, OLD.SourceLearningStandardId, OLD.TargetLearningStandardId, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.LearningStandardEquivalenceAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.LearningStandardEquivalenceAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.LearningStandardEquivalenceStrengthDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.LearningStandardEquivalenceStrengthDescriptor(LearningStandardEquivalenceStrengthDescriptorId, Id, ChangeVersion) - SELECT OLD.LearningStandardEquivalenceStrengthDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.LearningStandardEquivalenceStrengthDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.LearningStandardEquivalenceStrengthDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.LearningStandardEquivalenceStrengthDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.LearningStandardScopeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.LearningStandardScopeDescriptor(LearningStandardScopeDescriptorId, Id, ChangeVersion) - SELECT OLD.LearningStandardScopeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.LearningStandardScopeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.LearningStandardScopeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.LearningStandardScopeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.LearningStandard_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.LearningStandard(LearningStandardId, Id, ChangeVersion) - VALUES (OLD.LearningStandardId, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.LearningStandard - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.LearningStandard_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.LevelOfEducationDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.LevelOfEducationDescriptor(LevelOfEducationDescriptorId, Id, ChangeVersion) - SELECT OLD.LevelOfEducationDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.LevelOfEducationDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.LevelOfEducationDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.LevelOfEducationDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.LicenseStatusDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.LicenseStatusDescriptor(LicenseStatusDescriptorId, Id, ChangeVersion) - SELECT OLD.LicenseStatusDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.LicenseStatusDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.LicenseStatusDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.LicenseStatusDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.LicenseTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.LicenseTypeDescriptor(LicenseTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.LicenseTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.LicenseTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.LicenseTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.LicenseTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.LimitedEnglishProficiencyDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.LimitedEnglishProficiencyDescriptor(LimitedEnglishProficiencyDescriptorId, Id, ChangeVersion) - SELECT OLD.LimitedEnglishProficiencyDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.LimitedEnglishProficiencyDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.LimitedEnglishProficiencyDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.LimitedEnglishProficiencyDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.LocalEducationAgencyCategoryDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.LocalEducationAgencyCategoryDescriptor(LocalEducationAgencyCategoryDescriptorId, Id, ChangeVersion) - SELECT OLD.LocalEducationAgencyCategoryDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.LocalEducationAgencyCategoryDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.LocalEducationAgencyCategoryDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.LocalEducationAgencyCategoryDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.LocalEducationAgency_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.LocalEducationAgency(LocalEducationAgencyId, Id, ChangeVersion) - SELECT OLD.LocalEducationAgencyId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.EducationOrganization WHERE EducationOrganizationId = OLD.LocalEducationAgencyId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.LocalEducationAgency - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.LocalEducationAgency_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.LocaleDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.LocaleDescriptor(LocaleDescriptorId, Id, ChangeVersion) - SELECT OLD.LocaleDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.LocaleDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.LocaleDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.LocaleDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.Location_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.Location(ClassroomIdentificationCode, SchoolId, Id, ChangeVersion) - VALUES (OLD.ClassroomIdentificationCode, OLD.SchoolId, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.Location - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.Location_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.MagnetSpecialProgramEmphasisSchoolDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.MagnetSpecialProgramEmphasisSchoolDescriptor(MagnetSpecialProgramEmphasisSchoolDescriptorId, Id, ChangeVersion) - SELECT OLD.MagnetSpecialProgramEmphasisSchoolDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.MagnetSpecialProgramEmphasisSchoolDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.MagnetSpecialProgramEmphasisSchoolDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.MagnetSpecialProgramEmphasisSchoolDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.MediumOfInstructionDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.MediumOfInstructionDescriptor(MediumOfInstructionDescriptorId, Id, ChangeVersion) - SELECT OLD.MediumOfInstructionDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.MediumOfInstructionDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.MediumOfInstructionDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.MediumOfInstructionDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.MethodCreditEarnedDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.MethodCreditEarnedDescriptor(MethodCreditEarnedDescriptorId, Id, ChangeVersion) - SELECT OLD.MethodCreditEarnedDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.MethodCreditEarnedDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.MethodCreditEarnedDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.MethodCreditEarnedDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.MigrantEducationProgramServiceDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.MigrantEducationProgramServiceDescriptor(MigrantEducationProgramServiceDescriptorId, Id, ChangeVersion) - SELECT OLD.MigrantEducationProgramServiceDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.MigrantEducationProgramServiceDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.MigrantEducationProgramServiceDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.MigrantEducationProgramServiceDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.MonitoredDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.MonitoredDescriptor(MonitoredDescriptorId, Id, ChangeVersion) - SELECT OLD.MonitoredDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.MonitoredDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.MonitoredDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.MonitoredDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.NeglectedOrDelinquentProgramDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.NeglectedOrDelinquentProgramDescriptor(NeglectedOrDelinquentProgramDescriptorId, Id, ChangeVersion) - SELECT OLD.NeglectedOrDelinquentProgramDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.NeglectedOrDelinquentProgramDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.NeglectedOrDelinquentProgramDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.NeglectedOrDelinquentProgramDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.NeglectedOrDelinquentProgramServiceDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.NeglectedOrDelinquentProgramServiceDescriptor(NeglectedOrDelinquentProgramServiceDescriptorId, Id, ChangeVersion) - SELECT OLD.NeglectedOrDelinquentProgramServiceDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.NeglectedOrDelinquentProgramServiceDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.NeglectedOrDelinquentProgramServiceDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.NeglectedOrDelinquentProgramServiceDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.NetworkPurposeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.NetworkPurposeDescriptor(NetworkPurposeDescriptorId, Id, ChangeVersion) - SELECT OLD.NetworkPurposeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.NetworkPurposeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.NetworkPurposeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.NetworkPurposeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ObjectiveAssessment_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ObjectiveAssessment(AssessmentIdentifier, IdentificationCode, Namespace, Id, ChangeVersion) - VALUES (OLD.AssessmentIdentifier, OLD.IdentificationCode, OLD.Namespace, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ObjectiveAssessment - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ObjectiveAssessment_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.OldEthnicityDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.OldEthnicityDescriptor(OldEthnicityDescriptorId, Id, ChangeVersion) - SELECT OLD.OldEthnicityDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.OldEthnicityDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.OldEthnicityDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.OldEthnicityDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.OpenStaffPosition_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.OpenStaffPosition(EducationOrganizationId, RequisitionNumber, Id, ChangeVersion) - VALUES (OLD.EducationOrganizationId, OLD.RequisitionNumber, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.OpenStaffPosition - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.OpenStaffPosition_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.OperationalStatusDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.OperationalStatusDescriptor(OperationalStatusDescriptorId, Id, ChangeVersion) - SELECT OLD.OperationalStatusDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.OperationalStatusDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.OperationalStatusDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.OperationalStatusDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.OrganizationDepartment_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.OrganizationDepartment(OrganizationDepartmentId, Id, ChangeVersion) - SELECT OLD.OrganizationDepartmentId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.EducationOrganization WHERE EducationOrganizationId = OLD.OrganizationDepartmentId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.OrganizationDepartment - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.OrganizationDepartment_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.OtherNameTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.OtherNameTypeDescriptor(OtherNameTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.OtherNameTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.OtherNameTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.OtherNameTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.OtherNameTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.Parent_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.Parent(ParentUSI, Id, ChangeVersion) - VALUES (OLD.ParentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.Parent - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.Parent_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ParticipationDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ParticipationDescriptor(ParticipationDescriptorId, Id, ChangeVersion) - SELECT OLD.ParticipationDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ParticipationDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ParticipationDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ParticipationDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ParticipationStatusDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ParticipationStatusDescriptor(ParticipationStatusDescriptorId, Id, ChangeVersion) - SELECT OLD.ParticipationStatusDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ParticipationStatusDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ParticipationStatusDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ParticipationStatusDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.Payroll_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.Payroll(AccountIdentifier, AsOfDate, EducationOrganizationId, FiscalYear, StaffUSI, Id, ChangeVersion) - VALUES (OLD.AccountIdentifier, OLD.AsOfDate, OLD.EducationOrganizationId, OLD.FiscalYear, OLD.StaffUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.Payroll - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.Payroll_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.PerformanceBaseConversionDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.PerformanceBaseConversionDescriptor(PerformanceBaseConversionDescriptorId, Id, ChangeVersion) - SELECT OLD.PerformanceBaseConversionDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.PerformanceBaseConversionDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.PerformanceBaseConversionDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.PerformanceBaseConversionDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.PerformanceLevelDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.PerformanceLevelDescriptor(PerformanceLevelDescriptorId, Id, ChangeVersion) - SELECT OLD.PerformanceLevelDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.PerformanceLevelDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.PerformanceLevelDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.PerformanceLevelDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.Person_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.Person(PersonId, SourceSystemDescriptorId, Id, ChangeVersion) - VALUES (OLD.PersonId, OLD.SourceSystemDescriptorId, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.Person - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.Person_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.PersonalInformationVerificationDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.PersonalInformationVerificationDescriptor(PersonalInformationVerificationDescriptorId, Id, ChangeVersion) - SELECT OLD.PersonalInformationVerificationDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.PersonalInformationVerificationDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.PersonalInformationVerificationDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.PersonalInformationVerificationDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.PlatformTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.PlatformTypeDescriptor(PlatformTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.PlatformTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.PlatformTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.PlatformTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.PlatformTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.PopulationServedDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.PopulationServedDescriptor(PopulationServedDescriptorId, Id, ChangeVersion) - SELECT OLD.PopulationServedDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.PopulationServedDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.PopulationServedDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.PopulationServedDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.PostSecondaryEventCategoryDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.PostSecondaryEventCategoryDescriptor(PostSecondaryEventCategoryDescriptorId, Id, ChangeVersion) - SELECT OLD.PostSecondaryEventCategoryDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.PostSecondaryEventCategoryDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.PostSecondaryEventCategoryDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.PostSecondaryEventCategoryDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.PostSecondaryEvent_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.PostSecondaryEvent(EventDate, PostSecondaryEventCategoryDescriptorId, StudentUSI, Id, ChangeVersion) - VALUES (OLD.EventDate, OLD.PostSecondaryEventCategoryDescriptorId, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.PostSecondaryEvent - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.PostSecondaryEvent_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.PostSecondaryInstitutionLevelDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.PostSecondaryInstitutionLevelDescriptor(PostSecondaryInstitutionLevelDescriptorId, Id, ChangeVersion) - SELECT OLD.PostSecondaryInstitutionLevelDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.PostSecondaryInstitutionLevelDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.PostSecondaryInstitutionLevelDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.PostSecondaryInstitutionLevelDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.PostSecondaryInstitution_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.PostSecondaryInstitution(PostSecondaryInstitutionId, Id, ChangeVersion) - SELECT OLD.PostSecondaryInstitutionId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.EducationOrganization WHERE EducationOrganizationId = OLD.PostSecondaryInstitutionId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.PostSecondaryInstitution - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.PostSecondaryInstitution_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.PostingResultDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.PostingResultDescriptor(PostingResultDescriptorId, Id, ChangeVersion) - SELECT OLD.PostingResultDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.PostingResultDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.PostingResultDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.PostingResultDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ProficiencyDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ProficiencyDescriptor(ProficiencyDescriptorId, Id, ChangeVersion) - SELECT OLD.ProficiencyDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ProficiencyDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ProficiencyDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ProficiencyDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ProgramAssignmentDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ProgramAssignmentDescriptor(ProgramAssignmentDescriptorId, Id, ChangeVersion) - SELECT OLD.ProgramAssignmentDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ProgramAssignmentDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ProgramAssignmentDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ProgramAssignmentDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ProgramCharacteristicDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ProgramCharacteristicDescriptor(ProgramCharacteristicDescriptorId, Id, ChangeVersion) - SELECT OLD.ProgramCharacteristicDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ProgramCharacteristicDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ProgramCharacteristicDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ProgramCharacteristicDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ProgramSponsorDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ProgramSponsorDescriptor(ProgramSponsorDescriptorId, Id, ChangeVersion) - SELECT OLD.ProgramSponsorDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ProgramSponsorDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ProgramSponsorDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ProgramSponsorDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ProgramTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ProgramTypeDescriptor(ProgramTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.ProgramTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ProgramTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ProgramTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ProgramTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.Program_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.Program(EducationOrganizationId, ProgramName, ProgramTypeDescriptorId, Id, ChangeVersion) - VALUES (OLD.EducationOrganizationId, OLD.ProgramName, OLD.ProgramTypeDescriptorId, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.Program - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.Program_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ProgressDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ProgressDescriptor(ProgressDescriptorId, Id, ChangeVersion) - SELECT OLD.ProgressDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ProgressDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ProgressDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ProgressDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ProgressLevelDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ProgressLevelDescriptor(ProgressLevelDescriptorId, Id, ChangeVersion) - SELECT OLD.ProgressLevelDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ProgressLevelDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ProgressLevelDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ProgressLevelDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ProviderCategoryDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ProviderCategoryDescriptor(ProviderCategoryDescriptorId, Id, ChangeVersion) - SELECT OLD.ProviderCategoryDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ProviderCategoryDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ProviderCategoryDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ProviderCategoryDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ProviderProfitabilityDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ProviderProfitabilityDescriptor(ProviderProfitabilityDescriptorId, Id, ChangeVersion) - SELECT OLD.ProviderProfitabilityDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ProviderProfitabilityDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ProviderProfitabilityDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ProviderProfitabilityDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ProviderStatusDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ProviderStatusDescriptor(ProviderStatusDescriptorId, Id, ChangeVersion) - SELECT OLD.ProviderStatusDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ProviderStatusDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ProviderStatusDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ProviderStatusDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.PublicationStatusDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.PublicationStatusDescriptor(PublicationStatusDescriptorId, Id, ChangeVersion) - SELECT OLD.PublicationStatusDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.PublicationStatusDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.PublicationStatusDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.PublicationStatusDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.QuestionFormDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.QuestionFormDescriptor(QuestionFormDescriptorId, Id, ChangeVersion) - SELECT OLD.QuestionFormDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.QuestionFormDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.QuestionFormDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.QuestionFormDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.RaceDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.RaceDescriptor(RaceDescriptorId, Id, ChangeVersion) - SELECT OLD.RaceDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.RaceDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.RaceDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.RaceDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ReasonExitedDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ReasonExitedDescriptor(ReasonExitedDescriptorId, Id, ChangeVersion) - SELECT OLD.ReasonExitedDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ReasonExitedDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ReasonExitedDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ReasonExitedDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ReasonNotTestedDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ReasonNotTestedDescriptor(ReasonNotTestedDescriptorId, Id, ChangeVersion) - SELECT OLD.ReasonNotTestedDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ReasonNotTestedDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ReasonNotTestedDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ReasonNotTestedDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.RecognitionTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.RecognitionTypeDescriptor(RecognitionTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.RecognitionTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.RecognitionTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.RecognitionTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.RecognitionTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.RelationDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.RelationDescriptor(RelationDescriptorId, Id, ChangeVersion) - SELECT OLD.RelationDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.RelationDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.RelationDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.RelationDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.RepeatIdentifierDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.RepeatIdentifierDescriptor(RepeatIdentifierDescriptorId, Id, ChangeVersion) - SELECT OLD.RepeatIdentifierDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.RepeatIdentifierDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.RepeatIdentifierDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.RepeatIdentifierDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ReportCard_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ReportCard(EducationOrganizationId, GradingPeriodDescriptorId, GradingPeriodSchoolId, GradingPeriodSchoolYear, GradingPeriodSequence, StudentUSI, Id, ChangeVersion) - VALUES (OLD.EducationOrganizationId, OLD.GradingPeriodDescriptorId, OLD.GradingPeriodSchoolId, OLD.GradingPeriodSchoolYear, OLD.GradingPeriodSequence, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ReportCard - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ReportCard_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ReporterDescriptionDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ReporterDescriptionDescriptor(ReporterDescriptionDescriptorId, Id, ChangeVersion) - SELECT OLD.ReporterDescriptionDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ReporterDescriptionDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ReporterDescriptionDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ReporterDescriptionDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ResidencyStatusDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ResidencyStatusDescriptor(ResidencyStatusDescriptorId, Id, ChangeVersion) - SELECT OLD.ResidencyStatusDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ResidencyStatusDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ResidencyStatusDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ResidencyStatusDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ResponseIndicatorDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ResponseIndicatorDescriptor(ResponseIndicatorDescriptorId, Id, ChangeVersion) - SELECT OLD.ResponseIndicatorDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ResponseIndicatorDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ResponseIndicatorDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ResponseIndicatorDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ResponsibilityDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ResponsibilityDescriptor(ResponsibilityDescriptorId, Id, ChangeVersion) - SELECT OLD.ResponsibilityDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ResponsibilityDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ResponsibilityDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ResponsibilityDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.RestraintEventReasonDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.RestraintEventReasonDescriptor(RestraintEventReasonDescriptorId, Id, ChangeVersion) - SELECT OLD.RestraintEventReasonDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.RestraintEventReasonDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.RestraintEventReasonDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.RestraintEventReasonDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.RestraintEvent_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.RestraintEvent(RestraintEventIdentifier, SchoolId, StudentUSI, Id, ChangeVersion) - VALUES (OLD.RestraintEventIdentifier, OLD.SchoolId, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.RestraintEvent - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.RestraintEvent_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ResultDatatypeTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ResultDatatypeTypeDescriptor(ResultDatatypeTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.ResultDatatypeTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ResultDatatypeTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ResultDatatypeTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ResultDatatypeTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.RetestIndicatorDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.RetestIndicatorDescriptor(RetestIndicatorDescriptorId, Id, ChangeVersion) - SELECT OLD.RetestIndicatorDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.RetestIndicatorDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.RetestIndicatorDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.RetestIndicatorDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SchoolCategoryDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SchoolCategoryDescriptor(SchoolCategoryDescriptorId, Id, ChangeVersion) - SELECT OLD.SchoolCategoryDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.SchoolCategoryDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SchoolCategoryDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SchoolCategoryDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SchoolChoiceImplementStatusDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SchoolChoiceImplementStatusDescriptor(SchoolChoiceImplementStatusDescriptorId, Id, ChangeVersion) - SELECT OLD.SchoolChoiceImplementStatusDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.SchoolChoiceImplementStatusDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SchoolChoiceImplementStatusDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SchoolChoiceImplementStatusDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SchoolFoodServiceProgramServiceDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SchoolFoodServiceProgramServiceDescriptor(SchoolFoodServiceProgramServiceDescriptorId, Id, ChangeVersion) - SELECT OLD.SchoolFoodServiceProgramServiceDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.SchoolFoodServiceProgramServiceDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SchoolFoodServiceProgramServiceDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SchoolFoodServiceProgramServiceDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SchoolTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SchoolTypeDescriptor(SchoolTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.SchoolTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.SchoolTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SchoolTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SchoolTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.School_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.School(SchoolId, Id, ChangeVersion) - SELECT OLD.SchoolId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.EducationOrganization WHERE EducationOrganizationId = OLD.SchoolId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.School - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.School_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SectionAttendanceTakenEvent_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SectionAttendanceTakenEvent(CalendarCode, Date, LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, Id, ChangeVersion) - VALUES (OLD.CalendarCode, OLD.Date, OLD.LocalCourseCode, OLD.SchoolId, OLD.SchoolYear, OLD.SectionIdentifier, OLD.SessionName, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SectionAttendanceTakenEvent - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SectionAttendanceTakenEvent_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SectionCharacteristicDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SectionCharacteristicDescriptor(SectionCharacteristicDescriptorId, Id, ChangeVersion) - SELECT OLD.SectionCharacteristicDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.SectionCharacteristicDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SectionCharacteristicDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SectionCharacteristicDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.Section_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.Section(LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, Id, ChangeVersion) - VALUES (OLD.LocalCourseCode, OLD.SchoolId, OLD.SchoolYear, OLD.SectionIdentifier, OLD.SessionName, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.Section - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.Section_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SeparationDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SeparationDescriptor(SeparationDescriptorId, Id, ChangeVersion) - SELECT OLD.SeparationDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.SeparationDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SeparationDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SeparationDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SeparationReasonDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SeparationReasonDescriptor(SeparationReasonDescriptorId, Id, ChangeVersion) - SELECT OLD.SeparationReasonDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.SeparationReasonDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SeparationReasonDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SeparationReasonDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.ServiceDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.ServiceDescriptor(ServiceDescriptorId, Id, ChangeVersion) - SELECT OLD.ServiceDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.ServiceDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.ServiceDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.ServiceDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.Session_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.Session(SchoolId, SchoolYear, SessionName, Id, ChangeVersion) - VALUES (OLD.SchoolId, OLD.SchoolYear, OLD.SessionName, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.Session - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.Session_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SexDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SexDescriptor(SexDescriptorId, Id, ChangeVersion) - SELECT OLD.SexDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.SexDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SexDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SexDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SourceSystemDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SourceSystemDescriptor(SourceSystemDescriptorId, Id, ChangeVersion) - SELECT OLD.SourceSystemDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.SourceSystemDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SourceSystemDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SourceSystemDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SpecialEducationProgramServiceDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SpecialEducationProgramServiceDescriptor(SpecialEducationProgramServiceDescriptorId, Id, ChangeVersion) - SELECT OLD.SpecialEducationProgramServiceDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.SpecialEducationProgramServiceDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SpecialEducationProgramServiceDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SpecialEducationProgramServiceDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SpecialEducationSettingDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SpecialEducationSettingDescriptor(SpecialEducationSettingDescriptorId, Id, ChangeVersion) - SELECT OLD.SpecialEducationSettingDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.SpecialEducationSettingDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SpecialEducationSettingDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SpecialEducationSettingDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StaffAbsenceEvent_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StaffAbsenceEvent(AbsenceEventCategoryDescriptorId, EventDate, StaffUSI, Id, ChangeVersion) - VALUES (OLD.AbsenceEventCategoryDescriptorId, OLD.EventDate, OLD.StaffUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StaffAbsenceEvent - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StaffAbsenceEvent_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StaffClassificationDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StaffClassificationDescriptor(StaffClassificationDescriptorId, Id, ChangeVersion) - SELECT OLD.StaffClassificationDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.StaffClassificationDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StaffClassificationDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StaffClassificationDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StaffCohortAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StaffCohortAssociation(BeginDate, CohortIdentifier, EducationOrganizationId, StaffUSI, Id, ChangeVersion) - VALUES (OLD.BeginDate, OLD.CohortIdentifier, OLD.EducationOrganizationId, OLD.StaffUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StaffCohortAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StaffCohortAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StaffDisciplineIncidentAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StaffDisciplineIncidentAssociation(IncidentIdentifier, SchoolId, StaffUSI, Id, ChangeVersion) - VALUES (OLD.IncidentIdentifier, OLD.SchoolId, OLD.StaffUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StaffDisciplineIncidentAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StaffDisciplineIncidentAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StaffEducationOrganizationAssignmentAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StaffEducationOrganizationAssignmentAssociation(BeginDate, EducationOrganizationId, StaffClassificationDescriptorId, StaffUSI, Id, ChangeVersion) - VALUES (OLD.BeginDate, OLD.EducationOrganizationId, OLD.StaffClassificationDescriptorId, OLD.StaffUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StaffEducationOrganizationAssignmentAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StaffEducationOrganizationAssignmentAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StaffEducationOrganizationContactAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StaffEducationOrganizationContactAssociation(ContactTitle, EducationOrganizationId, StaffUSI, Id, ChangeVersion) - VALUES (OLD.ContactTitle, OLD.EducationOrganizationId, OLD.StaffUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StaffEducationOrganizationContactAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StaffEducationOrganizationContactAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StaffEducationOrganizationEmploymentAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StaffEducationOrganizationEmploymentAssociation(EducationOrganizationId, EmploymentStatusDescriptorId, HireDate, StaffUSI, Id, ChangeVersion) - VALUES (OLD.EducationOrganizationId, OLD.EmploymentStatusDescriptorId, OLD.HireDate, OLD.StaffUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StaffEducationOrganizationEmploymentAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StaffEducationOrganizationEmploymentAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StaffIdentificationSystemDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StaffIdentificationSystemDescriptor(StaffIdentificationSystemDescriptorId, Id, ChangeVersion) - SELECT OLD.StaffIdentificationSystemDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.StaffIdentificationSystemDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StaffIdentificationSystemDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StaffIdentificationSystemDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StaffLeaveEventCategoryDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StaffLeaveEventCategoryDescriptor(StaffLeaveEventCategoryDescriptorId, Id, ChangeVersion) - SELECT OLD.StaffLeaveEventCategoryDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.StaffLeaveEventCategoryDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StaffLeaveEventCategoryDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StaffLeaveEventCategoryDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StaffLeave_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StaffLeave(BeginDate, StaffLeaveEventCategoryDescriptorId, StaffUSI, Id, ChangeVersion) - VALUES (OLD.BeginDate, OLD.StaffLeaveEventCategoryDescriptorId, OLD.StaffUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StaffLeave - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StaffLeave_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StaffProgramAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StaffProgramAssociation(BeginDate, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StaffUSI, Id, ChangeVersion) - VALUES (OLD.BeginDate, OLD.ProgramEducationOrganizationId, OLD.ProgramName, OLD.ProgramTypeDescriptorId, OLD.StaffUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StaffProgramAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StaffProgramAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StaffSchoolAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StaffSchoolAssociation(ProgramAssignmentDescriptorId, SchoolId, StaffUSI, Id, ChangeVersion) - VALUES (OLD.ProgramAssignmentDescriptorId, OLD.SchoolId, OLD.StaffUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StaffSchoolAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StaffSchoolAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StaffSectionAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StaffSectionAssociation(LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, StaffUSI, Id, ChangeVersion) - VALUES (OLD.LocalCourseCode, OLD.SchoolId, OLD.SchoolYear, OLD.SectionIdentifier, OLD.SessionName, OLD.StaffUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StaffSectionAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StaffSectionAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.Staff_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.Staff(StaffUSI, Id, ChangeVersion) - VALUES (OLD.StaffUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.Staff - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.Staff_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StateAbbreviationDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StateAbbreviationDescriptor(StateAbbreviationDescriptorId, Id, ChangeVersion) - SELECT OLD.StateAbbreviationDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.StateAbbreviationDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StateAbbreviationDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StateAbbreviationDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StateEducationAgency_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StateEducationAgency(StateEducationAgencyId, Id, ChangeVersion) - SELECT OLD.StateEducationAgencyId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.EducationOrganization WHERE EducationOrganizationId = OLD.StateEducationAgencyId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StateEducationAgency - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StateEducationAgency_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentAcademicRecord_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentAcademicRecord(EducationOrganizationId, SchoolYear, StudentUSI, TermDescriptorId, Id, ChangeVersion) - VALUES (OLD.EducationOrganizationId, OLD.SchoolYear, OLD.StudentUSI, OLD.TermDescriptorId, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentAcademicRecord - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentAcademicRecord_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentAssessment_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentAssessment(AssessmentIdentifier, Namespace, StudentAssessmentIdentifier, StudentUSI, Id, ChangeVersion) - VALUES (OLD.AssessmentIdentifier, OLD.Namespace, OLD.StudentAssessmentIdentifier, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentAssessment - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentAssessment_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentCTEProgramAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentCTEProgramAssociation(BeginDate, EducationOrganizationId, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, ChangeVersion) - SELECT OLD.BeginDate, OLD.EducationOrganizationId, OLD.ProgramEducationOrganizationId, OLD.ProgramName, OLD.ProgramTypeDescriptorId, OLD.StudentUSI, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.GeneralStudentProgramAssociation WHERE BeginDate = OLD.BeginDate AND EducationOrganizationId = OLD.EducationOrganizationId AND ProgramEducationOrganizationId = OLD.ProgramEducationOrganizationId AND ProgramName = OLD.ProgramName AND ProgramTypeDescriptorId = OLD.ProgramTypeDescriptorId AND StudentUSI = OLD.StudentUSI; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentCTEProgramAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentCTEProgramAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentCharacteristicDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentCharacteristicDescriptor(StudentCharacteristicDescriptorId, Id, ChangeVersion) - SELECT OLD.StudentCharacteristicDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.StudentCharacteristicDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentCharacteristicDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentCharacteristicDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentCohortAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentCohortAssociation(BeginDate, CohortIdentifier, EducationOrganizationId, StudentUSI, Id, ChangeVersion) - VALUES (OLD.BeginDate, OLD.CohortIdentifier, OLD.EducationOrganizationId, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentCohortAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentCohortAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentCompetencyObjective_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentCompetencyObjective(GradingPeriodDescriptorId, GradingPeriodSchoolId, GradingPeriodSchoolYear, GradingPeriodSequence, Objective, ObjectiveEducationOrganizationId, ObjectiveGradeLevelDescriptorId, StudentUSI, Id, ChangeVersion) - VALUES (OLD.GradingPeriodDescriptorId, OLD.GradingPeriodSchoolId, OLD.GradingPeriodSchoolYear, OLD.GradingPeriodSequence, OLD.Objective, OLD.ObjectiveEducationOrganizationId, OLD.ObjectiveGradeLevelDescriptorId, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentCompetencyObjective - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentCompetencyObjective_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentDisciplineIncidentAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentDisciplineIncidentAssociation(IncidentIdentifier, SchoolId, StudentUSI, Id, ChangeVersion) - VALUES (OLD.IncidentIdentifier, OLD.SchoolId, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentDisciplineIncidentAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentDisciplineIncidentAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentDisciplineIncidentBehaviorAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentDisciplineIncidentBehaviorAssociation(BehaviorDescriptorId, IncidentIdentifier, SchoolId, StudentUSI, Id, ChangeVersion) - VALUES (OLD.BehaviorDescriptorId, OLD.IncidentIdentifier, OLD.SchoolId, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentDisciplineIncidentBehaviorAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentDisciplineIncidentBehaviorAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentDisciplineIncidentNonOffenderAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentDisciplineIncidentNonOffenderAssociation(IncidentIdentifier, SchoolId, StudentUSI, Id, ChangeVersion) - VALUES (OLD.IncidentIdentifier, OLD.SchoolId, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentDisciplineIncidentNonOffenderAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentDisciplineIncidentNonOffenderAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentEducationOrganizationAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentEducationOrganizationAssociation(EducationOrganizationId, StudentUSI, Id, ChangeVersion) - VALUES (OLD.EducationOrganizationId, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentEducationOrganizationAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentEducationOrganizationAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentEducationOrganizationResponsibilityAss_42aa64_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentEducationOrganizationResponsibilityAssociation(BeginDate, EducationOrganizationId, ResponsibilityDescriptorId, StudentUSI, Id, ChangeVersion) - VALUES (OLD.BeginDate, OLD.EducationOrganizationId, OLD.ResponsibilityDescriptorId, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentEducationOrganizationResponsibilityAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentEducationOrganizationResponsibilityAss_42aa64_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentGradebookEntry_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentGradebookEntry(BeginDate, DateAssigned, GradebookEntryTitle, LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, StudentUSI, Id, ChangeVersion) - VALUES (OLD.BeginDate, OLD.DateAssigned, OLD.GradebookEntryTitle, OLD.LocalCourseCode, OLD.SchoolId, OLD.SchoolYear, OLD.SectionIdentifier, OLD.SessionName, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentGradebookEntry - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentGradebookEntry_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentHomelessProgramAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentHomelessProgramAssociation(BeginDate, EducationOrganizationId, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, ChangeVersion) - SELECT OLD.BeginDate, OLD.EducationOrganizationId, OLD.ProgramEducationOrganizationId, OLD.ProgramName, OLD.ProgramTypeDescriptorId, OLD.StudentUSI, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.GeneralStudentProgramAssociation WHERE BeginDate = OLD.BeginDate AND EducationOrganizationId = OLD.EducationOrganizationId AND ProgramEducationOrganizationId = OLD.ProgramEducationOrganizationId AND ProgramName = OLD.ProgramName AND ProgramTypeDescriptorId = OLD.ProgramTypeDescriptorId AND StudentUSI = OLD.StudentUSI; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentHomelessProgramAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentHomelessProgramAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentIdentificationSystemDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentIdentificationSystemDescriptor(StudentIdentificationSystemDescriptorId, Id, ChangeVersion) - SELECT OLD.StudentIdentificationSystemDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.StudentIdentificationSystemDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentIdentificationSystemDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentIdentificationSystemDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentInterventionAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentInterventionAssociation(EducationOrganizationId, InterventionIdentificationCode, StudentUSI, Id, ChangeVersion) - VALUES (OLD.EducationOrganizationId, OLD.InterventionIdentificationCode, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentInterventionAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentInterventionAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentInterventionAttendanceEvent_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentInterventionAttendanceEvent(AttendanceEventCategoryDescriptorId, EducationOrganizationId, EventDate, InterventionIdentificationCode, StudentUSI, Id, ChangeVersion) - VALUES (OLD.AttendanceEventCategoryDescriptorId, OLD.EducationOrganizationId, OLD.EventDate, OLD.InterventionIdentificationCode, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentInterventionAttendanceEvent - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentInterventionAttendanceEvent_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentLanguageInstructionProgramAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentLanguageInstructionProgramAssociation(BeginDate, EducationOrganizationId, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, ChangeVersion) - SELECT OLD.BeginDate, OLD.EducationOrganizationId, OLD.ProgramEducationOrganizationId, OLD.ProgramName, OLD.ProgramTypeDescriptorId, OLD.StudentUSI, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.GeneralStudentProgramAssociation WHERE BeginDate = OLD.BeginDate AND EducationOrganizationId = OLD.EducationOrganizationId AND ProgramEducationOrganizationId = OLD.ProgramEducationOrganizationId AND ProgramName = OLD.ProgramName AND ProgramTypeDescriptorId = OLD.ProgramTypeDescriptorId AND StudentUSI = OLD.StudentUSI; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentLanguageInstructionProgramAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentLanguageInstructionProgramAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentLearningObjective_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentLearningObjective(GradingPeriodDescriptorId, GradingPeriodSchoolId, GradingPeriodSchoolYear, GradingPeriodSequence, LearningObjectiveId, Namespace, StudentUSI, Id, ChangeVersion) - VALUES (OLD.GradingPeriodDescriptorId, OLD.GradingPeriodSchoolId, OLD.GradingPeriodSchoolYear, OLD.GradingPeriodSequence, OLD.LearningObjectiveId, OLD.Namespace, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentLearningObjective - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentLearningObjective_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentMigrantEducationProgramAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentMigrantEducationProgramAssociation(BeginDate, EducationOrganizationId, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, ChangeVersion) - SELECT OLD.BeginDate, OLD.EducationOrganizationId, OLD.ProgramEducationOrganizationId, OLD.ProgramName, OLD.ProgramTypeDescriptorId, OLD.StudentUSI, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.GeneralStudentProgramAssociation WHERE BeginDate = OLD.BeginDate AND EducationOrganizationId = OLD.EducationOrganizationId AND ProgramEducationOrganizationId = OLD.ProgramEducationOrganizationId AND ProgramName = OLD.ProgramName AND ProgramTypeDescriptorId = OLD.ProgramTypeDescriptorId AND StudentUSI = OLD.StudentUSI; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentMigrantEducationProgramAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentMigrantEducationProgramAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentNeglectedOrDelinquentProgramAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentNeglectedOrDelinquentProgramAssociation(BeginDate, EducationOrganizationId, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, ChangeVersion) - SELECT OLD.BeginDate, OLD.EducationOrganizationId, OLD.ProgramEducationOrganizationId, OLD.ProgramName, OLD.ProgramTypeDescriptorId, OLD.StudentUSI, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.GeneralStudentProgramAssociation WHERE BeginDate = OLD.BeginDate AND EducationOrganizationId = OLD.EducationOrganizationId AND ProgramEducationOrganizationId = OLD.ProgramEducationOrganizationId AND ProgramName = OLD.ProgramName AND ProgramTypeDescriptorId = OLD.ProgramTypeDescriptorId AND StudentUSI = OLD.StudentUSI; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentNeglectedOrDelinquentProgramAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentNeglectedOrDelinquentProgramAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentParentAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentParentAssociation(ParentUSI, StudentUSI, Id, ChangeVersion) - VALUES (OLD.ParentUSI, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentParentAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentParentAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentParticipationCodeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentParticipationCodeDescriptor(StudentParticipationCodeDescriptorId, Id, ChangeVersion) - SELECT OLD.StudentParticipationCodeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.StudentParticipationCodeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentParticipationCodeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentParticipationCodeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentProgramAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentProgramAssociation(BeginDate, EducationOrganizationId, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, ChangeVersion) - SELECT OLD.BeginDate, OLD.EducationOrganizationId, OLD.ProgramEducationOrganizationId, OLD.ProgramName, OLD.ProgramTypeDescriptorId, OLD.StudentUSI, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.GeneralStudentProgramAssociation WHERE BeginDate = OLD.BeginDate AND EducationOrganizationId = OLD.EducationOrganizationId AND ProgramEducationOrganizationId = OLD.ProgramEducationOrganizationId AND ProgramName = OLD.ProgramName AND ProgramTypeDescriptorId = OLD.ProgramTypeDescriptorId AND StudentUSI = OLD.StudentUSI; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentProgramAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentProgramAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentProgramAttendanceEvent_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentProgramAttendanceEvent(AttendanceEventCategoryDescriptorId, EducationOrganizationId, EventDate, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, ChangeVersion) - VALUES (OLD.AttendanceEventCategoryDescriptorId, OLD.EducationOrganizationId, OLD.EventDate, OLD.ProgramEducationOrganizationId, OLD.ProgramName, OLD.ProgramTypeDescriptorId, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentProgramAttendanceEvent - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentProgramAttendanceEvent_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentSchoolAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentSchoolAssociation(EntryDate, SchoolId, StudentUSI, Id, ChangeVersion) - VALUES (OLD.EntryDate, OLD.SchoolId, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentSchoolAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentSchoolAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentSchoolAttendanceEvent_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentSchoolAttendanceEvent(AttendanceEventCategoryDescriptorId, EventDate, SchoolId, SchoolYear, SessionName, StudentUSI, Id, ChangeVersion) - VALUES (OLD.AttendanceEventCategoryDescriptorId, OLD.EventDate, OLD.SchoolId, OLD.SchoolYear, OLD.SessionName, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentSchoolAttendanceEvent - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentSchoolAttendanceEvent_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentSchoolFoodServiceProgramAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentSchoolFoodServiceProgramAssociation(BeginDate, EducationOrganizationId, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, ChangeVersion) - SELECT OLD.BeginDate, OLD.EducationOrganizationId, OLD.ProgramEducationOrganizationId, OLD.ProgramName, OLD.ProgramTypeDescriptorId, OLD.StudentUSI, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.GeneralStudentProgramAssociation WHERE BeginDate = OLD.BeginDate AND EducationOrganizationId = OLD.EducationOrganizationId AND ProgramEducationOrganizationId = OLD.ProgramEducationOrganizationId AND ProgramName = OLD.ProgramName AND ProgramTypeDescriptorId = OLD.ProgramTypeDescriptorId AND StudentUSI = OLD.StudentUSI; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentSchoolFoodServiceProgramAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentSchoolFoodServiceProgramAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentSectionAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentSectionAssociation(BeginDate, LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, StudentUSI, Id, ChangeVersion) - VALUES (OLD.BeginDate, OLD.LocalCourseCode, OLD.SchoolId, OLD.SchoolYear, OLD.SectionIdentifier, OLD.SessionName, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentSectionAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentSectionAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentSectionAttendanceEvent_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentSectionAttendanceEvent(AttendanceEventCategoryDescriptorId, EventDate, LocalCourseCode, SchoolId, SchoolYear, SectionIdentifier, SessionName, StudentUSI, Id, ChangeVersion) - VALUES (OLD.AttendanceEventCategoryDescriptorId, OLD.EventDate, OLD.LocalCourseCode, OLD.SchoolId, OLD.SchoolYear, OLD.SectionIdentifier, OLD.SessionName, OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentSectionAttendanceEvent - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentSectionAttendanceEvent_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentSpecialEducationProgramAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentSpecialEducationProgramAssociation(BeginDate, EducationOrganizationId, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, ChangeVersion) - SELECT OLD.BeginDate, OLD.EducationOrganizationId, OLD.ProgramEducationOrganizationId, OLD.ProgramName, OLD.ProgramTypeDescriptorId, OLD.StudentUSI, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.GeneralStudentProgramAssociation WHERE BeginDate = OLD.BeginDate AND EducationOrganizationId = OLD.EducationOrganizationId AND ProgramEducationOrganizationId = OLD.ProgramEducationOrganizationId AND ProgramName = OLD.ProgramName AND ProgramTypeDescriptorId = OLD.ProgramTypeDescriptorId AND StudentUSI = OLD.StudentUSI; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentSpecialEducationProgramAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentSpecialEducationProgramAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.StudentTitleIPartAProgramAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.StudentTitleIPartAProgramAssociation(BeginDate, EducationOrganizationId, ProgramEducationOrganizationId, ProgramName, ProgramTypeDescriptorId, StudentUSI, Id, ChangeVersion) - SELECT OLD.BeginDate, OLD.EducationOrganizationId, OLD.ProgramEducationOrganizationId, OLD.ProgramName, OLD.ProgramTypeDescriptorId, OLD.StudentUSI, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.GeneralStudentProgramAssociation WHERE BeginDate = OLD.BeginDate AND EducationOrganizationId = OLD.EducationOrganizationId AND ProgramEducationOrganizationId = OLD.ProgramEducationOrganizationId AND ProgramName = OLD.ProgramName AND ProgramTypeDescriptorId = OLD.ProgramTypeDescriptorId AND StudentUSI = OLD.StudentUSI; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.StudentTitleIPartAProgramAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.StudentTitleIPartAProgramAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.Student_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.Student(StudentUSI, Id, ChangeVersion) - VALUES (OLD.StudentUSI, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.Student - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.Student_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SurveyCategoryDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SurveyCategoryDescriptor(SurveyCategoryDescriptorId, Id, ChangeVersion) - SELECT OLD.SurveyCategoryDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.SurveyCategoryDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SurveyCategoryDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SurveyCategoryDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SurveyCourseAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SurveyCourseAssociation(CourseCode, EducationOrganizationId, Namespace, SurveyIdentifier, Id, ChangeVersion) - VALUES (OLD.CourseCode, OLD.EducationOrganizationId, OLD.Namespace, OLD.SurveyIdentifier, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SurveyCourseAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SurveyCourseAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SurveyLevelDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SurveyLevelDescriptor(SurveyLevelDescriptorId, Id, ChangeVersion) - SELECT OLD.SurveyLevelDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.SurveyLevelDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SurveyLevelDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SurveyLevelDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SurveyProgramAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SurveyProgramAssociation(EducationOrganizationId, Namespace, ProgramName, ProgramTypeDescriptorId, SurveyIdentifier, Id, ChangeVersion) - VALUES (OLD.EducationOrganizationId, OLD.Namespace, OLD.ProgramName, OLD.ProgramTypeDescriptorId, OLD.SurveyIdentifier, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SurveyProgramAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SurveyProgramAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SurveyQuestionResponse_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SurveyQuestionResponse(Namespace, QuestionCode, SurveyIdentifier, SurveyResponseIdentifier, Id, ChangeVersion) - VALUES (OLD.Namespace, OLD.QuestionCode, OLD.SurveyIdentifier, OLD.SurveyResponseIdentifier, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SurveyQuestionResponse - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SurveyQuestionResponse_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SurveyQuestion_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SurveyQuestion(Namespace, QuestionCode, SurveyIdentifier, Id, ChangeVersion) - VALUES (OLD.Namespace, OLD.QuestionCode, OLD.SurveyIdentifier, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SurveyQuestion - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SurveyQuestion_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SurveyResponseEducationOrganizationTargetAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SurveyResponseEducationOrganizationTargetAssociation(EducationOrganizationId, Namespace, SurveyIdentifier, SurveyResponseIdentifier, Id, ChangeVersion) - VALUES (OLD.EducationOrganizationId, OLD.Namespace, OLD.SurveyIdentifier, OLD.SurveyResponseIdentifier, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SurveyResponseEducationOrganizationTargetAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SurveyResponseEducationOrganizationTargetAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SurveyResponseStaffTargetAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SurveyResponseStaffTargetAssociation(Namespace, StaffUSI, SurveyIdentifier, SurveyResponseIdentifier, Id, ChangeVersion) - VALUES (OLD.Namespace, OLD.StaffUSI, OLD.SurveyIdentifier, OLD.SurveyResponseIdentifier, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SurveyResponseStaffTargetAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SurveyResponseStaffTargetAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SurveyResponse_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SurveyResponse(Namespace, SurveyIdentifier, SurveyResponseIdentifier, Id, ChangeVersion) - VALUES (OLD.Namespace, OLD.SurveyIdentifier, OLD.SurveyResponseIdentifier, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SurveyResponse - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SurveyResponse_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SurveySectionAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SurveySectionAssociation(LocalCourseCode, Namespace, SchoolId, SchoolYear, SectionIdentifier, SessionName, SurveyIdentifier, Id, ChangeVersion) - VALUES (OLD.LocalCourseCode, OLD.Namespace, OLD.SchoolId, OLD.SchoolYear, OLD.SectionIdentifier, OLD.SessionName, OLD.SurveyIdentifier, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SurveySectionAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SurveySectionAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SurveySectionResponseEducationOrganizationTar_730be1_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SurveySectionResponseEducationOrganizationTargetAssociation(EducationOrganizationId, Namespace, SurveyIdentifier, SurveyResponseIdentifier, SurveySectionTitle, Id, ChangeVersion) - VALUES (OLD.EducationOrganizationId, OLD.Namespace, OLD.SurveyIdentifier, OLD.SurveyResponseIdentifier, OLD.SurveySectionTitle, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SurveySectionResponseEducationOrganizationTargetAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SurveySectionResponseEducationOrganizationTar_730be1_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SurveySectionResponseStaffTargetAssociation_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SurveySectionResponseStaffTargetAssociation(Namespace, StaffUSI, SurveyIdentifier, SurveyResponseIdentifier, SurveySectionTitle, Id, ChangeVersion) - VALUES (OLD.Namespace, OLD.StaffUSI, OLD.SurveyIdentifier, OLD.SurveyResponseIdentifier, OLD.SurveySectionTitle, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SurveySectionResponseStaffTargetAssociation - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SurveySectionResponseStaffTargetAssociation_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SurveySectionResponse_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SurveySectionResponse(Namespace, SurveyIdentifier, SurveyResponseIdentifier, SurveySectionTitle, Id, ChangeVersion) - VALUES (OLD.Namespace, OLD.SurveyIdentifier, OLD.SurveyResponseIdentifier, OLD.SurveySectionTitle, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SurveySectionResponse - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SurveySectionResponse_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.SurveySection_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.SurveySection(Namespace, SurveyIdentifier, SurveySectionTitle, Id, ChangeVersion) - VALUES (OLD.Namespace, OLD.SurveyIdentifier, OLD.SurveySectionTitle, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.SurveySection - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.SurveySection_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.Survey_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.Survey(Namespace, SurveyIdentifier, Id, ChangeVersion) - VALUES (OLD.Namespace, OLD.SurveyIdentifier, OLD.Id, nextval('changes.ChangeVersionSequence')); - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.Survey - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.Survey_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.TeachingCredentialBasisDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.TeachingCredentialBasisDescriptor(TeachingCredentialBasisDescriptorId, Id, ChangeVersion) - SELECT OLD.TeachingCredentialBasisDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.TeachingCredentialBasisDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.TeachingCredentialBasisDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.TeachingCredentialBasisDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.TeachingCredentialDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.TeachingCredentialDescriptor(TeachingCredentialDescriptorId, Id, ChangeVersion) - SELECT OLD.TeachingCredentialDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.TeachingCredentialDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.TeachingCredentialDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.TeachingCredentialDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.TechnicalSkillsAssessmentDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.TechnicalSkillsAssessmentDescriptor(TechnicalSkillsAssessmentDescriptorId, Id, ChangeVersion) - SELECT OLD.TechnicalSkillsAssessmentDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.TechnicalSkillsAssessmentDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.TechnicalSkillsAssessmentDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.TechnicalSkillsAssessmentDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.TelephoneNumberTypeDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.TelephoneNumberTypeDescriptor(TelephoneNumberTypeDescriptorId, Id, ChangeVersion) - SELECT OLD.TelephoneNumberTypeDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.TelephoneNumberTypeDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.TelephoneNumberTypeDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.TelephoneNumberTypeDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.TermDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.TermDescriptor(TermDescriptorId, Id, ChangeVersion) - SELECT OLD.TermDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.TermDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.TermDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.TermDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.TitleIPartAParticipantDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.TitleIPartAParticipantDescriptor(TitleIPartAParticipantDescriptorId, Id, ChangeVersion) - SELECT OLD.TitleIPartAParticipantDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.TitleIPartAParticipantDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.TitleIPartAParticipantDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.TitleIPartAParticipantDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.TitleIPartAProgramServiceDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.TitleIPartAProgramServiceDescriptor(TitleIPartAProgramServiceDescriptorId, Id, ChangeVersion) - SELECT OLD.TitleIPartAProgramServiceDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.TitleIPartAProgramServiceDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.TitleIPartAProgramServiceDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.TitleIPartAProgramServiceDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.TitleIPartASchoolDesignationDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.TitleIPartASchoolDesignationDescriptor(TitleIPartASchoolDesignationDescriptorId, Id, ChangeVersion) - SELECT OLD.TitleIPartASchoolDesignationDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.TitleIPartASchoolDesignationDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.TitleIPartASchoolDesignationDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.TitleIPartASchoolDesignationDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.TribalAffiliationDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.TribalAffiliationDescriptor(TribalAffiliationDescriptorId, Id, ChangeVersion) - SELECT OLD.TribalAffiliationDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.TribalAffiliationDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.TribalAffiliationDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.TribalAffiliationDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.VisaDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.VisaDescriptor(VisaDescriptorId, Id, ChangeVersion) - SELECT OLD.VisaDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.VisaDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.VisaDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.VisaDescriptor_TR_DelTrkg(); - -CREATE FUNCTION tracked_deletes_edfi.WeaponDescriptor_TR_DelTrkg() - RETURNS trigger AS -$BODY$ -BEGIN - INSERT INTO tracked_deletes_edfi.WeaponDescriptor(WeaponDescriptorId, Id, ChangeVersion) - SELECT OLD.WeaponDescriptorId, Id, nextval('changes.ChangeVersionSequence') - FROM edfi.Descriptor WHERE DescriptorId = OLD.WeaponDescriptorId; - RETURN NULL; -END; -$BODY$ LANGUAGE plpgsql; - -CREATE TRIGGER TrackDeletes AFTER DELETE ON edfi.WeaponDescriptor - FOR EACH ROW EXECUTE PROCEDURE tracked_deletes_edfi.WeaponDescriptor_TR_DelTrkg(); - diff --git a/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0070-AddIndexChangeVersionForTables.sql b/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0070-AddIndexChangeVersionForTables.sql index d2006ba2e3..b0af2bb0a0 100644 --- a/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0070-AddIndexChangeVersionForTables.sql +++ b/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0070-AddIndexChangeVersionForTables.sql @@ -3,201 +3,201 @@ -- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. -- See the LICENSE and NOTICES files in the project root for more information. -CREATE INDEX IF NOT EXISTS UX_a97956_ChangeVersion ON edfi.AcademicWeek(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_a97956_changeversion ON edfi.academicweek(changeversion); -CREATE INDEX IF NOT EXISTS UX_7e1b0d_ChangeVersion ON edfi.Account(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_7e1b0d_changeversion ON edfi.account(changeversion); -CREATE INDEX IF NOT EXISTS UX_fb1ef3_ChangeVersion ON edfi.AccountCode(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_2d3c0c_changeversion ON edfi.accountabilityrating(changeversion); -CREATE INDEX IF NOT EXISTS UX_2d3c0c_ChangeVersion ON edfi.AccountabilityRating(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_fb1ef3_changeversion ON edfi.accountcode(changeversion); -CREATE INDEX IF NOT EXISTS UX_c40642_ChangeVersion ON edfi.Actual(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_c40642_changeversion ON edfi.actual(changeversion); -CREATE INDEX IF NOT EXISTS UX_7808ee_ChangeVersion ON edfi.Assessment(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_7808ee_changeversion ON edfi.assessment(changeversion); -CREATE INDEX IF NOT EXISTS UX_dc3dcf_ChangeVersion ON edfi.AssessmentItem(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_dc3dcf_changeversion ON edfi.assessmentitem(changeversion); -CREATE INDEX IF NOT EXISTS UX_a20588_ChangeVersion ON edfi.AssessmentScoreRangeLearningStandard(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_a20588_changeversion ON edfi.assessmentscorerangelearningstandard(changeversion); -CREATE INDEX IF NOT EXISTS UX_9bbaf5_ChangeVersion ON edfi.BellSchedule(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_9bbaf5_changeversion ON edfi.bellschedule(changeversion); -CREATE INDEX IF NOT EXISTS UX_1c6225_ChangeVersion ON edfi.Budget(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_1c6225_changeversion ON edfi.budget(changeversion); -CREATE INDEX IF NOT EXISTS UX_d5d0a3_ChangeVersion ON edfi.Calendar(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_d5d0a3_changeversion ON edfi.calendar(changeversion); -CREATE INDEX IF NOT EXISTS UX_8a9a67_ChangeVersion ON edfi.CalendarDate(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_8a9a67_changeversion ON edfi.calendardate(changeversion); -CREATE INDEX IF NOT EXISTS UX_01fe80_ChangeVersion ON edfi.ClassPeriod(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_01fe80_changeversion ON edfi.classperiod(changeversion); -CREATE INDEX IF NOT EXISTS UX_19c6d6_ChangeVersion ON edfi.Cohort(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_19c6d6_changeversion ON edfi.cohort(changeversion); -CREATE INDEX IF NOT EXISTS UX_f092ff_ChangeVersion ON edfi.CommunityProviderLicense(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_f092ff_changeversion ON edfi.communityproviderlicense(changeversion); -CREATE INDEX IF NOT EXISTS UX_5e9932_ChangeVersion ON edfi.CompetencyObjective(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_5e9932_changeversion ON edfi.competencyobjective(changeversion); -CREATE INDEX IF NOT EXISTS UX_57ca0f_ChangeVersion ON edfi.ContractedStaff(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_57ca0f_changeversion ON edfi.contractedstaff(changeversion); -CREATE INDEX IF NOT EXISTS UX_2096ce_ChangeVersion ON edfi.Course(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_2096ce_changeversion ON edfi.course(changeversion); -CREATE INDEX IF NOT EXISTS UX_0325c5_ChangeVersion ON edfi.CourseOffering(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_0325c5_changeversion ON edfi.courseoffering(changeversion); -CREATE INDEX IF NOT EXISTS UX_6acf2b_ChangeVersion ON edfi.CourseTranscript(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_6acf2b_changeversion ON edfi.coursetranscript(changeversion); -CREATE INDEX IF NOT EXISTS UX_b1c42b_ChangeVersion ON edfi.Credential(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_b1c42b_changeversion ON edfi.credential(changeversion); -CREATE INDEX IF NOT EXISTS UX_219915_ChangeVersion ON edfi.Descriptor(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_219915_changeversion ON edfi.descriptor(changeversion); -CREATE INDEX IF NOT EXISTS UX_eec7b6_ChangeVersion ON edfi.DisciplineAction(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_eec7b6_changeversion ON edfi.disciplineaction(changeversion); -CREATE INDEX IF NOT EXISTS UX_e45c0b_ChangeVersion ON edfi.DisciplineIncident(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_e45c0b_changeversion ON edfi.disciplineincident(changeversion); -CREATE INDEX IF NOT EXISTS UX_9965a5_ChangeVersion ON edfi.EducationContent(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_9965a5_changeversion ON edfi.educationcontent(changeversion); -CREATE INDEX IF NOT EXISTS UX_4525e6_ChangeVersion ON edfi.EducationOrganization(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_4525e6_changeversion ON edfi.educationorganization(changeversion); -CREATE INDEX IF NOT EXISTS UX_e670ae_ChangeVersion ON edfi.EducationOrganizationInterventionPrescriptionAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_e670ae_changeversion ON edfi.educationorganizationinterventionprescriptionassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_252151_ChangeVersion ON edfi.EducationOrganizationNetworkAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_252151_changeversion ON edfi.educationorganizationnetworkassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_74e4e5_ChangeVersion ON edfi.EducationOrganizationPeerAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_74e4e5_changeversion ON edfi.educationorganizationpeerassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_11f7b6_ChangeVersion ON edfi.FeederSchoolAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_11f7b6_changeversion ON edfi.feederschoolassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_0516f9_ChangeVersion ON edfi.GeneralStudentProgramAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_0516f9_changeversion ON edfi.generalstudentprogramassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_839e20_ChangeVersion ON edfi.Grade(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_839e20_changeversion ON edfi.grade(changeversion); -CREATE INDEX IF NOT EXISTS UX_466cfa_ChangeVersion ON edfi.GradebookEntry(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_466cfa_changeversion ON edfi.gradebookentry(changeversion); -CREATE INDEX IF NOT EXISTS UX_5a18f9_ChangeVersion ON edfi.GradingPeriod(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_5a18f9_changeversion ON edfi.gradingperiod(changeversion); -CREATE INDEX IF NOT EXISTS UX_be1ea4_ChangeVersion ON edfi.GraduationPlan(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_be1ea4_changeversion ON edfi.graduationplan(changeversion); -CREATE INDEX IF NOT EXISTS UX_0fae05_ChangeVersion ON edfi.Intervention(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_0fae05_changeversion ON edfi.intervention(changeversion); -CREATE INDEX IF NOT EXISTS UX_e93bc3_ChangeVersion ON edfi.InterventionPrescription(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_e93bc3_changeversion ON edfi.interventionprescription(changeversion); -CREATE INDEX IF NOT EXISTS UX_d92986_ChangeVersion ON edfi.InterventionStudy(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_d92986_changeversion ON edfi.interventionstudy(changeversion); -CREATE INDEX IF NOT EXISTS UX_588d15_ChangeVersion ON edfi.LearningObjective(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_588d15_changeversion ON edfi.learningobjective(changeversion); -CREATE INDEX IF NOT EXISTS UX_8ceb4c_ChangeVersion ON edfi.LearningStandard(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_8ceb4c_changeversion ON edfi.learningstandard(changeversion); -CREATE INDEX IF NOT EXISTS UX_17c02a_ChangeVersion ON edfi.LearningStandardEquivalenceAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_17c02a_changeversion ON edfi.learningstandardequivalenceassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_15b619_ChangeVersion ON edfi.Location(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_15b619_changeversion ON edfi.location(changeversion); -CREATE INDEX IF NOT EXISTS UX_269e10_ChangeVersion ON edfi.ObjectiveAssessment(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_269e10_changeversion ON edfi.objectiveassessment(changeversion); -CREATE INDEX IF NOT EXISTS UX_3cc1d4_ChangeVersion ON edfi.OpenStaffPosition(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_3cc1d4_changeversion ON edfi.openstaffposition(changeversion); -CREATE INDEX IF NOT EXISTS UX_5f7953_ChangeVersion ON edfi.Parent(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_5f7953_changeversion ON edfi.parent(changeversion); -CREATE INDEX IF NOT EXISTS UX_53fe8d_ChangeVersion ON edfi.Payroll(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_53fe8d_changeversion ON edfi.payroll(changeversion); -CREATE INDEX IF NOT EXISTS UX_6007db_ChangeVersion ON edfi.Person(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_6007db_changeversion ON edfi.person(changeversion); -CREATE INDEX IF NOT EXISTS UX_b8b6d7_ChangeVersion ON edfi.PostSecondaryEvent(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_b8b6d7_changeversion ON edfi.postsecondaryevent(changeversion); -CREATE INDEX IF NOT EXISTS UX_90920d_ChangeVersion ON edfi.Program(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_90920d_changeversion ON edfi.program(changeversion); -CREATE INDEX IF NOT EXISTS UX_ec1992_ChangeVersion ON edfi.ReportCard(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_ec1992_changeversion ON edfi.reportcard(changeversion); -CREATE INDEX IF NOT EXISTS UX_3800be_ChangeVersion ON edfi.RestraintEvent(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_3800be_changeversion ON edfi.restraintevent(changeversion); -CREATE INDEX IF NOT EXISTS UX_464d7a_ChangeVersion ON edfi.SchoolYearType(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_464d7a_changeversion ON edfi.schoolyeartype(changeversion); -CREATE INDEX IF NOT EXISTS UX_dfca5d_ChangeVersion ON edfi.Section(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_dfca5d_changeversion ON edfi.section(changeversion); -CREATE INDEX IF NOT EXISTS UX_7bbbe7_ChangeVersion ON edfi.SectionAttendanceTakenEvent(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_7bbbe7_changeversion ON edfi.sectionattendancetakenevent(changeversion); -CREATE INDEX IF NOT EXISTS UX_6959b4_ChangeVersion ON edfi.Session(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_6959b4_changeversion ON edfi.session(changeversion); -CREATE INDEX IF NOT EXISTS UX_681927_ChangeVersion ON edfi.Staff(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_681927_changeversion ON edfi.staff(changeversion); -CREATE INDEX IF NOT EXISTS UX_b13bbd_ChangeVersion ON edfi.StaffAbsenceEvent(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_b13bbd_changeversion ON edfi.staffabsenceevent(changeversion); -CREATE INDEX IF NOT EXISTS UX_170747_ChangeVersion ON edfi.StaffCohortAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_170747_changeversion ON edfi.staffcohortassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_af86db_ChangeVersion ON edfi.StaffDisciplineIncidentAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_af86db_changeversion ON edfi.staffdisciplineincidentassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_b9be24_ChangeVersion ON edfi.StaffEducationOrganizationAssignmentAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_b9be24_changeversion ON edfi.staffeducationorganizationassignmentassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_735dd8_ChangeVersion ON edfi.StaffEducationOrganizationContactAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_735dd8_changeversion ON edfi.staffeducationorganizationcontactassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_4e79b9_ChangeVersion ON edfi.StaffEducationOrganizationEmploymentAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_4e79b9_changeversion ON edfi.staffeducationorganizationemploymentassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_debd4f_ChangeVersion ON edfi.StaffLeave(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_debd4f_changeversion ON edfi.staffleave(changeversion); -CREATE INDEX IF NOT EXISTS UX_a9c0d9_ChangeVersion ON edfi.StaffProgramAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_a9c0d9_changeversion ON edfi.staffprogramassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_ce2080_ChangeVersion ON edfi.StaffSchoolAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_ce2080_changeversion ON edfi.staffschoolassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_515cb5_ChangeVersion ON edfi.StaffSectionAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_515cb5_changeversion ON edfi.staffsectionassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_2a164d_ChangeVersion ON edfi.Student(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_2a164d_changeversion ON edfi.student(changeversion); -CREATE INDEX IF NOT EXISTS UX_0ff8d6_ChangeVersion ON edfi.StudentAcademicRecord(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_0ff8d6_changeversion ON edfi.studentacademicrecord(changeversion); -CREATE INDEX IF NOT EXISTS UX_ee3b2a_ChangeVersion ON edfi.StudentAssessment(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_ee3b2a_changeversion ON edfi.studentassessment(changeversion); -CREATE INDEX IF NOT EXISTS UX_369ddc_ChangeVersion ON edfi.StudentCohortAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_369ddc_changeversion ON edfi.studentcohortassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_395c07_ChangeVersion ON edfi.StudentCompetencyObjective(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_395c07_changeversion ON edfi.studentcompetencyobjective(changeversion); -CREATE INDEX IF NOT EXISTS UX_679174_ChangeVersion ON edfi.StudentDisciplineIncidentAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_679174_changeversion ON edfi.studentdisciplineincidentassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_f4934f_ChangeVersion ON edfi.StudentDisciplineIncidentBehaviorAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_f4934f_changeversion ON edfi.studentdisciplineincidentbehaviorassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_4b43da_ChangeVersion ON edfi.StudentDisciplineIncidentNonOffenderAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_4b43da_changeversion ON edfi.studentdisciplineincidentnonoffenderassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_8e1257_ChangeVersion ON edfi.StudentEducationOrganizationAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_8e1257_changeversion ON edfi.studenteducationorganizationassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_42aa64_ChangeVersion ON edfi.StudentEducationOrganizationResponsibilityAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_42aa64_changeversion ON edfi.studenteducationorganizationresponsibilityassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_c2efaa_ChangeVersion ON edfi.StudentGradebookEntry(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_c2efaa_changeversion ON edfi.studentgradebookentry(changeversion); -CREATE INDEX IF NOT EXISTS UX_25cb9c_ChangeVersion ON edfi.StudentInterventionAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_25cb9c_changeversion ON edfi.studentinterventionassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_631023_ChangeVersion ON edfi.StudentInterventionAttendanceEvent(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_631023_changeversion ON edfi.studentinterventionattendanceevent(changeversion); -CREATE INDEX IF NOT EXISTS UX_baaa9d_ChangeVersion ON edfi.StudentLearningObjective(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_baaa9d_changeversion ON edfi.studentlearningobjective(changeversion); -CREATE INDEX IF NOT EXISTS UX_bf9d92_ChangeVersion ON edfi.StudentParentAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_bf9d92_changeversion ON edfi.studentparentassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_317aeb_ChangeVersion ON edfi.StudentProgramAttendanceEvent(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_317aeb_changeversion ON edfi.studentprogramattendanceevent(changeversion); -CREATE INDEX IF NOT EXISTS UX_857b52_ChangeVersion ON edfi.StudentSchoolAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_857b52_changeversion ON edfi.studentschoolassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_78fd7f_ChangeVersion ON edfi.StudentSchoolAttendanceEvent(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_78fd7f_changeversion ON edfi.studentschoolattendanceevent(changeversion); -CREATE INDEX IF NOT EXISTS UX_39aa3c_ChangeVersion ON edfi.StudentSectionAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_39aa3c_changeversion ON edfi.studentsectionassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_61b087_ChangeVersion ON edfi.StudentSectionAttendanceEvent(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_61b087_changeversion ON edfi.studentsectionattendanceevent(changeversion); -CREATE INDEX IF NOT EXISTS UX_211bb3_ChangeVersion ON edfi.Survey(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_211bb3_changeversion ON edfi.survey(changeversion); -CREATE INDEX IF NOT EXISTS UX_9f1246_ChangeVersion ON edfi.SurveyCourseAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_9f1246_changeversion ON edfi.surveycourseassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_e3e5a4_ChangeVersion ON edfi.SurveyProgramAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_e3e5a4_changeversion ON edfi.surveyprogramassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_1bb88c_ChangeVersion ON edfi.SurveyQuestion(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_1bb88c_changeversion ON edfi.surveyquestion(changeversion); -CREATE INDEX IF NOT EXISTS UX_eddd02_ChangeVersion ON edfi.SurveyQuestionResponse(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_eddd02_changeversion ON edfi.surveyquestionresponse(changeversion); -CREATE INDEX IF NOT EXISTS UX_8d6383_ChangeVersion ON edfi.SurveyResponse(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_8d6383_changeversion ON edfi.surveyresponse(changeversion); -CREATE INDEX IF NOT EXISTS UX_b2bd0a_ChangeVersion ON edfi.SurveyResponseEducationOrganizationTargetAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_b2bd0a_changeversion ON edfi.surveyresponseeducationorganizationtargetassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_f9457e_ChangeVersion ON edfi.SurveyResponseStaffTargetAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_f9457e_changeversion ON edfi.surveyresponsestafftargetassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_e5572a_ChangeVersion ON edfi.SurveySection(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_e5572a_changeversion ON edfi.surveysection(changeversion); -CREATE INDEX IF NOT EXISTS UX_c16804_ChangeVersion ON edfi.SurveySectionAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_c16804_changeversion ON edfi.surveysectionassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_2189c3_ChangeVersion ON edfi.SurveySectionResponse(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_2189c3_changeversion ON edfi.surveysectionresponse(changeversion); -CREATE INDEX IF NOT EXISTS UX_730be1_ChangeVersion ON edfi.SurveySectionResponseEducationOrganizationTargetAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_730be1_changeversion ON edfi.surveysectionresponseeducationorganizationtargetassociation(changeversion); -CREATE INDEX IF NOT EXISTS UX_39073d_ChangeVersion ON edfi.SurveySectionResponseStaffTargetAssociation(ChangeVersion); +CREATE INDEX IF NOT EXISTS ux_39073d_changeversion ON edfi.surveysectionresponsestafftargetassociation(changeversion); diff --git a/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0200-CreateTrackedChangeTables.sql b/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0200-CreateTrackedChangeTables.sql new file mode 100644 index 0000000000..1db985fea4 --- /dev/null +++ b/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0200-CreateTrackedChangeTables.sql @@ -0,0 +1,2042 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +DO $$ +BEGIN + +IF NOT EXISTS (SELECT 1 FROM information_schema.schemata WHERE schema_name = 'tracked_changes_edfi') THEN +CREATE SCHEMA tracked_changes_edfi; +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'academicweek') THEN +CREATE TABLE tracked_changes_edfi.academicweek +( + oldschoolid integer NOT NULL, + oldweekidentifier varchar(80) NOT NULL, + newschoolid integer NULL, + newweekidentifier varchar(80) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT academicweek_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'account') THEN +CREATE TABLE tracked_changes_edfi.account +( + oldaccountidentifier varchar(50) NOT NULL, + oldeducationorganizationid integer NOT NULL, + oldfiscalyear integer NOT NULL, + newaccountidentifier varchar(50) NULL, + neweducationorganizationid integer NULL, + newfiscalyear integer NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT account_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'accountabilityrating') THEN +CREATE TABLE tracked_changes_edfi.accountabilityrating +( + oldeducationorganizationid integer NOT NULL, + oldratingtitle varchar(60) NOT NULL, + oldschoolyear smallint NOT NULL, + neweducationorganizationid integer NULL, + newratingtitle varchar(60) NULL, + newschoolyear smallint NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT accountabilityrating_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'accountcode') THEN +CREATE TABLE tracked_changes_edfi.accountcode +( + oldaccountclassificationdescriptorid integer NOT NULL, + oldaccountclassificationdescriptornamespace varchar(255) NOT NULL, + oldaccountclassificationdescriptorcodevalue varchar(50) NOT NULL, + oldaccountcodenumber varchar(50) NOT NULL, + oldeducationorganizationid integer NOT NULL, + oldfiscalyear integer NOT NULL, + newaccountclassificationdescriptorid integer NULL, + newaccountclassificationdescriptornamespace varchar(255) NULL, + newaccountclassificationdescriptorcodevalue varchar(50) NULL, + newaccountcodenumber varchar(50) NULL, + neweducationorganizationid integer NULL, + newfiscalyear integer NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT accountcode_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'actual') THEN +CREATE TABLE tracked_changes_edfi.actual +( + oldaccountidentifier varchar(50) NOT NULL, + oldasofdate date NOT NULL, + oldeducationorganizationid integer NOT NULL, + oldfiscalyear integer NOT NULL, + newaccountidentifier varchar(50) NULL, + newasofdate date NULL, + neweducationorganizationid integer NULL, + newfiscalyear integer NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT actual_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'assessment') THEN +CREATE TABLE tracked_changes_edfi.assessment +( + oldassessmentidentifier varchar(60) NOT NULL, + oldnamespace varchar(255) NOT NULL, + newassessmentidentifier varchar(60) NULL, + newnamespace varchar(255) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT assessment_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'assessmentitem') THEN +CREATE TABLE tracked_changes_edfi.assessmentitem +( + oldassessmentidentifier varchar(60) NOT NULL, + oldidentificationcode varchar(60) NOT NULL, + oldnamespace varchar(255) NOT NULL, + newassessmentidentifier varchar(60) NULL, + newidentificationcode varchar(60) NULL, + newnamespace varchar(255) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT assessmentitem_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'assessmentscorerangelearningstandard') THEN +CREATE TABLE tracked_changes_edfi.assessmentscorerangelearningstandard +( + oldassessmentidentifier varchar(60) NOT NULL, + oldnamespace varchar(255) NOT NULL, + oldscorerangeid varchar(60) NOT NULL, + newassessmentidentifier varchar(60) NULL, + newnamespace varchar(255) NULL, + newscorerangeid varchar(60) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT assessmentscorerangelearningstandard_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'bellschedule') THEN +CREATE TABLE tracked_changes_edfi.bellschedule +( + oldbellschedulename varchar(60) NOT NULL, + oldschoolid integer NOT NULL, + newbellschedulename varchar(60) NULL, + newschoolid integer NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT bellschedule_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'budget') THEN +CREATE TABLE tracked_changes_edfi.budget +( + oldaccountidentifier varchar(50) NOT NULL, + oldasofdate date NOT NULL, + oldeducationorganizationid integer NOT NULL, + oldfiscalyear integer NOT NULL, + newaccountidentifier varchar(50) NULL, + newasofdate date NULL, + neweducationorganizationid integer NULL, + newfiscalyear integer NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT budget_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'calendar') THEN +CREATE TABLE tracked_changes_edfi.calendar +( + oldcalendarcode varchar(60) NOT NULL, + oldschoolid integer NOT NULL, + oldschoolyear smallint NOT NULL, + newcalendarcode varchar(60) NULL, + newschoolid integer NULL, + newschoolyear smallint NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT calendar_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'calendardate') THEN +CREATE TABLE tracked_changes_edfi.calendardate +( + oldcalendarcode varchar(60) NOT NULL, + olddate date NOT NULL, + oldschoolid integer NOT NULL, + oldschoolyear smallint NOT NULL, + newcalendarcode varchar(60) NULL, + newdate date NULL, + newschoolid integer NULL, + newschoolyear smallint NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT calendardate_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'classperiod') THEN +CREATE TABLE tracked_changes_edfi.classperiod +( + oldclassperiodname varchar(60) NOT NULL, + oldschoolid integer NOT NULL, + newclassperiodname varchar(60) NULL, + newschoolid integer NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT classperiod_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'cohort') THEN +CREATE TABLE tracked_changes_edfi.cohort +( + oldcohortidentifier varchar(20) NOT NULL, + oldeducationorganizationid integer NOT NULL, + newcohortidentifier varchar(20) NULL, + neweducationorganizationid integer NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT cohort_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'communityproviderlicense') THEN +CREATE TABLE tracked_changes_edfi.communityproviderlicense +( + oldcommunityproviderid integer NOT NULL, + oldlicenseidentifier varchar(20) NOT NULL, + oldlicensingorganization varchar(75) NOT NULL, + newcommunityproviderid integer NULL, + newlicenseidentifier varchar(20) NULL, + newlicensingorganization varchar(75) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT communityproviderlicense_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'competencyobjective') THEN +CREATE TABLE tracked_changes_edfi.competencyobjective +( + oldeducationorganizationid integer NOT NULL, + oldobjective varchar(60) NOT NULL, + oldobjectivegradeleveldescriptorid integer NOT NULL, + oldobjectivegradeleveldescriptornamespace varchar(255) NOT NULL, + oldobjectivegradeleveldescriptorcodevalue varchar(50) NOT NULL, + neweducationorganizationid integer NULL, + newobjective varchar(60) NULL, + newobjectivegradeleveldescriptorid integer NULL, + newobjectivegradeleveldescriptornamespace varchar(255) NULL, + newobjectivegradeleveldescriptorcodevalue varchar(50) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT competencyobjective_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'contractedstaff') THEN +CREATE TABLE tracked_changes_edfi.contractedstaff +( + oldaccountidentifier varchar(50) NOT NULL, + oldasofdate date NOT NULL, + oldeducationorganizationid integer NOT NULL, + oldfiscalyear integer NOT NULL, + oldstaffusi integer NOT NULL, + oldstaffuniqueid varchar(32) NOT NULL, + newaccountidentifier varchar(50) NULL, + newasofdate date NULL, + neweducationorganizationid integer NULL, + newfiscalyear integer NULL, + newstaffusi integer NULL, + newstaffuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT contractedstaff_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'course') THEN +CREATE TABLE tracked_changes_edfi.course +( + oldcoursecode varchar(60) NOT NULL, + oldeducationorganizationid integer NOT NULL, + newcoursecode varchar(60) NULL, + neweducationorganizationid integer NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT course_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'courseoffering') THEN +CREATE TABLE tracked_changes_edfi.courseoffering +( + oldlocalcoursecode varchar(60) NOT NULL, + oldschoolid integer NOT NULL, + oldschoolyear smallint NOT NULL, + oldsessionname varchar(60) NOT NULL, + newlocalcoursecode varchar(60) NULL, + newschoolid integer NULL, + newschoolyear smallint NULL, + newsessionname varchar(60) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT courseoffering_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'coursetranscript') THEN +CREATE TABLE tracked_changes_edfi.coursetranscript +( + oldcourseattemptresultdescriptorid integer NOT NULL, + oldcourseattemptresultdescriptornamespace varchar(255) NOT NULL, + oldcourseattemptresultdescriptorcodevalue varchar(50) NOT NULL, + oldcoursecode varchar(60) NOT NULL, + oldcourseeducationorganizationid integer NOT NULL, + oldeducationorganizationid integer NOT NULL, + oldschoolyear smallint NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + oldtermdescriptorid integer NOT NULL, + oldtermdescriptornamespace varchar(255) NOT NULL, + oldtermdescriptorcodevalue varchar(50) NOT NULL, + newcourseattemptresultdescriptorid integer NULL, + newcourseattemptresultdescriptornamespace varchar(255) NULL, + newcourseattemptresultdescriptorcodevalue varchar(50) NULL, + newcoursecode varchar(60) NULL, + newcourseeducationorganizationid integer NULL, + neweducationorganizationid integer NULL, + newschoolyear smallint NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + newtermdescriptorid integer NULL, + newtermdescriptornamespace varchar(255) NULL, + newtermdescriptorcodevalue varchar(50) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT coursetranscript_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'credential') THEN +CREATE TABLE tracked_changes_edfi.credential +( + oldcredentialidentifier varchar(60) NOT NULL, + oldstateofissuestateabbreviationdescriptorid integer NOT NULL, + oldstateofissuestateabbreviationdescriptornamespace varchar(255) NOT NULL, + oldstateofissuestateabbreviationdescriptorcodevalue varchar(50) NOT NULL, + newcredentialidentifier varchar(60) NULL, + newstateofissuestateabbreviationdescriptorid integer NULL, + newstateofissuestateabbreviationdescriptornamespace varchar(255) NULL, + newstateofissuestateabbreviationdescriptorcodevalue varchar(50) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT credential_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'descriptor') THEN +CREATE TABLE tracked_changes_edfi.descriptor +( + olddescriptorid integer NOT NULL, + oldcodevalue varchar(50) NOT NULL, + oldnamespace varchar(255) NOT NULL, + newdescriptorid integer NULL, + newcodevalue varchar(50) NULL, + newnamespace varchar(255) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT descriptor_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'disciplineaction') THEN +CREATE TABLE tracked_changes_edfi.disciplineaction +( + olddisciplineactionidentifier varchar(20) NOT NULL, + olddisciplinedate date NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + newdisciplineactionidentifier varchar(20) NULL, + newdisciplinedate date NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT disciplineaction_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'disciplineincident') THEN +CREATE TABLE tracked_changes_edfi.disciplineincident +( + oldincidentidentifier varchar(20) NOT NULL, + oldschoolid integer NOT NULL, + newincidentidentifier varchar(20) NULL, + newschoolid integer NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT disciplineincident_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'educationcontent') THEN +CREATE TABLE tracked_changes_edfi.educationcontent +( + oldcontentidentifier varchar(225) NOT NULL, + newcontentidentifier varchar(225) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT educationcontent_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'educationorganization') THEN +CREATE TABLE tracked_changes_edfi.educationorganization +( + oldeducationorganizationid integer NOT NULL, + neweducationorganizationid integer NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT educationorganization_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'educationorganizationinterventionprescriptionassociation') THEN +CREATE TABLE tracked_changes_edfi.educationorganizationinterventionprescriptionassociation +( + oldeducationorganizationid integer NOT NULL, + oldinterventionprescriptioneducationorganizationid integer NOT NULL, + oldinterventionprescriptionidentificationcode varchar(60) NOT NULL, + neweducationorganizationid integer NULL, + newinterventionprescriptioneducationorganizationid integer NULL, + newinterventionprescriptionidentificationcode varchar(60) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT educationorganizationinterventionprescriptionassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'educationorganizationnetworkassociation') THEN +CREATE TABLE tracked_changes_edfi.educationorganizationnetworkassociation +( + oldeducationorganizationnetworkid integer NOT NULL, + oldmembereducationorganizationid integer NOT NULL, + neweducationorganizationnetworkid integer NULL, + newmembereducationorganizationid integer NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT educationorganizationnetworkassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'educationorganizationpeerassociation') THEN +CREATE TABLE tracked_changes_edfi.educationorganizationpeerassociation +( + oldeducationorganizationid integer NOT NULL, + oldpeereducationorganizationid integer NOT NULL, + neweducationorganizationid integer NULL, + newpeereducationorganizationid integer NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT educationorganizationpeerassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'feederschoolassociation') THEN +CREATE TABLE tracked_changes_edfi.feederschoolassociation +( + oldbegindate date NOT NULL, + oldfeederschoolid integer NOT NULL, + oldschoolid integer NOT NULL, + newbegindate date NULL, + newfeederschoolid integer NULL, + newschoolid integer NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT feederschoolassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'generalstudentprogramassociation') THEN +CREATE TABLE tracked_changes_edfi.generalstudentprogramassociation +( + oldbegindate date NOT NULL, + oldeducationorganizationid integer NOT NULL, + oldprogrameducationorganizationid integer NOT NULL, + oldprogramname varchar(60) NOT NULL, + oldprogramtypedescriptorid integer NOT NULL, + oldprogramtypedescriptornamespace varchar(255) NOT NULL, + oldprogramtypedescriptorcodevalue varchar(50) NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + newbegindate date NULL, + neweducationorganizationid integer NULL, + newprogrameducationorganizationid integer NULL, + newprogramname varchar(60) NULL, + newprogramtypedescriptorid integer NULL, + newprogramtypedescriptornamespace varchar(255) NULL, + newprogramtypedescriptorcodevalue varchar(50) NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT generalstudentprogramassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'grade') THEN +CREATE TABLE tracked_changes_edfi.grade +( + oldbegindate date NOT NULL, + oldgradetypedescriptorid integer NOT NULL, + oldgradetypedescriptornamespace varchar(255) NOT NULL, + oldgradetypedescriptorcodevalue varchar(50) NOT NULL, + oldgradingperioddescriptorid integer NOT NULL, + oldgradingperioddescriptornamespace varchar(255) NOT NULL, + oldgradingperioddescriptorcodevalue varchar(50) NOT NULL, + oldgradingperiodschoolyear smallint NOT NULL, + oldgradingperiodsequence integer NOT NULL, + oldlocalcoursecode varchar(60) NOT NULL, + oldschoolid integer NOT NULL, + oldschoolyear smallint NOT NULL, + oldsectionidentifier varchar(255) NOT NULL, + oldsessionname varchar(60) NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + newbegindate date NULL, + newgradetypedescriptorid integer NULL, + newgradetypedescriptornamespace varchar(255) NULL, + newgradetypedescriptorcodevalue varchar(50) NULL, + newgradingperioddescriptorid integer NULL, + newgradingperioddescriptornamespace varchar(255) NULL, + newgradingperioddescriptorcodevalue varchar(50) NULL, + newgradingperiodschoolyear smallint NULL, + newgradingperiodsequence integer NULL, + newlocalcoursecode varchar(60) NULL, + newschoolid integer NULL, + newschoolyear smallint NULL, + newsectionidentifier varchar(255) NULL, + newsessionname varchar(60) NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT grade_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'gradebookentry') THEN +CREATE TABLE tracked_changes_edfi.gradebookentry +( + olddateassigned date NOT NULL, + oldgradebookentrytitle varchar(60) NOT NULL, + oldlocalcoursecode varchar(60) NOT NULL, + oldschoolid integer NOT NULL, + oldschoolyear smallint NOT NULL, + oldsectionidentifier varchar(255) NOT NULL, + oldsessionname varchar(60) NOT NULL, + newdateassigned date NULL, + newgradebookentrytitle varchar(60) NULL, + newlocalcoursecode varchar(60) NULL, + newschoolid integer NULL, + newschoolyear smallint NULL, + newsectionidentifier varchar(255) NULL, + newsessionname varchar(60) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT gradebookentry_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'gradingperiod') THEN +CREATE TABLE tracked_changes_edfi.gradingperiod +( + oldgradingperioddescriptorid integer NOT NULL, + oldgradingperioddescriptornamespace varchar(255) NOT NULL, + oldgradingperioddescriptorcodevalue varchar(50) NOT NULL, + oldperiodsequence integer NOT NULL, + oldschoolid integer NOT NULL, + oldschoolyear smallint NOT NULL, + newgradingperioddescriptorid integer NULL, + newgradingperioddescriptornamespace varchar(255) NULL, + newgradingperioddescriptorcodevalue varchar(50) NULL, + newperiodsequence integer NULL, + newschoolid integer NULL, + newschoolyear smallint NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT gradingperiod_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'graduationplan') THEN +CREATE TABLE tracked_changes_edfi.graduationplan +( + oldeducationorganizationid integer NOT NULL, + oldgraduationplantypedescriptorid integer NOT NULL, + oldgraduationplantypedescriptornamespace varchar(255) NOT NULL, + oldgraduationplantypedescriptorcodevalue varchar(50) NOT NULL, + oldgraduationschoolyear smallint NOT NULL, + neweducationorganizationid integer NULL, + newgraduationplantypedescriptorid integer NULL, + newgraduationplantypedescriptornamespace varchar(255) NULL, + newgraduationplantypedescriptorcodevalue varchar(50) NULL, + newgraduationschoolyear smallint NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT graduationplan_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'intervention') THEN +CREATE TABLE tracked_changes_edfi.intervention +( + oldeducationorganizationid integer NOT NULL, + oldinterventionidentificationcode varchar(60) NOT NULL, + neweducationorganizationid integer NULL, + newinterventionidentificationcode varchar(60) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT intervention_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'interventionprescription') THEN +CREATE TABLE tracked_changes_edfi.interventionprescription +( + oldeducationorganizationid integer NOT NULL, + oldinterventionprescriptionidentificationcode varchar(60) NOT NULL, + neweducationorganizationid integer NULL, + newinterventionprescriptionidentificationcode varchar(60) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT interventionprescription_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'interventionstudy') THEN +CREATE TABLE tracked_changes_edfi.interventionstudy +( + oldeducationorganizationid integer NOT NULL, + oldinterventionstudyidentificationcode varchar(60) NOT NULL, + neweducationorganizationid integer NULL, + newinterventionstudyidentificationcode varchar(60) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT interventionstudy_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'learningobjective') THEN +CREATE TABLE tracked_changes_edfi.learningobjective +( + oldlearningobjectiveid varchar(60) NOT NULL, + oldnamespace varchar(255) NOT NULL, + newlearningobjectiveid varchar(60) NULL, + newnamespace varchar(255) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT learningobjective_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'learningstandard') THEN +CREATE TABLE tracked_changes_edfi.learningstandard +( + oldlearningstandardid varchar(60) NOT NULL, + newlearningstandardid varchar(60) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT learningstandard_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'learningstandardequivalenceassociation') THEN +CREATE TABLE tracked_changes_edfi.learningstandardequivalenceassociation +( + oldnamespace varchar(255) NOT NULL, + oldsourcelearningstandardid varchar(60) NOT NULL, + oldtargetlearningstandardid varchar(60) NOT NULL, + newnamespace varchar(255) NULL, + newsourcelearningstandardid varchar(60) NULL, + newtargetlearningstandardid varchar(60) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT learningstandardequivalenceassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'location') THEN +CREATE TABLE tracked_changes_edfi.location +( + oldclassroomidentificationcode varchar(60) NOT NULL, + oldschoolid integer NOT NULL, + newclassroomidentificationcode varchar(60) NULL, + newschoolid integer NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT location_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'objectiveassessment') THEN +CREATE TABLE tracked_changes_edfi.objectiveassessment +( + oldassessmentidentifier varchar(60) NOT NULL, + oldidentificationcode varchar(60) NOT NULL, + oldnamespace varchar(255) NOT NULL, + newassessmentidentifier varchar(60) NULL, + newidentificationcode varchar(60) NULL, + newnamespace varchar(255) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT objectiveassessment_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'openstaffposition') THEN +CREATE TABLE tracked_changes_edfi.openstaffposition +( + oldeducationorganizationid integer NOT NULL, + oldrequisitionnumber varchar(20) NOT NULL, + neweducationorganizationid integer NULL, + newrequisitionnumber varchar(20) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT openstaffposition_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'parent') THEN +CREATE TABLE tracked_changes_edfi.parent +( + oldparentusi integer NOT NULL, + oldparentuniqueid varchar(32) NOT NULL, + newparentusi integer NULL, + newparentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT parent_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'payroll') THEN +CREATE TABLE tracked_changes_edfi.payroll +( + oldaccountidentifier varchar(50) NOT NULL, + oldasofdate date NOT NULL, + oldeducationorganizationid integer NOT NULL, + oldfiscalyear integer NOT NULL, + oldstaffusi integer NOT NULL, + oldstaffuniqueid varchar(32) NOT NULL, + newaccountidentifier varchar(50) NULL, + newasofdate date NULL, + neweducationorganizationid integer NULL, + newfiscalyear integer NULL, + newstaffusi integer NULL, + newstaffuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT payroll_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'person') THEN +CREATE TABLE tracked_changes_edfi.person +( + oldpersonid varchar(32) NOT NULL, + oldsourcesystemdescriptorid integer NOT NULL, + oldsourcesystemdescriptornamespace varchar(255) NOT NULL, + oldsourcesystemdescriptorcodevalue varchar(50) NOT NULL, + newpersonid varchar(32) NULL, + newsourcesystemdescriptorid integer NULL, + newsourcesystemdescriptornamespace varchar(255) NULL, + newsourcesystemdescriptorcodevalue varchar(50) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT person_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'postsecondaryevent') THEN +CREATE TABLE tracked_changes_edfi.postsecondaryevent +( + oldeventdate date NOT NULL, + oldpostsecondaryeventcategorydescriptorid integer NOT NULL, + oldpostsecondaryeventcategorydescriptornamespace varchar(255) NOT NULL, + oldpostsecondaryeventcategorydescriptorcodevalue varchar(50) NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + neweventdate date NULL, + newpostsecondaryeventcategorydescriptorid integer NULL, + newpostsecondaryeventcategorydescriptornamespace varchar(255) NULL, + newpostsecondaryeventcategorydescriptorcodevalue varchar(50) NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT postsecondaryevent_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'program') THEN +CREATE TABLE tracked_changes_edfi.program +( + oldeducationorganizationid integer NOT NULL, + oldprogramname varchar(60) NOT NULL, + oldprogramtypedescriptorid integer NOT NULL, + oldprogramtypedescriptornamespace varchar(255) NOT NULL, + oldprogramtypedescriptorcodevalue varchar(50) NOT NULL, + neweducationorganizationid integer NULL, + newprogramname varchar(60) NULL, + newprogramtypedescriptorid integer NULL, + newprogramtypedescriptornamespace varchar(255) NULL, + newprogramtypedescriptorcodevalue varchar(50) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT program_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'reportcard') THEN +CREATE TABLE tracked_changes_edfi.reportcard +( + oldeducationorganizationid integer NOT NULL, + oldgradingperioddescriptorid integer NOT NULL, + oldgradingperioddescriptornamespace varchar(255) NOT NULL, + oldgradingperioddescriptorcodevalue varchar(50) NOT NULL, + oldgradingperiodschoolid integer NOT NULL, + oldgradingperiodschoolyear smallint NOT NULL, + oldgradingperiodsequence integer NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + neweducationorganizationid integer NULL, + newgradingperioddescriptorid integer NULL, + newgradingperioddescriptornamespace varchar(255) NULL, + newgradingperioddescriptorcodevalue varchar(50) NULL, + newgradingperiodschoolid integer NULL, + newgradingperiodschoolyear smallint NULL, + newgradingperiodsequence integer NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT reportcard_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'restraintevent') THEN +CREATE TABLE tracked_changes_edfi.restraintevent +( + oldrestrainteventidentifier varchar(20) NOT NULL, + oldschoolid integer NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + newrestrainteventidentifier varchar(20) NULL, + newschoolid integer NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT restraintevent_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'schoolyeartype') THEN +CREATE TABLE tracked_changes_edfi.schoolyeartype +( + oldschoolyear smallint NOT NULL, + newschoolyear smallint NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT schoolyeartype_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'section') THEN +CREATE TABLE tracked_changes_edfi.section +( + oldlocalcoursecode varchar(60) NOT NULL, + oldschoolid integer NOT NULL, + oldschoolyear smallint NOT NULL, + oldsectionidentifier varchar(255) NOT NULL, + oldsessionname varchar(60) NOT NULL, + newlocalcoursecode varchar(60) NULL, + newschoolid integer NULL, + newschoolyear smallint NULL, + newsectionidentifier varchar(255) NULL, + newsessionname varchar(60) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT section_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'sectionattendancetakenevent') THEN +CREATE TABLE tracked_changes_edfi.sectionattendancetakenevent +( + oldcalendarcode varchar(60) NOT NULL, + olddate date NOT NULL, + oldlocalcoursecode varchar(60) NOT NULL, + oldschoolid integer NOT NULL, + oldschoolyear smallint NOT NULL, + oldsectionidentifier varchar(255) NOT NULL, + oldsessionname varchar(60) NOT NULL, + newcalendarcode varchar(60) NULL, + newdate date NULL, + newlocalcoursecode varchar(60) NULL, + newschoolid integer NULL, + newschoolyear smallint NULL, + newsectionidentifier varchar(255) NULL, + newsessionname varchar(60) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT sectionattendancetakenevent_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'session') THEN +CREATE TABLE tracked_changes_edfi.session +( + oldschoolid integer NOT NULL, + oldschoolyear smallint NOT NULL, + oldsessionname varchar(60) NOT NULL, + newschoolid integer NULL, + newschoolyear smallint NULL, + newsessionname varchar(60) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT session_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'staff') THEN +CREATE TABLE tracked_changes_edfi.staff +( + oldstaffusi integer NOT NULL, + oldstaffuniqueid varchar(32) NOT NULL, + newstaffusi integer NULL, + newstaffuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT staff_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'staffabsenceevent') THEN +CREATE TABLE tracked_changes_edfi.staffabsenceevent +( + oldabsenceeventcategorydescriptorid integer NOT NULL, + oldabsenceeventcategorydescriptornamespace varchar(255) NOT NULL, + oldabsenceeventcategorydescriptorcodevalue varchar(50) NOT NULL, + oldeventdate date NOT NULL, + oldstaffusi integer NOT NULL, + oldstaffuniqueid varchar(32) NOT NULL, + newabsenceeventcategorydescriptorid integer NULL, + newabsenceeventcategorydescriptornamespace varchar(255) NULL, + newabsenceeventcategorydescriptorcodevalue varchar(50) NULL, + neweventdate date NULL, + newstaffusi integer NULL, + newstaffuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT staffabsenceevent_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'staffcohortassociation') THEN +CREATE TABLE tracked_changes_edfi.staffcohortassociation +( + oldbegindate date NOT NULL, + oldcohortidentifier varchar(20) NOT NULL, + oldeducationorganizationid integer NOT NULL, + oldstaffusi integer NOT NULL, + oldstaffuniqueid varchar(32) NOT NULL, + newbegindate date NULL, + newcohortidentifier varchar(20) NULL, + neweducationorganizationid integer NULL, + newstaffusi integer NULL, + newstaffuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT staffcohortassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'staffdisciplineincidentassociation') THEN +CREATE TABLE tracked_changes_edfi.staffdisciplineincidentassociation +( + oldincidentidentifier varchar(20) NOT NULL, + oldschoolid integer NOT NULL, + oldstaffusi integer NOT NULL, + oldstaffuniqueid varchar(32) NOT NULL, + newincidentidentifier varchar(20) NULL, + newschoolid integer NULL, + newstaffusi integer NULL, + newstaffuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT staffdisciplineincidentassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'staffeducationorganizationassignmentassociation') THEN +CREATE TABLE tracked_changes_edfi.staffeducationorganizationassignmentassociation +( + oldbegindate date NOT NULL, + oldeducationorganizationid integer NOT NULL, + oldstaffclassificationdescriptorid integer NOT NULL, + oldstaffclassificationdescriptornamespace varchar(255) NOT NULL, + oldstaffclassificationdescriptorcodevalue varchar(50) NOT NULL, + oldstaffusi integer NOT NULL, + oldstaffuniqueid varchar(32) NOT NULL, + newbegindate date NULL, + neweducationorganizationid integer NULL, + newstaffclassificationdescriptorid integer NULL, + newstaffclassificationdescriptornamespace varchar(255) NULL, + newstaffclassificationdescriptorcodevalue varchar(50) NULL, + newstaffusi integer NULL, + newstaffuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT staffeducationorganizationassignmentassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'staffeducationorganizationcontactassociation') THEN +CREATE TABLE tracked_changes_edfi.staffeducationorganizationcontactassociation +( + oldcontacttitle varchar(75) NOT NULL, + oldeducationorganizationid integer NOT NULL, + oldstaffusi integer NOT NULL, + oldstaffuniqueid varchar(32) NOT NULL, + newcontacttitle varchar(75) NULL, + neweducationorganizationid integer NULL, + newstaffusi integer NULL, + newstaffuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT staffeducationorganizationcontactassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'staffeducationorganizationemploymentassociation') THEN +CREATE TABLE tracked_changes_edfi.staffeducationorganizationemploymentassociation +( + oldeducationorganizationid integer NOT NULL, + oldemploymentstatusdescriptorid integer NOT NULL, + oldemploymentstatusdescriptornamespace varchar(255) NOT NULL, + oldemploymentstatusdescriptorcodevalue varchar(50) NOT NULL, + oldhiredate date NOT NULL, + oldstaffusi integer NOT NULL, + oldstaffuniqueid varchar(32) NOT NULL, + neweducationorganizationid integer NULL, + newemploymentstatusdescriptorid integer NULL, + newemploymentstatusdescriptornamespace varchar(255) NULL, + newemploymentstatusdescriptorcodevalue varchar(50) NULL, + newhiredate date NULL, + newstaffusi integer NULL, + newstaffuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT staffeducationorganizationemploymentassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'staffleave') THEN +CREATE TABLE tracked_changes_edfi.staffleave +( + oldbegindate date NOT NULL, + oldstaffleaveeventcategorydescriptorid integer NOT NULL, + oldstaffleaveeventcategorydescriptornamespace varchar(255) NOT NULL, + oldstaffleaveeventcategorydescriptorcodevalue varchar(50) NOT NULL, + oldstaffusi integer NOT NULL, + oldstaffuniqueid varchar(32) NOT NULL, + newbegindate date NULL, + newstaffleaveeventcategorydescriptorid integer NULL, + newstaffleaveeventcategorydescriptornamespace varchar(255) NULL, + newstaffleaveeventcategorydescriptorcodevalue varchar(50) NULL, + newstaffusi integer NULL, + newstaffuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT staffleave_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'staffprogramassociation') THEN +CREATE TABLE tracked_changes_edfi.staffprogramassociation +( + oldbegindate date NOT NULL, + oldprogrameducationorganizationid integer NOT NULL, + oldprogramname varchar(60) NOT NULL, + oldprogramtypedescriptorid integer NOT NULL, + oldprogramtypedescriptornamespace varchar(255) NOT NULL, + oldprogramtypedescriptorcodevalue varchar(50) NOT NULL, + oldstaffusi integer NOT NULL, + oldstaffuniqueid varchar(32) NOT NULL, + newbegindate date NULL, + newprogrameducationorganizationid integer NULL, + newprogramname varchar(60) NULL, + newprogramtypedescriptorid integer NULL, + newprogramtypedescriptornamespace varchar(255) NULL, + newprogramtypedescriptorcodevalue varchar(50) NULL, + newstaffusi integer NULL, + newstaffuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT staffprogramassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'staffschoolassociation') THEN +CREATE TABLE tracked_changes_edfi.staffschoolassociation +( + oldprogramassignmentdescriptorid integer NOT NULL, + oldprogramassignmentdescriptornamespace varchar(255) NOT NULL, + oldprogramassignmentdescriptorcodevalue varchar(50) NOT NULL, + oldschoolid integer NOT NULL, + oldstaffusi integer NOT NULL, + oldstaffuniqueid varchar(32) NOT NULL, + newprogramassignmentdescriptorid integer NULL, + newprogramassignmentdescriptornamespace varchar(255) NULL, + newprogramassignmentdescriptorcodevalue varchar(50) NULL, + newschoolid integer NULL, + newstaffusi integer NULL, + newstaffuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT staffschoolassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'staffsectionassociation') THEN +CREATE TABLE tracked_changes_edfi.staffsectionassociation +( + oldlocalcoursecode varchar(60) NOT NULL, + oldschoolid integer NOT NULL, + oldschoolyear smallint NOT NULL, + oldsectionidentifier varchar(255) NOT NULL, + oldsessionname varchar(60) NOT NULL, + oldstaffusi integer NOT NULL, + oldstaffuniqueid varchar(32) NOT NULL, + newlocalcoursecode varchar(60) NULL, + newschoolid integer NULL, + newschoolyear smallint NULL, + newsectionidentifier varchar(255) NULL, + newsessionname varchar(60) NULL, + newstaffusi integer NULL, + newstaffuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT staffsectionassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'student') THEN +CREATE TABLE tracked_changes_edfi.student +( + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT student_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'studentacademicrecord') THEN +CREATE TABLE tracked_changes_edfi.studentacademicrecord +( + oldeducationorganizationid integer NOT NULL, + oldschoolyear smallint NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + oldtermdescriptorid integer NOT NULL, + oldtermdescriptornamespace varchar(255) NOT NULL, + oldtermdescriptorcodevalue varchar(50) NOT NULL, + neweducationorganizationid integer NULL, + newschoolyear smallint NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + newtermdescriptorid integer NULL, + newtermdescriptornamespace varchar(255) NULL, + newtermdescriptorcodevalue varchar(50) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT studentacademicrecord_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'studentassessment') THEN +CREATE TABLE tracked_changes_edfi.studentassessment +( + oldassessmentidentifier varchar(60) NOT NULL, + oldnamespace varchar(255) NOT NULL, + oldstudentassessmentidentifier varchar(60) NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + newassessmentidentifier varchar(60) NULL, + newnamespace varchar(255) NULL, + newstudentassessmentidentifier varchar(60) NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT studentassessment_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'studentcohortassociation') THEN +CREATE TABLE tracked_changes_edfi.studentcohortassociation +( + oldbegindate date NOT NULL, + oldcohortidentifier varchar(20) NOT NULL, + oldeducationorganizationid integer NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + newbegindate date NULL, + newcohortidentifier varchar(20) NULL, + neweducationorganizationid integer NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT studentcohortassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'studentcompetencyobjective') THEN +CREATE TABLE tracked_changes_edfi.studentcompetencyobjective +( + oldgradingperioddescriptorid integer NOT NULL, + oldgradingperioddescriptornamespace varchar(255) NOT NULL, + oldgradingperioddescriptorcodevalue varchar(50) NOT NULL, + oldgradingperiodschoolid integer NOT NULL, + oldgradingperiodschoolyear smallint NOT NULL, + oldgradingperiodsequence integer NOT NULL, + oldobjective varchar(60) NOT NULL, + oldobjectiveeducationorganizationid integer NOT NULL, + oldobjectivegradeleveldescriptorid integer NOT NULL, + oldobjectivegradeleveldescriptornamespace varchar(255) NOT NULL, + oldobjectivegradeleveldescriptorcodevalue varchar(50) NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + newgradingperioddescriptorid integer NULL, + newgradingperioddescriptornamespace varchar(255) NULL, + newgradingperioddescriptorcodevalue varchar(50) NULL, + newgradingperiodschoolid integer NULL, + newgradingperiodschoolyear smallint NULL, + newgradingperiodsequence integer NULL, + newobjective varchar(60) NULL, + newobjectiveeducationorganizationid integer NULL, + newobjectivegradeleveldescriptorid integer NULL, + newobjectivegradeleveldescriptornamespace varchar(255) NULL, + newobjectivegradeleveldescriptorcodevalue varchar(50) NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT studentcompetencyobjective_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'studentdisciplineincidentassociation') THEN +CREATE TABLE tracked_changes_edfi.studentdisciplineincidentassociation +( + oldincidentidentifier varchar(20) NOT NULL, + oldschoolid integer NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + newincidentidentifier varchar(20) NULL, + newschoolid integer NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT studentdisciplineincidentassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'studentdisciplineincidentbehaviorassociation') THEN +CREATE TABLE tracked_changes_edfi.studentdisciplineincidentbehaviorassociation +( + oldbehaviordescriptorid integer NOT NULL, + oldbehaviordescriptornamespace varchar(255) NOT NULL, + oldbehaviordescriptorcodevalue varchar(50) NOT NULL, + oldincidentidentifier varchar(20) NOT NULL, + oldschoolid integer NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + newbehaviordescriptorid integer NULL, + newbehaviordescriptornamespace varchar(255) NULL, + newbehaviordescriptorcodevalue varchar(50) NULL, + newincidentidentifier varchar(20) NULL, + newschoolid integer NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT studentdisciplineincidentbehaviorassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'studentdisciplineincidentnonoffenderassociation') THEN +CREATE TABLE tracked_changes_edfi.studentdisciplineincidentnonoffenderassociation +( + oldincidentidentifier varchar(20) NOT NULL, + oldschoolid integer NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + newincidentidentifier varchar(20) NULL, + newschoolid integer NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT studentdisciplineincidentnonoffenderassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'studenteducationorganizationassociation') THEN +CREATE TABLE tracked_changes_edfi.studenteducationorganizationassociation +( + oldeducationorganizationid integer NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + neweducationorganizationid integer NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT studenteducationorganizationassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'studenteducationorganizationresponsibilityassociation') THEN +CREATE TABLE tracked_changes_edfi.studenteducationorganizationresponsibilityassociation +( + oldbegindate date NOT NULL, + oldeducationorganizationid integer NOT NULL, + oldresponsibilitydescriptorid integer NOT NULL, + oldresponsibilitydescriptornamespace varchar(255) NOT NULL, + oldresponsibilitydescriptorcodevalue varchar(50) NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + newbegindate date NULL, + neweducationorganizationid integer NULL, + newresponsibilitydescriptorid integer NULL, + newresponsibilitydescriptornamespace varchar(255) NULL, + newresponsibilitydescriptorcodevalue varchar(50) NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT studenteducationorganizationresponsibilityassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'studentgradebookentry') THEN +CREATE TABLE tracked_changes_edfi.studentgradebookentry +( + oldbegindate date NOT NULL, + olddateassigned date NOT NULL, + oldgradebookentrytitle varchar(60) NOT NULL, + oldlocalcoursecode varchar(60) NOT NULL, + oldschoolid integer NOT NULL, + oldschoolyear smallint NOT NULL, + oldsectionidentifier varchar(255) NOT NULL, + oldsessionname varchar(60) NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + newbegindate date NULL, + newdateassigned date NULL, + newgradebookentrytitle varchar(60) NULL, + newlocalcoursecode varchar(60) NULL, + newschoolid integer NULL, + newschoolyear smallint NULL, + newsectionidentifier varchar(255) NULL, + newsessionname varchar(60) NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT studentgradebookentry_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'studentinterventionassociation') THEN +CREATE TABLE tracked_changes_edfi.studentinterventionassociation +( + oldeducationorganizationid integer NOT NULL, + oldinterventionidentificationcode varchar(60) NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + neweducationorganizationid integer NULL, + newinterventionidentificationcode varchar(60) NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT studentinterventionassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'studentinterventionattendanceevent') THEN +CREATE TABLE tracked_changes_edfi.studentinterventionattendanceevent +( + oldattendanceeventcategorydescriptorid integer NOT NULL, + oldattendanceeventcategorydescriptornamespace varchar(255) NOT NULL, + oldattendanceeventcategorydescriptorcodevalue varchar(50) NOT NULL, + oldeducationorganizationid integer NOT NULL, + oldeventdate date NOT NULL, + oldinterventionidentificationcode varchar(60) NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + newattendanceeventcategorydescriptorid integer NULL, + newattendanceeventcategorydescriptornamespace varchar(255) NULL, + newattendanceeventcategorydescriptorcodevalue varchar(50) NULL, + neweducationorganizationid integer NULL, + neweventdate date NULL, + newinterventionidentificationcode varchar(60) NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT studentinterventionattendanceevent_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'studentlearningobjective') THEN +CREATE TABLE tracked_changes_edfi.studentlearningobjective +( + oldgradingperioddescriptorid integer NOT NULL, + oldgradingperioddescriptornamespace varchar(255) NOT NULL, + oldgradingperioddescriptorcodevalue varchar(50) NOT NULL, + oldgradingperiodschoolid integer NOT NULL, + oldgradingperiodschoolyear smallint NOT NULL, + oldgradingperiodsequence integer NOT NULL, + oldlearningobjectiveid varchar(60) NOT NULL, + oldnamespace varchar(255) NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + newgradingperioddescriptorid integer NULL, + newgradingperioddescriptornamespace varchar(255) NULL, + newgradingperioddescriptorcodevalue varchar(50) NULL, + newgradingperiodschoolid integer NULL, + newgradingperiodschoolyear smallint NULL, + newgradingperiodsequence integer NULL, + newlearningobjectiveid varchar(60) NULL, + newnamespace varchar(255) NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT studentlearningobjective_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'studentparentassociation') THEN +CREATE TABLE tracked_changes_edfi.studentparentassociation +( + oldparentusi integer NOT NULL, + oldparentuniqueid varchar(32) NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + newparentusi integer NULL, + newparentuniqueid varchar(32) NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT studentparentassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'studentprogramattendanceevent') THEN +CREATE TABLE tracked_changes_edfi.studentprogramattendanceevent +( + oldattendanceeventcategorydescriptorid integer NOT NULL, + oldattendanceeventcategorydescriptornamespace varchar(255) NOT NULL, + oldattendanceeventcategorydescriptorcodevalue varchar(50) NOT NULL, + oldeducationorganizationid integer NOT NULL, + oldeventdate date NOT NULL, + oldprogrameducationorganizationid integer NOT NULL, + oldprogramname varchar(60) NOT NULL, + oldprogramtypedescriptorid integer NOT NULL, + oldprogramtypedescriptornamespace varchar(255) NOT NULL, + oldprogramtypedescriptorcodevalue varchar(50) NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + newattendanceeventcategorydescriptorid integer NULL, + newattendanceeventcategorydescriptornamespace varchar(255) NULL, + newattendanceeventcategorydescriptorcodevalue varchar(50) NULL, + neweducationorganizationid integer NULL, + neweventdate date NULL, + newprogrameducationorganizationid integer NULL, + newprogramname varchar(60) NULL, + newprogramtypedescriptorid integer NULL, + newprogramtypedescriptornamespace varchar(255) NULL, + newprogramtypedescriptorcodevalue varchar(50) NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT studentprogramattendanceevent_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'studentschoolassociation') THEN +CREATE TABLE tracked_changes_edfi.studentschoolassociation +( + oldentrydate date NOT NULL, + oldschoolid integer NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + newentrydate date NULL, + newschoolid integer NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT studentschoolassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'studentschoolattendanceevent') THEN +CREATE TABLE tracked_changes_edfi.studentschoolattendanceevent +( + oldattendanceeventcategorydescriptorid integer NOT NULL, + oldattendanceeventcategorydescriptornamespace varchar(255) NOT NULL, + oldattendanceeventcategorydescriptorcodevalue varchar(50) NOT NULL, + oldeventdate date NOT NULL, + oldschoolid integer NOT NULL, + oldschoolyear smallint NOT NULL, + oldsessionname varchar(60) NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + newattendanceeventcategorydescriptorid integer NULL, + newattendanceeventcategorydescriptornamespace varchar(255) NULL, + newattendanceeventcategorydescriptorcodevalue varchar(50) NULL, + neweventdate date NULL, + newschoolid integer NULL, + newschoolyear smallint NULL, + newsessionname varchar(60) NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT studentschoolattendanceevent_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'studentsectionassociation') THEN +CREATE TABLE tracked_changes_edfi.studentsectionassociation +( + oldbegindate date NOT NULL, + oldlocalcoursecode varchar(60) NOT NULL, + oldschoolid integer NOT NULL, + oldschoolyear smallint NOT NULL, + oldsectionidentifier varchar(255) NOT NULL, + oldsessionname varchar(60) NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + newbegindate date NULL, + newlocalcoursecode varchar(60) NULL, + newschoolid integer NULL, + newschoolyear smallint NULL, + newsectionidentifier varchar(255) NULL, + newsessionname varchar(60) NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT studentsectionassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'studentsectionattendanceevent') THEN +CREATE TABLE tracked_changes_edfi.studentsectionattendanceevent +( + oldattendanceeventcategorydescriptorid integer NOT NULL, + oldattendanceeventcategorydescriptornamespace varchar(255) NOT NULL, + oldattendanceeventcategorydescriptorcodevalue varchar(50) NOT NULL, + oldeventdate date NOT NULL, + oldlocalcoursecode varchar(60) NOT NULL, + oldschoolid integer NOT NULL, + oldschoolyear smallint NOT NULL, + oldsectionidentifier varchar(255) NOT NULL, + oldsessionname varchar(60) NOT NULL, + oldstudentusi integer NOT NULL, + oldstudentuniqueid varchar(32) NOT NULL, + newattendanceeventcategorydescriptorid integer NULL, + newattendanceeventcategorydescriptornamespace varchar(255) NULL, + newattendanceeventcategorydescriptorcodevalue varchar(50) NULL, + neweventdate date NULL, + newlocalcoursecode varchar(60) NULL, + newschoolid integer NULL, + newschoolyear smallint NULL, + newsectionidentifier varchar(255) NULL, + newsessionname varchar(60) NULL, + newstudentusi integer NULL, + newstudentuniqueid varchar(32) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT studentsectionattendanceevent_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'survey') THEN +CREATE TABLE tracked_changes_edfi.survey +( + oldnamespace varchar(255) NOT NULL, + oldsurveyidentifier varchar(60) NOT NULL, + newnamespace varchar(255) NULL, + newsurveyidentifier varchar(60) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT survey_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'surveycourseassociation') THEN +CREATE TABLE tracked_changes_edfi.surveycourseassociation +( + oldcoursecode varchar(60) NOT NULL, + oldeducationorganizationid integer NOT NULL, + oldnamespace varchar(255) NOT NULL, + oldsurveyidentifier varchar(60) NOT NULL, + newcoursecode varchar(60) NULL, + neweducationorganizationid integer NULL, + newnamespace varchar(255) NULL, + newsurveyidentifier varchar(60) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT surveycourseassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'surveyprogramassociation') THEN +CREATE TABLE tracked_changes_edfi.surveyprogramassociation +( + oldeducationorganizationid integer NOT NULL, + oldnamespace varchar(255) NOT NULL, + oldprogramname varchar(60) NOT NULL, + oldprogramtypedescriptorid integer NOT NULL, + oldprogramtypedescriptornamespace varchar(255) NOT NULL, + oldprogramtypedescriptorcodevalue varchar(50) NOT NULL, + oldsurveyidentifier varchar(60) NOT NULL, + neweducationorganizationid integer NULL, + newnamespace varchar(255) NULL, + newprogramname varchar(60) NULL, + newprogramtypedescriptorid integer NULL, + newprogramtypedescriptornamespace varchar(255) NULL, + newprogramtypedescriptorcodevalue varchar(50) NULL, + newsurveyidentifier varchar(60) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT surveyprogramassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'surveyquestion') THEN +CREATE TABLE tracked_changes_edfi.surveyquestion +( + oldnamespace varchar(255) NOT NULL, + oldquestioncode varchar(60) NOT NULL, + oldsurveyidentifier varchar(60) NOT NULL, + newnamespace varchar(255) NULL, + newquestioncode varchar(60) NULL, + newsurveyidentifier varchar(60) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT surveyquestion_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'surveyquestionresponse') THEN +CREATE TABLE tracked_changes_edfi.surveyquestionresponse +( + oldnamespace varchar(255) NOT NULL, + oldquestioncode varchar(60) NOT NULL, + oldsurveyidentifier varchar(60) NOT NULL, + oldsurveyresponseidentifier varchar(60) NOT NULL, + newnamespace varchar(255) NULL, + newquestioncode varchar(60) NULL, + newsurveyidentifier varchar(60) NULL, + newsurveyresponseidentifier varchar(60) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT surveyquestionresponse_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'surveyresponse') THEN +CREATE TABLE tracked_changes_edfi.surveyresponse +( + oldnamespace varchar(255) NOT NULL, + oldsurveyidentifier varchar(60) NOT NULL, + oldsurveyresponseidentifier varchar(60) NOT NULL, + newnamespace varchar(255) NULL, + newsurveyidentifier varchar(60) NULL, + newsurveyresponseidentifier varchar(60) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT surveyresponse_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'surveyresponseeducationorganizationtargetassociation') THEN +CREATE TABLE tracked_changes_edfi.surveyresponseeducationorganizationtargetassociation +( + oldeducationorganizationid integer NOT NULL, + oldnamespace varchar(255) NOT NULL, + oldsurveyidentifier varchar(60) NOT NULL, + oldsurveyresponseidentifier varchar(60) NOT NULL, + neweducationorganizationid integer NULL, + newnamespace varchar(255) NULL, + newsurveyidentifier varchar(60) NULL, + newsurveyresponseidentifier varchar(60) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT surveyresponseeducationorganizationtargetassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'surveyresponsestafftargetassociation') THEN +CREATE TABLE tracked_changes_edfi.surveyresponsestafftargetassociation +( + oldnamespace varchar(255) NOT NULL, + oldstaffusi integer NOT NULL, + oldstaffuniqueid varchar(32) NOT NULL, + oldsurveyidentifier varchar(60) NOT NULL, + oldsurveyresponseidentifier varchar(60) NOT NULL, + newnamespace varchar(255) NULL, + newstaffusi integer NULL, + newstaffuniqueid varchar(32) NULL, + newsurveyidentifier varchar(60) NULL, + newsurveyresponseidentifier varchar(60) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT surveyresponsestafftargetassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'surveysection') THEN +CREATE TABLE tracked_changes_edfi.surveysection +( + oldnamespace varchar(255) NOT NULL, + oldsurveyidentifier varchar(60) NOT NULL, + oldsurveysectiontitle varchar(255) NOT NULL, + newnamespace varchar(255) NULL, + newsurveyidentifier varchar(60) NULL, + newsurveysectiontitle varchar(255) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT surveysection_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'surveysectionassociation') THEN +CREATE TABLE tracked_changes_edfi.surveysectionassociation +( + oldlocalcoursecode varchar(60) NOT NULL, + oldnamespace varchar(255) NOT NULL, + oldschoolid integer NOT NULL, + oldschoolyear smallint NOT NULL, + oldsectionidentifier varchar(255) NOT NULL, + oldsessionname varchar(60) NOT NULL, + oldsurveyidentifier varchar(60) NOT NULL, + newlocalcoursecode varchar(60) NULL, + newnamespace varchar(255) NULL, + newschoolid integer NULL, + newschoolyear smallint NULL, + newsectionidentifier varchar(255) NULL, + newsessionname varchar(60) NULL, + newsurveyidentifier varchar(60) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT surveysectionassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'surveysectionresponse') THEN +CREATE TABLE tracked_changes_edfi.surveysectionresponse +( + oldnamespace varchar(255) NOT NULL, + oldsurveyidentifier varchar(60) NOT NULL, + oldsurveyresponseidentifier varchar(60) NOT NULL, + oldsurveysectiontitle varchar(255) NOT NULL, + newnamespace varchar(255) NULL, + newsurveyidentifier varchar(60) NULL, + newsurveyresponseidentifier varchar(60) NULL, + newsurveysectiontitle varchar(255) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT surveysectionresponse_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'surveysectionresponseeducationorganizationtargetassociation') THEN +CREATE TABLE tracked_changes_edfi.surveysectionresponseeducationorganizationtargetassociation +( + oldeducationorganizationid integer NOT NULL, + oldnamespace varchar(255) NOT NULL, + oldsurveyidentifier varchar(60) NOT NULL, + oldsurveyresponseidentifier varchar(60) NOT NULL, + oldsurveysectiontitle varchar(255) NOT NULL, + neweducationorganizationid integer NULL, + newnamespace varchar(255) NULL, + newsurveyidentifier varchar(60) NULL, + newsurveyresponseidentifier varchar(60) NULL, + newsurveysectiontitle varchar(255) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT surveysectionresponseeducationorganizationtargetassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_edfi' AND table_name = 'surveysectionresponsestafftargetassociation') THEN +CREATE TABLE tracked_changes_edfi.surveysectionresponsestafftargetassociation +( + oldnamespace varchar(255) NOT NULL, + oldstaffusi integer NOT NULL, + oldstaffuniqueid varchar(32) NOT NULL, + oldsurveyidentifier varchar(60) NOT NULL, + oldsurveyresponseidentifier varchar(60) NOT NULL, + oldsurveysectiontitle varchar(255) NOT NULL, + newnamespace varchar(255) NULL, + newstaffusi integer NULL, + newstaffuniqueid varchar(32) NULL, + newsurveyidentifier varchar(60) NULL, + newsurveyresponseidentifier varchar(60) NULL, + newsurveysectiontitle varchar(255) NULL, + id uuid NOT NULL, + changeversion bigint NOT NULL, + discriminator varchar(128) NULL, + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT surveysectionresponsestafftargetassociation_pk PRIMARY KEY (changeversion) +); +END IF; + +END +$$; \ No newline at end of file diff --git a/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0210-CreateTriggersForChangeVersionAndKeyChanges.sql b/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0210-CreateTriggersForChangeVersionAndKeyChanges.sql new file mode 100644 index 0000000000..f8c166ef01 --- /dev/null +++ b/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0210-CreateTriggersForChangeVersionAndKeyChanges.sql @@ -0,0 +1,923 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +DO $$ +BEGIN +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'academicweek') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.academicweek + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'account') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.account + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'accountabilityrating') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.accountabilityrating + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'accountcode') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.accountcode + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'actual') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.actual + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'assessment') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.assessment + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'assessmentitem') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.assessmentitem + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'assessmentscorerangelearningstandard') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.assessmentscorerangelearningstandard + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'bellschedule') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.bellschedule + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'budget') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.budget + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'calendar') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.calendar + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'calendardate') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.calendardate + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'classperiod') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.classperiod + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.classperiod_keychg() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + -- Handle key changes + INSERT INTO tracked_changes_edfi.classperiod( + oldclassperiodname, oldschoolid, + newclassperiodname, newschoolid, + id, changeversion) + VALUES( + old.classperiodname, old.schoolid, + new.classperiodname, new.schoolid, + old.id, (nextval('changes.changeversionsequence'))); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'handlekeychanges' AND event_object_schema = 'edfi' AND event_object_table = 'classperiod') THEN + CREATE TRIGGER HandleKeyChanges AFTER UPDATE OF classperiodname, schoolid ON edfi.classperiod + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.classperiod_keychg(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'cohort') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.cohort + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'communityproviderlicense') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.communityproviderlicense + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'competencyobjective') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.competencyobjective + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'contractedstaff') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.contractedstaff + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'course') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.course + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'courseoffering') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.courseoffering + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.courseoffering_keychg() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + -- Handle key changes + INSERT INTO tracked_changes_edfi.courseoffering( + oldlocalcoursecode, oldschoolid, oldschoolyear, oldsessionname, + newlocalcoursecode, newschoolid, newschoolyear, newsessionname, + id, changeversion) + VALUES( + old.localcoursecode, old.schoolid, old.schoolyear, old.sessionname, + new.localcoursecode, new.schoolid, new.schoolyear, new.sessionname, + old.id, (nextval('changes.changeversionsequence'))); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'handlekeychanges' AND event_object_schema = 'edfi' AND event_object_table = 'courseoffering') THEN + CREATE TRIGGER HandleKeyChanges AFTER UPDATE OF localcoursecode, schoolid, schoolyear, sessionname ON edfi.courseoffering + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.courseoffering_keychg(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'coursetranscript') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.coursetranscript + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'credential') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.credential + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'descriptor') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.descriptor + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'disciplineaction') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.disciplineaction + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'disciplineincident') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.disciplineincident + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'educationcontent') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.educationcontent + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'educationorganization') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.educationorganization + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'educationorganizationinterventionprescriptionassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.educationorganizationinterventionprescriptionassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'educationorganizationnetworkassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.educationorganizationnetworkassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'educationorganizationpeerassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.educationorganizationpeerassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'feederschoolassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.feederschoolassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'generalstudentprogramassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.generalstudentprogramassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'grade') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.grade + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.grade_keychg() + RETURNS trigger AS +$BODY$ +DECLARE + dj1 edfi.descriptor%ROWTYPE; + dj2 edfi.descriptor%ROWTYPE; + dj10 edfi.student%ROWTYPE; + ij1 edfi.descriptor%ROWTYPE; + ij2 edfi.descriptor%ROWTYPE; + ij10 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj1 * FROM edfi.descriptor j1 WHERE descriptorid = old.gradetypedescriptorid; + SELECT INTO dj2 * FROM edfi.descriptor j2 WHERE descriptorid = old.gradingperioddescriptorid; + SELECT INTO dj10 * FROM edfi.student j10 WHERE studentusi = old.studentusi; + SELECT INTO ij1 * FROM edfi.descriptor j1 WHERE descriptorid = new.gradetypedescriptorid; + SELECT INTO ij2 * FROM edfi.descriptor j2 WHERE descriptorid = new.gradingperioddescriptorid; + SELECT INTO ij10 * FROM edfi.student j10 WHERE studentusi = new.studentusi; + + -- Handle key changes + INSERT INTO tracked_changes_edfi.grade( + oldbegindate, oldgradetypedescriptorid, oldgradetypedescriptornamespace, oldgradetypedescriptorcodevalue, oldgradingperioddescriptorid, oldgradingperioddescriptornamespace, oldgradingperioddescriptorcodevalue, oldgradingperiodschoolyear, oldgradingperiodsequence, oldlocalcoursecode, oldschoolid, oldschoolyear, oldsectionidentifier, oldsessionname, oldstudentusi, oldstudentuniqueid, + newbegindate, newgradetypedescriptorid, newgradetypedescriptornamespace, newgradetypedescriptorcodevalue, newgradingperioddescriptorid, newgradingperioddescriptornamespace, newgradingperioddescriptorcodevalue, newgradingperiodschoolyear, newgradingperiodsequence, newlocalcoursecode, newschoolid, newschoolyear, newsectionidentifier, newsessionname, newstudentusi, newstudentuniqueid, + id, changeversion) + VALUES( + old.begindate, old.gradetypedescriptorid, dj1.namespace, dj1.codevalue, old.gradingperioddescriptorid, dj2.namespace, dj2.codevalue, old.gradingperiodschoolyear, old.gradingperiodsequence, old.localcoursecode, old.schoolid, old.schoolyear, old.sectionidentifier, old.sessionname, old.studentusi, dj10.studentuniqueid, + new.begindate, new.gradetypedescriptorid, ij1.namespace, ij1.codevalue, new.gradingperioddescriptorid, ij2.namespace, ij2.codevalue, new.gradingperiodschoolyear, new.gradingperiodsequence, new.localcoursecode, new.schoolid, new.schoolyear, new.sectionidentifier, new.sessionname, new.studentusi, ij10.studentuniqueid, + old.id, (nextval('changes.changeversionsequence'))); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'handlekeychanges' AND event_object_schema = 'edfi' AND event_object_table = 'grade') THEN + CREATE TRIGGER HandleKeyChanges AFTER UPDATE OF begindate, gradetypedescriptorid, gradingperioddescriptorid, gradingperiodschoolyear, gradingperiodsequence, localcoursecode, schoolid, schoolyear, sectionidentifier, sessionname, studentusi ON edfi.grade + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.grade_keychg(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'gradebookentry') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.gradebookentry + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.gradebookentry_keychg() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + -- Handle key changes + INSERT INTO tracked_changes_edfi.gradebookentry( + olddateassigned, oldgradebookentrytitle, oldlocalcoursecode, oldschoolid, oldschoolyear, oldsectionidentifier, oldsessionname, + newdateassigned, newgradebookentrytitle, newlocalcoursecode, newschoolid, newschoolyear, newsectionidentifier, newsessionname, + id, changeversion) + VALUES( + old.dateassigned, old.gradebookentrytitle, old.localcoursecode, old.schoolid, old.schoolyear, old.sectionidentifier, old.sessionname, + new.dateassigned, new.gradebookentrytitle, new.localcoursecode, new.schoolid, new.schoolyear, new.sectionidentifier, new.sessionname, + old.id, (nextval('changes.changeversionsequence'))); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'handlekeychanges' AND event_object_schema = 'edfi' AND event_object_table = 'gradebookentry') THEN + CREATE TRIGGER HandleKeyChanges AFTER UPDATE OF dateassigned, gradebookentrytitle, localcoursecode, schoolid, schoolyear, sectionidentifier, sessionname ON edfi.gradebookentry + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.gradebookentry_keychg(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'gradingperiod') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.gradingperiod + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'graduationplan') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.graduationplan + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'intervention') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.intervention + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'interventionprescription') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.interventionprescription + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'interventionstudy') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.interventionstudy + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'learningobjective') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.learningobjective + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'learningstandard') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.learningstandard + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'learningstandardequivalenceassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.learningstandardequivalenceassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'location') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.location + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.location_keychg() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + -- Handle key changes + INSERT INTO tracked_changes_edfi.location( + oldclassroomidentificationcode, oldschoolid, + newclassroomidentificationcode, newschoolid, + id, changeversion) + VALUES( + old.classroomidentificationcode, old.schoolid, + new.classroomidentificationcode, new.schoolid, + old.id, (nextval('changes.changeversionsequence'))); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'handlekeychanges' AND event_object_schema = 'edfi' AND event_object_table = 'location') THEN + CREATE TRIGGER HandleKeyChanges AFTER UPDATE OF classroomidentificationcode, schoolid ON edfi.location + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.location_keychg(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'objectiveassessment') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.objectiveassessment + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'openstaffposition') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.openstaffposition + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'parent') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.parent + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'payroll') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.payroll + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'person') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.person + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'postsecondaryevent') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.postsecondaryevent + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'program') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.program + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'reportcard') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.reportcard + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'restraintevent') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.restraintevent + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'schoolyeartype') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.schoolyeartype + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'section') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.section + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.section_keychg() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + -- Handle key changes + INSERT INTO tracked_changes_edfi.section( + oldlocalcoursecode, oldschoolid, oldschoolyear, oldsectionidentifier, oldsessionname, + newlocalcoursecode, newschoolid, newschoolyear, newsectionidentifier, newsessionname, + id, changeversion) + VALUES( + old.localcoursecode, old.schoolid, old.schoolyear, old.sectionidentifier, old.sessionname, + new.localcoursecode, new.schoolid, new.schoolyear, new.sectionidentifier, new.sessionname, + old.id, (nextval('changes.changeversionsequence'))); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'handlekeychanges' AND event_object_schema = 'edfi' AND event_object_table = 'section') THEN + CREATE TRIGGER HandleKeyChanges AFTER UPDATE OF localcoursecode, schoolid, schoolyear, sectionidentifier, sessionname ON edfi.section + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.section_keychg(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'sectionattendancetakenevent') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.sectionattendancetakenevent + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.sectionattendancetakenevent_keychg() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + -- Handle key changes + INSERT INTO tracked_changes_edfi.sectionattendancetakenevent( + oldcalendarcode, olddate, oldlocalcoursecode, oldschoolid, oldschoolyear, oldsectionidentifier, oldsessionname, + newcalendarcode, newdate, newlocalcoursecode, newschoolid, newschoolyear, newsectionidentifier, newsessionname, + id, changeversion) + VALUES( + old.calendarcode, old.date, old.localcoursecode, old.schoolid, old.schoolyear, old.sectionidentifier, old.sessionname, + new.calendarcode, new.date, new.localcoursecode, new.schoolid, new.schoolyear, new.sectionidentifier, new.sessionname, + old.id, (nextval('changes.changeversionsequence'))); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'handlekeychanges' AND event_object_schema = 'edfi' AND event_object_table = 'sectionattendancetakenevent') THEN + CREATE TRIGGER HandleKeyChanges AFTER UPDATE OF calendarcode, date, localcoursecode, schoolid, schoolyear, sectionidentifier, sessionname ON edfi.sectionattendancetakenevent + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.sectionattendancetakenevent_keychg(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'session') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.session + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.session_keychg() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + -- Handle key changes + INSERT INTO tracked_changes_edfi.session( + oldschoolid, oldschoolyear, oldsessionname, + newschoolid, newschoolyear, newsessionname, + id, changeversion) + VALUES( + old.schoolid, old.schoolyear, old.sessionname, + new.schoolid, new.schoolyear, new.sessionname, + old.id, (nextval('changes.changeversionsequence'))); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'handlekeychanges' AND event_object_schema = 'edfi' AND event_object_table = 'session') THEN + CREATE TRIGGER HandleKeyChanges AFTER UPDATE OF schoolid, schoolyear, sessionname ON edfi.session + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.session_keychg(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'staff') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.staff + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'staffabsenceevent') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.staffabsenceevent + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'staffcohortassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.staffcohortassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'staffdisciplineincidentassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.staffdisciplineincidentassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'staffeducationorganizationassignmentassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.staffeducationorganizationassignmentassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'staffeducationorganizationcontactassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.staffeducationorganizationcontactassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'staffeducationorganizationemploymentassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.staffeducationorganizationemploymentassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'staffleave') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.staffleave + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'staffprogramassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.staffprogramassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'staffschoolassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.staffschoolassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'staffsectionassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.staffsectionassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.staffsectionassociation_keychg() + RETURNS trigger AS +$BODY$ +DECLARE + dj5 edfi.staff%ROWTYPE; + ij5 edfi.staff%ROWTYPE; +BEGIN + SELECT INTO dj5 * FROM edfi.staff j5 WHERE staffusi = old.staffusi; + SELECT INTO ij5 * FROM edfi.staff j5 WHERE staffusi = new.staffusi; + + -- Handle key changes + INSERT INTO tracked_changes_edfi.staffsectionassociation( + oldlocalcoursecode, oldschoolid, oldschoolyear, oldsectionidentifier, oldsessionname, oldstaffusi, oldstaffuniqueid, + newlocalcoursecode, newschoolid, newschoolyear, newsectionidentifier, newsessionname, newstaffusi, newstaffuniqueid, + id, changeversion) + VALUES( + old.localcoursecode, old.schoolid, old.schoolyear, old.sectionidentifier, old.sessionname, old.staffusi, dj5.staffuniqueid, + new.localcoursecode, new.schoolid, new.schoolyear, new.sectionidentifier, new.sessionname, new.staffusi, ij5.staffuniqueid, + old.id, (nextval('changes.changeversionsequence'))); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'handlekeychanges' AND event_object_schema = 'edfi' AND event_object_table = 'staffsectionassociation') THEN + CREATE TRIGGER HandleKeyChanges AFTER UPDATE OF localcoursecode, schoolid, schoolyear, sectionidentifier, sessionname, staffusi ON edfi.staffsectionassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.staffsectionassociation_keychg(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'student') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.student + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'studentacademicrecord') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.studentacademicrecord + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'studentassessment') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.studentassessment + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'studentcohortassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.studentcohortassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'studentcompetencyobjective') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.studentcompetencyobjective + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'studentdisciplineincidentassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.studentdisciplineincidentassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'studentdisciplineincidentbehaviorassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.studentdisciplineincidentbehaviorassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'studentdisciplineincidentnonoffenderassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.studentdisciplineincidentnonoffenderassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'studenteducationorganizationassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.studenteducationorganizationassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'studenteducationorganizationresponsibilityassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.studenteducationorganizationresponsibilityassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'studentgradebookentry') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.studentgradebookentry + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentgradebookentry_keychg() + RETURNS trigger AS +$BODY$ +DECLARE + dj8 edfi.student%ROWTYPE; + ij8 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj8 * FROM edfi.student j8 WHERE studentusi = old.studentusi; + SELECT INTO ij8 * FROM edfi.student j8 WHERE studentusi = new.studentusi; + + -- Handle key changes + INSERT INTO tracked_changes_edfi.studentgradebookentry( + oldbegindate, olddateassigned, oldgradebookentrytitle, oldlocalcoursecode, oldschoolid, oldschoolyear, oldsectionidentifier, oldsessionname, oldstudentusi, oldstudentuniqueid, + newbegindate, newdateassigned, newgradebookentrytitle, newlocalcoursecode, newschoolid, newschoolyear, newsectionidentifier, newsessionname, newstudentusi, newstudentuniqueid, + id, changeversion) + VALUES( + old.begindate, old.dateassigned, old.gradebookentrytitle, old.localcoursecode, old.schoolid, old.schoolyear, old.sectionidentifier, old.sessionname, old.studentusi, dj8.studentuniqueid, + new.begindate, new.dateassigned, new.gradebookentrytitle, new.localcoursecode, new.schoolid, new.schoolyear, new.sectionidentifier, new.sessionname, new.studentusi, ij8.studentuniqueid, + old.id, (nextval('changes.changeversionsequence'))); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'handlekeychanges' AND event_object_schema = 'edfi' AND event_object_table = 'studentgradebookentry') THEN + CREATE TRIGGER HandleKeyChanges AFTER UPDATE OF begindate, dateassigned, gradebookentrytitle, localcoursecode, schoolid, schoolyear, sectionidentifier, sessionname, studentusi ON edfi.studentgradebookentry + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentgradebookentry_keychg(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'studentinterventionassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.studentinterventionassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'studentinterventionattendanceevent') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.studentinterventionattendanceevent + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'studentlearningobjective') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.studentlearningobjective + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'studentparentassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.studentparentassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'studentprogramattendanceevent') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.studentprogramattendanceevent + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'studentschoolassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.studentschoolassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentschoolassociation_keychg() + RETURNS trigger AS +$BODY$ +DECLARE + dj2 edfi.student%ROWTYPE; + ij2 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj2 * FROM edfi.student j2 WHERE studentusi = old.studentusi; + SELECT INTO ij2 * FROM edfi.student j2 WHERE studentusi = new.studentusi; + + -- Handle key changes + INSERT INTO tracked_changes_edfi.studentschoolassociation( + oldentrydate, oldschoolid, oldstudentusi, oldstudentuniqueid, + newentrydate, newschoolid, newstudentusi, newstudentuniqueid, + id, changeversion) + VALUES( + old.entrydate, old.schoolid, old.studentusi, dj2.studentuniqueid, + new.entrydate, new.schoolid, new.studentusi, ij2.studentuniqueid, + old.id, (nextval('changes.changeversionsequence'))); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'handlekeychanges' AND event_object_schema = 'edfi' AND event_object_table = 'studentschoolassociation') THEN + CREATE TRIGGER HandleKeyChanges AFTER UPDATE OF entrydate, schoolid, studentusi ON edfi.studentschoolassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentschoolassociation_keychg(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'studentschoolattendanceevent') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.studentschoolattendanceevent + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentschoolattendanceevent_keychg() + RETURNS trigger AS +$BODY$ +DECLARE + dj0 edfi.descriptor%ROWTYPE; + dj5 edfi.student%ROWTYPE; + ij0 edfi.descriptor%ROWTYPE; + ij5 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj0 * FROM edfi.descriptor j0 WHERE descriptorid = old.attendanceeventcategorydescriptorid; + SELECT INTO dj5 * FROM edfi.student j5 WHERE studentusi = old.studentusi; + SELECT INTO ij0 * FROM edfi.descriptor j0 WHERE descriptorid = new.attendanceeventcategorydescriptorid; + SELECT INTO ij5 * FROM edfi.student j5 WHERE studentusi = new.studentusi; + + -- Handle key changes + INSERT INTO tracked_changes_edfi.studentschoolattendanceevent( + oldattendanceeventcategorydescriptorid, oldattendanceeventcategorydescriptornamespace, oldattendanceeventcategorydescriptorcodevalue, oldeventdate, oldschoolid, oldschoolyear, oldsessionname, oldstudentusi, oldstudentuniqueid, + newattendanceeventcategorydescriptorid, newattendanceeventcategorydescriptornamespace, newattendanceeventcategorydescriptorcodevalue, neweventdate, newschoolid, newschoolyear, newsessionname, newstudentusi, newstudentuniqueid, + id, changeversion) + VALUES( + old.attendanceeventcategorydescriptorid, dj0.namespace, dj0.codevalue, old.eventdate, old.schoolid, old.schoolyear, old.sessionname, old.studentusi, dj5.studentuniqueid, + new.attendanceeventcategorydescriptorid, ij0.namespace, ij0.codevalue, new.eventdate, new.schoolid, new.schoolyear, new.sessionname, new.studentusi, ij5.studentuniqueid, + old.id, (nextval('changes.changeversionsequence'))); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'handlekeychanges' AND event_object_schema = 'edfi' AND event_object_table = 'studentschoolattendanceevent') THEN + CREATE TRIGGER HandleKeyChanges AFTER UPDATE OF attendanceeventcategorydescriptorid, eventdate, schoolid, schoolyear, sessionname, studentusi ON edfi.studentschoolattendanceevent + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentschoolattendanceevent_keychg(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'studentsectionassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.studentsectionassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentsectionassociation_keychg() + RETURNS trigger AS +$BODY$ +DECLARE + dj6 edfi.student%ROWTYPE; + ij6 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj6 * FROM edfi.student j6 WHERE studentusi = old.studentusi; + SELECT INTO ij6 * FROM edfi.student j6 WHERE studentusi = new.studentusi; + + -- Handle key changes + INSERT INTO tracked_changes_edfi.studentsectionassociation( + oldbegindate, oldlocalcoursecode, oldschoolid, oldschoolyear, oldsectionidentifier, oldsessionname, oldstudentusi, oldstudentuniqueid, + newbegindate, newlocalcoursecode, newschoolid, newschoolyear, newsectionidentifier, newsessionname, newstudentusi, newstudentuniqueid, + id, changeversion) + VALUES( + old.begindate, old.localcoursecode, old.schoolid, old.schoolyear, old.sectionidentifier, old.sessionname, old.studentusi, dj6.studentuniqueid, + new.begindate, new.localcoursecode, new.schoolid, new.schoolyear, new.sectionidentifier, new.sessionname, new.studentusi, ij6.studentuniqueid, + old.id, (nextval('changes.changeversionsequence'))); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'handlekeychanges' AND event_object_schema = 'edfi' AND event_object_table = 'studentsectionassociation') THEN + CREATE TRIGGER HandleKeyChanges AFTER UPDATE OF begindate, localcoursecode, schoolid, schoolyear, sectionidentifier, sessionname, studentusi ON edfi.studentsectionassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentsectionassociation_keychg(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'studentsectionattendanceevent') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.studentsectionattendanceevent + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentsectionattendanceevent_keychg() + RETURNS trigger AS +$BODY$ +DECLARE + dj0 edfi.descriptor%ROWTYPE; + dj7 edfi.student%ROWTYPE; + ij0 edfi.descriptor%ROWTYPE; + ij7 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj0 * FROM edfi.descriptor j0 WHERE descriptorid = old.attendanceeventcategorydescriptorid; + SELECT INTO dj7 * FROM edfi.student j7 WHERE studentusi = old.studentusi; + SELECT INTO ij0 * FROM edfi.descriptor j0 WHERE descriptorid = new.attendanceeventcategorydescriptorid; + SELECT INTO ij7 * FROM edfi.student j7 WHERE studentusi = new.studentusi; + + -- Handle key changes + INSERT INTO tracked_changes_edfi.studentsectionattendanceevent( + oldattendanceeventcategorydescriptorid, oldattendanceeventcategorydescriptornamespace, oldattendanceeventcategorydescriptorcodevalue, oldeventdate, oldlocalcoursecode, oldschoolid, oldschoolyear, oldsectionidentifier, oldsessionname, oldstudentusi, oldstudentuniqueid, + newattendanceeventcategorydescriptorid, newattendanceeventcategorydescriptornamespace, newattendanceeventcategorydescriptorcodevalue, neweventdate, newlocalcoursecode, newschoolid, newschoolyear, newsectionidentifier, newsessionname, newstudentusi, newstudentuniqueid, + id, changeversion) + VALUES( + old.attendanceeventcategorydescriptorid, dj0.namespace, dj0.codevalue, old.eventdate, old.localcoursecode, old.schoolid, old.schoolyear, old.sectionidentifier, old.sessionname, old.studentusi, dj7.studentuniqueid, + new.attendanceeventcategorydescriptorid, ij0.namespace, ij0.codevalue, new.eventdate, new.localcoursecode, new.schoolid, new.schoolyear, new.sectionidentifier, new.sessionname, new.studentusi, ij7.studentuniqueid, + old.id, (nextval('changes.changeversionsequence'))); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'handlekeychanges' AND event_object_schema = 'edfi' AND event_object_table = 'studentsectionattendanceevent') THEN + CREATE TRIGGER HandleKeyChanges AFTER UPDATE OF attendanceeventcategorydescriptorid, eventdate, localcoursecode, schoolid, schoolyear, sectionidentifier, sessionname, studentusi ON edfi.studentsectionattendanceevent + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentsectionattendanceevent_keychg(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'survey') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.survey + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'surveycourseassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.surveycourseassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'surveyprogramassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.surveyprogramassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'surveyquestion') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.surveyquestion + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'surveyquestionresponse') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.surveyquestionresponse + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'surveyresponse') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.surveyresponse + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'surveyresponseeducationorganizationtargetassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.surveyresponseeducationorganizationtargetassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'surveyresponsestafftargetassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.surveyresponsestafftargetassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'surveysection') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.surveysection + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'surveysectionassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.surveysectionassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.surveysectionassociation_keychg() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + -- Handle key changes + INSERT INTO tracked_changes_edfi.surveysectionassociation( + oldlocalcoursecode, oldnamespace, oldschoolid, oldschoolyear, oldsectionidentifier, oldsessionname, oldsurveyidentifier, + newlocalcoursecode, newnamespace, newschoolid, newschoolyear, newsectionidentifier, newsessionname, newsurveyidentifier, + id, changeversion) + VALUES( + old.localcoursecode, old.namespace, old.schoolid, old.schoolyear, old.sectionidentifier, old.sessionname, old.surveyidentifier, + new.localcoursecode, new.namespace, new.schoolid, new.schoolyear, new.sectionidentifier, new.sessionname, new.surveyidentifier, + old.id, (nextval('changes.changeversionsequence'))); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'handlekeychanges' AND event_object_schema = 'edfi' AND event_object_table = 'surveysectionassociation') THEN + CREATE TRIGGER HandleKeyChanges AFTER UPDATE OF localcoursecode, namespace, schoolid, schoolyear, sectionidentifier, sessionname, surveyidentifier ON edfi.surveysectionassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.surveysectionassociation_keychg(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'surveysectionresponse') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.surveysectionresponse + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'surveysectionresponseeducationorganizationtargetassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.surveysectionresponseeducationorganizationtargetassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = 'edfi' AND event_object_table = 'surveysectionresponsestafftargetassociation') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON edfi.surveysectionresponsestafftargetassociation + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +END +$$; \ No newline at end of file diff --git a/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0220-CreateTriggersForDeleteTracking.sql b/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0220-CreateTriggersForDeleteTracking.sql new file mode 100644 index 0000000000..739e5921b3 --- /dev/null +++ b/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0220-CreateTriggersForDeleteTracking.sql @@ -0,0 +1,5320 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +DO $$ +BEGIN +CREATE OR REPLACE FUNCTION tracked_changes_edfi.absenceeventcategorydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.absenceeventcategorydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.AbsenceEventCategoryDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.absenceeventcategorydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'absenceeventcategorydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.absenceeventcategorydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.absenceeventcategorydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.academichonorcategorydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.academichonorcategorydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.AcademicHonorCategoryDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.academichonorcategorydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'academichonorcategorydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.academichonorcategorydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.academichonorcategorydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.academicsubjectdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.academicsubjectdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.AcademicSubjectDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.academicsubjectdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'academicsubjectdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.academicsubjectdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.academicsubjectdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.academicweek_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.academicweek( + oldschoolid, oldweekidentifier, + id, discriminator, changeversion) + VALUES( + OLD.schoolid, OLD.weekidentifier, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'academicweek') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.academicweek + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.academicweek_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.accommodationdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.accommodationdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.AccommodationDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.accommodationdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'accommodationdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.accommodationdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.accommodationdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.account_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.account( + oldaccountidentifier, oldeducationorganizationid, oldfiscalyear, + id, discriminator, changeversion) + VALUES( + OLD.accountidentifier, OLD.educationorganizationid, OLD.fiscalyear, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'account') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.account + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.account_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.accountabilityrating_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.accountabilityrating( + oldeducationorganizationid, oldratingtitle, oldschoolyear, + id, discriminator, changeversion) + VALUES( + OLD.educationorganizationid, OLD.ratingtitle, OLD.schoolyear, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'accountabilityrating') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.accountabilityrating + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.accountabilityrating_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.accountclassificationdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.accountclassificationdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.AccountClassificationDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.accountclassificationdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'accountclassificationdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.accountclassificationdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.accountclassificationdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.accountcode_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj0 edfi.descriptor%ROWTYPE; +BEGIN + SELECT INTO dj0 * FROM edfi.descriptor j0 WHERE descriptorid = old.accountclassificationdescriptorid; + + INSERT INTO tracked_changes_edfi.accountcode( + oldaccountclassificationdescriptorid, oldaccountclassificationdescriptornamespace, oldaccountclassificationdescriptorcodevalue, oldaccountcodenumber, oldeducationorganizationid, oldfiscalyear, + id, discriminator, changeversion) + VALUES( + OLD.accountclassificationdescriptorid, dj0.namespace, dj0.codevalue, OLD.accountcodenumber, OLD.educationorganizationid, OLD.fiscalyear, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'accountcode') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.accountcode + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.accountcode_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.achievementcategorydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.achievementcategorydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.AchievementCategoryDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.achievementcategorydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'achievementcategorydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.achievementcategorydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.achievementcategorydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.actual_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.actual( + oldaccountidentifier, oldasofdate, oldeducationorganizationid, oldfiscalyear, + id, discriminator, changeversion) + VALUES( + OLD.accountidentifier, OLD.asofdate, OLD.educationorganizationid, OLD.fiscalyear, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'actual') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.actual + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.actual_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.additionalcredittypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.additionalcredittypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.AdditionalCreditTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.additionalcredittypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'additionalcredittypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.additionalcredittypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.additionalcredittypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.addresstypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.addresstypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.AddressTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.addresstypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'addresstypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.addresstypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.addresstypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.administrationenvironmentdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.administrationenvironmentdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.AdministrationEnvironmentDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.administrationenvironmentdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'administrationenvironmentdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.administrationenvironmentdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.administrationenvironmentdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.administrativefundingcontroldescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.administrativefundingcontroldescriptorid, b.codevalue, b.namespace, b.id, 'edfi.AdministrativeFundingControlDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.administrativefundingcontroldescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'administrativefundingcontroldescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.administrativefundingcontroldescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.administrativefundingcontroldescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.ancestryethnicorigindescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.ancestryethnicorigindescriptorid, b.codevalue, b.namespace, b.id, 'edfi.AncestryEthnicOriginDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.ancestryethnicorigindescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'ancestryethnicorigindescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.ancestryethnicorigindescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.ancestryethnicorigindescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.assessment_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.assessment( + oldassessmentidentifier, oldnamespace, + id, discriminator, changeversion) + VALUES( + OLD.assessmentidentifier, OLD.namespace, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'assessment') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.assessment + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.assessment_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.assessmentcategorydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.assessmentcategorydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.AssessmentCategoryDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.assessmentcategorydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'assessmentcategorydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.assessmentcategorydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.assessmentcategorydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.assessmentidentificationsystemdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.assessmentidentificationsystemdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.AssessmentIdentificationSystemDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.assessmentidentificationsystemdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'assessmentidentificationsystemdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.assessmentidentificationsystemdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.assessmentidentificationsystemdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.assessmentitem_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.assessmentitem( + oldassessmentidentifier, oldidentificationcode, oldnamespace, + id, discriminator, changeversion) + VALUES( + OLD.assessmentidentifier, OLD.identificationcode, OLD.namespace, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'assessmentitem') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.assessmentitem + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.assessmentitem_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.assessmentitemcategorydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.assessmentitemcategorydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.AssessmentItemCategoryDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.assessmentitemcategorydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'assessmentitemcategorydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.assessmentitemcategorydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.assessmentitemcategorydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.assessmentitemresultdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.assessmentitemresultdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.AssessmentItemResultDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.assessmentitemresultdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'assessmentitemresultdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.assessmentitemresultdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.assessmentitemresultdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.assessmentperioddescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.assessmentperioddescriptorid, b.codevalue, b.namespace, b.id, 'edfi.AssessmentPeriodDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.assessmentperioddescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'assessmentperioddescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.assessmentperioddescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.assessmentperioddescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.assessmentreportingmethoddescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.assessmentreportingmethoddescriptorid, b.codevalue, b.namespace, b.id, 'edfi.AssessmentReportingMethodDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.assessmentreportingmethoddescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'assessmentreportingmethoddescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.assessmentreportingmethoddescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.assessmentreportingmethoddescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.assessmentscorerangelearningstandard_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.assessmentscorerangelearningstandard( + oldassessmentidentifier, oldnamespace, oldscorerangeid, + id, discriminator, changeversion) + VALUES( + OLD.assessmentidentifier, OLD.namespace, OLD.scorerangeid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'assessmentscorerangelearningstandard') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.assessmentscorerangelearningstandard + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.assessmentscorerangelearningstandard_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.attemptstatusdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.attemptstatusdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.AttemptStatusDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.attemptstatusdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'attemptstatusdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.attemptstatusdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.attemptstatusdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.attendanceeventcategorydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.attendanceeventcategorydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.AttendanceEventCategoryDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.attendanceeventcategorydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'attendanceeventcategorydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.attendanceeventcategorydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.attendanceeventcategorydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.behaviordescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.behaviordescriptorid, b.codevalue, b.namespace, b.id, 'edfi.BehaviorDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.behaviordescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'behaviordescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.behaviordescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.behaviordescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.bellschedule_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.bellschedule( + oldbellschedulename, oldschoolid, + id, discriminator, changeversion) + VALUES( + OLD.bellschedulename, OLD.schoolid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'bellschedule') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.bellschedule + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.bellschedule_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.budget_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.budget( + oldaccountidentifier, oldasofdate, oldeducationorganizationid, oldfiscalyear, + id, discriminator, changeversion) + VALUES( + OLD.accountidentifier, OLD.asofdate, OLD.educationorganizationid, OLD.fiscalyear, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'budget') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.budget + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.budget_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.calendar_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.calendar( + oldcalendarcode, oldschoolid, oldschoolyear, + id, discriminator, changeversion) + VALUES( + OLD.calendarcode, OLD.schoolid, OLD.schoolyear, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'calendar') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.calendar + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.calendar_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.calendardate_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.calendardate( + oldcalendarcode, olddate, oldschoolid, oldschoolyear, + id, discriminator, changeversion) + VALUES( + OLD.calendarcode, OLD.date, OLD.schoolid, OLD.schoolyear, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'calendardate') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.calendardate + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.calendardate_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.calendareventdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.calendareventdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CalendarEventDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.calendareventdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'calendareventdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.calendareventdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.calendareventdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.calendartypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.calendartypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CalendarTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.calendartypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'calendartypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.calendartypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.calendartypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.careerpathwaydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.careerpathwaydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CareerPathwayDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.careerpathwaydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'careerpathwaydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.careerpathwaydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.careerpathwaydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.charterapprovalagencytypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.charterapprovalagencytypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CharterApprovalAgencyTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.charterapprovalagencytypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'charterapprovalagencytypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.charterapprovalagencytypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.charterapprovalagencytypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.charterstatusdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.charterstatusdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CharterStatusDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.charterstatusdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'charterstatusdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.charterstatusdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.charterstatusdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.citizenshipstatusdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.citizenshipstatusdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CitizenshipStatusDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.citizenshipstatusdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'citizenshipstatusdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.citizenshipstatusdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.citizenshipstatusdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.classperiod_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.classperiod( + oldclassperiodname, oldschoolid, + id, discriminator, changeversion) + VALUES( + OLD.classperiodname, OLD.schoolid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'classperiod') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.classperiod + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.classperiod_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.classroompositiondescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.classroompositiondescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ClassroomPositionDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.classroompositiondescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'classroompositiondescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.classroompositiondescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.classroompositiondescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.cohort_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.cohort( + oldcohortidentifier, oldeducationorganizationid, + id, discriminator, changeversion) + VALUES( + OLD.cohortidentifier, OLD.educationorganizationid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'cohort') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.cohort + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.cohort_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.cohortscopedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.cohortscopedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CohortScopeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.cohortscopedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'cohortscopedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.cohortscopedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.cohortscopedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.cohorttypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.cohorttypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CohortTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.cohorttypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'cohorttypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.cohorttypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.cohorttypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.cohortyeartypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.cohortyeartypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CohortYearTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.cohortyeartypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'cohortyeartypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.cohortyeartypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.cohortyeartypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.communityproviderlicense_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.communityproviderlicense( + oldcommunityproviderid, oldlicenseidentifier, oldlicensingorganization, + id, discriminator, changeversion) + VALUES( + OLD.communityproviderid, OLD.licenseidentifier, OLD.licensingorganization, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'communityproviderlicense') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.communityproviderlicense + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.communityproviderlicense_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.competencyleveldescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.competencyleveldescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CompetencyLevelDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.competencyleveldescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'competencyleveldescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.competencyleveldescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.competencyleveldescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.competencyobjective_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj2 edfi.descriptor%ROWTYPE; +BEGIN + SELECT INTO dj2 * FROM edfi.descriptor j2 WHERE descriptorid = old.objectivegradeleveldescriptorid; + + INSERT INTO tracked_changes_edfi.competencyobjective( + oldeducationorganizationid, oldobjective, oldobjectivegradeleveldescriptorid, oldobjectivegradeleveldescriptornamespace, oldobjectivegradeleveldescriptorcodevalue, + id, discriminator, changeversion) + VALUES( + OLD.educationorganizationid, OLD.objective, OLD.objectivegradeleveldescriptorid, dj2.namespace, dj2.codevalue, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'competencyobjective') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.competencyobjective + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.competencyobjective_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.contacttypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.contacttypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ContactTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.contacttypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'contacttypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.contacttypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.contacttypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.contentclassdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.contentclassdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ContentClassDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.contentclassdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'contentclassdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.contentclassdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.contentclassdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.continuationofservicesreasondescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.continuationofservicesreasondescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ContinuationOfServicesReasonDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.continuationofservicesreasondescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'continuationofservicesreasondescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.continuationofservicesreasondescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.continuationofservicesreasondescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.contractedstaff_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj4 edfi.staff%ROWTYPE; +BEGIN + SELECT INTO dj4 * FROM edfi.staff j4 WHERE staffusi = old.staffusi; + + INSERT INTO tracked_changes_edfi.contractedstaff( + oldaccountidentifier, oldasofdate, oldeducationorganizationid, oldfiscalyear, oldstaffusi, oldstaffuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.accountidentifier, OLD.asofdate, OLD.educationorganizationid, OLD.fiscalyear, OLD.staffusi, dj4.staffuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'contractedstaff') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.contractedstaff + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.contractedstaff_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.costratedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.costratedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CostRateDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.costratedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'costratedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.costratedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.costratedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.countrydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.countrydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CountryDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.countrydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'countrydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.countrydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.countrydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.course_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.course( + oldcoursecode, oldeducationorganizationid, + id, discriminator, changeversion) + VALUES( + OLD.coursecode, OLD.educationorganizationid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'course') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.course + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.course_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.courseattemptresultdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.courseattemptresultdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CourseAttemptResultDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.courseattemptresultdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'courseattemptresultdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.courseattemptresultdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.courseattemptresultdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.coursedefinedbydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.coursedefinedbydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CourseDefinedByDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.coursedefinedbydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'coursedefinedbydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.coursedefinedbydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.coursedefinedbydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.coursegpaapplicabilitydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.coursegpaapplicabilitydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CourseGPAApplicabilityDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.coursegpaapplicabilitydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'coursegpaapplicabilitydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.coursegpaapplicabilitydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.coursegpaapplicabilitydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.courseidentificationsystemdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.courseidentificationsystemdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CourseIdentificationSystemDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.courseidentificationsystemdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'courseidentificationsystemdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.courseidentificationsystemdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.courseidentificationsystemdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.courselevelcharacteristicdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.courselevelcharacteristicdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CourseLevelCharacteristicDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.courselevelcharacteristicdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'courselevelcharacteristicdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.courselevelcharacteristicdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.courselevelcharacteristicdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.courseoffering_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.courseoffering( + oldlocalcoursecode, oldschoolid, oldschoolyear, oldsessionname, + id, discriminator, changeversion) + VALUES( + OLD.localcoursecode, OLD.schoolid, OLD.schoolyear, OLD.sessionname, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'courseoffering') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.courseoffering + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.courseoffering_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.courserepeatcodedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.courserepeatcodedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CourseRepeatCodeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.courserepeatcodedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'courserepeatcodedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.courserepeatcodedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.courserepeatcodedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.coursetranscript_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj0 edfi.descriptor%ROWTYPE; + dj5 edfi.student%ROWTYPE; + dj6 edfi.descriptor%ROWTYPE; +BEGIN + SELECT INTO dj0 * FROM edfi.descriptor j0 WHERE descriptorid = old.courseattemptresultdescriptorid; + SELECT INTO dj5 * FROM edfi.student j5 WHERE studentusi = old.studentusi; + SELECT INTO dj6 * FROM edfi.descriptor j6 WHERE descriptorid = old.termdescriptorid; + + INSERT INTO tracked_changes_edfi.coursetranscript( + oldcourseattemptresultdescriptorid, oldcourseattemptresultdescriptornamespace, oldcourseattemptresultdescriptorcodevalue, oldcoursecode, oldcourseeducationorganizationid, oldeducationorganizationid, oldschoolyear, oldstudentusi, oldstudentuniqueid, oldtermdescriptorid, oldtermdescriptornamespace, oldtermdescriptorcodevalue, + id, discriminator, changeversion) + VALUES( + OLD.courseattemptresultdescriptorid, dj0.namespace, dj0.codevalue, OLD.coursecode, OLD.courseeducationorganizationid, OLD.educationorganizationid, OLD.schoolyear, OLD.studentusi, dj5.studentuniqueid, OLD.termdescriptorid, dj6.namespace, dj6.codevalue, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'coursetranscript') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.coursetranscript + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.coursetranscript_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.credential_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj1 edfi.descriptor%ROWTYPE; +BEGIN + SELECT INTO dj1 * FROM edfi.descriptor j1 WHERE descriptorid = old.stateofissuestateabbreviationdescriptorid; + + INSERT INTO tracked_changes_edfi.credential( + oldcredentialidentifier, oldstateofissuestateabbreviationdescriptorid, oldstateofissuestateabbreviationdescriptornamespace, oldstateofissuestateabbreviationdescriptorcodevalue, + id, discriminator, changeversion) + VALUES( + OLD.credentialidentifier, OLD.stateofissuestateabbreviationdescriptorid, dj1.namespace, dj1.codevalue, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'credential') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.credential + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.credential_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.credentialfielddescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.credentialfielddescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CredentialFieldDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.credentialfielddescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'credentialfielddescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.credentialfielddescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.credentialfielddescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.credentialtypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.credentialtypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CredentialTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.credentialtypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'credentialtypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.credentialtypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.credentialtypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.creditcategorydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.creditcategorydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CreditCategoryDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.creditcategorydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'creditcategorydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.creditcategorydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.creditcategorydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.credittypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.credittypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CreditTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.credittypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'credittypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.credittypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.credittypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.cteprogramservicedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.cteprogramservicedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CTEProgramServiceDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.cteprogramservicedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'cteprogramservicedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.cteprogramservicedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.cteprogramservicedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.curriculumuseddescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.curriculumuseddescriptorid, b.codevalue, b.namespace, b.id, 'edfi.CurriculumUsedDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.curriculumuseddescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'curriculumuseddescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.curriculumuseddescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.curriculumuseddescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.deliverymethoddescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.deliverymethoddescriptorid, b.codevalue, b.namespace, b.id, 'edfi.DeliveryMethodDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.deliverymethoddescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'deliverymethoddescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.deliverymethoddescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.deliverymethoddescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.diagnosisdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.diagnosisdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.DiagnosisDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.diagnosisdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'diagnosisdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.diagnosisdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.diagnosisdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.diplomaleveldescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.diplomaleveldescriptorid, b.codevalue, b.namespace, b.id, 'edfi.DiplomaLevelDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.diplomaleveldescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'diplomaleveldescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.diplomaleveldescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.diplomaleveldescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.diplomatypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.diplomatypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.DiplomaTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.diplomatypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'diplomatypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.diplomatypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.diplomatypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.disabilitydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.disabilitydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.DisabilityDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.disabilitydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'disabilitydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.disabilitydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.disabilitydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.disabilitydesignationdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.disabilitydesignationdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.DisabilityDesignationDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.disabilitydesignationdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'disabilitydesignationdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.disabilitydesignationdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.disabilitydesignationdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.disabilitydeterminationsourcetypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.disabilitydeterminationsourcetypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.DisabilityDeterminationSourceTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.disabilitydeterminationsourcetypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'disabilitydeterminationsourcetypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.disabilitydeterminationsourcetypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.disabilitydeterminationsourcetypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.disciplineaction_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj2 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj2 * FROM edfi.student j2 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.disciplineaction( + olddisciplineactionidentifier, olddisciplinedate, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.disciplineactionidentifier, OLD.disciplinedate, OLD.studentusi, dj2.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'disciplineaction') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.disciplineaction + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.disciplineaction_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.disciplineactionlengthdifferencereasondescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.disciplineactionlengthdifferencereasondescriptorid, b.codevalue, b.namespace, b.id, 'edfi.DisciplineActionLengthDifferenceReasonDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.disciplineactionlengthdifferencereasondescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'disciplineactionlengthdifferencereasondescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.disciplineactionlengthdifferencereasondescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.disciplineactionlengthdifferencereasondescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.disciplinedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.disciplinedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.DisciplineDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.disciplinedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'disciplinedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.disciplinedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.disciplinedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.disciplineincident_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.disciplineincident( + oldincidentidentifier, oldschoolid, + id, discriminator, changeversion) + VALUES( + OLD.incidentidentifier, OLD.schoolid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'disciplineincident') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.disciplineincident + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.disciplineincident_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.disciplineincidentparticipationcodedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.disciplineincidentparticipationcodedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.DisciplineIncidentParticipationCodeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.disciplineincidentparticipationcodedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'disciplineincidentparticipationcodedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.disciplineincidentparticipationcodedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.disciplineincidentparticipationcodedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.educationalenvironmentdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.educationalenvironmentdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.EducationalEnvironmentDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.educationalenvironmentdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'educationalenvironmentdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.educationalenvironmentdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.educationalenvironmentdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.educationcontent_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.educationcontent( + oldcontentidentifier, + id, discriminator, changeversion) + VALUES( + OLD.contentidentifier, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'educationcontent') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.educationcontent + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.educationcontent_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.educationorganization_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.educationorganization( + oldeducationorganizationid, + id, discriminator, changeversion) + VALUES( + OLD.educationorganizationid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'educationorganization') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.educationorganization + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.educationorganization_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.educationorganizationcategorydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.educationorganizationcategorydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.EducationOrganizationCategoryDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.educationorganizationcategorydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'educationorganizationcategorydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.educationorganizationcategorydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.educationorganizationcategorydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.educationorganizationidentificationsystemdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.educationorganizationidentificationsystemdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.EducationOrganizationIdentificationSystemDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.educationorganizationidentificationsystemdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'educationorganizationidentificationsystemdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.educationorganizationidentificationsystemdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.educationorganizationidentificationsystemdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.educationorganizationinterventionprescriptionass_e670ae_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.educationorganizationinterventionprescriptionassociation( + oldeducationorganizationid, oldinterventionprescriptioneducationorganizationid, oldinterventionprescriptionidentificationcode, + id, discriminator, changeversion) + VALUES( + OLD.educationorganizationid, OLD.interventionprescriptioneducationorganizationid, OLD.interventionprescriptionidentificationcode, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'educationorganizationinterventionprescriptionassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.educationorganizationinterventionprescriptionassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.educationorganizationinterventionprescriptionass_e670ae_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.educationorganizationnetworkassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.educationorganizationnetworkassociation( + oldeducationorganizationnetworkid, oldmembereducationorganizationid, + id, discriminator, changeversion) + VALUES( + OLD.educationorganizationnetworkid, OLD.membereducationorganizationid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'educationorganizationnetworkassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.educationorganizationnetworkassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.educationorganizationnetworkassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.educationorganizationpeerassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.educationorganizationpeerassociation( + oldeducationorganizationid, oldpeereducationorganizationid, + id, discriminator, changeversion) + VALUES( + OLD.educationorganizationid, OLD.peereducationorganizationid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'educationorganizationpeerassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.educationorganizationpeerassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.educationorganizationpeerassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.educationplandescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.educationplandescriptorid, b.codevalue, b.namespace, b.id, 'edfi.EducationPlanDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.educationplandescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'educationplandescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.educationplandescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.educationplandescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.electronicmailtypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.electronicmailtypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ElectronicMailTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.electronicmailtypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'electronicmailtypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.electronicmailtypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.electronicmailtypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.employmentstatusdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.employmentstatusdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.EmploymentStatusDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.employmentstatusdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'employmentstatusdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.employmentstatusdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.employmentstatusdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.entrygradelevelreasondescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.entrygradelevelreasondescriptorid, b.codevalue, b.namespace, b.id, 'edfi.EntryGradeLevelReasonDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.entrygradelevelreasondescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'entrygradelevelreasondescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.entrygradelevelreasondescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.entrygradelevelreasondescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.entrytypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.entrytypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.EntryTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.entrytypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'entrytypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.entrytypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.entrytypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.eventcircumstancedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.eventcircumstancedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.EventCircumstanceDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.eventcircumstancedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'eventcircumstancedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.eventcircumstancedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.eventcircumstancedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.exitwithdrawtypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.exitwithdrawtypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ExitWithdrawTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.exitwithdrawtypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'exitwithdrawtypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.exitwithdrawtypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.exitwithdrawtypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.feederschoolassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.feederschoolassociation( + oldbegindate, oldfeederschoolid, oldschoolid, + id, discriminator, changeversion) + VALUES( + OLD.begindate, OLD.feederschoolid, OLD.schoolid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'feederschoolassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.feederschoolassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.feederschoolassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.generalstudentprogramassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj4 edfi.descriptor%ROWTYPE; + dj5 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj4 * FROM edfi.descriptor j4 WHERE descriptorid = old.programtypedescriptorid; + SELECT INTO dj5 * FROM edfi.student j5 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.generalstudentprogramassociation( + oldbegindate, oldeducationorganizationid, oldprogrameducationorganizationid, oldprogramname, oldprogramtypedescriptorid, oldprogramtypedescriptornamespace, oldprogramtypedescriptorcodevalue, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.begindate, OLD.educationorganizationid, OLD.programeducationorganizationid, OLD.programname, OLD.programtypedescriptorid, dj4.namespace, dj4.codevalue, OLD.studentusi, dj5.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'generalstudentprogramassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.generalstudentprogramassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.generalstudentprogramassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.grade_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj1 edfi.descriptor%ROWTYPE; + dj2 edfi.descriptor%ROWTYPE; + dj10 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj1 * FROM edfi.descriptor j1 WHERE descriptorid = old.gradetypedescriptorid; + SELECT INTO dj2 * FROM edfi.descriptor j2 WHERE descriptorid = old.gradingperioddescriptorid; + SELECT INTO dj10 * FROM edfi.student j10 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.grade( + oldbegindate, oldgradetypedescriptorid, oldgradetypedescriptornamespace, oldgradetypedescriptorcodevalue, oldgradingperioddescriptorid, oldgradingperioddescriptornamespace, oldgradingperioddescriptorcodevalue, oldgradingperiodschoolyear, oldgradingperiodsequence, oldlocalcoursecode, oldschoolid, oldschoolyear, oldsectionidentifier, oldsessionname, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.begindate, OLD.gradetypedescriptorid, dj1.namespace, dj1.codevalue, OLD.gradingperioddescriptorid, dj2.namespace, dj2.codevalue, OLD.gradingperiodschoolyear, OLD.gradingperiodsequence, OLD.localcoursecode, OLD.schoolid, OLD.schoolyear, OLD.sectionidentifier, OLD.sessionname, OLD.studentusi, dj10.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'grade') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.grade + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.grade_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.gradebookentry_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.gradebookentry( + olddateassigned, oldgradebookentrytitle, oldlocalcoursecode, oldschoolid, oldschoolyear, oldsectionidentifier, oldsessionname, + id, discriminator, changeversion) + VALUES( + OLD.dateassigned, OLD.gradebookentrytitle, OLD.localcoursecode, OLD.schoolid, OLD.schoolyear, OLD.sectionidentifier, OLD.sessionname, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'gradebookentry') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.gradebookentry + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.gradebookentry_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.gradebookentrytypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.gradebookentrytypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.GradebookEntryTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.gradebookentrytypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'gradebookentrytypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.gradebookentrytypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.gradebookentrytypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.gradeleveldescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.gradeleveldescriptorid, b.codevalue, b.namespace, b.id, 'edfi.GradeLevelDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.gradeleveldescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'gradeleveldescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.gradeleveldescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.gradeleveldescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.gradepointaveragetypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.gradepointaveragetypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.GradePointAverageTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.gradepointaveragetypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'gradepointaveragetypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.gradepointaveragetypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.gradepointaveragetypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.gradetypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.gradetypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.GradeTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.gradetypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'gradetypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.gradetypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.gradetypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.gradingperiod_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj0 edfi.descriptor%ROWTYPE; +BEGIN + SELECT INTO dj0 * FROM edfi.descriptor j0 WHERE descriptorid = old.gradingperioddescriptorid; + + INSERT INTO tracked_changes_edfi.gradingperiod( + oldgradingperioddescriptorid, oldgradingperioddescriptornamespace, oldgradingperioddescriptorcodevalue, oldperiodsequence, oldschoolid, oldschoolyear, + id, discriminator, changeversion) + VALUES( + OLD.gradingperioddescriptorid, dj0.namespace, dj0.codevalue, OLD.periodsequence, OLD.schoolid, OLD.schoolyear, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'gradingperiod') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.gradingperiod + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.gradingperiod_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.gradingperioddescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.gradingperioddescriptorid, b.codevalue, b.namespace, b.id, 'edfi.GradingPeriodDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.gradingperioddescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'gradingperioddescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.gradingperioddescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.gradingperioddescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.graduationplan_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj1 edfi.descriptor%ROWTYPE; +BEGIN + SELECT INTO dj1 * FROM edfi.descriptor j1 WHERE descriptorid = old.graduationplantypedescriptorid; + + INSERT INTO tracked_changes_edfi.graduationplan( + oldeducationorganizationid, oldgraduationplantypedescriptorid, oldgraduationplantypedescriptornamespace, oldgraduationplantypedescriptorcodevalue, oldgraduationschoolyear, + id, discriminator, changeversion) + VALUES( + OLD.educationorganizationid, OLD.graduationplantypedescriptorid, dj1.namespace, dj1.codevalue, OLD.graduationschoolyear, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'graduationplan') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.graduationplan + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.graduationplan_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.graduationplantypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.graduationplantypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.GraduationPlanTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.graduationplantypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'graduationplantypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.graduationplantypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.graduationplantypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.gunfreeschoolsactreportingstatusdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.gunfreeschoolsactreportingstatusdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.GunFreeSchoolsActReportingStatusDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.gunfreeschoolsactreportingstatusdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'gunfreeschoolsactreportingstatusdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.gunfreeschoolsactreportingstatusdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.gunfreeschoolsactreportingstatusdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.homelessprimarynighttimeresidencedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.homelessprimarynighttimeresidencedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.HomelessPrimaryNighttimeResidenceDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.homelessprimarynighttimeresidencedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'homelessprimarynighttimeresidencedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.homelessprimarynighttimeresidencedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.homelessprimarynighttimeresidencedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.homelessprogramservicedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.homelessprogramservicedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.HomelessProgramServiceDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.homelessprogramservicedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'homelessprogramservicedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.homelessprogramservicedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.homelessprogramservicedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.identificationdocumentusedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.identificationdocumentusedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.IdentificationDocumentUseDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.identificationdocumentusedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'identificationdocumentusedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.identificationdocumentusedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.identificationdocumentusedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.incidentlocationdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.incidentlocationdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.IncidentLocationDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.incidentlocationdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'incidentlocationdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.incidentlocationdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.incidentlocationdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.indicatordescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.indicatordescriptorid, b.codevalue, b.namespace, b.id, 'edfi.IndicatorDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.indicatordescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'indicatordescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.indicatordescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.indicatordescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.indicatorgroupdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.indicatorgroupdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.IndicatorGroupDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.indicatorgroupdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'indicatorgroupdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.indicatorgroupdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.indicatorgroupdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.indicatorleveldescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.indicatorleveldescriptorid, b.codevalue, b.namespace, b.id, 'edfi.IndicatorLevelDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.indicatorleveldescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'indicatorleveldescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.indicatorleveldescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.indicatorleveldescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.institutiontelephonenumbertypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.institutiontelephonenumbertypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.InstitutionTelephoneNumberTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.institutiontelephonenumbertypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'institutiontelephonenumbertypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.institutiontelephonenumbertypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.institutiontelephonenumbertypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.interactivitystyledescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.interactivitystyledescriptorid, b.codevalue, b.namespace, b.id, 'edfi.InteractivityStyleDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.interactivitystyledescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'interactivitystyledescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.interactivitystyledescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.interactivitystyledescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.internetaccessdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.internetaccessdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.InternetAccessDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.internetaccessdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'internetaccessdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.internetaccessdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.internetaccessdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.intervention_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.intervention( + oldeducationorganizationid, oldinterventionidentificationcode, + id, discriminator, changeversion) + VALUES( + OLD.educationorganizationid, OLD.interventionidentificationcode, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'intervention') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.intervention + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.intervention_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.interventionclassdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.interventionclassdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.InterventionClassDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.interventionclassdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'interventionclassdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.interventionclassdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.interventionclassdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.interventioneffectivenessratingdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.interventioneffectivenessratingdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.InterventionEffectivenessRatingDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.interventioneffectivenessratingdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'interventioneffectivenessratingdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.interventioneffectivenessratingdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.interventioneffectivenessratingdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.interventionprescription_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.interventionprescription( + oldeducationorganizationid, oldinterventionprescriptionidentificationcode, + id, discriminator, changeversion) + VALUES( + OLD.educationorganizationid, OLD.interventionprescriptionidentificationcode, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'interventionprescription') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.interventionprescription + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.interventionprescription_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.interventionstudy_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.interventionstudy( + oldeducationorganizationid, oldinterventionstudyidentificationcode, + id, discriminator, changeversion) + VALUES( + OLD.educationorganizationid, OLD.interventionstudyidentificationcode, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'interventionstudy') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.interventionstudy + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.interventionstudy_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.languagedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.languagedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.LanguageDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.languagedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'languagedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.languagedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.languagedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.languageinstructionprogramservicedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.languageinstructionprogramservicedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.LanguageInstructionProgramServiceDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.languageinstructionprogramservicedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'languageinstructionprogramservicedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.languageinstructionprogramservicedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.languageinstructionprogramservicedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.languageusedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.languageusedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.LanguageUseDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.languageusedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'languageusedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.languageusedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.languageusedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.learningobjective_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.learningobjective( + oldlearningobjectiveid, oldnamespace, + id, discriminator, changeversion) + VALUES( + OLD.learningobjectiveid, OLD.namespace, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'learningobjective') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.learningobjective + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.learningobjective_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.learningstandard_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.learningstandard( + oldlearningstandardid, + id, discriminator, changeversion) + VALUES( + OLD.learningstandardid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'learningstandard') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.learningstandard + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.learningstandard_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.learningstandardcategorydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.learningstandardcategorydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.LearningStandardCategoryDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.learningstandardcategorydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'learningstandardcategorydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.learningstandardcategorydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.learningstandardcategorydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.learningstandardequivalenceassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.learningstandardequivalenceassociation( + oldnamespace, oldsourcelearningstandardid, oldtargetlearningstandardid, + id, discriminator, changeversion) + VALUES( + OLD.namespace, OLD.sourcelearningstandardid, OLD.targetlearningstandardid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'learningstandardequivalenceassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.learningstandardequivalenceassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.learningstandardequivalenceassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.learningstandardequivalencestrengthdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.learningstandardequivalencestrengthdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.LearningStandardEquivalenceStrengthDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.learningstandardequivalencestrengthdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'learningstandardequivalencestrengthdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.learningstandardequivalencestrengthdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.learningstandardequivalencestrengthdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.learningstandardscopedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.learningstandardscopedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.LearningStandardScopeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.learningstandardscopedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'learningstandardscopedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.learningstandardscopedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.learningstandardscopedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.levelofeducationdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.levelofeducationdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.LevelOfEducationDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.levelofeducationdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'levelofeducationdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.levelofeducationdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.levelofeducationdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.licensestatusdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.licensestatusdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.LicenseStatusDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.licensestatusdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'licensestatusdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.licensestatusdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.licensestatusdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.licensetypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.licensetypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.LicenseTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.licensetypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'licensetypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.licensetypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.licensetypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.limitedenglishproficiencydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.limitedenglishproficiencydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.LimitedEnglishProficiencyDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.limitedenglishproficiencydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'limitedenglishproficiencydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.limitedenglishproficiencydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.limitedenglishproficiencydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.localedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.localedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.LocaleDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.localedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'localedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.localedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.localedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.localeducationagencycategorydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.localeducationagencycategorydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.LocalEducationAgencyCategoryDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.localeducationagencycategorydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'localeducationagencycategorydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.localeducationagencycategorydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.localeducationagencycategorydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.location_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.location( + oldclassroomidentificationcode, oldschoolid, + id, discriminator, changeversion) + VALUES( + OLD.classroomidentificationcode, OLD.schoolid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'location') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.location + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.location_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.magnetspecialprogramemphasisschooldescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.magnetspecialprogramemphasisschooldescriptorid, b.codevalue, b.namespace, b.id, 'edfi.MagnetSpecialProgramEmphasisSchoolDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.magnetspecialprogramemphasisschooldescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'magnetspecialprogramemphasisschooldescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.magnetspecialprogramemphasisschooldescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.magnetspecialprogramemphasisschooldescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.mediumofinstructiondescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.mediumofinstructiondescriptorid, b.codevalue, b.namespace, b.id, 'edfi.MediumOfInstructionDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.mediumofinstructiondescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'mediumofinstructiondescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.mediumofinstructiondescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.mediumofinstructiondescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.methodcreditearneddescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.methodcreditearneddescriptorid, b.codevalue, b.namespace, b.id, 'edfi.MethodCreditEarnedDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.methodcreditearneddescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'methodcreditearneddescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.methodcreditearneddescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.methodcreditearneddescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.migranteducationprogramservicedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.migranteducationprogramservicedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.MigrantEducationProgramServiceDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.migranteducationprogramservicedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'migranteducationprogramservicedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.migranteducationprogramservicedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.migranteducationprogramservicedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.monitoreddescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.monitoreddescriptorid, b.codevalue, b.namespace, b.id, 'edfi.MonitoredDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.monitoreddescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'monitoreddescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.monitoreddescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.monitoreddescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.neglectedordelinquentprogramdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.neglectedordelinquentprogramdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.NeglectedOrDelinquentProgramDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.neglectedordelinquentprogramdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'neglectedordelinquentprogramdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.neglectedordelinquentprogramdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.neglectedordelinquentprogramdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.neglectedordelinquentprogramservicedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.neglectedordelinquentprogramservicedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.NeglectedOrDelinquentProgramServiceDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.neglectedordelinquentprogramservicedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'neglectedordelinquentprogramservicedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.neglectedordelinquentprogramservicedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.neglectedordelinquentprogramservicedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.networkpurposedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.networkpurposedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.NetworkPurposeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.networkpurposedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'networkpurposedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.networkpurposedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.networkpurposedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.objectiveassessment_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.objectiveassessment( + oldassessmentidentifier, oldidentificationcode, oldnamespace, + id, discriminator, changeversion) + VALUES( + OLD.assessmentidentifier, OLD.identificationcode, OLD.namespace, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'objectiveassessment') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.objectiveassessment + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.objectiveassessment_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.oldethnicitydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.oldethnicitydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.OldEthnicityDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.oldethnicitydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'oldethnicitydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.oldethnicitydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.oldethnicitydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.openstaffposition_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.openstaffposition( + oldeducationorganizationid, oldrequisitionnumber, + id, discriminator, changeversion) + VALUES( + OLD.educationorganizationid, OLD.requisitionnumber, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'openstaffposition') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.openstaffposition + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.openstaffposition_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.operationalstatusdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.operationalstatusdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.OperationalStatusDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.operationalstatusdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'operationalstatusdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.operationalstatusdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.operationalstatusdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.othernametypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.othernametypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.OtherNameTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.othernametypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'othernametypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.othernametypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.othernametypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.parent_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.parent( + oldparentusi, oldparentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.parentusi, OLD.parentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'parent') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.parent + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.parent_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.participationdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.participationdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ParticipationDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.participationdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'participationdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.participationdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.participationdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.participationstatusdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.participationstatusdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ParticipationStatusDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.participationstatusdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'participationstatusdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.participationstatusdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.participationstatusdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.payroll_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj4 edfi.staff%ROWTYPE; +BEGIN + SELECT INTO dj4 * FROM edfi.staff j4 WHERE staffusi = old.staffusi; + + INSERT INTO tracked_changes_edfi.payroll( + oldaccountidentifier, oldasofdate, oldeducationorganizationid, oldfiscalyear, oldstaffusi, oldstaffuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.accountidentifier, OLD.asofdate, OLD.educationorganizationid, OLD.fiscalyear, OLD.staffusi, dj4.staffuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'payroll') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.payroll + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.payroll_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.performancebaseconversiondescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.performancebaseconversiondescriptorid, b.codevalue, b.namespace, b.id, 'edfi.PerformanceBaseConversionDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.performancebaseconversiondescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'performancebaseconversiondescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.performancebaseconversiondescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.performancebaseconversiondescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.performanceleveldescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.performanceleveldescriptorid, b.codevalue, b.namespace, b.id, 'edfi.PerformanceLevelDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.performanceleveldescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'performanceleveldescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.performanceleveldescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.performanceleveldescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.person_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj1 edfi.descriptor%ROWTYPE; +BEGIN + SELECT INTO dj1 * FROM edfi.descriptor j1 WHERE descriptorid = old.sourcesystemdescriptorid; + + INSERT INTO tracked_changes_edfi.person( + oldpersonid, oldsourcesystemdescriptorid, oldsourcesystemdescriptornamespace, oldsourcesystemdescriptorcodevalue, + id, discriminator, changeversion) + VALUES( + OLD.personid, OLD.sourcesystemdescriptorid, dj1.namespace, dj1.codevalue, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'person') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.person + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.person_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.personalinformationverificationdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.personalinformationverificationdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.PersonalInformationVerificationDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.personalinformationverificationdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'personalinformationverificationdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.personalinformationverificationdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.personalinformationverificationdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.platformtypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.platformtypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.PlatformTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.platformtypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'platformtypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.platformtypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.platformtypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.populationserveddescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.populationserveddescriptorid, b.codevalue, b.namespace, b.id, 'edfi.PopulationServedDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.populationserveddescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'populationserveddescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.populationserveddescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.populationserveddescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.postingresultdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.postingresultdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.PostingResultDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.postingresultdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'postingresultdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.postingresultdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.postingresultdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.postsecondaryevent_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj1 edfi.descriptor%ROWTYPE; + dj2 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj1 * FROM edfi.descriptor j1 WHERE descriptorid = old.postsecondaryeventcategorydescriptorid; + SELECT INTO dj2 * FROM edfi.student j2 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.postsecondaryevent( + oldeventdate, oldpostsecondaryeventcategorydescriptorid, oldpostsecondaryeventcategorydescriptornamespace, oldpostsecondaryeventcategorydescriptorcodevalue, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.eventdate, OLD.postsecondaryeventcategorydescriptorid, dj1.namespace, dj1.codevalue, OLD.studentusi, dj2.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'postsecondaryevent') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.postsecondaryevent + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.postsecondaryevent_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.postsecondaryeventcategorydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.postsecondaryeventcategorydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.PostSecondaryEventCategoryDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.postsecondaryeventcategorydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'postsecondaryeventcategorydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.postsecondaryeventcategorydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.postsecondaryeventcategorydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.postsecondaryinstitutionleveldescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.postsecondaryinstitutionleveldescriptorid, b.codevalue, b.namespace, b.id, 'edfi.PostSecondaryInstitutionLevelDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.postsecondaryinstitutionleveldescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'postsecondaryinstitutionleveldescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.postsecondaryinstitutionleveldescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.postsecondaryinstitutionleveldescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.proficiencydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.proficiencydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ProficiencyDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.proficiencydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'proficiencydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.proficiencydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.proficiencydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.program_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj2 edfi.descriptor%ROWTYPE; +BEGIN + SELECT INTO dj2 * FROM edfi.descriptor j2 WHERE descriptorid = old.programtypedescriptorid; + + INSERT INTO tracked_changes_edfi.program( + oldeducationorganizationid, oldprogramname, oldprogramtypedescriptorid, oldprogramtypedescriptornamespace, oldprogramtypedescriptorcodevalue, + id, discriminator, changeversion) + VALUES( + OLD.educationorganizationid, OLD.programname, OLD.programtypedescriptorid, dj2.namespace, dj2.codevalue, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'program') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.program + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.program_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.programassignmentdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.programassignmentdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ProgramAssignmentDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.programassignmentdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'programassignmentdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.programassignmentdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.programassignmentdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.programcharacteristicdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.programcharacteristicdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ProgramCharacteristicDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.programcharacteristicdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'programcharacteristicdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.programcharacteristicdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.programcharacteristicdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.programsponsordescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.programsponsordescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ProgramSponsorDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.programsponsordescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'programsponsordescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.programsponsordescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.programsponsordescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.programtypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.programtypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ProgramTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.programtypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'programtypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.programtypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.programtypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.progressdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.progressdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ProgressDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.progressdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'progressdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.progressdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.progressdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.progressleveldescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.progressleveldescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ProgressLevelDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.progressleveldescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'progressleveldescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.progressleveldescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.progressleveldescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.providercategorydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.providercategorydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ProviderCategoryDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.providercategorydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'providercategorydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.providercategorydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.providercategorydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.providerprofitabilitydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.providerprofitabilitydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ProviderProfitabilityDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.providerprofitabilitydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'providerprofitabilitydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.providerprofitabilitydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.providerprofitabilitydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.providerstatusdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.providerstatusdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ProviderStatusDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.providerstatusdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'providerstatusdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.providerstatusdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.providerstatusdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.publicationstatusdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.publicationstatusdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.PublicationStatusDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.publicationstatusdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'publicationstatusdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.publicationstatusdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.publicationstatusdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.questionformdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.questionformdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.QuestionFormDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.questionformdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'questionformdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.questionformdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.questionformdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.racedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.racedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.RaceDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.racedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'racedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.racedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.racedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.reasonexiteddescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.reasonexiteddescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ReasonExitedDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.reasonexiteddescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'reasonexiteddescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.reasonexiteddescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.reasonexiteddescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.reasonnottesteddescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.reasonnottesteddescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ReasonNotTestedDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.reasonnottesteddescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'reasonnottesteddescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.reasonnottesteddescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.reasonnottesteddescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.recognitiontypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.recognitiontypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.RecognitionTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.recognitiontypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'recognitiontypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.recognitiontypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.recognitiontypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.relationdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.relationdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.RelationDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.relationdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'relationdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.relationdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.relationdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.repeatidentifierdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.repeatidentifierdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.RepeatIdentifierDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.repeatidentifierdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'repeatidentifierdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.repeatidentifierdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.repeatidentifierdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.reportcard_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj1 edfi.descriptor%ROWTYPE; + dj5 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj1 * FROM edfi.descriptor j1 WHERE descriptorid = old.gradingperioddescriptorid; + SELECT INTO dj5 * FROM edfi.student j5 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.reportcard( + oldeducationorganizationid, oldgradingperioddescriptorid, oldgradingperioddescriptornamespace, oldgradingperioddescriptorcodevalue, oldgradingperiodschoolid, oldgradingperiodschoolyear, oldgradingperiodsequence, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.educationorganizationid, OLD.gradingperioddescriptorid, dj1.namespace, dj1.codevalue, OLD.gradingperiodschoolid, OLD.gradingperiodschoolyear, OLD.gradingperiodsequence, OLD.studentusi, dj5.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'reportcard') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.reportcard + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.reportcard_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.reporterdescriptiondescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.reporterdescriptiondescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ReporterDescriptionDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.reporterdescriptiondescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'reporterdescriptiondescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.reporterdescriptiondescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.reporterdescriptiondescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.residencystatusdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.residencystatusdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ResidencyStatusDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.residencystatusdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'residencystatusdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.residencystatusdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.residencystatusdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.responseindicatordescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.responseindicatordescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ResponseIndicatorDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.responseindicatordescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'responseindicatordescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.responseindicatordescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.responseindicatordescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.responsibilitydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.responsibilitydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ResponsibilityDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.responsibilitydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'responsibilitydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.responsibilitydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.responsibilitydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.restraintevent_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj2 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj2 * FROM edfi.student j2 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.restraintevent( + oldrestrainteventidentifier, oldschoolid, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.restrainteventidentifier, OLD.schoolid, OLD.studentusi, dj2.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'restraintevent') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.restraintevent + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.restraintevent_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.restrainteventreasondescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.restrainteventreasondescriptorid, b.codevalue, b.namespace, b.id, 'edfi.RestraintEventReasonDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.restrainteventreasondescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'restrainteventreasondescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.restrainteventreasondescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.restrainteventreasondescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.resultdatatypetypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.resultdatatypetypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ResultDatatypeTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.resultdatatypetypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'resultdatatypetypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.resultdatatypetypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.resultdatatypetypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.retestindicatordescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.retestindicatordescriptorid, b.codevalue, b.namespace, b.id, 'edfi.RetestIndicatorDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.retestindicatordescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'retestindicatordescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.retestindicatordescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.retestindicatordescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.schoolcategorydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.schoolcategorydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.SchoolCategoryDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.schoolcategorydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'schoolcategorydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.schoolcategorydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.schoolcategorydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.schoolchoiceimplementstatusdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.schoolchoiceimplementstatusdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.SchoolChoiceImplementStatusDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.schoolchoiceimplementstatusdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'schoolchoiceimplementstatusdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.schoolchoiceimplementstatusdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.schoolchoiceimplementstatusdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.schoolfoodserviceprogramservicedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.schoolfoodserviceprogramservicedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.SchoolFoodServiceProgramServiceDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.schoolfoodserviceprogramservicedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'schoolfoodserviceprogramservicedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.schoolfoodserviceprogramservicedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.schoolfoodserviceprogramservicedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.schooltypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.schooltypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.SchoolTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.schooltypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'schooltypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.schooltypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.schooltypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.schoolyeartype_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.schoolyeartype( + oldschoolyear, + id, changeversion) + VALUES( + OLD.schoolyear, + OLD.id, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'schoolyeartype') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.schoolyeartype + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.schoolyeartype_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.section_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.section( + oldlocalcoursecode, oldschoolid, oldschoolyear, oldsectionidentifier, oldsessionname, + id, discriminator, changeversion) + VALUES( + OLD.localcoursecode, OLD.schoolid, OLD.schoolyear, OLD.sectionidentifier, OLD.sessionname, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'section') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.section + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.section_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.sectionattendancetakenevent_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.sectionattendancetakenevent( + oldcalendarcode, olddate, oldlocalcoursecode, oldschoolid, oldschoolyear, oldsectionidentifier, oldsessionname, + id, discriminator, changeversion) + VALUES( + OLD.calendarcode, OLD.date, OLD.localcoursecode, OLD.schoolid, OLD.schoolyear, OLD.sectionidentifier, OLD.sessionname, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'sectionattendancetakenevent') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.sectionattendancetakenevent + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.sectionattendancetakenevent_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.sectioncharacteristicdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.sectioncharacteristicdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.SectionCharacteristicDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.sectioncharacteristicdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'sectioncharacteristicdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.sectioncharacteristicdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.sectioncharacteristicdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.separationdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.separationdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.SeparationDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.separationdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'separationdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.separationdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.separationdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.separationreasondescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.separationreasondescriptorid, b.codevalue, b.namespace, b.id, 'edfi.SeparationReasonDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.separationreasondescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'separationreasondescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.separationreasondescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.separationreasondescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.servicedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.servicedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.ServiceDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.servicedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'servicedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.servicedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.servicedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.session_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.session( + oldschoolid, oldschoolyear, oldsessionname, + id, discriminator, changeversion) + VALUES( + OLD.schoolid, OLD.schoolyear, OLD.sessionname, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'session') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.session + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.session_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.sexdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.sexdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.SexDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.sexdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'sexdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.sexdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.sexdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.sourcesystemdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.sourcesystemdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.SourceSystemDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.sourcesystemdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'sourcesystemdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.sourcesystemdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.sourcesystemdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.specialeducationprogramservicedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.specialeducationprogramservicedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.SpecialEducationProgramServiceDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.specialeducationprogramservicedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'specialeducationprogramservicedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.specialeducationprogramservicedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.specialeducationprogramservicedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.specialeducationsettingdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.specialeducationsettingdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.SpecialEducationSettingDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.specialeducationsettingdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'specialeducationsettingdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.specialeducationsettingdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.specialeducationsettingdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.staff_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.staff( + oldstaffusi, oldstaffuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.staffusi, OLD.staffuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'staff') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.staff + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.staff_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.staffabsenceevent_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj0 edfi.descriptor%ROWTYPE; + dj2 edfi.staff%ROWTYPE; +BEGIN + SELECT INTO dj0 * FROM edfi.descriptor j0 WHERE descriptorid = old.absenceeventcategorydescriptorid; + SELECT INTO dj2 * FROM edfi.staff j2 WHERE staffusi = old.staffusi; + + INSERT INTO tracked_changes_edfi.staffabsenceevent( + oldabsenceeventcategorydescriptorid, oldabsenceeventcategorydescriptornamespace, oldabsenceeventcategorydescriptorcodevalue, oldeventdate, oldstaffusi, oldstaffuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.absenceeventcategorydescriptorid, dj0.namespace, dj0.codevalue, OLD.eventdate, OLD.staffusi, dj2.staffuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'staffabsenceevent') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.staffabsenceevent + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.staffabsenceevent_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.staffclassificationdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.staffclassificationdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.StaffClassificationDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.staffclassificationdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'staffclassificationdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.staffclassificationdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.staffclassificationdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.staffcohortassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj3 edfi.staff%ROWTYPE; +BEGIN + SELECT INTO dj3 * FROM edfi.staff j3 WHERE staffusi = old.staffusi; + + INSERT INTO tracked_changes_edfi.staffcohortassociation( + oldbegindate, oldcohortidentifier, oldeducationorganizationid, oldstaffusi, oldstaffuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.begindate, OLD.cohortidentifier, OLD.educationorganizationid, OLD.staffusi, dj3.staffuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'staffcohortassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.staffcohortassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.staffcohortassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.staffdisciplineincidentassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj2 edfi.staff%ROWTYPE; +BEGIN + SELECT INTO dj2 * FROM edfi.staff j2 WHERE staffusi = old.staffusi; + + INSERT INTO tracked_changes_edfi.staffdisciplineincidentassociation( + oldincidentidentifier, oldschoolid, oldstaffusi, oldstaffuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.incidentidentifier, OLD.schoolid, OLD.staffusi, dj2.staffuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'staffdisciplineincidentassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.staffdisciplineincidentassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.staffdisciplineincidentassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.staffeducationorganizationassignmentassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj2 edfi.descriptor%ROWTYPE; + dj3 edfi.staff%ROWTYPE; +BEGIN + SELECT INTO dj2 * FROM edfi.descriptor j2 WHERE descriptorid = old.staffclassificationdescriptorid; + SELECT INTO dj3 * FROM edfi.staff j3 WHERE staffusi = old.staffusi; + + INSERT INTO tracked_changes_edfi.staffeducationorganizationassignmentassociation( + oldbegindate, oldeducationorganizationid, oldstaffclassificationdescriptorid, oldstaffclassificationdescriptornamespace, oldstaffclassificationdescriptorcodevalue, oldstaffusi, oldstaffuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.begindate, OLD.educationorganizationid, OLD.staffclassificationdescriptorid, dj2.namespace, dj2.codevalue, OLD.staffusi, dj3.staffuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'staffeducationorganizationassignmentassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.staffeducationorganizationassignmentassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.staffeducationorganizationassignmentassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.staffeducationorganizationcontactassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj2 edfi.staff%ROWTYPE; +BEGIN + SELECT INTO dj2 * FROM edfi.staff j2 WHERE staffusi = old.staffusi; + + INSERT INTO tracked_changes_edfi.staffeducationorganizationcontactassociation( + oldcontacttitle, oldeducationorganizationid, oldstaffusi, oldstaffuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.contacttitle, OLD.educationorganizationid, OLD.staffusi, dj2.staffuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'staffeducationorganizationcontactassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.staffeducationorganizationcontactassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.staffeducationorganizationcontactassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.staffeducationorganizationemploymentassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj1 edfi.descriptor%ROWTYPE; + dj3 edfi.staff%ROWTYPE; +BEGIN + SELECT INTO dj1 * FROM edfi.descriptor j1 WHERE descriptorid = old.employmentstatusdescriptorid; + SELECT INTO dj3 * FROM edfi.staff j3 WHERE staffusi = old.staffusi; + + INSERT INTO tracked_changes_edfi.staffeducationorganizationemploymentassociation( + oldeducationorganizationid, oldemploymentstatusdescriptorid, oldemploymentstatusdescriptornamespace, oldemploymentstatusdescriptorcodevalue, oldhiredate, oldstaffusi, oldstaffuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.educationorganizationid, OLD.employmentstatusdescriptorid, dj1.namespace, dj1.codevalue, OLD.hiredate, OLD.staffusi, dj3.staffuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'staffeducationorganizationemploymentassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.staffeducationorganizationemploymentassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.staffeducationorganizationemploymentassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.staffidentificationsystemdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.staffidentificationsystemdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.StaffIdentificationSystemDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.staffidentificationsystemdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'staffidentificationsystemdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.staffidentificationsystemdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.staffidentificationsystemdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.staffleave_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj1 edfi.descriptor%ROWTYPE; + dj2 edfi.staff%ROWTYPE; +BEGIN + SELECT INTO dj1 * FROM edfi.descriptor j1 WHERE descriptorid = old.staffleaveeventcategorydescriptorid; + SELECT INTO dj2 * FROM edfi.staff j2 WHERE staffusi = old.staffusi; + + INSERT INTO tracked_changes_edfi.staffleave( + oldbegindate, oldstaffleaveeventcategorydescriptorid, oldstaffleaveeventcategorydescriptornamespace, oldstaffleaveeventcategorydescriptorcodevalue, oldstaffusi, oldstaffuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.begindate, OLD.staffleaveeventcategorydescriptorid, dj1.namespace, dj1.codevalue, OLD.staffusi, dj2.staffuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'staffleave') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.staffleave + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.staffleave_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.staffleaveeventcategorydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.staffleaveeventcategorydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.StaffLeaveEventCategoryDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.staffleaveeventcategorydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'staffleaveeventcategorydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.staffleaveeventcategorydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.staffleaveeventcategorydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.staffprogramassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj3 edfi.descriptor%ROWTYPE; + dj4 edfi.staff%ROWTYPE; +BEGIN + SELECT INTO dj3 * FROM edfi.descriptor j3 WHERE descriptorid = old.programtypedescriptorid; + SELECT INTO dj4 * FROM edfi.staff j4 WHERE staffusi = old.staffusi; + + INSERT INTO tracked_changes_edfi.staffprogramassociation( + oldbegindate, oldprogrameducationorganizationid, oldprogramname, oldprogramtypedescriptorid, oldprogramtypedescriptornamespace, oldprogramtypedescriptorcodevalue, oldstaffusi, oldstaffuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.begindate, OLD.programeducationorganizationid, OLD.programname, OLD.programtypedescriptorid, dj3.namespace, dj3.codevalue, OLD.staffusi, dj4.staffuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'staffprogramassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.staffprogramassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.staffprogramassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.staffschoolassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj0 edfi.descriptor%ROWTYPE; + dj2 edfi.staff%ROWTYPE; +BEGIN + SELECT INTO dj0 * FROM edfi.descriptor j0 WHERE descriptorid = old.programassignmentdescriptorid; + SELECT INTO dj2 * FROM edfi.staff j2 WHERE staffusi = old.staffusi; + + INSERT INTO tracked_changes_edfi.staffschoolassociation( + oldprogramassignmentdescriptorid, oldprogramassignmentdescriptornamespace, oldprogramassignmentdescriptorcodevalue, oldschoolid, oldstaffusi, oldstaffuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.programassignmentdescriptorid, dj0.namespace, dj0.codevalue, OLD.schoolid, OLD.staffusi, dj2.staffuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'staffschoolassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.staffschoolassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.staffschoolassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.staffsectionassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj5 edfi.staff%ROWTYPE; +BEGIN + SELECT INTO dj5 * FROM edfi.staff j5 WHERE staffusi = old.staffusi; + + INSERT INTO tracked_changes_edfi.staffsectionassociation( + oldlocalcoursecode, oldschoolid, oldschoolyear, oldsectionidentifier, oldsessionname, oldstaffusi, oldstaffuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.localcoursecode, OLD.schoolid, OLD.schoolyear, OLD.sectionidentifier, OLD.sessionname, OLD.staffusi, dj5.staffuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'staffsectionassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.staffsectionassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.staffsectionassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.stateabbreviationdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.stateabbreviationdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.StateAbbreviationDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.stateabbreviationdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'stateabbreviationdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.stateabbreviationdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.stateabbreviationdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.student_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.student( + oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.studentusi, OLD.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'student') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.student + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.student_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentacademicrecord_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj2 edfi.student%ROWTYPE; + dj3 edfi.descriptor%ROWTYPE; +BEGIN + SELECT INTO dj2 * FROM edfi.student j2 WHERE studentusi = old.studentusi; + SELECT INTO dj3 * FROM edfi.descriptor j3 WHERE descriptorid = old.termdescriptorid; + + INSERT INTO tracked_changes_edfi.studentacademicrecord( + oldeducationorganizationid, oldschoolyear, oldstudentusi, oldstudentuniqueid, oldtermdescriptorid, oldtermdescriptornamespace, oldtermdescriptorcodevalue, + id, discriminator, changeversion) + VALUES( + OLD.educationorganizationid, OLD.schoolyear, OLD.studentusi, dj2.studentuniqueid, OLD.termdescriptorid, dj3.namespace, dj3.codevalue, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'studentacademicrecord') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.studentacademicrecord + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentacademicrecord_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentassessment_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj3 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj3 * FROM edfi.student j3 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.studentassessment( + oldassessmentidentifier, oldnamespace, oldstudentassessmentidentifier, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.assessmentidentifier, OLD.namespace, OLD.studentassessmentidentifier, OLD.studentusi, dj3.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'studentassessment') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.studentassessment + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentassessment_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentcharacteristicdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.studentcharacteristicdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.StudentCharacteristicDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.studentcharacteristicdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'studentcharacteristicdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.studentcharacteristicdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentcharacteristicdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentcohortassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj3 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj3 * FROM edfi.student j3 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.studentcohortassociation( + oldbegindate, oldcohortidentifier, oldeducationorganizationid, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.begindate, OLD.cohortidentifier, OLD.educationorganizationid, OLD.studentusi, dj3.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'studentcohortassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.studentcohortassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentcohortassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentcompetencyobjective_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj0 edfi.descriptor%ROWTYPE; + dj6 edfi.descriptor%ROWTYPE; + dj7 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj0 * FROM edfi.descriptor j0 WHERE descriptorid = old.gradingperioddescriptorid; + SELECT INTO dj6 * FROM edfi.descriptor j6 WHERE descriptorid = old.objectivegradeleveldescriptorid; + SELECT INTO dj7 * FROM edfi.student j7 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.studentcompetencyobjective( + oldgradingperioddescriptorid, oldgradingperioddescriptornamespace, oldgradingperioddescriptorcodevalue, oldgradingperiodschoolid, oldgradingperiodschoolyear, oldgradingperiodsequence, oldobjective, oldobjectiveeducationorganizationid, oldobjectivegradeleveldescriptorid, oldobjectivegradeleveldescriptornamespace, oldobjectivegradeleveldescriptorcodevalue, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.gradingperioddescriptorid, dj0.namespace, dj0.codevalue, OLD.gradingperiodschoolid, OLD.gradingperiodschoolyear, OLD.gradingperiodsequence, OLD.objective, OLD.objectiveeducationorganizationid, OLD.objectivegradeleveldescriptorid, dj6.namespace, dj6.codevalue, OLD.studentusi, dj7.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'studentcompetencyobjective') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.studentcompetencyobjective + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentcompetencyobjective_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentdisciplineincidentassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj2 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj2 * FROM edfi.student j2 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.studentdisciplineincidentassociation( + oldincidentidentifier, oldschoolid, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.incidentidentifier, OLD.schoolid, OLD.studentusi, dj2.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'studentdisciplineincidentassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.studentdisciplineincidentassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentdisciplineincidentassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentdisciplineincidentbehaviorassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj0 edfi.descriptor%ROWTYPE; + dj3 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj0 * FROM edfi.descriptor j0 WHERE descriptorid = old.behaviordescriptorid; + SELECT INTO dj3 * FROM edfi.student j3 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.studentdisciplineincidentbehaviorassociation( + oldbehaviordescriptorid, oldbehaviordescriptornamespace, oldbehaviordescriptorcodevalue, oldincidentidentifier, oldschoolid, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.behaviordescriptorid, dj0.namespace, dj0.codevalue, OLD.incidentidentifier, OLD.schoolid, OLD.studentusi, dj3.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'studentdisciplineincidentbehaviorassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.studentdisciplineincidentbehaviorassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentdisciplineincidentbehaviorassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentdisciplineincidentnonoffenderassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj2 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj2 * FROM edfi.student j2 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.studentdisciplineincidentnonoffenderassociation( + oldincidentidentifier, oldschoolid, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.incidentidentifier, OLD.schoolid, OLD.studentusi, dj2.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'studentdisciplineincidentnonoffenderassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.studentdisciplineincidentnonoffenderassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentdisciplineincidentnonoffenderassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studenteducationorganizationassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj1 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj1 * FROM edfi.student j1 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.studenteducationorganizationassociation( + oldeducationorganizationid, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.educationorganizationid, OLD.studentusi, dj1.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'studenteducationorganizationassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.studenteducationorganizationassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studenteducationorganizationassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studenteducationorganizationresponsibilityassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj2 edfi.descriptor%ROWTYPE; + dj3 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj2 * FROM edfi.descriptor j2 WHERE descriptorid = old.responsibilitydescriptorid; + SELECT INTO dj3 * FROM edfi.student j3 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.studenteducationorganizationresponsibilityassociation( + oldbegindate, oldeducationorganizationid, oldresponsibilitydescriptorid, oldresponsibilitydescriptornamespace, oldresponsibilitydescriptorcodevalue, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.begindate, OLD.educationorganizationid, OLD.responsibilitydescriptorid, dj2.namespace, dj2.codevalue, OLD.studentusi, dj3.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'studenteducationorganizationresponsibilityassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.studenteducationorganizationresponsibilityassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studenteducationorganizationresponsibilityassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentgradebookentry_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj8 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj8 * FROM edfi.student j8 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.studentgradebookentry( + oldbegindate, olddateassigned, oldgradebookentrytitle, oldlocalcoursecode, oldschoolid, oldschoolyear, oldsectionidentifier, oldsessionname, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.begindate, OLD.dateassigned, OLD.gradebookentrytitle, OLD.localcoursecode, OLD.schoolid, OLD.schoolyear, OLD.sectionidentifier, OLD.sessionname, OLD.studentusi, dj8.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'studentgradebookentry') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.studentgradebookentry + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentgradebookentry_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentidentificationsystemdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.studentidentificationsystemdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.StudentIdentificationSystemDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.studentidentificationsystemdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'studentidentificationsystemdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.studentidentificationsystemdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentidentificationsystemdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentinterventionassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj2 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj2 * FROM edfi.student j2 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.studentinterventionassociation( + oldeducationorganizationid, oldinterventionidentificationcode, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.educationorganizationid, OLD.interventionidentificationcode, OLD.studentusi, dj2.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'studentinterventionassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.studentinterventionassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentinterventionassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentinterventionattendanceevent_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj0 edfi.descriptor%ROWTYPE; + dj4 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj0 * FROM edfi.descriptor j0 WHERE descriptorid = old.attendanceeventcategorydescriptorid; + SELECT INTO dj4 * FROM edfi.student j4 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.studentinterventionattendanceevent( + oldattendanceeventcategorydescriptorid, oldattendanceeventcategorydescriptornamespace, oldattendanceeventcategorydescriptorcodevalue, oldeducationorganizationid, oldeventdate, oldinterventionidentificationcode, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.attendanceeventcategorydescriptorid, dj0.namespace, dj0.codevalue, OLD.educationorganizationid, OLD.eventdate, OLD.interventionidentificationcode, OLD.studentusi, dj4.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'studentinterventionattendanceevent') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.studentinterventionattendanceevent + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentinterventionattendanceevent_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentlearningobjective_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj0 edfi.descriptor%ROWTYPE; + dj6 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj0 * FROM edfi.descriptor j0 WHERE descriptorid = old.gradingperioddescriptorid; + SELECT INTO dj6 * FROM edfi.student j6 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.studentlearningobjective( + oldgradingperioddescriptorid, oldgradingperioddescriptornamespace, oldgradingperioddescriptorcodevalue, oldgradingperiodschoolid, oldgradingperiodschoolyear, oldgradingperiodsequence, oldlearningobjectiveid, oldnamespace, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.gradingperioddescriptorid, dj0.namespace, dj0.codevalue, OLD.gradingperiodschoolid, OLD.gradingperiodschoolyear, OLD.gradingperiodsequence, OLD.learningobjectiveid, OLD.namespace, OLD.studentusi, dj6.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'studentlearningobjective') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.studentlearningobjective + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentlearningobjective_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentparentassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj0 edfi.parent%ROWTYPE; + dj1 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj0 * FROM edfi.parent j0 WHERE parentusi = old.parentusi; + SELECT INTO dj1 * FROM edfi.student j1 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.studentparentassociation( + oldparentusi, oldparentuniqueid, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.parentusi, dj0.parentuniqueid, OLD.studentusi, dj1.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'studentparentassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.studentparentassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentparentassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentparticipationcodedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.studentparticipationcodedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.StudentParticipationCodeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.studentparticipationcodedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'studentparticipationcodedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.studentparticipationcodedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentparticipationcodedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentprogramattendanceevent_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj0 edfi.descriptor%ROWTYPE; + dj5 edfi.descriptor%ROWTYPE; + dj6 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj0 * FROM edfi.descriptor j0 WHERE descriptorid = old.attendanceeventcategorydescriptorid; + SELECT INTO dj5 * FROM edfi.descriptor j5 WHERE descriptorid = old.programtypedescriptorid; + SELECT INTO dj6 * FROM edfi.student j6 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.studentprogramattendanceevent( + oldattendanceeventcategorydescriptorid, oldattendanceeventcategorydescriptornamespace, oldattendanceeventcategorydescriptorcodevalue, oldeducationorganizationid, oldeventdate, oldprogrameducationorganizationid, oldprogramname, oldprogramtypedescriptorid, oldprogramtypedescriptornamespace, oldprogramtypedescriptorcodevalue, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.attendanceeventcategorydescriptorid, dj0.namespace, dj0.codevalue, OLD.educationorganizationid, OLD.eventdate, OLD.programeducationorganizationid, OLD.programname, OLD.programtypedescriptorid, dj5.namespace, dj5.codevalue, OLD.studentusi, dj6.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'studentprogramattendanceevent') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.studentprogramattendanceevent + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentprogramattendanceevent_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentschoolassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj2 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj2 * FROM edfi.student j2 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.studentschoolassociation( + oldentrydate, oldschoolid, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.entrydate, OLD.schoolid, OLD.studentusi, dj2.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'studentschoolassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.studentschoolassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentschoolassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentschoolattendanceevent_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj0 edfi.descriptor%ROWTYPE; + dj5 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj0 * FROM edfi.descriptor j0 WHERE descriptorid = old.attendanceeventcategorydescriptorid; + SELECT INTO dj5 * FROM edfi.student j5 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.studentschoolattendanceevent( + oldattendanceeventcategorydescriptorid, oldattendanceeventcategorydescriptornamespace, oldattendanceeventcategorydescriptorcodevalue, oldeventdate, oldschoolid, oldschoolyear, oldsessionname, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.attendanceeventcategorydescriptorid, dj0.namespace, dj0.codevalue, OLD.eventdate, OLD.schoolid, OLD.schoolyear, OLD.sessionname, OLD.studentusi, dj5.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'studentschoolattendanceevent') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.studentschoolattendanceevent + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentschoolattendanceevent_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentsectionassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj6 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj6 * FROM edfi.student j6 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.studentsectionassociation( + oldbegindate, oldlocalcoursecode, oldschoolid, oldschoolyear, oldsectionidentifier, oldsessionname, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.begindate, OLD.localcoursecode, OLD.schoolid, OLD.schoolyear, OLD.sectionidentifier, OLD.sessionname, OLD.studentusi, dj6.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'studentsectionassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.studentsectionassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentsectionassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.studentsectionattendanceevent_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj0 edfi.descriptor%ROWTYPE; + dj7 edfi.student%ROWTYPE; +BEGIN + SELECT INTO dj0 * FROM edfi.descriptor j0 WHERE descriptorid = old.attendanceeventcategorydescriptorid; + SELECT INTO dj7 * FROM edfi.student j7 WHERE studentusi = old.studentusi; + + INSERT INTO tracked_changes_edfi.studentsectionattendanceevent( + oldattendanceeventcategorydescriptorid, oldattendanceeventcategorydescriptornamespace, oldattendanceeventcategorydescriptorcodevalue, oldeventdate, oldlocalcoursecode, oldschoolid, oldschoolyear, oldsectionidentifier, oldsessionname, oldstudentusi, oldstudentuniqueid, + id, discriminator, changeversion) + VALUES( + OLD.attendanceeventcategorydescriptorid, dj0.namespace, dj0.codevalue, OLD.eventdate, OLD.localcoursecode, OLD.schoolid, OLD.schoolyear, OLD.sectionidentifier, OLD.sessionname, OLD.studentusi, dj7.studentuniqueid, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'studentsectionattendanceevent') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.studentsectionattendanceevent + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.studentsectionattendanceevent_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.survey_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.survey( + oldnamespace, oldsurveyidentifier, + id, discriminator, changeversion) + VALUES( + OLD.namespace, OLD.surveyidentifier, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'survey') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.survey + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.survey_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.surveycategorydescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.surveycategorydescriptorid, b.codevalue, b.namespace, b.id, 'edfi.SurveyCategoryDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.surveycategorydescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'surveycategorydescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.surveycategorydescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.surveycategorydescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.surveycourseassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.surveycourseassociation( + oldcoursecode, oldeducationorganizationid, oldnamespace, oldsurveyidentifier, + id, discriminator, changeversion) + VALUES( + OLD.coursecode, OLD.educationorganizationid, OLD.namespace, OLD.surveyidentifier, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'surveycourseassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.surveycourseassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.surveycourseassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.surveyleveldescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.surveyleveldescriptorid, b.codevalue, b.namespace, b.id, 'edfi.SurveyLevelDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.surveyleveldescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'surveyleveldescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.surveyleveldescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.surveyleveldescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.surveyprogramassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj3 edfi.descriptor%ROWTYPE; +BEGIN + SELECT INTO dj3 * FROM edfi.descriptor j3 WHERE descriptorid = old.programtypedescriptorid; + + INSERT INTO tracked_changes_edfi.surveyprogramassociation( + oldeducationorganizationid, oldnamespace, oldprogramname, oldprogramtypedescriptorid, oldprogramtypedescriptornamespace, oldprogramtypedescriptorcodevalue, oldsurveyidentifier, + id, discriminator, changeversion) + VALUES( + OLD.educationorganizationid, OLD.namespace, OLD.programname, OLD.programtypedescriptorid, dj3.namespace, dj3.codevalue, OLD.surveyidentifier, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'surveyprogramassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.surveyprogramassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.surveyprogramassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.surveyquestion_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.surveyquestion( + oldnamespace, oldquestioncode, oldsurveyidentifier, + id, discriminator, changeversion) + VALUES( + OLD.namespace, OLD.questioncode, OLD.surveyidentifier, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'surveyquestion') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.surveyquestion + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.surveyquestion_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.surveyquestionresponse_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.surveyquestionresponse( + oldnamespace, oldquestioncode, oldsurveyidentifier, oldsurveyresponseidentifier, + id, discriminator, changeversion) + VALUES( + OLD.namespace, OLD.questioncode, OLD.surveyidentifier, OLD.surveyresponseidentifier, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'surveyquestionresponse') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.surveyquestionresponse + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.surveyquestionresponse_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.surveyresponse_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.surveyresponse( + oldnamespace, oldsurveyidentifier, oldsurveyresponseidentifier, + id, discriminator, changeversion) + VALUES( + OLD.namespace, OLD.surveyidentifier, OLD.surveyresponseidentifier, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'surveyresponse') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.surveyresponse + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.surveyresponse_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.surveyresponseeducationorganizationtargetassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.surveyresponseeducationorganizationtargetassociation( + oldeducationorganizationid, oldnamespace, oldsurveyidentifier, oldsurveyresponseidentifier, + id, discriminator, changeversion) + VALUES( + OLD.educationorganizationid, OLD.namespace, OLD.surveyidentifier, OLD.surveyresponseidentifier, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'surveyresponseeducationorganizationtargetassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.surveyresponseeducationorganizationtargetassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.surveyresponseeducationorganizationtargetassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.surveyresponsestafftargetassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj1 edfi.staff%ROWTYPE; +BEGIN + SELECT INTO dj1 * FROM edfi.staff j1 WHERE staffusi = old.staffusi; + + INSERT INTO tracked_changes_edfi.surveyresponsestafftargetassociation( + oldnamespace, oldstaffusi, oldstaffuniqueid, oldsurveyidentifier, oldsurveyresponseidentifier, + id, discriminator, changeversion) + VALUES( + OLD.namespace, OLD.staffusi, dj1.staffuniqueid, OLD.surveyidentifier, OLD.surveyresponseidentifier, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'surveyresponsestafftargetassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.surveyresponsestafftargetassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.surveyresponsestafftargetassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.surveysection_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.surveysection( + oldnamespace, oldsurveyidentifier, oldsurveysectiontitle, + id, discriminator, changeversion) + VALUES( + OLD.namespace, OLD.surveyidentifier, OLD.surveysectiontitle, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'surveysection') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.surveysection + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.surveysection_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.surveysectionassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.surveysectionassociation( + oldlocalcoursecode, oldnamespace, oldschoolid, oldschoolyear, oldsectionidentifier, oldsessionname, oldsurveyidentifier, + id, discriminator, changeversion) + VALUES( + OLD.localcoursecode, OLD.namespace, OLD.schoolid, OLD.schoolyear, OLD.sectionidentifier, OLD.sessionname, OLD.surveyidentifier, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'surveysectionassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.surveysectionassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.surveysectionassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.surveysectionresponse_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.surveysectionresponse( + oldnamespace, oldsurveyidentifier, oldsurveyresponseidentifier, oldsurveysectiontitle, + id, discriminator, changeversion) + VALUES( + OLD.namespace, OLD.surveyidentifier, OLD.surveyresponseidentifier, OLD.surveysectiontitle, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'surveysectionresponse') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.surveysectionresponse + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.surveysectionresponse_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.surveysectionresponseeducationorganizationtarget_730be1_deleted() + RETURNS trigger AS +$BODY$ +DECLARE +BEGIN + + INSERT INTO tracked_changes_edfi.surveysectionresponseeducationorganizationtargetassociation( + oldeducationorganizationid, oldnamespace, oldsurveyidentifier, oldsurveyresponseidentifier, oldsurveysectiontitle, + id, discriminator, changeversion) + VALUES( + OLD.educationorganizationid, OLD.namespace, OLD.surveyidentifier, OLD.surveyresponseidentifier, OLD.surveysectiontitle, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'surveysectionresponseeducationorganizationtargetassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.surveysectionresponseeducationorganizationtargetassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.surveysectionresponseeducationorganizationtarget_730be1_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.surveysectionresponsestafftargetassociation_deleted() + RETURNS trigger AS +$BODY$ +DECLARE + dj1 edfi.staff%ROWTYPE; +BEGIN + SELECT INTO dj1 * FROM edfi.staff j1 WHERE staffusi = old.staffusi; + + INSERT INTO tracked_changes_edfi.surveysectionresponsestafftargetassociation( + oldnamespace, oldstaffusi, oldstaffuniqueid, oldsurveyidentifier, oldsurveyresponseidentifier, oldsurveysectiontitle, + id, discriminator, changeversion) + VALUES( + OLD.namespace, OLD.staffusi, dj1.staffuniqueid, OLD.surveyidentifier, OLD.surveyresponseidentifier, OLD.surveysectiontitle, + OLD.id, OLD.discriminator, nextval('changes.changeversionsequence')); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'surveysectionresponsestafftargetassociation') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.surveysectionresponsestafftargetassociation + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.surveysectionresponsestafftargetassociation_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.teachingcredentialbasisdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.teachingcredentialbasisdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.TeachingCredentialBasisDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.teachingcredentialbasisdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'teachingcredentialbasisdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.teachingcredentialbasisdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.teachingcredentialbasisdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.teachingcredentialdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.teachingcredentialdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.TeachingCredentialDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.teachingcredentialdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'teachingcredentialdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.teachingcredentialdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.teachingcredentialdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.technicalskillsassessmentdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.technicalskillsassessmentdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.TechnicalSkillsAssessmentDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.technicalskillsassessmentdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'technicalskillsassessmentdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.technicalskillsassessmentdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.technicalskillsassessmentdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.telephonenumbertypedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.telephonenumbertypedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.TelephoneNumberTypeDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.telephonenumbertypedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'telephonenumbertypedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.telephonenumbertypedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.telephonenumbertypedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.termdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.termdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.TermDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.termdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'termdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.termdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.termdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.titleipartaparticipantdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.titleipartaparticipantdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.TitleIPartAParticipantDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.titleipartaparticipantdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'titleipartaparticipantdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.titleipartaparticipantdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.titleipartaparticipantdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.titleipartaprogramservicedescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.titleipartaprogramservicedescriptorid, b.codevalue, b.namespace, b.id, 'edfi.TitleIPartAProgramServiceDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.titleipartaprogramservicedescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'titleipartaprogramservicedescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.titleipartaprogramservicedescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.titleipartaprogramservicedescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.titleipartaschooldesignationdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.titleipartaschooldesignationdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.TitleIPartASchoolDesignationDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.titleipartaschooldesignationdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'titleipartaschooldesignationdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.titleipartaschooldesignationdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.titleipartaschooldesignationdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.tribalaffiliationdescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.tribalaffiliationdescriptorid, b.codevalue, b.namespace, b.id, 'edfi.TribalAffiliationDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.tribalaffiliationdescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'tribalaffiliationdescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.tribalaffiliationdescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.tribalaffiliationdescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.visadescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.visadescriptorid, b.codevalue, b.namespace, b.id, 'edfi.VisaDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.visadescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'visadescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.visadescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.visadescriptor_deleted(); +END IF; + +CREATE OR REPLACE FUNCTION tracked_changes_edfi.weapondescriptor_deleted() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_edfi.descriptor(olddescriptorid, oldcodevalue, oldnamespace, id, discriminator, changeversion) + SELECT OLD.weapondescriptorid, b.codevalue, b.namespace, b.id, 'edfi.WeaponDescriptor', nextval('changes.ChangeVersionSequence') + FROM edfi.descriptor b WHERE old.weapondescriptorid = b.descriptorid; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = 'edfi' AND event_object_table = 'weapondescriptor') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON edfi.weapondescriptor + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_edfi.weapondescriptor_deleted(); +END IF; + +END +$$; \ No newline at end of file diff --git a/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/1020-AuthViewsIncludingDeletes.sql b/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/1020-AuthViewsIncludingDeletes.sql new file mode 100644 index 0000000000..f4a624a6c6 --- /dev/null +++ b/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/1020-AuthViewsIncludingDeletes.sql @@ -0,0 +1,201 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +DROP VIEW IF EXISTS auth.localeducationagencyidtostudentusiincludingdeletes; + +CREATE VIEW auth.localeducationagencyidtostudentusiincludingdeletes(localeducationagencyid, studentusi) AS + SELECT sch.localeducationagencyid, ssa.studentusi + FROM edfi.school sch + JOIN edfi.studentschoolassociation ssa ON sch.schoolid = ssa.schoolid + + UNION + + SELECT sch.localeducationagencyid, ssa_tc.oldstudentusi as studentusi + FROM edfi.school sch + JOIN tracked_changes_edfi.studentschoolassociation ssa_tc ON sch.schoolid = ssa_tc.oldschoolid; + +ALTER TABLE auth.localeducationagencyidtostudentusiincludingdeletes OWNER TO postgres; + +DROP VIEW IF EXISTS auth.localeducationagencyidtostaffusiincludingdeletes; + +CREATE VIEW auth.localeducationagencyidtostaffusiincludingdeletes(localeducationagencyid, staffusi) AS + -- LEA employment + SELECT lea.localeducationagencyid, emp.staffusi + FROM edfi.localeducationagency lea + JOIN edfi.staffeducationorganizationemploymentassociation emp + ON lea.localeducationagencyid = emp.educationorganizationid + + UNION + + -- LEA employment (deleted employment) + SELECT lea.localeducationagencyid, emp_tc.oldstaffusi as staffusi + FROM edfi.localeducationagency lea + JOIN tracked_changes_edfi.staffeducationorganizationemploymentassociation emp_tc + ON lea.localeducationagencyid = emp_tc.oldeducationorganizationid + + UNION + + -- LEA-level organization department employment + SELECT lea.localeducationagencyid, emp.staffusi + FROM edfi.localeducationagency lea + JOIN edfi.organizationdepartment od + ON lea.localeducationagencyid = od.parenteducationorganizationid + JOIN edfi.staffeducationorganizationemploymentassociation emp + ON od.organizationdepartmentid = emp.educationorganizationid + + UNION + + -- LEA-level organization department employment (deleted employment) + SELECT lea.localeducationagencyid, emp_tc.oldstaffusi as staffusi + FROM edfi.localeducationagency lea + JOIN edfi.organizationdepartment od + ON lea.localeducationagencyid = od.parenteducationorganizationid + JOIN tracked_changes_edfi.staffeducationorganizationemploymentassociation emp_tc + ON od.organizationdepartmentid = emp_tc.oldeducationorganizationid + + UNION + + -- LEA assignment + SELECT lea.localeducationagencyid, assgn.staffusi + FROM edfi.localeducationagency lea + JOIN edfi.staffeducationorganizationassignmentassociation assgn + ON lea.localeducationagencyid = assgn.educationorganizationid + + UNION + + -- LEA assignment (deleted assignment) + SELECT lea.localeducationagencyid, assgn_tc.oldstaffusi as staffusi + FROM edfi.localeducationagency lea + JOIN tracked_changes_edfi.staffeducationorganizationassignmentassociation assgn_tc + ON lea.localeducationagencyid = assgn_tc.oldeducationorganizationid + + UNION + + -- LEA-level organization department assignment + SELECT lea.localeducationagencyid, assgn.staffusi + FROM edfi.localeducationagency lea + JOIN edfi.organizationdepartment od + ON lea.localeducationagencyid = od.parenteducationorganizationid + JOIN edfi.staffeducationorganizationassignmentassociation assgn + ON od.organizationdepartmentid = assgn.educationorganizationid + + UNION + + -- LEA-level organization department assignment (deleted assignment) + SELECT lea.localeducationagencyid, assgn_tc.oldstaffusi as staffusi + FROM edfi.localeducationagency lea + JOIN edfi.organizationdepartment od + ON lea.localeducationagencyid = od.parenteducationorganizationid + JOIN tracked_changes_edfi.staffeducationorganizationassignmentassociation assgn_tc + ON od.organizationdepartmentid = assgn_tc.oldeducationorganizationid + + UNION + + -- School employment + SELECT sch.localeducationagencyid, emp.staffusi + FROM edfi.school sch + JOIN edfi.staffeducationorganizationemploymentassociation emp + ON sch.schoolid = emp.educationorganizationid + + UNION + + -- School employment (deleted employment) + SELECT sch.localeducationagencyid, emp_tc.oldstaffusi as staffusi + FROM edfi.school sch + JOIN tracked_changes_edfi.staffeducationorganizationemploymentassociation emp_tc + ON sch.schoolid = emp_tc.oldeducationorganizationid + + UNION + + -- School-level organization department employment + SELECT sch.localeducationagencyid, emp.staffusi + FROM edfi.school sch + JOIN edfi.organizationdepartment od + ON sch.schoolid = od.parenteducationorganizationid + JOIN edfi.staffeducationorganizationemploymentassociation emp + ON od.organizationdepartmentid = emp.educationorganizationid + + UNION + + -- School-level organization department employment (deleted employment) + SELECT sch.localeducationagencyid, emp_tc.oldstaffusi as staffusi + FROM edfi.school sch + JOIN edfi.organizationdepartment od + ON sch.schoolid = od.parenteducationorganizationid + JOIN tracked_changes_edfi.staffeducationorganizationemploymentassociation emp_tc + ON od.organizationdepartmentid = emp_tc.oldeducationorganizationid + + UNION + + -- School assignment + SELECT sch.localeducationagencyid, assgn.staffusi + FROM edfi.school sch + JOIN edfi.staffeducationorganizationassignmentassociation assgn + ON sch.schoolid = assgn.educationorganizationid + + UNION + + -- School assignment (deleted assignment) + SELECT sch.localeducationagencyid, assgn_tc.oldstaffusi as staffusi + FROM edfi.school sch + JOIN tracked_changes_edfi.staffeducationorganizationassignmentassociation assgn_tc + ON sch.schoolid = assgn_tc.oldeducationorganizationid + + UNION + + -- School-level organization department assignment + SELECT sch.localeducationagencyid, assgn.staffusi + FROM edfi.school sch + JOIN edfi.organizationdepartment od + ON sch.schoolid = od.parenteducationorganizationid + JOIN edfi.staffeducationorganizationassignmentassociation assgn + ON od.organizationdepartmentid = assgn.educationorganizationid + + UNION + + SELECT sch.localeducationagencyid, assgn_tc.oldstaffusi as staffusi + FROM edfi.school sch + JOIN edfi.organizationdepartment od + ON sch.schoolid = od.parenteducationorganizationid + JOIN tracked_changes_edfi.staffeducationorganizationassignmentassociation assgn_tc + ON od.organizationdepartmentid = assgn_tc.oldeducationorganizationid; + +ALTER TABLE auth.localeducationagencyidtostaffusiincludingdeletes OWNER TO postgres; + +DROP VIEW IF EXISTS auth.localeducationagencyidtoparentusiincludingdeletes; + +CREATE VIEW auth.localeducationagencyidtoparentusiincludingdeletes(localeducationagencyid, parentusi) AS + -- Intact studentschoolassociation and intact studentparentassociation + SELECT sch.localeducationagencyid, spa.parentusi + FROM edfi.school sch + JOIN edfi.studentschoolassociation ssa ON sch.schoolid = ssa.schoolid + JOIN edfi.student s ON ssa.studentusi = s.studentusi + JOIN edfi.studentparentassociation spa ON ssa.studentusi = spa.studentusi + + UNION + + -- Intact studentschoolassociation and deleted studentparentassociation + SELECT sch.localeducationagencyid, spa_tc.oldparentusi as parentusi + FROM edfi.school sch + JOIN edfi.studentschoolassociation ssa ON sch.schoolid = ssa.schoolid + JOIN tracked_changes_edfi.studentparentassociation spa_tc ON ssa.studentusi = spa_tc.oldstudentusi + + UNION + + -- Deleted studentschoolassociation and intact studentparentassociation + SELECT sch.localeducationagencyid, spa.parentusi + FROM edfi.school sch + JOIN tracked_changes_edfi.studentschoolassociation ssa_tc ON sch.schoolid = ssa_tc.oldschoolid + JOIN edfi.studentparentassociation spa ON ssa_tc.oldstudentusi = spa.studentusi + + UNION + + -- Deleted studentschoolassociation and studentparentassociation + SELECT sch.localeducationagencyid, spa_tc.oldparentusi as parentusi + FROM edfi.school sch + JOIN tracked_changes_edfi.studentschoolassociation ssa_tc ON sch.schoolid = ssa_tc.oldschoolid + JOIN tracked_changes_edfi.studentparentassociation spa_tc ON ssa_tc.oldstudentusi = spa_tc.oldstudentusi; + +ALTER TABLE auth.localeducationagencyidtoparentusi OWNER TO postgres; diff --git a/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/1030-AuthViewsIncludingDeletes-SchoolClient.sql b/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/1030-AuthViewsIncludingDeletes-SchoolClient.sql new file mode 100644 index 0000000000..94c421b83a --- /dev/null +++ b/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/1030-AuthViewsIncludingDeletes-SchoolClient.sql @@ -0,0 +1,119 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +DROP VIEW IF EXISTS auth.schoolidtostudentusiincludingdeletes; + +CREATE VIEW auth.schoolidtostudentusiincludingdeletes(schoolid, studentusi) AS + -- School to Student + SELECT ssa.schoolid, ssa.studentusi + FROM edfi.studentschoolassociation ssa + + UNION + + -- School to Student (deleted) + SELECT sch.schoolid, ssa_tc.oldstudentusi as studentusi + FROM edfi.school sch + JOIN tracked_changes_edfi.studentschoolassociation ssa_tc + ON sch.schoolid = ssa_tc.oldschoolid; + +ALTER TABLE auth.schoolidtostudentusiincludingdeletes OWNER TO postgres; + +DROP VIEW IF EXISTS auth.schoolidtostaffusiincludingdeletes; + +CREATE VIEW auth.schoolidtostaffusiincludingdeletes(schoolid, staffusi) AS + -- School to Staff (through School employment) + SELECT sch.schoolid, seo_empl.staffusi + FROM edfi.school sch + JOIN edfi.staffeducationorganizationemploymentassociation seo_empl + ON sch.SchoolId = seo_empl.educationorganizationid + + UNION + + -- School to Staff (through deleted School employment) + SELECT sch.schoolid, seo_empl_tc.oldstaffusi AS staffusi + FROM edfi.school sch + JOIN tracked_changes_edfi.staffeducationorganizationemploymentassociation seo_empl_tc + ON sch.schoolid = seo_empl_tc.oldeducationorganizationid + + UNION + + -- School to Staff (through School-level department employment) + SELECT sch.schoolid, seo_empl.staffusi + FROM edfi.school sch + JOIN edfi.organizationdepartment od + ON sch.SchoolId = od.parenteducationorganizationid + JOIN edfi.staffeducationorganizationemploymentassociation seo_empl + ON od.organizationdepartmentid = seo_empl.educationorganizationid + + UNION + + -- School to Staff (through deleted School-level department employment) + SELECT sch.schoolid + ,seo_empl_tc.oldstaffusi AS staffusi + FROM edfi.school sch + JOIN edfi.organizationdepartment od + ON sch.schoolid = od.parenteducationorganizationid + JOIN tracked_changes_edfi.staffeducationorganizationemploymentassociation seo_empl_tc + ON od.organizationdepartmentid = seo_empl_tc.oldeducationorganizationid + + UNION + + -- School to Staff (through School assignment) + SELECT sch.schoolid + ,seo_assgn.staffusi + FROM edfi.school sch + JOIN edfi.staffeducationorganizationassignmentassociation seo_assgn + ON sch.schoolid = seo_assgn.educationorganizationid + + UNION + + -- School to Staff (through deleted School assignment) + SELECT sch.schoolid + ,seo_assgn_tc.oldstaffusi AS staffusi + FROM edfi.school sch + JOIN tracked_changes_edfi.staffeducationorganizationassignmentassociation seo_assgn_tc + ON sch.schoolid = seo_assgn_tc.oldeducationorganizationid + + UNION + + -- School to Staff (through School-level department assignment) + SELECT sch.schoolid + ,seo_assgn.staffusi + FROM edfi.school sch + JOIN edfi.organizationdepartment od + ON sch.schoolid = od.parenteducationorganizationid + JOIN edfi.staffeducationorganizationassignmentassociation seo_assgn + ON od.organizationdepartmentid = seo_assgn.educationorganizationid + + UNION + + -- School to Staff (through deleted School-level department assignment) + SELECT sch.schoolid + ,seo_assgn_tc.oldstaffusi AS staffusi + FROM edfi.school sch + JOIN edfi.organizationdepartment od + ON sch.schoolid = od.parenteducationorganizationid + JOIN tracked_changes_edfi.staffeducationorganizationassignmentassociation seo_assgn_tc + ON od.organizationdepartmentid = seo_assgn_tc.oldeducationorganizationid; + +ALTER TABLE auth.schoolidtostaffusiincludingdeletes OWNER TO postgres; + +DROP VIEW IF EXISTS auth.parentusitoschoolidincludingdeletes; + +CREATE VIEW auth.parentusitoschoolidincludingdeletes(schoolid, parentusi) AS + -- School to Parent USI + SELECT ssa.schoolid, spa.parentusi + FROM edfi.studentschoolassociation ssa + JOIN edfi.studentparentassociation spa + ON ssa.studentusi = spa.studentusi + + UNION + + SELECT ssa.schoolid, spa_tc.oldparentusi AS ParentUSI + FROM edfi.studentschoolassociation ssa + JOIN tracked_changes_edfi.studentparentassociation spa_tc + ON ssa.studentusi = spa_tc.oldstudentusi; + +ALTER TABLE auth.parentusitoschoolidincludingdeletes OWNER TO postgres; diff --git a/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Conventions/ExtensionsConventionsTests.cs b/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Conventions/ExtensionsConventionsTests.cs index 2f6dfb3689..9581fa7eb8 100644 --- a/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Conventions/ExtensionsConventionsTests.cs +++ b/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Conventions/ExtensionsConventionsTests.cs @@ -302,7 +302,8 @@ protected override void Act() new IDomainModelDefinitionsProvider[] { new DomainModelDefinitionsProvider(), new EdFiDomainModelDefinitionsProvider() - }).GetDomainModel(); + }, + new IDomainModelDefinitionsTransformer[0]).GetDomainModel(); ExtensionsConventions.GetAggregateExtensionMemberName( domainModel.Entities.FirstOrDefault(e => e.Name == "StaffLeaveExtension")); @@ -332,7 +333,8 @@ protected override void Act() new IDomainModelDefinitionsProvider[] { new DomainModelDefinitionsProvider(), new EdFiDomainModelDefinitionsProvider() - }).GetDomainModel(); + }, + new IDomainModelDefinitionsTransformer[0]).GetDomainModel(); _actualResult = ExtensionsConventions.GetAggregateExtensionMemberName( domainModel.Entities.FirstOrDefault(e => e.Name == "StaffLeaveReason")); @@ -410,7 +412,8 @@ protected override void Act() new IDomainModelDefinitionsProvider[] { new DomainModelDefinitionsProvider(), new EdFiDomainModelDefinitionsProvider() - }).GetDomainModel(); + }, + new IDomainModelDefinitionsTransformer[0]).GetDomainModel(); _staffLeaveEntity = domainModel.Entities.First(e => e.Name == "StaffLeave"); @@ -447,7 +450,8 @@ protected override void Act() new IDomainModelDefinitionsProvider[] { new DomainModelDefinitionsProvider(), new EdFiDomainModelDefinitionsProvider() - }).GetDomainModel(); + }, + new IDomainModelDefinitionsTransformer[0]).GetDomainModel(); _entity = domainModel.Entities.First(e => e.Name == _entityName); diff --git a/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Models/Domain/DomainModelTests.cs b/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Models/Domain/DomainModelTests.cs index 7ab1dd4557..410d915387 100644 --- a/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Models/Domain/DomainModelTests.cs +++ b/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Models/Domain/DomainModelTests.cs @@ -112,7 +112,8 @@ protected override void Act() new[] { _domainModelDefinitionsProvider - }); + }, + new IDomainModelDefinitionsTransformer[0]); _domainModel = domainModelProvider.GetDomainModel(); } @@ -251,7 +252,8 @@ protected override void Arrange() new[] { _extensionDefinitionsProvider, new EdFiDomainModelDefinitionsProvider() - }); + }, + new IDomainModelDefinitionsTransformer[0]); } protected override void Act() diff --git a/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Models/Resource/FilterContextTests.cs b/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Models/Resource/FilterContextTests.cs index a2e82cfa25..8e0837300d 100644 --- a/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Models/Resource/FilterContextTests.cs +++ b/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Models/Resource/FilterContextTests.cs @@ -244,7 +244,8 @@ internal static Resource_Resource GetTestResourceForWithAnExtension() domainCoreDefinitionProvider, extensionDefinitionProvider }; - DomainModelProvider ddm = new DomainModelProvider(providerList); + DomainModelProvider ddm = new DomainModelProvider(providerList, + new IDomainModelDefinitionsTransformer[0]); var domainModel = ddm.GetDomainModel(); diff --git a/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Models/Resource/ProfileResourceMembersFilterProviderTests.cs b/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Models/Resource/ProfileResourceMembersFilterProviderTests.cs index 7c63985718..183a71a9f1 100644 --- a/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Models/Resource/ProfileResourceMembersFilterProviderTests.cs +++ b/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Models/Resource/ProfileResourceMembersFilterProviderTests.cs @@ -333,7 +333,8 @@ internal static Resource_Resource GetTestResourceForWithAnExtension() domainCoreDefinitionProvider, extensionDefinitionProvider }; - DomainModelProvider ddm = new DomainModelProvider(providerList); + DomainModelProvider ddm = new DomainModelProvider(providerList, + new IDomainModelDefinitionsTransformer[0]); var domainModel = ddm.GetDomainModel(); diff --git a/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Models/Resource/ProfileResourceModelTests.cs b/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Models/Resource/ProfileResourceModelTests.cs index 13ec39bf56..10024c9c1b 100644 --- a/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Models/Resource/ProfileResourceModelTests.cs +++ b/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Models/Resource/ProfileResourceModelTests.cs @@ -8,6 +8,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Xml.Linq; +using EdFi.Ods.Common.Models; using EdFi.Ods.Common.Models.Definitions; using EdFi.Ods.Common.Models.Domain; using EdFi.Ods.Common.Models.Resource; @@ -262,7 +263,8 @@ protected override void Arrange() "); - _resourceModel = new DomainModelProvider(DomainModelDefinitionsProviderHelper.DefinitionProviders) + _resourceModel = new DomainModelProvider(DomainModelDefinitionsProviderHelper.DefinitionProviders, + new IDomainModelDefinitionsTransformer[0]) .GetDomainModel() .ResourceModel; } @@ -352,7 +354,8 @@ protected override void Arrange() "); - _resourceModel = new DomainModelProvider(DomainModelDefinitionsProviderHelper.DefinitionProviders) + _resourceModel = new DomainModelProvider(DomainModelDefinitionsProviderHelper.DefinitionProviders, + new IDomainModelDefinitionsTransformer[0]) .GetDomainModel() .ResourceModel; } diff --git a/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Models/Resource/ResourceTests.cs b/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Models/Resource/ResourceTests.cs index 809a2809c4..4ba65fbae9 100644 --- a/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Models/Resource/ResourceTests.cs +++ b/Application/EdFi.Ods.Tests/EdFi.Ods.Common/Models/Resource/ResourceTests.cs @@ -723,7 +723,8 @@ protected override void Arrange() new[] { definitionsProvider - }); + }, + new IDomainModelDefinitionsTransformer[0]); _resourceModelProvider = new ResourceModelProvider(_domainModelProvider); } @@ -854,7 +855,8 @@ protected override void Arrange() new[] { definitionsProvider, extensionDefinitionsProvider - }); + }, + new IDomainModelDefinitionsTransformer[0]); _resourceModelProvider = new ResourceModelProvider(_domainModelProvider); } @@ -1026,7 +1028,8 @@ protected override void Arrange() new[] { definitionsProvider, extensionDefinitionsProvider - }); + }, + new IDomainModelDefinitionsTransformer[0]); _resourceModelProvider = new ResourceModelProvider(_domainModelProvider); } @@ -1231,7 +1234,8 @@ protected override void Arrange() new[] { definitionsProvider, extensionDefinitionsProvider - }); + }, + new IDomainModelDefinitionsTransformer[0]); _resourceModelProvider = new ResourceModelProvider(_domainModelProvider); } @@ -1464,7 +1468,8 @@ protected override void Arrange() new[] { definitionsProvider, extensionDefinitionsProvider - }); + }, + new IDomainModelDefinitionsTransformer[0]); _resourceModelProvider = new ResourceModelProvider(_domainModelProvider); } diff --git a/Application/EdFi.Ods.Tests/EdFi.Ods.Common/SchemaNameMapProviderTests.cs b/Application/EdFi.Ods.Tests/EdFi.Ods.Common/SchemaNameMapProviderTests.cs index cc536c7ac7..f798c7b480 100644 --- a/Application/EdFi.Ods.Tests/EdFi.Ods.Common/SchemaNameMapProviderTests.cs +++ b/Application/EdFi.Ods.Tests/EdFi.Ods.Common/SchemaNameMapProviderTests.cs @@ -47,7 +47,8 @@ private static SchemaNameMapProvider GetSchemaNameMapProvider(string logicalSche new[] { domainModelDefinitionsProvider, domainModelDefinitionsProvider2 - }) + }, + new IDomainModelDefinitionsTransformer[0]) .GetDomainModel() .Schemas; diff --git a/Application/Test.Common/DomainModelDefinitionsProviderHelper.cs b/Application/Test.Common/DomainModelDefinitionsProviderHelper.cs index f59d8d8787..19e5a22ff6 100644 --- a/Application/Test.Common/DomainModelDefinitionsProviderHelper.cs +++ b/Application/Test.Common/DomainModelDefinitionsProviderHelper.cs @@ -28,7 +28,7 @@ public static class DomainModelDefinitionsProviderHelper }; public static IDomainModelProvider DomainModelProvider = - new DomainModelProvider(DefinitionProviders); + new DomainModelProvider(DefinitionProviders, new IDomainModelDefinitionsTransformer[0]); public static IResourceModelProvider ResourceModelProvider = new ResourceModelProvider(DomainModelProvider); diff --git a/Artifacts/MsSql/Data/Security/1080-AddReadChangesAction-DeletesAuthStrategy.sql b/Artifacts/MsSql/Data/Security/1080-AddReadChangesAction-DeletesAuthStrategy.sql new file mode 100644 index 0000000000..df5e82e12b --- /dev/null +++ b/Artifacts/MsSql/Data/Security/1080-AddReadChangesAction-DeletesAuthStrategy.sql @@ -0,0 +1,11 @@ +DECLARE + @applicationId AS INT +BEGIN + INSERT INTO dbo.Actions (ActionName, ActionUri) VALUES ('ReadChanges', 'http://ed-fi.org/odsapi/actions/readChanges'); + + SELECT @applicationId = ApplicationId + FROM dbo.Applications WHERE ApplicationName = 'Ed-Fi ODS API'; + + INSERT INTO dbo.AuthorizationStrategies(DisplayName, AuthorizationStrategyName, Application_ApplicationId) + VALUES ('Relationships with Education Organizations and People (including deletes)', 'RelationshipsWithEdOrgsAndPeopleIncludingDeletes', @applicationId); +END diff --git a/Artifacts/MsSql/Data/Security/Changes/0010-API-Publisher-Reader-Security-Metadata.sql b/Artifacts/MsSql/Data/Security/Changes/0010-API-Publisher-Reader-Security-Metadata.sql new file mode 100644 index 0000000000..6dbf2b8e96 --- /dev/null +++ b/Artifacts/MsSql/Data/Security/Changes/0010-API-Publisher-Reader-Security-Metadata.sql @@ -0,0 +1,1200 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +BEGIN + DECLARE + @applicationId AS INT, + @claimId AS INT, + @claimName AS nvarchar(max), + @parentResourceClaimId AS INT, + @existingParentResourceClaimId AS INT, + @claimSetId AS INT, + @claimSetName AS nvarchar(max), + @authorizationStrategyId AS INT, + @msg AS nvarchar(max), + @createActionId AS INT, + @readActionId AS INT, + @updateActionId AS INT, + @deleteActionId AS INT, + @readChangesActionId AS INT + + DECLARE @claimIdStack AS TABLE (Id INT IDENTITY, ResourceClaimId INT) + + SELECT @applicationId = ApplicationId + FROM [dbo].[Applications] WHERE ApplicationName = 'Ed-Fi ODS API'; + + SELECT @createActionId = ActionId + FROM [dbo].[Actions] WHERE ActionName = 'Create'; + + SELECT @readActionId = ActionId + FROM [dbo].[Actions] WHERE ActionName = 'Read'; + + SELECT @updateActionId = ActionId + FROM [dbo].[Actions] WHERE ActionName = 'Update'; + + SELECT @deleteActionId = ActionId + FROM [dbo].[Actions] WHERE ActionName = 'Delete'; + + SELECT @readChangesActionId = ActionId + FROM [dbo].[Actions] WHERE ActionName = 'ReadChanges'; + + BEGIN TRANSACTION + + -- Push claimId to the stack + INSERT INTO @claimIdStack (ResourceClaimId) VALUES (@claimId) + + -- Processing children of root + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/edFiTypes' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/edFiTypes' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('edFiTypes', 'edFiTypes', 'http://ed-fi.org/ods/identity/claims/domains/edFiTypes', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/edFiTypes + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Reader' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/systemDescriptors' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/systemDescriptors' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('systemDescriptors', 'systemDescriptors', 'http://ed-fi.org/ods/identity/claims/domains/systemDescriptors', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/systemDescriptors + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Reader' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific ReadChanges authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ').' + ELSE + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadChangesActionId, @authorizationStrategyId) -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/managedDescriptors' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/managedDescriptors' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('managedDescriptors', 'managedDescriptors', 'http://ed-fi.org/ods/identity/claims/domains/managedDescriptors', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/managedDescriptors + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Reader' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific ReadChanges authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ').' + ELSE + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadChangesActionId, @authorizationStrategyId) -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/educationOrganizations' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/educationOrganizations' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('educationOrganizations', 'educationOrganizations', 'http://ed-fi.org/ods/identity/claims/domains/educationOrganizations', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/educationOrganizations + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Reader' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific ReadChanges authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ').' + ELSE + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadChangesActionId, @authorizationStrategyId) -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/people' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/people' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('people', 'people', 'http://ed-fi.org/ods/identity/claims/domains/people', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/people + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Reader' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific ReadChanges authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'RelationshipsWithEdOrgsAndPeopleIncludingDeletes' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ').' + ELSE + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadChangesActionId, @authorizationStrategyId) -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('relationshipBasedData', 'relationshipBasedData', 'http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Reader' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific ReadChanges authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'RelationshipsWithEdOrgsAndPeopleIncludingDeletes' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ').' + ELSE + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadChangesActionId, @authorizationStrategyId) -- ReadChanges + -- Push claimId to the stack + INSERT INTO @claimIdStack (ResourceClaimId) VALUES (@claimId) + + -- Processing children of http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/communityProviderLicense' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/communityProviderLicense' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('communityProviderLicense', 'communityProviderLicense', 'http://ed-fi.org/ods/identity/claims/communityProviderLicense', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/communityProviderLicense + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Reader' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific ReadChanges authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ').' + ELSE + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadChangesActionId, @authorizationStrategyId) -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/person' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/person' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('person', 'person', 'http://ed-fi.org/ods/identity/claims/person', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/person + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Reader' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific ReadChanges authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ').' + ELSE + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadChangesActionId, @authorizationStrategyId) -- ReadChanges + + -- Pop the stack + DELETE FROM @claimIdStack WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('assessmentMetadata', 'assessmentMetadata', 'http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Reader' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific ReadChanges authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NamespaceBased' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ').' + ELSE + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadChangesActionId, @authorizationStrategyId) -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/educationStandards' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/educationStandards' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('educationStandards', 'educationStandards', 'http://ed-fi.org/ods/identity/claims/domains/educationStandards', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/educationStandards + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Reader' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific ReadChanges authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NamespaceBased' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ').' + ELSE + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadChangesActionId, @authorizationStrategyId) -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/primaryRelationships' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/primaryRelationships' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('primaryRelationships', 'primaryRelationships', 'http://ed-fi.org/ods/identity/claims/domains/primaryRelationships', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/primaryRelationships + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Reader' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific ReadChanges authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'RelationshipsWithEdOrgsAndPeopleIncludingDeletes' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ').' + ELSE + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadChangesActionId, @authorizationStrategyId) -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/educationContent' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/educationContent' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('educationContent', 'educationContent', 'http://ed-fi.org/ods/identity/claims/educationContent', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/educationContent + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Reader' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific ReadChanges authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NamespaceBased' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ').' + ELSE + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadChangesActionId, @authorizationStrategyId) -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/publishing/snapshot' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/publishing/snapshot' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('snapshot', 'snapshot', 'http://ed-fi.org/ods/identity/claims/publishing/snapshot', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/publishing/snapshot + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Reader' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Pop the stack + DELETE FROM @claimIdStack WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + COMMIT TRANSACTION +END \ No newline at end of file diff --git a/Artifacts/MsSql/Data/Security/Changes/0020-API-Publisher-Writer-Security-Metadata.sql b/Artifacts/MsSql/Data/Security/Changes/0020-API-Publisher-Writer-Security-Metadata.sql new file mode 100644 index 0000000000..6d0acd6b0a --- /dev/null +++ b/Artifacts/MsSql/Data/Security/Changes/0020-API-Publisher-Writer-Security-Metadata.sql @@ -0,0 +1,1518 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +BEGIN + DECLARE + @applicationId AS INT, + @claimId AS INT, + @claimName AS nvarchar(max), + @parentResourceClaimId AS INT, + @existingParentResourceClaimId AS INT, + @claimSetId AS INT, + @claimSetName AS nvarchar(max), + @authorizationStrategyId AS INT, + @msg AS nvarchar(max), + @createActionId AS INT, + @readActionId AS INT, + @updateActionId AS INT, + @deleteActionId AS INT, + @readChangesActionId AS INT + + DECLARE @claimIdStack AS TABLE (Id INT IDENTITY, ResourceClaimId INT) + + SELECT @applicationId = ApplicationId + FROM [dbo].[Applications] WHERE ApplicationName = 'Ed-Fi ODS API'; + + SELECT @createActionId = ActionId + FROM [dbo].[Actions] WHERE ActionName = 'Create'; + + SELECT @readActionId = ActionId + FROM [dbo].[Actions] WHERE ActionName = 'Read'; + + SELECT @updateActionId = ActionId + FROM [dbo].[Actions] WHERE ActionName = 'Update'; + + SELECT @deleteActionId = ActionId + FROM [dbo].[Actions] WHERE ActionName = 'Delete'; + + SELECT @readChangesActionId = ActionId + FROM [dbo].[Actions] WHERE ActionName = 'ReadChanges'; + + BEGIN TRANSACTION + + -- Push claimId to the stack + INSERT INTO @claimIdStack (ResourceClaimId) VALUES (@claimId) + + -- Processing children of root + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/edFiTypes' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/edFiTypes' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('edFiTypes', 'edFiTypes', 'http://ed-fi.org/ods/identity/claims/domains/edFiTypes', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/edFiTypes + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Writer' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Create authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ').' + ELSE + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @CreateActionId, @authorizationStrategyId) -- Create + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific Update authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ').' + ELSE + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @UpdateActionId, @authorizationStrategyId) -- Update + + -- Claim set-specific Delete authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ').' + ELSE + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @DeleteActionId, @authorizationStrategyId) -- Delete + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/systemDescriptors' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/systemDescriptors' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('systemDescriptors', 'systemDescriptors', 'http://ed-fi.org/ods/identity/claims/domains/systemDescriptors', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/systemDescriptors + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Writer' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Create authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ').' + ELSE + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @CreateActionId, @authorizationStrategyId) -- Create + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific Update authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ').' + ELSE + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @UpdateActionId, @authorizationStrategyId) -- Update + + -- Claim set-specific Delete authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ').' + ELSE + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @DeleteActionId, @authorizationStrategyId) -- Delete + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/managedDescriptors' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/managedDescriptors' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('managedDescriptors', 'managedDescriptors', 'http://ed-fi.org/ods/identity/claims/domains/managedDescriptors', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/managedDescriptors + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Writer' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Create authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ').' + ELSE + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @CreateActionId, @authorizationStrategyId) -- Create + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific Update authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ').' + ELSE + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @UpdateActionId, @authorizationStrategyId) -- Update + + -- Claim set-specific Delete authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ').' + ELSE + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @DeleteActionId, @authorizationStrategyId) -- Delete + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/educationOrganizations' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/educationOrganizations' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('educationOrganizations', 'educationOrganizations', 'http://ed-fi.org/ods/identity/claims/domains/educationOrganizations', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/educationOrganizations + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Writer' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Create authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ').' + ELSE + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @CreateActionId, @authorizationStrategyId) -- Create + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific Update authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ').' + ELSE + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @UpdateActionId, @authorizationStrategyId) -- Update + + -- Claim set-specific Delete authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ').' + ELSE + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @DeleteActionId, @authorizationStrategyId) -- Delete + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/people' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/people' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('people', 'people', 'http://ed-fi.org/ods/identity/claims/domains/people', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/people + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Writer' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Create authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ').' + ELSE + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @CreateActionId, @authorizationStrategyId) -- Create + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific Update authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ').' + ELSE + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @UpdateActionId, @authorizationStrategyId) -- Update + + -- Claim set-specific Delete authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ').' + ELSE + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @DeleteActionId, @authorizationStrategyId) -- Delete + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('relationshipBasedData', 'relationshipBasedData', 'http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Writer' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Create authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ').' + ELSE + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @CreateActionId, @authorizationStrategyId) -- Create + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific Update authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ').' + ELSE + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @UpdateActionId, @authorizationStrategyId) -- Update + + -- Claim set-specific Delete authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ').' + ELSE + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @DeleteActionId, @authorizationStrategyId) -- Delete + -- Push claimId to the stack + INSERT INTO @claimIdStack (ResourceClaimId) VALUES (@claimId) + + -- Processing children of http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/communityProviderLicense' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/communityProviderLicense' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('communityProviderLicense', 'communityProviderLicense', 'http://ed-fi.org/ods/identity/claims/communityProviderLicense', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/communityProviderLicense + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Writer' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Create authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ').' + ELSE + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @CreateActionId, @authorizationStrategyId) -- Create + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific Update authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ').' + ELSE + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @UpdateActionId, @authorizationStrategyId) -- Update + + -- Claim set-specific Delete authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ').' + ELSE + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @DeleteActionId, @authorizationStrategyId) -- Delete + + -- Pop the stack + DELETE FROM @claimIdStack WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('assessmentMetadata', 'assessmentMetadata', 'http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Writer' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Create authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ').' + ELSE + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @CreateActionId, @authorizationStrategyId) -- Create + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific Update authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ').' + ELSE + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @UpdateActionId, @authorizationStrategyId) -- Update + + -- Claim set-specific Delete authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ').' + ELSE + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @DeleteActionId, @authorizationStrategyId) -- Delete + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/educationStandards' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/educationStandards' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('educationStandards', 'educationStandards', 'http://ed-fi.org/ods/identity/claims/domains/educationStandards', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/educationStandards + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Writer' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Create authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ').' + ELSE + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @CreateActionId, @authorizationStrategyId) -- Create + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific Update authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ').' + ELSE + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @UpdateActionId, @authorizationStrategyId) -- Update + + -- Claim set-specific Delete authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ').' + ELSE + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @DeleteActionId, @authorizationStrategyId) -- Delete + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/primaryRelationships' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/primaryRelationships' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('primaryRelationships', 'primaryRelationships', 'http://ed-fi.org/ods/identity/claims/domains/primaryRelationships', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/primaryRelationships + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Writer' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Create authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ').' + ELSE + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @CreateActionId, @authorizationStrategyId) -- Create + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific Update authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ').' + ELSE + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @UpdateActionId, @authorizationStrategyId) -- Update + + -- Claim set-specific Delete authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ').' + ELSE + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @DeleteActionId, @authorizationStrategyId) -- Delete + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/surveyDomain' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/surveyDomain' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('surveyDomain', 'surveyDomain', 'http://ed-fi.org/ods/identity/claims/domains/surveyDomain', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/surveyDomain + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Writer' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Create authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ').' + ELSE + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @CreateActionId, @authorizationStrategyId) -- Create + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific Update authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ').' + ELSE + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @UpdateActionId, @authorizationStrategyId) -- Update + + -- Claim set-specific Delete authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ').' + ELSE + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @DeleteActionId, @authorizationStrategyId) -- Delete + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/educationContent' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/educationContent' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('educationContent', 'educationContent', 'http://ed-fi.org/ods/identity/claims/educationContent', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/educationContent + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi API Publisher - Writer' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Create authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ').' + ELSE + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @CreateActionId, @authorizationStrategyId) -- Create + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific Update authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ').' + ELSE + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @UpdateActionId, @authorizationStrategyId) -- Update + + -- Claim set-specific Delete authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ').' + ELSE + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @DeleteActionId, @authorizationStrategyId) -- Delete + + -- Pop the stack + DELETE FROM @claimIdStack WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + COMMIT TRANSACTION +END \ No newline at end of file diff --git a/Artifacts/MsSql/Data/Security/Changes/0030-Sandbox-Publishing-Security-Metadata.sql b/Artifacts/MsSql/Data/Security/Changes/0030-Sandbox-Publishing-Security-Metadata.sql new file mode 100644 index 0000000000..f073ffd16d --- /dev/null +++ b/Artifacts/MsSql/Data/Security/Changes/0030-Sandbox-Publishing-Security-Metadata.sql @@ -0,0 +1,1179 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +BEGIN + DECLARE + @applicationId AS INT, + @claimId AS INT, + @claimName AS nvarchar(max), + @parentResourceClaimId AS INT, + @existingParentResourceClaimId AS INT, + @claimSetId AS INT, + @claimSetName AS nvarchar(max), + @authorizationStrategyId AS INT, + @msg AS nvarchar(max), + @createActionId AS INT, + @readActionId AS INT, + @updateActionId AS INT, + @deleteActionId AS INT, + @readChangesActionId AS INT + + DECLARE @claimIdStack AS TABLE (Id INT IDENTITY, ResourceClaimId INT) + + SELECT @applicationId = ApplicationId + FROM [dbo].[Applications] WHERE ApplicationName = 'Ed-Fi ODS API'; + + SELECT @createActionId = ActionId + FROM [dbo].[Actions] WHERE ActionName = 'Create'; + + SELECT @readActionId = ActionId + FROM [dbo].[Actions] WHERE ActionName = 'Read'; + + SELECT @updateActionId = ActionId + FROM [dbo].[Actions] WHERE ActionName = 'Update'; + + SELECT @deleteActionId = ActionId + FROM [dbo].[Actions] WHERE ActionName = 'Delete'; + + SELECT @readChangesActionId = ActionId + FROM [dbo].[Actions] WHERE ActionName = 'ReadChanges'; + + BEGIN TRANSACTION + + -- Push claimId to the stack + INSERT INTO @claimIdStack (ResourceClaimId) VALUES (@claimId) + + -- Processing children of root + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/systemDescriptors' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/systemDescriptors' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('systemDescriptors', 'systemDescriptors', 'http://ed-fi.org/ods/identity/claims/domains/systemDescriptors', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/systemDescriptors + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi Sandbox' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi Sandbox' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Create authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ').' + ELSE + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @CreateActionId, @authorizationStrategyId) -- Create + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific Update authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ').' + ELSE + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @UpdateActionId, @authorizationStrategyId) -- Update + + -- Claim set-specific Delete authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ').' + ELSE + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @DeleteActionId, @authorizationStrategyId) -- Delete + + -- Claim set-specific ReadChanges authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ').' + ELSE + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadChangesActionId, @authorizationStrategyId) -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/managedDescriptors' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/managedDescriptors' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('managedDescriptors', 'managedDescriptors', 'http://ed-fi.org/ods/identity/claims/domains/managedDescriptors', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/managedDescriptors + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi Sandbox' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi Sandbox' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Create authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ').' + ELSE + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @CreateActionId, @authorizationStrategyId) -- Create + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific Update authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ').' + ELSE + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @UpdateActionId, @authorizationStrategyId) -- Update + + -- Claim set-specific Delete authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ').' + ELSE + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @DeleteActionId, @authorizationStrategyId) -- Delete + + -- Claim set-specific ReadChanges authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ').' + ELSE + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadChangesActionId, @authorizationStrategyId) -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/educationOrganizations' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/educationOrganizations' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('educationOrganizations', 'educationOrganizations', 'http://ed-fi.org/ods/identity/claims/domains/educationOrganizations', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/educationOrganizations + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi Sandbox' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi Sandbox' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Create authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ').' + ELSE + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @CreateActionId, @authorizationStrategyId) -- Create + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific Update authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ').' + ELSE + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @UpdateActionId, @authorizationStrategyId) -- Update + + -- Claim set-specific Delete authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ').' + ELSE + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @DeleteActionId, @authorizationStrategyId) -- Delete + + -- Claim set-specific ReadChanges authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ').' + ELSE + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadChangesActionId, @authorizationStrategyId) -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/people' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/people' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('people', 'people', 'http://ed-fi.org/ods/identity/claims/domains/people', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/people + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi Sandbox' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi Sandbox' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Create authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ').' + ELSE + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @CreateActionId, @authorizationStrategyId) -- Create + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific Update authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ').' + ELSE + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @UpdateActionId, @authorizationStrategyId) -- Update + + -- Claim set-specific Delete authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ').' + ELSE + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @DeleteActionId, @authorizationStrategyId) -- Delete + + -- Claim set-specific ReadChanges authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'RelationshipsWithEdOrgsAndPeopleIncludingDeletes' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ').' + ELSE + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadChangesActionId, @authorizationStrategyId) -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('relationshipBasedData', 'relationshipBasedData', 'http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi Sandbox' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi Sandbox' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Create authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ').' + ELSE + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @CreateActionId, @authorizationStrategyId) -- Create + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific Update authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ').' + ELSE + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @UpdateActionId, @authorizationStrategyId) -- Update + + -- Claim set-specific Delete authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ').' + ELSE + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @DeleteActionId, @authorizationStrategyId) -- Delete + + -- Claim set-specific ReadChanges authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'RelationshipsWithEdOrgsAndPeopleIncludingDeletes' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ').' + ELSE + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadChangesActionId, @authorizationStrategyId) -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('assessmentMetadata', 'assessmentMetadata', 'http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi Sandbox' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi Sandbox' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Create authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ').' + ELSE + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @CreateActionId, @authorizationStrategyId) -- Create + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific Update authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ').' + ELSE + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @UpdateActionId, @authorizationStrategyId) -- Update + + -- Claim set-specific Delete authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ').' + ELSE + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @DeleteActionId, @authorizationStrategyId) -- Delete + + -- Claim set-specific ReadChanges authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NamespaceBased' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ').' + ELSE + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadChangesActionId, @authorizationStrategyId) -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/educationStandards' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/educationStandards' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('educationStandards', 'educationStandards', 'http://ed-fi.org/ods/identity/claims/domains/educationStandards', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/educationStandards + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi Sandbox' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi Sandbox' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Create authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ').' + ELSE + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @CreateActionId, @authorizationStrategyId) -- Create + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific Update authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ').' + ELSE + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @UpdateActionId, @authorizationStrategyId) -- Update + + -- Claim set-specific Delete authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ').' + ELSE + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @DeleteActionId, @authorizationStrategyId) -- Delete + + -- Claim set-specific ReadChanges authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NamespaceBased' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ').' + ELSE + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadChangesActionId, @authorizationStrategyId) -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/primaryRelationships' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/domains/primaryRelationships' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('primaryRelationships', 'primaryRelationships', 'http://ed-fi.org/ods/identity/claims/domains/primaryRelationships', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/domains/primaryRelationships + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi Sandbox' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi Sandbox' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Create authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ').' + ELSE + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @CreateActionId, @authorizationStrategyId) -- Create + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific Update authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ').' + ELSE + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @UpdateActionId, @authorizationStrategyId) -- Update + + -- Claim set-specific Delete authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ').' + ELSE + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @DeleteActionId, @authorizationStrategyId) -- Delete + + -- Claim set-specific ReadChanges authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'RelationshipsWithEdOrgsAndPeopleIncludingDeletes' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ').' + ELSE + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadChangesActionId, @authorizationStrategyId) -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/educationContent' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimName = 'http://ed-fi.org/ods/identity/claims/educationContent' + SET @claimId = NULL + + SELECT @claimId = ResourceClaimId, @existingParentResourceClaimId = ParentResourceClaimId + FROM dbo.ResourceClaims + WHERE ClaimName = @claimName + + SELECT @parentResourceClaimId = ResourceClaimId + FROM @claimIdStack + WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + IF @claimId IS NULL + BEGIN + PRINT 'Creating new claim: ' + @claimName + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('educationContent', 'educationContent', 'http://ed-fi.org/ods/identity/claims/educationContent', @parentResourceClaimId, @applicationId) + + SET @claimId = SCOPE_IDENTITY() + END + ELSE + BEGIN + IF @parentResourceClaimId != @existingParentResourceClaimId OR (@parentResourceClaimId IS NULL AND @existingParentResourceClaimId IS NOT NULL) OR (@parentResourceClaimId IS NOT NULL AND @existingParentResourceClaimId IS NULL) + BEGIN + PRINT 'Repointing claim ''' + @claimName + ''' (ResourceClaimId=' + CONVERT(nvarchar, @claimId) + ') to new parent (ResourceClaimId=' + CONVERT(nvarchar, @parentResourceClaimId) + ')' + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = @parentResourceClaimId + WHERE ResourceClaimId = @claimId + END + END + + -- Processing claim sets for http://ed-fi.org/ods/identity/claims/educationContent + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi Sandbox' + ---------------------------------------------------------------------------------------------------------------------------- + SET @claimSetName = 'Ed-Fi Sandbox' + SET @claimSetId = NULL + + SELECT @claimSetId = ClaimSetId + FROM dbo.ClaimSets + WHERE ClaimSetName = @claimSetName + + IF @claimSetId IS NULL + BEGIN + PRINT 'Creating new claim set: ' + @claimSetName + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (@claimSetName, @applicationId) + + SET @claimSetId = SCOPE_IDENTITY() + END + + PRINT 'Deleting existing actions for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ') on resource claim ''' + @claimName + '''.' + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = @claimSetId AND ResourceClaim_ResourceClaimId = @claimId + + + -- Claim set-specific Create authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ').' + ELSE + PRINT 'Creating ''Create'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @CreateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @CreateActionId, @authorizationStrategyId) -- Create + + -- Claim set-specific Read authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ').' + ELSE + PRINT 'Creating ''Read'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadActionId, @authorizationStrategyId) -- Read + + -- Claim set-specific Update authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ').' + ELSE + PRINT 'Creating ''Update'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @UpdateActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @UpdateActionId, @authorizationStrategyId) -- Update + + -- Claim set-specific Delete authorization + SET @authorizationStrategyId = NULL + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ').' + ELSE + PRINT 'Creating ''Delete'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @DeleteActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @DeleteActionId, @authorizationStrategyId) -- Delete + + -- Claim set-specific ReadChanges authorization + SET @authorizationStrategyId = NULL + + + SELECT @authorizationStrategyId = a.AuthorizationStrategyId + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NamespaceBased' + + + IF @authorizationStrategyId IS NULL + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ').' + ELSE + PRINT 'Creating ''ReadChanges'' action for claim set ''' + @claimSetName + ''' (claimSetId=' + CONVERT(nvarchar, @claimSetId) + ', actionId = ' + CONVERT(nvarchar, @ReadChangesActionId) + ', authorizationStrategyId = ' + CONVERT(nvarchar, @authorizationStrategyId) + ').' + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (@claimId, @claimSetId, @ReadChangesActionId, @authorizationStrategyId) -- ReadChanges + + -- Pop the stack + DELETE FROM @claimIdStack WHERE Id = (SELECT Max(Id) FROM @claimIdStack) + + COMMIT TRANSACTION +END \ No newline at end of file diff --git a/Artifacts/PgSql/Data/Security/1080-AddReadChangesAction-DeletesAuthStrategy.sql b/Artifacts/PgSql/Data/Security/1080-AddReadChangesAction-DeletesAuthStrategy.sql new file mode 100644 index 0000000000..92dcd7347c --- /dev/null +++ b/Artifacts/PgSql/Data/Security/1080-AddReadChangesAction-DeletesAuthStrategy.sql @@ -0,0 +1,13 @@ +DO $$ +DECLARE + application_id INTEGER; +BEGIN + INSERT INTO dbo.Actions (ActionName, ActionUri) VALUES ('ReadChanges', 'http://ed-fi.org/odsapi/actions/readChanges'); + + SELECT applicationid INTO application_id + FROM dbo.applications WHERE ApplicationName = 'Ed-Fi ODS API'; + + INSERT INTO dbo.authorizationstrategies(displayname, authorizationstrategyname, application_applicationid) + VALUES ('Relationships with Education Organizations and People (including deletes)', 'RelationshipsWithEdOrgsAndPeopleIncludingDeletes', application_id); +END $$; + diff --git a/Artifacts/PgSql/Data/Security/Changes/0010-API-Publisher-Reader-Security-Metadata.sql b/Artifacts/PgSql/Data/Security/Changes/0010-API-Publisher-Reader-Security-Metadata.sql new file mode 100644 index 0000000000..6b36001500 --- /dev/null +++ b/Artifacts/PgSql/Data/Security/Changes/0010-API-Publisher-Reader-Security-Metadata.sql @@ -0,0 +1,1143 @@ + +DO $$ +DECLARE + application_id INTEGER; + claim_id INTEGER; + claim_name VARCHAR(2048); + parent_resource_claim_id INTEGER; + existing_parent_resource_claim_id INTEGER; + claim_set_id INTEGER; + claim_set_name VARCHAR(255); + authorization_strategy_id INTEGER; + create_action_id INTEGER; + read_action_id INTEGER; + update_action_id INTEGER; + delete_action_id INTEGER; + readchanges_action_id INTEGER; + claim_id_stack INTEGER ARRAY; +BEGIN + SELECT applicationid INTO application_id + FROM dbo.applications WHERE ApplicationName = 'Ed-Fi ODS API'; + + SELECT actionid INTO create_action_id + FROM dbo.actions WHERE ActionName = 'Create'; + + SELECT actionid INTO read_action_id + FROM dbo.actions WHERE ActionName = 'Read'; + + SELECT actionid INTO update_action_id + FROM dbo.actions WHERE ActionName = 'Update'; + + SELECT actionid INTO delete_action_id + FROM dbo.actions WHERE ActionName = 'Delete'; + + SELECT actionid INTO readchanges_action_id + FROM dbo.actions WHERE ActionName = 'ReadChanges'; + + + -- Push claimId to the stack + claim_id_stack := array_append(claim_id_stack, claim_id); + + -- Processing children of root + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/edFiTypes' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/edFiTypes'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('edFiTypes', 'edFiTypes', 'http://ed-fi.org/ods/identity/claims/domains/edFiTypes', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/edFiTypes + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Reader'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/systemDescriptors' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/systemDescriptors'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('systemDescriptors', 'systemDescriptors', 'http://ed-fi.org/ods/identity/claims/domains/systemDescriptors', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/systemDescriptors + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Reader'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific ReadChanges authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, ReadChanges_action_id, authorization_strategy_id); -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/managedDescriptors' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/managedDescriptors'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('managedDescriptors', 'managedDescriptors', 'http://ed-fi.org/ods/identity/claims/domains/managedDescriptors', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/managedDescriptors + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Reader'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific ReadChanges authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, ReadChanges_action_id, authorization_strategy_id); -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/educationOrganizations' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/educationOrganizations'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('educationOrganizations', 'educationOrganizations', 'http://ed-fi.org/ods/identity/claims/domains/educationOrganizations', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/educationOrganizations + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Reader'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific ReadChanges authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, ReadChanges_action_id, authorization_strategy_id); -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/people' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/people'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('people', 'people', 'http://ed-fi.org/ods/identity/claims/domains/people', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/people + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Reader'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific ReadChanges authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'RelationshipsWithEdOrgsAndPeopleIncludingDeletes'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, ReadChanges_action_id, authorization_strategy_id); -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('relationshipBasedData', 'relationshipBasedData', 'http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Reader'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific ReadChanges authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'RelationshipsWithEdOrgsAndPeopleIncludingDeletes'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, ReadChanges_action_id, authorization_strategy_id); -- ReadChanges + -- Push claimId to the stack + claim_id_stack := array_append(claim_id_stack, claim_id); + + -- Processing children of http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/communityProviderLicense' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/communityProviderLicense'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('communityProviderLicense', 'communityProviderLicense', 'http://ed-fi.org/ods/identity/claims/communityProviderLicense', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/communityProviderLicense + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Reader'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific ReadChanges authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, ReadChanges_action_id, authorization_strategy_id); -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/person' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/person'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('person', 'person', 'http://ed-fi.org/ods/identity/claims/person', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/person + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Reader'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific ReadChanges authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, ReadChanges_action_id, authorization_strategy_id); -- ReadChanges + + -- Pop the stack + claim_id_stack := (select claim_id_stack[1:array_upper(claim_id_stack, 1) - 1]); + + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('assessmentMetadata', 'assessmentMetadata', 'http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Reader'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific ReadChanges authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NamespaceBased'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, ReadChanges_action_id, authorization_strategy_id); -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/educationStandards' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/educationStandards'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('educationStandards', 'educationStandards', 'http://ed-fi.org/ods/identity/claims/domains/educationStandards', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/educationStandards + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Reader'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific ReadChanges authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NamespaceBased'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, ReadChanges_action_id, authorization_strategy_id); -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/primaryRelationships' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/primaryRelationships'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('primaryRelationships', 'primaryRelationships', 'http://ed-fi.org/ods/identity/claims/domains/primaryRelationships', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/primaryRelationships + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Reader'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific ReadChanges authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'RelationshipsWithEdOrgsAndPeopleIncludingDeletes'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, ReadChanges_action_id, authorization_strategy_id); -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/educationContent' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/educationContent'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('educationContent', 'educationContent', 'http://ed-fi.org/ods/identity/claims/educationContent', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/educationContent + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Reader'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific ReadChanges authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NamespaceBased'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, ReadChanges_action_id, authorization_strategy_id); -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/publishing/snapshot' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/publishing/snapshot'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('snapshot', 'snapshot', 'http://ed-fi.org/ods/identity/claims/publishing/snapshot', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/publishing/snapshot + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Reader' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Reader'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Pop the stack + claim_id_stack := (select claim_id_stack[1:array_upper(claim_id_stack, 1) - 1]); + + COMMIT; + + -- TODO: Remove - For interactive development only + -- SELECT dbo.GetAuthorizationMetadataDocument(); + -- ROLLBACK; +END $$; diff --git a/Artifacts/PgSql/Data/Security/Changes/0020-API-Publisher-Writer-Security-Metadata.sql b/Artifacts/PgSql/Data/Security/Changes/0020-API-Publisher-Writer-Security-Metadata.sql new file mode 100644 index 0000000000..e0a66fadb3 --- /dev/null +++ b/Artifacts/PgSql/Data/Security/Changes/0020-API-Publisher-Writer-Security-Metadata.sql @@ -0,0 +1,1491 @@ + +DO $$ +DECLARE + application_id INTEGER; + claim_id INTEGER; + claim_name VARCHAR(2048); + parent_resource_claim_id INTEGER; + existing_parent_resource_claim_id INTEGER; + claim_set_id INTEGER; + claim_set_name VARCHAR(255); + authorization_strategy_id INTEGER; + create_action_id INTEGER; + read_action_id INTEGER; + update_action_id INTEGER; + delete_action_id INTEGER; + readchanges_action_id INTEGER; + claim_id_stack INTEGER ARRAY; +BEGIN + SELECT applicationid INTO application_id + FROM dbo.applications WHERE ApplicationName = 'Ed-Fi ODS API'; + + SELECT actionid INTO create_action_id + FROM dbo.actions WHERE ActionName = 'Create'; + + SELECT actionid INTO read_action_id + FROM dbo.actions WHERE ActionName = 'Read'; + + SELECT actionid INTO update_action_id + FROM dbo.actions WHERE ActionName = 'Update'; + + SELECT actionid INTO delete_action_id + FROM dbo.actions WHERE ActionName = 'Delete'; + + SELECT actionid INTO readchanges_action_id + FROM dbo.actions WHERE ActionName = 'ReadChanges'; + + + -- Push claimId to the stack + claim_id_stack := array_append(claim_id_stack, claim_id); + + -- Processing children of root + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/edFiTypes' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/edFiTypes'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('edFiTypes', 'edFiTypes', 'http://ed-fi.org/ods/identity/claims/domains/edFiTypes', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/edFiTypes + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Writer'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Create authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Create_action_id, authorization_strategy_id); -- Create + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific Update authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Update_action_id, authorization_strategy_id); -- Update + + -- Claim set-specific Delete authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Delete_action_id, authorization_strategy_id); -- Delete + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/systemDescriptors' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/systemDescriptors'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('systemDescriptors', 'systemDescriptors', 'http://ed-fi.org/ods/identity/claims/domains/systemDescriptors', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/systemDescriptors + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Writer'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Create authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Create_action_id, authorization_strategy_id); -- Create + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific Update authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Update_action_id, authorization_strategy_id); -- Update + + -- Claim set-specific Delete authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Delete_action_id, authorization_strategy_id); -- Delete + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/managedDescriptors' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/managedDescriptors'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('managedDescriptors', 'managedDescriptors', 'http://ed-fi.org/ods/identity/claims/domains/managedDescriptors', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/managedDescriptors + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Writer'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Create authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Create_action_id, authorization_strategy_id); -- Create + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific Update authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Update_action_id, authorization_strategy_id); -- Update + + -- Claim set-specific Delete authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Delete_action_id, authorization_strategy_id); -- Delete + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/educationOrganizations' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/educationOrganizations'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('educationOrganizations', 'educationOrganizations', 'http://ed-fi.org/ods/identity/claims/domains/educationOrganizations', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/educationOrganizations + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Writer'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Create authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Create_action_id, authorization_strategy_id); -- Create + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific Update authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Update_action_id, authorization_strategy_id); -- Update + + -- Claim set-specific Delete authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Delete_action_id, authorization_strategy_id); -- Delete + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/people' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/people'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('people', 'people', 'http://ed-fi.org/ods/identity/claims/domains/people', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/people + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Writer'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Create authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Create_action_id, authorization_strategy_id); -- Create + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific Update authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Update_action_id, authorization_strategy_id); -- Update + + -- Claim set-specific Delete authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Delete_action_id, authorization_strategy_id); -- Delete + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('relationshipBasedData', 'relationshipBasedData', 'http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Writer'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Create authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Create_action_id, authorization_strategy_id); -- Create + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific Update authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Update_action_id, authorization_strategy_id); -- Update + + -- Claim set-specific Delete authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Delete_action_id, authorization_strategy_id); -- Delete + -- Push claimId to the stack + claim_id_stack := array_append(claim_id_stack, claim_id); + + -- Processing children of http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/communityProviderLicense' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/communityProviderLicense'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('communityProviderLicense', 'communityProviderLicense', 'http://ed-fi.org/ods/identity/claims/communityProviderLicense', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/communityProviderLicense + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Writer'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Create authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Create_action_id, authorization_strategy_id); -- Create + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific Update authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Update_action_id, authorization_strategy_id); -- Update + + -- Claim set-specific Delete authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Delete_action_id, authorization_strategy_id); -- Delete + + -- Pop the stack + claim_id_stack := (select claim_id_stack[1:array_upper(claim_id_stack, 1) - 1]); + + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('assessmentMetadata', 'assessmentMetadata', 'http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Writer'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Create authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Create_action_id, authorization_strategy_id); -- Create + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific Update authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Update_action_id, authorization_strategy_id); -- Update + + -- Claim set-specific Delete authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Delete_action_id, authorization_strategy_id); -- Delete + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/educationStandards' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/educationStandards'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('educationStandards', 'educationStandards', 'http://ed-fi.org/ods/identity/claims/domains/educationStandards', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/educationStandards + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Writer'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Create authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Create_action_id, authorization_strategy_id); -- Create + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific Update authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Update_action_id, authorization_strategy_id); -- Update + + -- Claim set-specific Delete authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Delete_action_id, authorization_strategy_id); -- Delete + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/primaryRelationships' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/primaryRelationships'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('primaryRelationships', 'primaryRelationships', 'http://ed-fi.org/ods/identity/claims/domains/primaryRelationships', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/primaryRelationships + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Writer'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Create authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Create_action_id, authorization_strategy_id); -- Create + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific Update authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Update_action_id, authorization_strategy_id); -- Update + + -- Claim set-specific Delete authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Delete_action_id, authorization_strategy_id); -- Delete + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/surveyDomain' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/surveyDomain'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('surveyDomain', 'surveyDomain', 'http://ed-fi.org/ods/identity/claims/domains/surveyDomain', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/surveyDomain + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Writer'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Create authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Create_action_id, authorization_strategy_id); -- Create + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific Update authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Update_action_id, authorization_strategy_id); -- Update + + -- Claim set-specific Delete authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Delete_action_id, authorization_strategy_id); -- Delete + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/educationContent' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/educationContent'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('educationContent', 'educationContent', 'http://ed-fi.org/ods/identity/claims/educationContent', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/educationContent + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi API Publisher - Writer' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi API Publisher - Writer'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Create authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Create_action_id, authorization_strategy_id); -- Create + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific Update authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Update_action_id, authorization_strategy_id); -- Update + + -- Claim set-specific Delete authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Delete_action_id, authorization_strategy_id); -- Delete + + -- Pop the stack + claim_id_stack := (select claim_id_stack[1:array_upper(claim_id_stack, 1) - 1]); + + COMMIT; + + -- TODO: Remove - For interactive development only + -- SELECT dbo.GetAuthorizationMetadataDocument(); + -- ROLLBACK; +END $$; diff --git a/Artifacts/PgSql/Data/Security/Changes/0030-Sandbox-Publishing-Security-Metadata.sql b/Artifacts/PgSql/Data/Security/Changes/0030-Sandbox-Publishing-Security-Metadata.sql new file mode 100644 index 0000000000..a45ac4a622 --- /dev/null +++ b/Artifacts/PgSql/Data/Security/Changes/0030-Sandbox-Publishing-Security-Metadata.sql @@ -0,0 +1,1171 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +DO $$ +DECLARE + application_id INTEGER; + claim_id INTEGER; + claim_name VARCHAR(2048); + parent_resource_claim_id INTEGER; + existing_parent_resource_claim_id INTEGER; + claim_set_id INTEGER; + claim_set_name VARCHAR(255); + authorization_strategy_id INTEGER; + create_action_id INTEGER; + read_action_id INTEGER; + update_action_id INTEGER; + delete_action_id INTEGER; + readchanges_action_id INTEGER; + claim_id_stack INTEGER ARRAY; +BEGIN + SELECT applicationid INTO application_id + FROM dbo.applications WHERE ApplicationName = 'Ed-Fi ODS API'; + + SELECT actionid INTO create_action_id + FROM dbo.actions WHERE ActionName = 'Create'; + + SELECT actionid INTO read_action_id + FROM dbo.actions WHERE ActionName = 'Read'; + + SELECT actionid INTO update_action_id + FROM dbo.actions WHERE ActionName = 'Update'; + + SELECT actionid INTO delete_action_id + FROM dbo.actions WHERE ActionName = 'Delete'; + + SELECT actionid INTO readchanges_action_id + FROM dbo.actions WHERE ActionName = 'ReadChanges'; + + + -- Push claimId to the stack + claim_id_stack := array_append(claim_id_stack, claim_id); + + -- Processing children of root + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/systemDescriptors' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/systemDescriptors'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('systemDescriptors', 'systemDescriptors', 'http://ed-fi.org/ods/identity/claims/domains/systemDescriptors', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/systemDescriptors + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi Sandbox' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi Sandbox'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Create authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Create_action_id, authorization_strategy_id); -- Create + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific Update authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Update_action_id, authorization_strategy_id); -- Update + + -- Claim set-specific Delete authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Delete_action_id, authorization_strategy_id); -- Delete + + -- Claim set-specific ReadChanges authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, ReadChanges_action_id, authorization_strategy_id); -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/managedDescriptors' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/managedDescriptors'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('managedDescriptors', 'managedDescriptors', 'http://ed-fi.org/ods/identity/claims/domains/managedDescriptors', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/managedDescriptors + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi Sandbox' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi Sandbox'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Create authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Create_action_id, authorization_strategy_id); -- Create + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific Update authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Update_action_id, authorization_strategy_id); -- Update + + -- Claim set-specific Delete authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Delete_action_id, authorization_strategy_id); -- Delete + + -- Claim set-specific ReadChanges authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, ReadChanges_action_id, authorization_strategy_id); -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/educationOrganizations' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/educationOrganizations'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('educationOrganizations', 'educationOrganizations', 'http://ed-fi.org/ods/identity/claims/domains/educationOrganizations', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/educationOrganizations + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi Sandbox' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi Sandbox'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Create authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Create_action_id, authorization_strategy_id); -- Create + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific Update authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Update_action_id, authorization_strategy_id); -- Update + + -- Claim set-specific Delete authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Delete_action_id, authorization_strategy_id); -- Delete + + -- Claim set-specific ReadChanges authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NoFurtherAuthorizationRequired'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, ReadChanges_action_id, authorization_strategy_id); -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/people' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/people'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('people', 'people', 'http://ed-fi.org/ods/identity/claims/domains/people', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/people + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi Sandbox' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi Sandbox'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Create authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Create_action_id, authorization_strategy_id); -- Create + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific Update authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Update_action_id, authorization_strategy_id); -- Update + + -- Claim set-specific Delete authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Delete_action_id, authorization_strategy_id); -- Delete + + -- Claim set-specific ReadChanges authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'RelationshipsWithEdOrgsAndPeopleIncludingDeletes'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, ReadChanges_action_id, authorization_strategy_id); -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('relationshipBasedData', 'relationshipBasedData', 'http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/relationshipBasedData + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi Sandbox' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi Sandbox'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Create authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Create_action_id, authorization_strategy_id); -- Create + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific Update authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Update_action_id, authorization_strategy_id); -- Update + + -- Claim set-specific Delete authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Delete_action_id, authorization_strategy_id); -- Delete + + -- Claim set-specific ReadChanges authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'RelationshipsWithEdOrgsAndPeopleIncludingDeletes'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, ReadChanges_action_id, authorization_strategy_id); -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('assessmentMetadata', 'assessmentMetadata', 'http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/assessmentMetadata + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi Sandbox' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi Sandbox'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Create authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Create_action_id, authorization_strategy_id); -- Create + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific Update authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Update_action_id, authorization_strategy_id); -- Update + + -- Claim set-specific Delete authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Delete_action_id, authorization_strategy_id); -- Delete + + -- Claim set-specific ReadChanges authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NamespaceBased'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, ReadChanges_action_id, authorization_strategy_id); -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/educationStandards' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/educationStandards'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('educationStandards', 'educationStandards', 'http://ed-fi.org/ods/identity/claims/domains/educationStandards', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/educationStandards + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi Sandbox' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi Sandbox'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Create authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Create_action_id, authorization_strategy_id); -- Create + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific Update authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Update_action_id, authorization_strategy_id); -- Update + + -- Claim set-specific Delete authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Delete_action_id, authorization_strategy_id); -- Delete + + -- Claim set-specific ReadChanges authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NamespaceBased'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, ReadChanges_action_id, authorization_strategy_id); -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/domains/primaryRelationships' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/domains/primaryRelationships'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('primaryRelationships', 'primaryRelationships', 'http://ed-fi.org/ods/identity/claims/domains/primaryRelationships', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/domains/primaryRelationships + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi Sandbox' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi Sandbox'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Create authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Create_action_id, authorization_strategy_id); -- Create + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific Update authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Update_action_id, authorization_strategy_id); -- Update + + -- Claim set-specific Delete authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Delete_action_id, authorization_strategy_id); -- Delete + + -- Claim set-specific ReadChanges authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'RelationshipsWithEdOrgsAndPeopleIncludingDeletes'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, ReadChanges_action_id, authorization_strategy_id); -- ReadChanges + ---------------------------------------------------------------------------------------------------------------------------- + -- Resource Claim: 'http://ed-fi.org/ods/identity/claims/educationContent' + ---------------------------------------------------------------------------------------------------------------------------- + claim_name := 'http://ed-fi.org/ods/identity/claims/educationContent'; + claim_id := NULL; + + SELECT ResourceClaimId, ParentResourceClaimId INTO claim_id, existing_parent_resource_claim_id + FROM dbo.ResourceClaims + WHERE ClaimName = claim_name; + + parent_resource_claim_id := claim_id_stack[array_upper(claim_id_stack, 1)]; + + IF claim_id IS NULL THEN + RAISE NOTICE 'Creating new claim: %', claim_name; + + INSERT INTO dbo.ResourceClaims(DisplayName, ResourceName, ClaimName, ParentResourceClaimId, Application_ApplicationId) + VALUES ('educationContent', 'educationContent', 'http://ed-fi.org/ods/identity/claims/educationContent', parent_resource_claim_id, application_id) + RETURNING ResourceClaimId + INTO claim_id; + ELSE + IF parent_resource_claim_id != existing_parent_resource_claim_id OR (parent_resource_claim_id IS NULL AND existing_parent_resource_claim_id IS NOT NULL) OR (parent_resource_claim_id IS NOT NULL AND existing_parent_resource_claim_id IS NULL) THEN + RAISE NOTICE USING MESSAGE = 'Repointing claim ''' || claim_name || ''' (ResourceClaimId=' || claim_id || ') to new parent (from ResourceClaimId=' || COALESCE(existing_parent_resource_claim_id, 0) || ' to ResourceClaimId=' || COALESCE(parent_resource_claim_id, 0) || ')'; + + UPDATE dbo.ResourceClaims + SET ParentResourceClaimId = parent_resource_claim_id + WHERE ResourceClaimId = claim_id; + END IF; + END IF; + + -- Processing claimsets for http://ed-fi.org/ods/identity/claims/educationContent + ---------------------------------------------------------------------------------------------------------------------------- + -- Claim set: 'Ed-Fi Sandbox' + ---------------------------------------------------------------------------------------------------------------------------- + claim_set_name := 'Ed-Fi Sandbox'; + claim_set_id := NULL; + + SELECT ClaimSetId INTO claim_set_id + FROM dbo.ClaimSets + WHERE ClaimSetName = claim_set_name; + + IF claim_set_id IS NULL THEN + RAISE NOTICE 'Creating new claim set: %', claim_set_name; + + INSERT INTO dbo.ClaimSets(ClaimSetName, Application_ApplicationId) + VALUES (claim_set_name, application_id) + RETURNING ClaimSetId + INTO claim_set_id; + END IF; + + + RAISE NOTICE USING MESSAGE = 'Deleting existing actions for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ') on resource claim ''' || claim_name || '''.'; + DELETE FROM dbo.ClaimSetResourceClaims + WHERE ClaimSet_ClaimSetId = claim_set_id AND ResourceClaim_ResourceClaimId = claim_id; + + + -- Claim set-specific Create authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Create'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Create_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Create_action_id, authorization_strategy_id); -- Create + + -- Claim set-specific Read authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Read'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Read_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Read_action_id, authorization_strategy_id); -- Read + + -- Claim set-specific Update authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Update'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Update_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Update_action_id, authorization_strategy_id); -- Update + + -- Claim set-specific Delete authorization + authorization_strategy_id := NULL; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''Delete'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || Delete_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, Delete_action_id, authorization_strategy_id); -- Delete + + -- Claim set-specific ReadChanges authorization + authorization_strategy_id := NULL; + + + SELECT a.AuthorizationStrategyId INTO authorization_strategy_id + FROM dbo.AuthorizationStrategies a + WHERE a.AuthorizationStrategyName = 'NamespaceBased'; + + + IF authorization_strategy_id IS NULL THEN + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ').'; + ELSE + RAISE NOTICE USING MESSAGE = 'Creating ''ReadChanges'' action for claim set ''' || claim_set_name || ''' (claimSetId=' || claim_set_id || ', actionId = ' || ReadChanges_action_id || ', authorizationStrategyId = ' || authorization_strategy_id || ').'; + END IF; + + INSERT INTO dbo.ClaimSetResourceClaims(ResourceClaim_ResourceClaimId, ClaimSet_ClaimSetId, Action_ActionId, AuthorizationStrategyOverride_AuthorizationStrategyId) + VALUES (claim_id, claim_set_id, ReadChanges_action_id, authorization_strategy_id); -- ReadChanges + + -- Pop the stack + claim_id_stack := (select claim_id_stack[1:array_upper(claim_id_stack, 1) - 1]); + + COMMIT; + + -- TODO: Remove - For interactive development only + -- SELECT dbo.GetAuthorizationMetadataDocument(); + -- ROLLBACK; +END $$; \ No newline at end of file diff --git a/Utilities/CodeGeneration/EdFi.Ods.CodeGen.Tests/IntegrationTests/Profiles/ProfileTestDataHelper.cs b/Utilities/CodeGeneration/EdFi.Ods.CodeGen.Tests/IntegrationTests/Profiles/ProfileTestDataHelper.cs index e3c64ca8c3..b52ade2a80 100644 --- a/Utilities/CodeGeneration/EdFi.Ods.CodeGen.Tests/IntegrationTests/Profiles/ProfileTestDataHelper.cs +++ b/Utilities/CodeGeneration/EdFi.Ods.CodeGen.Tests/IntegrationTests/Profiles/ProfileTestDataHelper.cs @@ -11,6 +11,7 @@ using EdFi.Ods.CodeGen.Providers; using EdFi.Ods.CodeGen.Tests.IntegrationTests._Helpers; using EdFi.Ods.Common.Metadata.Schemas; +using EdFi.Ods.Common.Models; using EdFi.Ods.Common.Models.Domain; using NUnit.Framework; @@ -27,8 +28,9 @@ public ProfileTestDataHelper(string fileName) _domainModel = new DomainModelProvider( container.Resolve() - .DomainModelDefinitionProviders() - .ToList()).GetDomainModel(); + .DomainModelDefinitionProviders(), + new IDomainModelDefinitionsTransformer[0]) + .GetDomainModel(); Validator = GetValidator(fileName); } diff --git a/Utilities/CodeGeneration/EdFi.Ods.CodeGen.Tests/UnitTests/Processing/TemplateContextProviderTests.cs b/Utilities/CodeGeneration/EdFi.Ods.CodeGen.Tests/UnitTests/Processing/TemplateContextProviderTests.cs index 106992ea8b..95464a9384 100644 --- a/Utilities/CodeGeneration/EdFi.Ods.CodeGen.Tests/UnitTests/Processing/TemplateContextProviderTests.cs +++ b/Utilities/CodeGeneration/EdFi.Ods.CodeGen.Tests/UnitTests/Processing/TemplateContextProviderTests.cs @@ -58,7 +58,7 @@ protected override void Arrange() A.CallTo(() => _domainModelDefinitionsProviderProvider.DomainModelDefinitionProviders()) .Returns(_domainModelDefinitionsProviders); - _templateContextProvider = new TemplateContextProvider(_domainModelDefinitionsProviderProvider); + _templateContextProvider = new TemplateContextProvider(_domainModelDefinitionsProviderProvider, new IDomainModelDefinitionsTransformer[0]); } protected override void Act() @@ -109,7 +109,7 @@ protected override void Arrange() A.CallTo(() => _domainModelDefinitionsProviderProvider.DomainModelDefinitionProviders()) .Returns(_domainModelDefinitionsProviders); - _templateContextProvider = new TemplateContextProvider(_domainModelDefinitionsProviderProvider); + _templateContextProvider = new TemplateContextProvider(_domainModelDefinitionsProviderProvider, new IDomainModelDefinitionsTransformer[0]); } protected override void Act() diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/ChangeQueriesDatabaseConstants.cs b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/ChangeQueriesDatabaseConstants.cs new file mode 100644 index 0000000000..8d336dc741 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/ChangeQueriesDatabaseConstants.cs @@ -0,0 +1,31 @@ +namespace EdFi.Ods.ChangeQueries.SqlGeneration +{ + // TODO: This should reuse the class declared in the EdFi.Ods.Features + public class ChangeQueriesDatabaseConstants + { + /// + /// Gets the database schema name for the Change Events table. + /// + public const string SchemaName = "changes"; + + /// + /// Gets the column name used for tracking changed records + /// + public const string ChangeVersionColumnName = "ChangeVersion"; + + /// + /// Prefix applied to the schema name holding the tracked change tables for a data standard schema. + /// + public const string TrackedChangesSchemaPrefix = "tracked_changes_"; + + /// + /// Prefix applied to the identifier column name containing the previous value. + /// + public const string OldKeyValueColumnPrefix = "Old"; + + /// + /// Prefix applied to the identifier column name containing the new value. + /// + public const string NewKeyValueColumnPrefix = "New"; + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/ChangeQueriesPlugin.cs b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/ChangeQueriesPlugin.cs new file mode 100644 index 0000000000..76c4654ec2 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/ChangeQueriesPlugin.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using Autofac; +using EdFi.Ods.Common.Models; +using EdFi.Ods.Generator.Database.TemplateModelProviders; +using EdFi.Ods.Generator.Database.Transformers; +using EdFi.Ods.Generator.Rendering; +using EdFi.Ods.Generator.Templating; + +namespace EdFi.Ods.ChangeQueries.SqlGeneration +{ + public class ChangeQueriesPlugin : IRenderingPlugin + { + public void Initialize(ContainerBuilder containerBuilder) + { + // Register domain model transformers + containerBuilder + .RegisterType() + .As(); + + // Register template model providers + containerBuilder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()) + .AssignableTo() + .AsImplementedInterfaces(); + + // Register enhancers for Database artifacts generation + containerBuilder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()) + .AssignableTo() + .AsImplementedInterfaces(); + + containerBuilder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()) + .AssignableTo() + .AsImplementedInterfaces(); + } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/EdFi.Ods.ChangeQueries.SqlGeneration.csproj b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/EdFi.Ods.ChangeQueries.SqlGeneration.csproj new file mode 100644 index 0000000000..14f134b826 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/EdFi.Ods.ChangeQueries.SqlGeneration.csproj @@ -0,0 +1,16 @@ + + + + netcoreapp3.1 + + + + + + + + + + + + diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/ChangeDataColumnsTableEnhancer.cs b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/ChangeDataColumnsTableEnhancer.cs new file mode 100644 index 0000000000..abeca650b0 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/ChangeDataColumnsTableEnhancer.cs @@ -0,0 +1,63 @@ +using System.Linq; +using EdFi.Ods.Common.Models.Domain; +using EdFi.Ods.Generator; +using EdFi.Ods.Generator.Database.DataTypes; +using EdFi.Ods.Generator.Database.NamingConventions; +using EdFi.Ods.Generator.Database.TemplateModelProviders; + +namespace EdFi.Ods.ChangeQueries.SqlGeneration.Enhancers +{ + public class ChangeDataColumnsTableEnhancer : ITableEnhancer + { + private readonly IDatabaseNamingConvention _databaseNamingConvention; + private readonly IDatabaseTypeTranslator _databaseTypeTranslator; + + public ChangeDataColumnsTableEnhancer( + IDatabaseNamingConventionFactory databaseNamingConventionFactory, + IDatabaseTypeTranslatorFactory databaseTypeTranslatorFactory, + IDatabaseOptions options) + { + string databaseEngine = options.DatabaseEngine; + + _databaseNamingConvention = databaseNamingConventionFactory.CreateNamingConvention(databaseEngine); + _databaseTypeTranslator = databaseTypeTranslatorFactory.CreateTranslator(databaseEngine); + } + + public Table EnhanceTable(Entity entity, Table table, dynamic tableProps) + { + if (entity.IsDerived) + { + tableProps.ChangeDataColumns = ChangeQueriesHelpers.GetChangeQueriesPropertiesForColumns(entity) + .SelectMany((p, i) => p.ExpandForApiResourceData(i, _databaseNamingConvention, _databaseTypeTranslator)) + // .Select((c, i) => new SimpleColumn(c.ColumnName, c.DataType, c.SelectExpression)) + .ToArray(); + // .Select( + // c => new Dictionary() + // { + // { "ColumnName", c.ColumnName }, + // { "ColumnDataType", c.ColumnDataType }, + // }); + } + else + { + tableProps.ChangeDataColumns = ChangeQueriesHelpers.GetChangeQueriesPropertiesForColumns(entity) + .SelectMany((p, i) => p.ExpandForApiResourceData(i, _databaseNamingConvention, _databaseTypeTranslator)) + .Select( + (c, i) => new SimpleColumn + { + IsFirst = i == 0, + ColumnName = c.ColumnName, + DataType = c.DataType, + SelectExpression = c.SelectExpression, + }) + .ToArray(); + + tableProps.Joins = ChangeQueriesHelpers.GetChangeQueriesPropertiesForColumns(entity) + .SelectMany((p, i) => p.JoinForApiResourceData(i, _databaseNamingConvention)) + .ToArray(); + } + + return table; + } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/ChangeQueriesHelpers.cs b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/ChangeQueriesHelpers.cs new file mode 100644 index 0000000000..bc2648808d --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/ChangeQueriesHelpers.cs @@ -0,0 +1,19 @@ +using System.Collections.Generic; +using System.Linq; +using EdFi.Ods.Common.Models.Domain; + +namespace EdFi.Ods.ChangeQueries.SqlGeneration.Enhancers +{ + public static class ChangeQueriesHelpers + { + public static IEnumerable GetChangeQueriesPropertiesForColumns(Entity e) + { + return e.Identifier.Properties + .Union(e.AlternateIdentifiers.SelectMany(i => i.Properties.Where(p => !IsResourceIdentifier(p)))) + .Union(e.BaseEntity?.AlternateIdentifiers.SelectMany(i => i.Properties.Where(p => !IsResourceIdentifier(p))) + ?? Enumerable.Empty()); + + bool IsResourceIdentifier(EntityProperty property) => property.PropertyName == "Id"; + } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/DescriptorDiscriminatorTableEnhancer.cs b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/DescriptorDiscriminatorTableEnhancer.cs new file mode 100644 index 0000000000..d605ba722b --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/DescriptorDiscriminatorTableEnhancer.cs @@ -0,0 +1,42 @@ +using EdFi.Ods.Common.Models.Domain; +using EdFi.Ods.Generator; +using EdFi.Ods.Generator.Database; +using EdFi.Ods.Generator.Database.DataTypes; +using EdFi.Ods.Generator.Database.NamingConventions; +using EdFi.Ods.Generator.Database.TemplateModelProviders; + +namespace EdFi.Ods.ChangeQueries.SqlGeneration.Enhancers +{ + /// + /// Implements a table enhancer that adds a Discriminator column to the Descriptor base table (which is currently explicitly + /// excluded from the MetaEd model for edfi.Descriptor). + /// + public class DescriptorDiscriminatorTableEnhancer : ITableEnhancer + { + private readonly IDatabaseNamingConvention _databaseNamingConvention; + private readonly IDatabaseTypeTranslator _databaseTypeConvention; + + public DescriptorDiscriminatorTableEnhancer( + IDatabaseTypeTranslatorFactory databaseTypeTranslatorFactory, + IDatabaseNamingConventionFactory databaseNamingConventionFactory, + IDatabaseOptions databaseOptions) + { + _databaseNamingConvention = databaseNamingConventionFactory.CreateNamingConvention(databaseOptions.DatabaseEngine); + _databaseTypeConvention = databaseTypeTranslatorFactory.CreateTranslator(databaseOptions.DatabaseEngine); + } + + public Table EnhanceTable(Entity entity, Table table, dynamic tableProps) + { + if (entity.IsDescriptorBaseEntity()) + { + // Add the Discriminator column, if it's not already there + if (table.DiscriminatorColumn == null) + { + table.DiscriminatorColumn = ColumnHelper.CreateDiscriminatorColumn(_databaseNamingConvention, _databaseTypeConvention); + } + } + + return table; + } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/EntityPropertyExtensions.cs b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/EntityPropertyExtensions.cs new file mode 100644 index 0000000000..e3f01eeefb --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/EntityPropertyExtensions.cs @@ -0,0 +1,36 @@ +using System.Linq; +using EdFi.Ods.Common.Models.Domain; +using EdFi.Ods.Generator.Extensions; + +namespace EdFi.Ods.ChangeQueries.SqlGeneration.Enhancers +{ + public static class EntityPropertyExtensions + { + /// + /// Indicates whether the entity property represent a usage of an USI (internal surrogate id for a person) + /// rather than the definition of it (on a the associated Person entity). + /// + /// The entity property to be evaluated. + /// true is the property is a usage (downstream foreign key of the USI definition); otherwise false. + public static bool IsUSIUsage(this EntityProperty entityProperty) + { + return + entityProperty.PropertyName.EndsWith("USI") + && entityProperty.IncomingAssociations.Any() + && entityProperty.Entity.Name != entityProperty.PropertyName.TrimSuffix("USI"); + } + public static Entity PersonEntity(this EntityProperty entityProperty) + { + if (!IsUSIUsage(entityProperty)) + return null; + var currentProperty = entityProperty; + while (currentProperty.IncomingAssociations.Any()) + { + currentProperty = currentProperty.IncomingAssociations.First() + .PropertyMappingByThisName[currentProperty.PropertyName] + .OtherProperty; + } + return currentProperty.Entity; + } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/PostgreSql/DeleteTriggerTableEnhancer.cs b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/PostgreSql/DeleteTriggerTableEnhancer.cs new file mode 100644 index 0000000000..86a46c6d87 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/PostgreSql/DeleteTriggerTableEnhancer.cs @@ -0,0 +1,35 @@ +using EdFi.Ods.Common.Models.Domain; +using EdFi.Ods.Generator; +using EdFi.Ods.Generator.Database.NamingConventions; +using EdFi.Ods.Generator.Database.TemplateModelProviders; +using EdFi.Ods.Generator.Models; +using EdFi.Ods.Generator.Rendering; + +namespace EdFi.Ods.ChangeQueries.SqlGeneration.Enhancers.PostgreSql +{ + [RenderCondition("DatabaseEngine", "PostgreSql")] + public class DeleteTriggerTableEnhancer : ITableEnhancer + { + private readonly IDatabaseNamingConvention _namingConvention; + + public DeleteTriggerTableEnhancer( + IDatabaseNamingConventionFactory databaseNamingConventionFactory, + IDatabaseOptions databaseOptions) + { + _namingConvention = databaseNamingConventionFactory.CreateNamingConvention(databaseOptions.DatabaseEngine); + } + + public Table EnhanceTable(Entity entity, Table table, dynamic tableProps) + { + if (entity.IsAggregateRoot) + { + tableProps.ChangeQueries ??= new DynamicModel(); + + tableProps.ChangeQueries.TrackedDeleteTriggerName = + _namingConvention.IdentifierName(entity.Name, suffix: "_tr_deltrkg"); + } + + return table; + } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/PostgreSql/ShortHashTableEnhancer.cs b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/PostgreSql/ShortHashTableEnhancer.cs new file mode 100644 index 0000000000..cbf79627e9 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/PostgreSql/ShortHashTableEnhancer.cs @@ -0,0 +1,29 @@ +using EdFi.Ods.Common.Models.Domain; +using EdFi.Ods.Generator; +using EdFi.Ods.Generator.Database.NamingConventions; +using EdFi.Ods.Generator.Database.TemplateModelProviders; +using EdFi.Ods.Generator.Extensions; +using EdFi.Ods.Generator.Rendering; + +namespace EdFi.Ods.ChangeQueries.SqlGeneration.Enhancers.PostgreSql +{ + [RenderCondition("DatabaseEngine", "PostgreSql")] + public class ShortHashTableEnhancer : ITableEnhancer + { + private readonly IDatabaseNamingConvention _namingConvention; + + public ShortHashTableEnhancer( + IDatabaseNamingConventionFactory databaseNamingConventionFactory, + IDatabaseOptions databaseOptions) + { + _namingConvention = databaseNamingConventionFactory.CreateNamingConvention(databaseOptions.DatabaseEngine); + } + + public Table EnhanceTable(Entity entity, Table table, dynamic tableProps) + { + tableProps.TableNameShortHash = entity.Name.GetTruncatedHash(); + + return table; + } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/PostgreSql/TriggerFunctionNamesTableEnhancer.cs b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/PostgreSql/TriggerFunctionNamesTableEnhancer.cs new file mode 100644 index 0000000000..f344cec4e9 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/PostgreSql/TriggerFunctionNamesTableEnhancer.cs @@ -0,0 +1,44 @@ +using EdFi.Ods.Common.Models.Domain; +using EdFi.Ods.Generator; +using EdFi.Ods.Generator.Database.NamingConventions; +using EdFi.Ods.Generator.Database.TemplateModelProviders; +using EdFi.Ods.Generator.Models; +using EdFi.Ods.Generator.Rendering; + +namespace EdFi.Ods.ChangeQueries.SqlGeneration.Enhancers.PostgreSql +{ + [RenderCondition("DatabaseEngine", "PostgreSql")] + public class TriggerFunctionNamesTableEnhancer : ITableEnhancer + { + private readonly IDatabaseNamingConvention _namingConvention; + + public TriggerFunctionNamesTableEnhancer( + IDatabaseNamingConventionFactory databaseNamingConventionFactory, + IDatabaseOptions databaseOptions) + { + _namingConvention = databaseNamingConventionFactory.CreateNamingConvention(databaseOptions.DatabaseEngine); + } + + public Table EnhanceTable(Entity entity, Table table, dynamic tableProps) + { + if (entity.IsAggregateRoot) + { + tableProps.ChangeQueries ??= new DynamicModel(); + + if (!entity.IsDerived) + { + tableProps.ChangeQueries.KeyChangeFunctionName = + _namingConvention.IdentifierName(entity.Name, suffix: "_keychg"); + } + + if (!entity.IsDescriptorBaseEntity()) + { + tableProps.ChangeQueries.DeletedFunctionName = + _namingConvention.IdentifierName(entity.Name, suffix: "_deleted"); + } + } + + return table; + } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/PropertyExtensions.cs b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/PropertyExtensions.cs new file mode 100644 index 0000000000..e6937f73fe --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/PropertyExtensions.cs @@ -0,0 +1,72 @@ +using System.Collections.Generic; +using System.Linq; +using EdFi.Common.Extensions; +using EdFi.Ods.Common.Models.Domain; +using EdFi.Ods.Generator.Database.DataTypes; +using EdFi.Ods.Generator.Database.NamingConventions; + +namespace EdFi.Ods.ChangeQueries.SqlGeneration.Enhancers +{ + public static class PropertyExtensions + { + public static IEnumerable ExpandForApiResourceData(this EntityProperty property, int joinAliasIndex, + IDatabaseNamingConvention databaseNamingConvention, + IDatabaseTypeTranslator databaseTypeTranslator) + { + yield return new SimpleColumn( + databaseNamingConvention.ColumnName(property.PropertyName), + databaseTypeTranslator.GetSqlType(property.PropertyType)); + + if (property.IsLookup) + { + yield return new SimpleColumn( + databaseNamingConvention.ColumnName(property.PropertyName.ReplaceSuffix("Id", "Namespace")), + databaseTypeTranslator.GetSqlType(property.LookupEntity.BaseEntity.PropertyByName["Namespace"].PropertyType), + $"j{joinAliasIndex}.{databaseNamingConvention.ColumnName(property.LookupEntity.BaseEntity.PropertyByName["Namespace"].PropertyName)}"); + + yield return new SimpleColumn( + databaseNamingConvention.ColumnName(property.PropertyName.ReplaceSuffix("Id", "CodeValue")), + databaseTypeTranslator.GetSqlType(property.LookupEntity.BaseEntity.PropertyByName["CodeValue"].PropertyType), + $"j{joinAliasIndex}.{databaseNamingConvention.ColumnName(property.LookupEntity.BaseEntity.PropertyByName["CodeValue"].PropertyName)}"); + } + else if (property.IsUSIUsage()) + { + var personEntity = property.PersonEntity(); + + yield return new SimpleColumn( + databaseNamingConvention.ColumnName(property.PropertyName.ReplaceSuffix("USI", "UniqueId")), + databaseTypeTranslator.GetSqlType(personEntity.PropertyByName[personEntity.Name + "UniqueId"].PropertyType), + $"j{joinAliasIndex}.{databaseNamingConvention.ColumnName(personEntity.PropertyByName[personEntity.Name + "UniqueId"].PropertyName)}"); + } + } + + public static IEnumerable JoinForApiResourceData(this EntityProperty property, int joinAliasIndex, + IDatabaseNamingConvention databaseNamingConvention) + { + if (property.IsLookup) + { + yield return new SingleColumnJoin( + property.LookupEntity.BaseEntity.Schema, + databaseNamingConvention.TableName(property.LookupEntity.BaseEntity), + $"j{joinAliasIndex}", + property.PropertyType.IsNullable, + databaseNamingConvention.ColumnName(property), + databaseNamingConvention.ColumnName(property.LookupEntity.BaseAssociation.PropertyMappings.Single().OtherProperty) + ); + } + else if (property.IsUSIUsage()) + { + var personEntity = property.PersonEntity(); + + yield return new SingleColumnJoin( + personEntity.Schema, + databaseNamingConvention.TableName(personEntity), + $"j{joinAliasIndex}", + property.PropertyType.IsNullable, + databaseNamingConvention.ColumnName(property), + databaseNamingConvention.ColumnName(personEntity.Identifier.Properties.Single()) + ); + } + } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/SimpleColumn.cs b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/SimpleColumn.cs new file mode 100644 index 0000000000..5c0c8b2e7e --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/SimpleColumn.cs @@ -0,0 +1,43 @@ +using EdFi.Ods.Common.Models.Domain; + +namespace EdFi.Ods.ChangeQueries.SqlGeneration.Enhancers +{ + /// + /// Represents a column with just a name. + /// + public class SimpleColumn + { + public SimpleColumn() { } + + public SimpleColumn(string columnName, string dataType, string selectExpression = null, bool? isFirst = null) + { + ColumnName = columnName; + DataType = dataType; + SelectExpression = selectExpression; + IsFirst = isFirst; + } + + // public SimpleColumn(EntityProperty property) + // { + // ColumnName = property.PropertyName; + // ColumnDataType = ColumnDataType; + // } + + public string ColumnName { get; set; } + + /// + /// Contains the fully defined SQL data type definition for the target database (when used in SQL DDL generation). + /// + public string DataType { get; set; } + + /// + /// Contains the SELECT expression for the column (when used in SQL DML generation). + /// + public string SelectExpression { get; set; } + + /// + /// Indicates whether the column is the first columns in a set, or null if this is not known or relevant. + /// + public bool? IsFirst { get; set; } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/SingleColumnJoin.cs b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/SingleColumnJoin.cs new file mode 100644 index 0000000000..80f493b795 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Enhancers/SingleColumnJoin.cs @@ -0,0 +1,28 @@ +namespace EdFi.Ods.ChangeQueries.SqlGeneration.Enhancers +{ + public class SingleColumnJoin + { + public SingleColumnJoin( + string schema, + string tableName, + string joinAlias, + bool isLeftJoin, + string thisJoinColumnName, + string otherJoinColumnName) + { + Schema = schema; + TableName = tableName; + JoinAlias = joinAlias; + IsLeftJoin = isLeftJoin; + ThisJoinColumnName = thisJoinColumnName; + OtherJoinColumnName = otherJoinColumnName; + } + + public string Schema { get; } + public string TableName { get; } + public string JoinAlias { get; } + public bool IsLeftJoin { get; } + public string ThisJoinColumnName { get; set; } + public string OtherJoinColumnName { get; set; } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/TemplateModelProviders/CreateChangesSchema.cs b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/TemplateModelProviders/CreateChangesSchema.cs new file mode 100644 index 0000000000..7246091cc6 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/TemplateModelProviders/CreateChangesSchema.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; +using EdFi.Ods.Generator.Templating; + +namespace EdFi.Ods.ChangeQueries.SqlGeneration.TemplateModelProviders +{ + public class CreateChangesSchema : ITemplateModelProvider + { + public object GetTemplateModel(IDictionary properties) + { + return new Model {ChangesSchema = ChangeQueriesDatabaseConstants.SchemaName}; + } + + private class Model + { + public string ChangesSchema { get; set; } + } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/AddColumnChangeVersionForTables.mustache b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/AddColumnChangeVersionForTables.mustache new file mode 100644 index 0000000000..27fa21365e --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/AddColumnChangeVersionForTables.mustache @@ -0,0 +1,14 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +{{#Tables}} + {{#IsAggregateRoot}} + {{^IsDerived}} +IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[{{Schema}}].[{{TableName}}]') AND name = 'ChangeVersion') +ALTER TABLE [{{Schema}}].[{{TableName}}] ADD [ChangeVersion] [BIGINT] DEFAULT (NEXT VALUE FOR [changes].[ChangeVersionSequence]) NOT NULL; + + {{/IsDerived}} + {{/IsAggregateRoot}} +{{/Tables}} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/AddIndexChangeVersionForTables.mustache b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/AddIndexChangeVersionForTables.mustache new file mode 100644 index 0000000000..e778ba29ae --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/AddIndexChangeVersionForTables.mustache @@ -0,0 +1,17 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +{{#Tables}} + {{#IsAggregateRoot}} + {{^IsDerived}} +BEGIN TRANSACTION + IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'{{Schema}}.{{TableName}}') AND name = N'UX_{{TableName}}_ChangeVersion') + CREATE INDEX [UX_{{TableName}}_ChangeVersion] ON [{{Schema}}].[{{TableName}}] ([ChangeVersion] ASC) + GO +COMMIT + + {{/IsDerived}} + {{/IsAggregateRoot}} +{{/Tables}} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/CreateChangeVersionSequence.mustache b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/CreateChangeVersionSequence.mustache new file mode 100644 index 0000000000..797fec01ef --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/CreateChangeVersionSequence.mustache @@ -0,0 +1,10 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +IF NOT EXISTS (SELECT * FROM sys.sequences WHERE object_id = OBJECT_ID(N'[{{ChangesSchema}}].[ChangeVersionSequence]')) +BEGIN +CREATE SEQUENCE [{{ChangesSchema}}].[ChangeVersionSequence] START WITH 0 +END +GO diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/CreateChangesSchema.mustache b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/CreateChangesSchema.mustache new file mode 100644 index 0000000000..0f3cfad3df --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/CreateChangesSchema.mustache @@ -0,0 +1,8 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = N'{{ChangesSchema}}') +EXEC sys.sp_executesql N'CREATE SCHEMA [{{ChangesSchema}}]' +GO diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/CreateDeletedForTrackingTriggers.mustache b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/CreateDeletedForTrackingTriggers.mustache new file mode 100644 index 0000000000..b3b3d0fe11 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/CreateDeletedForTrackingTriggers.mustache @@ -0,0 +1,57 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +{{#Tables}} + {{#IsAggregateRoot}} + {{#IsDescriptorTable}} +DROP TRIGGER IF EXISTS [{{Schema}}].[{{Schema}}_{{TableName}}_TR_DeleteTracking] +GO + +CREATE TRIGGER [{{Schema}}].[{{Schema}}_{{TableName}}_TR_DeleteTracking] ON [{{Schema}}].[{{TableName}}] AFTER DELETE AS +BEGIN + IF @@rowcount = 0 + RETURN + + SET NOCOUNT ON + + INSERT INTO [tracked_changes_{{BaseTableSchema}}].[{{BaseTableName}}]({{#PrimaryKeyColumns}}Old{{BaseColumnName}}, {{/PrimaryKeyColumns}}{{#BaseAlternateKeyColumns}}Old{{ColumnName}}, {{/BaseAlternateKeyColumns}}Id, Discriminator, ChangeVersion) + SELECT {{#PrimaryKeyColumns}}d.{{ColumnName}}, {{/PrimaryKeyColumns}}{{#BaseAlternateKeyColumns}}b.{{ColumnName}}, {{/BaseAlternateKeyColumns}}b.Id, {{#IsDescriptorTable}}{{#FullName}}'{{Schema}}.{{Name}}', {{/FullName}}{{/IsDescriptorTable}}{{^IsDescriptorTable}}b.Discriminator, {{/IsDescriptorTable}}(NEXT VALUE FOR [changes].[ChangeVersionSequence]) + FROM deleted d + INNER JOIN {{BaseTableSchema}}.{{BaseTableName}} b ON {{#PrimaryKeyColumns}}{{^IsFirst}} AND {{/IsFirst}}d.{{ColumnName}} = b.{{BaseColumnName}}{{/PrimaryKeyColumns}} +END +GO + +ALTER TABLE [{{Schema}}].[{{TableName}}] ENABLE TRIGGER [{{Schema}}_{{TableName}}_TR_DeleteTracking] +GO + {{/IsDescriptorTable}} + {{^IsDerived}} + {{^IsDescriptorBaseTable}}{{! We can't use the delete trigger on the Descriptor base table because it doesn't have a populated Discriminator column in the ODS as of at least v5.2 }} +DROP TRIGGER IF EXISTS [{{Schema}}].[{{Schema}}_{{TableName}}_TR_DeleteTracking] +GO + +CREATE TRIGGER [{{Schema}}].[{{Schema}}_{{TableName}}_TR_DeleteTracking] ON [{{Schema}}].[{{TableName}}] AFTER DELETE AS +BEGIN + IF @@rowcount = 0 + RETURN + + SET NOCOUNT ON + + INSERT INTO [tracked_changes_{{Schema}}].[{{TableName}}]({{#ChangeDataColumns}}Old{{ColumnName}}, {{/ChangeDataColumns}}Id, {{#HasDiscriminatorColumn}}Discriminator, {{/HasDiscriminatorColumn}}ChangeVersion) + SELECT {{#ChangeDataColumns}}{{#SelectExpression}}{{SelectExpression}}{{/SelectExpression}}{{^SelectExpression}}d.{{ColumnName}}{{/SelectExpression}}, {{/ChangeDataColumns}}d.Id, {{#HasDiscriminatorColumn}}d.Discriminator, {{/HasDiscriminatorColumn}}(NEXT VALUE FOR [changes].[ChangeVersionSequence]) + FROM deleted d + {{#Joins}} + {{#IsLeftJoin}}LEFT {{/IsLeftJoin}}{{^IsLeftJoin}}INNER {{/IsLeftJoin}}JOIN {{Schema}}.{{TableName}} {{JoinAlias}} + ON d.{{ThisJoinColumnName}} = {{JoinAlias}}.{{OtherJoinColumnName}} + {{/Joins}} +END +GO + +ALTER TABLE [{{Schema}}].[{{TableName}}] ENABLE TRIGGER [{{Schema}}_{{TableName}}_TR_DeleteTracking] +GO + + {{/IsDescriptorBaseTable}} + {{/IsDerived}} + {{/IsAggregateRoot}} +{{/Tables}} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/CreateTrackedChangeTables.mustache b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/CreateTrackedChangeTables.mustache new file mode 100644 index 0000000000..67248ebf00 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/CreateTrackedChangeTables.mustache @@ -0,0 +1,35 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +{{#Schemas}} +IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = N'tracked_changes_{{Schema}}') +EXEC sys.sp_executesql N'CREATE SCHEMA [tracked_changes_{{Schema}}]' +GO + +{{/Schemas}} +{{#Tables}} + {{#IsAggregateRoot}} + {{^IsDerived}} +IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[tracked_changes_{{Schema}}].[{{TableName}}]')) +CREATE TABLE [tracked_changes_{{Schema}}].[{{TableName}}] +( + {{#ChangeDataColumns}} + Old{{ColumnName}} {{DataType}} NOT NULL, + {{/ChangeDataColumns}} + {{#ChangeDataColumns}} + New{{ColumnName}} {{DataType}} NULL, + {{/ChangeDataColumns}} + Id uniqueidentifier NOT NULL, + ChangeVersion bigint NOT NULL, + {{#DiscriminatorColumn}} + {{ColumnName}} {{DataType}} {{#IsNullable}}NULL{{/IsNullable}}{{^IsNullable}} NOT NULL{{/IsNullable}}, + {{/DiscriminatorColumn}} + CreateDate DateTime2 NOT NULL DEFAULT (getutcdate()), + CONSTRAINT {{PrimaryKeyConstraintName}} PRIMARY KEY CLUSTERED (ChangeVersion) +) + + {{/IsDerived}} + {{/IsAggregateRoot}} +{{/Tables}} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/CreateTriggerUpdateChangeVersionGenerator.mustache b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/CreateTriggerUpdateChangeVersionGenerator.mustache new file mode 100644 index 0000000000..39d84ae0fb --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/CreateTriggerUpdateChangeVersionGenerator.mustache @@ -0,0 +1,47 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +{{#Tables}} + {{#IsAggregateRoot}} + {{^IsDerived}} +DROP TRIGGER IF EXISTS [{{Schema}}].[{{Schema}}_{{TableName}}_TR_UpdateChangeVersion] +GO + +CREATE TRIGGER [{{Schema}}].[{{Schema}}_{{TableName}}_TR_UpdateChangeVersion] ON [{{Schema}}].[{{TableName}}] AFTER UPDATE AS +BEGIN + SET NOCOUNT ON; + UPDATE [{{Schema}}].[{{TableName}}] + SET ChangeVersion = (NEXT VALUE FOR [changes].[ChangeVersionSequence]) + FROM [{{Schema}}].[{{TableName}}] u + WHERE EXISTS (SELECT 1 FROM inserted i WHERE i.id = u.id); +{{#KeyValuesCanChange}} + + -- Handle key changes + INSERT INTO tracked_changes_{{Schema}}.{{TableName}}( + {{#ChangeDataColumns}}Old{{ColumnName}}, {{/ChangeDataColumns}} + {{#ChangeDataColumns}}New{{ColumnName}}, {{/ChangeDataColumns}} + Id, {{#HasDiscriminator}}Discriminator, {{/HasDiscriminator}}ChangeVersion) + SELECT + {{#ChangeDataColumns}}{{#SelectExpression}}d{{SelectExpression}}{{/SelectExpression}}{{^SelectExpression}}d.{{ColumnName}}{{/SelectExpression}}, {{/ChangeDataColumns}} + {{#ChangeDataColumns}}{{#SelectExpression}}i{{SelectExpression}}{{/SelectExpression}}{{^SelectExpression}}i.{{ColumnName}}{{/SelectExpression}}, {{/ChangeDataColumns}} + d.Id, {{#HasDiscriminator}}d.Discriminator, {{/HasDiscriminator}}(NEXT VALUE FOR [changes].[ChangeVersionSequence]) + FROM deleted d INNER JOIN inserted i ON d.Id = i.Id + {{#Joins}} + {{#IsLeftJoin}}LEFT {{/IsLeftJoin}}{{^IsLeftJoin}}INNER {{/IsLeftJoin}}JOIN {{Schema}}.{{TableName}} d{{JoinAlias}} + ON d.{{ThisJoinColumnName}} = d{{JoinAlias}}.{{OtherJoinColumnName}} + {{/Joins}} + {{#Joins}} + {{#IsLeftJoin}}LEFT {{/IsLeftJoin}}{{^IsLeftJoin}}INNER {{/IsLeftJoin}}JOIN {{Schema}}.{{TableName}} i{{JoinAlias}} + ON i.{{ThisJoinColumnName}} = i{{JoinAlias}}.{{OtherJoinColumnName}} + {{/Joins}} + WHERE + {{#PrimaryKeyColumns}}{{^IsFirst}} OR {{/IsFirst}}d.{{ColumnName}} <> i.{{ColumnName}}{{/PrimaryKeyColumns}}; +{{/KeyValuesCanChange}} +END +GO + + {{/IsDerived}} + {{/IsAggregateRoot}} +{{/Tables}} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/DropTrackedDeleteSchema.mustache b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/DropTrackedDeleteSchema.mustache new file mode 100644 index 0000000000..f65c7eaa2f --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/DropTrackedDeleteSchema.mustache @@ -0,0 +1,8 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +{{#Schemas}} +DROP SCHEMA IF EXISTS [tracked_deletes_{{Schema}}]; +{{/Schemas}} diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/DropTrackedDeleteTables.mustache b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/DropTrackedDeleteTables.mustache new file mode 100644 index 0000000000..751d570ee6 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/MsSql/Structure/Ods/Changes/DropTrackedDeleteTables.mustache @@ -0,0 +1,10 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +{{#Tables}} + {{#IsAggregateRoot}} +DROP TABLE IF EXISTS [tracked_deletes_{{Schema}}].[{{TableName}}] + {{/IsAggregateRoot}} +{{/Tables}} diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/AddColumnChangeVersionForTables.mustache b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/AddColumnChangeVersionForTables.mustache new file mode 100644 index 0000000000..f2e14975fa --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/AddColumnChangeVersionForTables.mustache @@ -0,0 +1,20 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +DO $$ +BEGIN +{{#Tables}} + {{#IsAggregateRoot}} + {{^IsDerived}} +IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='{{Schema}}' AND table_name='{{TableName}}' AND column_name='changeversion') THEN + ALTER TABLE {{Schema}}.{{TableName}} + ADD ChangeVersion BIGINT DEFAULT nextval('changes.ChangeVersionSequence') NOT NULL; +END IF; + + {{/IsDerived}} + {{/IsAggregateRoot}} +{{/Tables}} +END +$$; \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/AddIndexChangeVersionForTables.mustache b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/AddIndexChangeVersionForTables.mustache new file mode 100644 index 0000000000..10fca3bc92 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/AddIndexChangeVersionForTables.mustache @@ -0,0 +1,13 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +{{#Tables}} + {{#IsAggregateRoot}} + {{^IsDerived}} +CREATE INDEX IF NOT EXISTS ux_{{TableNameShortHash}}_changeversion ON {{Schema}}.{{TableName}}(changeversion); + + {{/IsDerived}} + {{/IsAggregateRoot}} +{{/Tables}} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/CreateChangeVersionSequence.mustache b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/CreateChangeVersionSequence.mustache new file mode 100644 index 0000000000..ed492b3484 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/CreateChangeVersionSequence.mustache @@ -0,0 +1,15 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +CREATE SEQUENCE IF NOT EXISTS changes.ChangeVersionSequence START WITH 1; + +CREATE OR REPLACE FUNCTION changes.updateChangeVersion() + RETURNS trigger AS +$BODY$ +BEGIN + new.ChangeVersion := nextval('changes.ChangeVersionSequence'); + RETURN new; +END; +$BODY$ LANGUAGE plpgsql; diff --git a/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0045-CreateTrackedDeleteSchema.sql b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/CreateChangesSchema.mustache similarity index 75% rename from Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0045-CreateTrackedDeleteSchema.sql rename to Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/CreateChangesSchema.mustache index f37f10ba9a..9db97ab9ca 100644 --- a/Application/EdFi.Ods.Standard/Artifacts/PgSql/Structure/Ods/Changes/0045-CreateTrackedDeleteSchema.sql +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/CreateChangesSchema.mustache @@ -8,11 +8,11 @@ BEGIN IF NOT EXISTS( SELECT schema_name FROM information_schema.schemata - WHERE schema_name = 'tracked_deletes_edfi' + WHERE schema_name = 'changes' ) THEN - EXECUTE 'CREATE SCHEMA tracked_deletes_edfi AUTHORIZATION postgres'; + EXECUTE 'CREATE SCHEMA changes AUTHORIZATION postgres'; END IF; END -$$; +$$; \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/CreateDeletedForTrackingTriggers.mustache b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/CreateDeletedForTrackingTriggers.mustache new file mode 100644 index 0000000000..bfc4e3c7d1 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/CreateDeletedForTrackingTriggers.mustache @@ -0,0 +1,64 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +DO $$ +BEGIN +{{#Tables}} + {{#IsAggregateRoot}} + {{#IsDescriptorTable}} +CREATE OR REPLACE FUNCTION tracked_changes_{{Schema}}.{{#ChangeQueries}}{{DeletedFunctionName}}{{/ChangeQueries}}() + RETURNS trigger AS +$BODY$ +BEGIN + INSERT INTO tracked_changes_{{BaseTableSchema}}.{{BaseTableName}}({{#PrimaryKeyColumns}}old{{BaseColumnName}}, {{/PrimaryKeyColumns}}{{#BaseAlternateKeyColumns}}old{{ColumnName}}, {{/BaseAlternateKeyColumns}}id, discriminator, changeversion) + SELECT {{#PrimaryKeyColumns}}OLD.{{ColumnName}}, {{/PrimaryKeyColumns}}{{#BaseAlternateKeyColumns}}b.{{ColumnName}}, {{/BaseAlternateKeyColumns}}b.id, {{#IsDescriptorTable}}{{#FullName}}'{{Schema}}.{{Name}}', {{/FullName}}{{/IsDescriptorTable}}{{^IsDescriptorTable}}b.discriminator, {{/IsDescriptorTable}}nextval('changes.ChangeVersionSequence') + FROM {{BaseTableSchema}}.{{BaseTableName}} b WHERE {{#PrimaryKeyColumns}}{{^IsFirst}} AND {{/IsFirst}}old.{{ColumnName}} = b.{{BaseColumnName}}{{/PrimaryKeyColumns}}; + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = '{{Schema}}' AND event_object_table = '{{TableName}}') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON {{Schema}}.{{TableName}} + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_{{Schema}}.{{#ChangeQueries}}{{DeletedFunctionName}}{{/ChangeQueries}}(); +END IF; + + {{/IsDescriptorTable}} + {{^IsDerived}} + {{^IsDescriptorBaseTable}}{{! We can't use the delete trigger on the Descriptor base table because it doesn't have a populated Discriminator column in the ODS as of at least v5.2 }} +CREATE OR REPLACE FUNCTION tracked_changes_{{Schema}}.{{#ChangeQueries}}{{DeletedFunctionName}}{{/ChangeQueries}}() + RETURNS trigger AS +$BODY$ +DECLARE +{{#Joins}} + d{{JoinAlias}} {{Schema}}.{{TableName}}%ROWTYPE; +{{/Joins}} +BEGIN +{{#Joins}} + SELECT INTO d{{JoinAlias}} * FROM {{Schema}}.{{TableName}} {{JoinAlias}} WHERE {{OtherJoinColumnName}} = old.{{ThisJoinColumnName}}; +{{/Joins}} + + INSERT INTO tracked_changes_{{Schema}}.{{TableName}}( + {{#ChangeDataColumns}}old{{ColumnName}}, {{/ChangeDataColumns}} + id, {{#HasDiscriminator}}discriminator, {{/HasDiscriminator}}changeversion) + VALUES( + {{#ChangeDataColumns}}{{#SelectExpression}}d{{SelectExpression}}{{/SelectExpression}}{{^SelectExpression}}old.{{ColumnName}}{{/SelectExpression}}, {{/ChangeDataColumns}} + old.id, {{#HasDiscriminator}}d.discriminator, {{/HasDiscriminator}}(nextval('changes.changeversionsequence'))); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'trackdeletes' AND event_object_schema = '{{Schema}}' AND event_object_table = '{{TableName}}') THEN + CREATE TRIGGER trackdeletes AFTER DELETE ON {{Schema}}.{{TableName}} + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_{{Schema}}.{{#ChangeQueries}}{{DeletedFunctionName}}{{/ChangeQueries}}(); +END IF; + + {{/IsDescriptorBaseTable}} + {{/IsDerived}} + {{/IsAggregateRoot}} +{{/Tables}} +END +$$; \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/CreateTrackedChangeTables.mustache b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/CreateTrackedChangeTables.mustache new file mode 100644 index 0000000000..208308fd41 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/CreateTrackedChangeTables.mustache @@ -0,0 +1,41 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +DO $$ +BEGIN + +{{#Schemas}} +IF NOT EXISTS (SELECT 1 FROM information_schema.schemata WHERE schema_name = 'tracked_changes_{{Schema}}') THEN +CREATE SCHEMA tracked_changes_{{Schema}}; +END IF; + +{{/Schemas}} +{{#Tables}} + {{#IsAggregateRoot}} + {{^IsDerived}} +IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'tracked_changes_{{Schema}}' AND table_name = '{{TableName}}') THEN +CREATE TABLE tracked_changes_{{Schema}}.{{TableName}} +( + {{#ChangeDataColumns}} + old{{ColumnName}} {{DataType}} NOT NULL, + {{/ChangeDataColumns}} + {{#ChangeDataColumns}} + new{{ColumnName}} {{DataType}} NULL, + {{/ChangeDataColumns}} + id uuid NOT NULL, + changeversion bigint NOT NULL, + {{#DiscriminatorColumn}} + {{ColumnName}} {{DataType}} {{#IsNullable}}NULL{{/IsNullable}}{{^IsNullable}} NOT NULL{{/IsNullable}}, + {{/DiscriminatorColumn}} + createdate timestamp NOT NULL DEFAULT (now()), + CONSTRAINT {{PrimaryKeyConstraintName}} PRIMARY KEY (changeversion) +); +END IF; + + {{/IsDerived}} + {{/IsAggregateRoot}} +{{/Tables}} +END +$$; \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/CreateTriggerUpdateChangeVersionGenerator.mustache b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/CreateTriggerUpdateChangeVersionGenerator.mustache new file mode 100644 index 0000000000..a937307b15 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/CreateTriggerUpdateChangeVersionGenerator.mustache @@ -0,0 +1,59 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +DO $$ +BEGIN +{{#Tables}} + {{#IsAggregateRoot}} + {{^IsDerived}} +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'updatechangeversion' AND event_object_schema = '{{Schema}}' AND event_object_table = '{{TableName}}') THEN + CREATE TRIGGER UpdateChangeVersion BEFORE UPDATE ON {{Schema}}.{{TableName}} + FOR EACH ROW EXECUTE PROCEDURE changes.UpdateChangeVersion(); +END IF; + +{{#KeyValuesCanChange}} +CREATE OR REPLACE FUNCTION tracked_changes_{{Schema}}.{{#ChangeQueries}}{{KeyChangeFunctionName}}{{/ChangeQueries}}() + RETURNS trigger AS +$BODY$ +DECLARE +{{#Joins}} + d{{JoinAlias}} {{Schema}}.{{TableName}}%ROWTYPE; +{{/Joins}} +{{#Joins}} + i{{JoinAlias}} {{Schema}}.{{TableName}}%ROWTYPE; +{{/Joins}} +BEGIN +{{#Joins}} + SELECT INTO d{{JoinAlias}} * FROM {{Schema}}.{{TableName}} {{JoinAlias}} WHERE {{OtherJoinColumnName}} = old.{{ThisJoinColumnName}}; +{{/Joins}} +{{#Joins}} + SELECT INTO i{{JoinAlias}} * FROM {{Schema}}.{{TableName}} {{JoinAlias}} WHERE {{OtherJoinColumnName}} = new.{{ThisJoinColumnName}}; +{{/Joins}} + + -- Handle key changes + INSERT INTO tracked_changes_{{Schema}}.{{TableName}}( + {{#ChangeDataColumns}}old{{ColumnName}}, {{/ChangeDataColumns}} + {{#ChangeDataColumns}}new{{ColumnName}}, {{/ChangeDataColumns}} + id, {{#HasDiscriminator}}discriminator, {{/HasDiscriminator}}changeversion) + VALUES( + {{#ChangeDataColumns}}{{#SelectExpression}}d{{SelectExpression}}{{/SelectExpression}}{{^SelectExpression}}old.{{ColumnName}}{{/SelectExpression}}, {{/ChangeDataColumns}} + {{#ChangeDataColumns}}{{#SelectExpression}}i{{SelectExpression}}{{/SelectExpression}}{{^SelectExpression}}new.{{ColumnName}}{{/SelectExpression}}, {{/ChangeDataColumns}} + old.id, {{#HasDiscriminator}}d.discriminator, {{/HasDiscriminator}}(nextval('changes.changeversionsequence'))); + + RETURN null; +END; +$BODY$ LANGUAGE plpgsql; + +IF NOT EXISTS(SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'handlekeychanges' AND event_object_schema = '{{Schema}}' AND event_object_table = '{{TableName}}') THEN + CREATE TRIGGER HandleKeyChanges AFTER UPDATE OF {{#PrimaryKeyColumns}}{{^IsFirst}}, {{/IsFirst}}{{ColumnName}}{{/PrimaryKeyColumns}} ON {{Schema}}.{{TableName}} + FOR EACH ROW EXECUTE PROCEDURE tracked_changes_{{Schema}}.{{#ChangeQueries}}{{KeyChangeFunctionName}}{{/ChangeQueries}}(); +END IF; + +{{/KeyValuesCanChange}} + {{/IsDerived}} + {{/IsAggregateRoot}} +{{/Tables}} +END +$$; \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/DropTrackedDeleteSchema.mustache b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/DropTrackedDeleteSchema.mustache new file mode 100644 index 0000000000..5c49591262 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/DropTrackedDeleteSchema.mustache @@ -0,0 +1,8 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +{{#Schemas}} +DROP SCHEMA IF EXISTS tracked_deletes_{{Schema}}; +{{/Schemas}} diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/DropTrackedDeleteTables.mustache b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/DropTrackedDeleteTables.mustache new file mode 100644 index 0000000000..7f5af17f14 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/Templates/PgSql/Structure/Ods/Changes/DropTrackedDeleteTables.mustache @@ -0,0 +1,11 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- Licensed to the Ed-Fi Alliance under one or more agreements. +-- The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +-- See the LICENSE and NOTICES files in the project root for more information. + +{{#Tables}} + {{#IsAggregateRoot}} +DROP TABLE IF EXISTS tracked_deletes_{{Schema}}.{{TableName}}; +DROP FUNCTION IF EXISTS tracked_deletes_{{Schema}}.{{#ChangeQueries}}{{TrackedDeleteTriggerName}}{{/ChangeQueries}}() CASCADE; + {{/IsAggregateRoot}} +{{/Tables}} diff --git a/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/renderings.json b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/renderings.json new file mode 100644 index 0000000000..0d32f33711 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.ChangeQueries.SqlGeneration/renderings.json @@ -0,0 +1,76 @@ +{ + "Renderings": [ + { + "Template": "{{DatabaseEngineCode}}.Structure.Ods.Changes.DropTrackedDeleteTables", + "ModelProvider": "Database", + "OutputPath": "{{DatabaseEngineCode}}\\Structure\\Ods\\Changes\\0004-DropTrackedDeleteTables-NEW.sql", + "Conditions": { + "DatabaseEngine": "(SqlServer|PostgreSql)" + } + }, + { + "Template": "{{DatabaseEngineCode}}.Structure.Ods.Changes.DropTrackedDeleteSchema", + "ModelProvider": "Database", + "OutputPath": "{{DatabaseEngineCode}}\\Structure\\Ods\\Changes\\0005-DropTrackedDeleteSchema-NEW.sql", + "Conditions": { + "DatabaseEngine": "(SqlServer|PostgreSql)" + } + }, + { + "Template": "{{DatabaseEngineCode}}.Structure.Ods.Changes.CreateChangesSchema", + "ModelProvider": "CreateChangesSchema", + "OutputPath": "{{DatabaseEngineCode}}\\Structure\\Ods\\Changes\\0010-CreateChangesSchema-NEW.sql", + "Conditions": { + "DatabaseEngine": "(SqlServer|PostgreSql)" + } + }, + { + "Template": "{{DatabaseEngineCode}}.Structure.Ods.Changes.CreateChangeVersionSequence", + "ModelProvider": "CreateChangesSchema", + "OutputPath": "{{DatabaseEngineCode}}\\Structure\\Ods\\Changes\\0020-CreateChangeVersionSequence-NEW.sql", + "Conditions": { + "DatabaseEngine": "(SqlServer|PostgreSql)" + } + }, + { + "Template": "{{DatabaseEngineCode}}.Structure.Ods.Changes.AddColumnChangeVersionForTables", + "ModelProvider": "Database", + "OutputPath": "{{DatabaseEngineCode}}\\Structure\\Ods\\Changes\\0030-AddColumnChangeVersionForTables-NEW.sql", + "Conditions": { + "DatabaseEngine": "(SqlServer|PostgreSql)" + } + }, + { + "Template": "{{DatabaseEngineCode}}.Structure.Ods.Changes.CreateTrackedChangeTables", + "ModelProvider": "Database", + "OutputPath": "{{DatabaseEngineCode}}\\Structure\\Ods\\Changes\\0035-CreateTrackedChangeTables-NEW.sql", + "Conditions": { + "DatabaseEngine": "(SqlServer|PostgreSql)" + } + }, + { + "Template": "{{DatabaseEngineCode}}.Structure.Ods.Changes.CreateTriggerUpdateChangeVersionGenerator", + "ModelProvider": "Database", + "OutputPath": "{{DatabaseEngineCode}}\\Structure\\Ods\\Changes\\0040-CreateTriggerUpdateChangeVersionGenerator-NEW.sql", + "Conditions": { + "DatabaseEngine": "(SqlServer|PostgreSql)" + } + }, + { + "Template": "{{DatabaseEngineCode}}.Structure.Ods.Changes.CreateDeletedForTrackingTriggers", + "ModelProvider": "Database", + "OutputPath": "{{DatabaseEngineCode}}\\Structure\\Ods\\Changes\\0060-CreateDeletedForTrackingTriggers-NEW.sql", + "Conditions": { + "DatabaseEngine": "(SqlServer|PostgreSql)" + } + }, + { + "Template": "{{DatabaseEngineCode}}.Structure.Ods.Changes.AddIndexChangeVersionForTables", + "ModelProvider": "Database", + "OutputPath": "{{DatabaseEngineCode}}\\Structure\\Ods\\Changes\\0070-AddIndexChangeVersionForTables-NEW.sql", + "Conditions": { + "DatabaseEngine": "(SqlServer|PostgreSql)" + } + } + ] +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.Generator.sln b/Utilities/Generator/EdFi.Ods.Generator.sln new file mode 100644 index 0000000000..483a2997e1 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator.sln @@ -0,0 +1,62 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30114.105 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EdFi.Ods.Generator", "EdFi.Ods.Generator\EdFi.Ods.Generator.csproj", "{CB8A8F76-A6F2-436F-A7B9-62D8873A2A01}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EdFi.Ods.Common", "..\..\Application\EdFi.Ods.Common\EdFi.Ods.Common.csproj", "{3F50E96B-2F22-4E02-9D3C-CFF4F5727B7F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EdFi.Ods.ChangeQueries.SqlGeneration", "EdFi.Ods.ChangeQueries.SqlGeneration\EdFi.Ods.ChangeQueries.SqlGeneration.csproj", "{116DEF82-D989-4CC4-868E-6D3FF6897F09}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {CB8A8F76-A6F2-436F-A7B9-62D8873A2A01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CB8A8F76-A6F2-436F-A7B9-62D8873A2A01}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CB8A8F76-A6F2-436F-A7B9-62D8873A2A01}.Debug|x64.ActiveCfg = Debug|Any CPU + {CB8A8F76-A6F2-436F-A7B9-62D8873A2A01}.Debug|x64.Build.0 = Debug|Any CPU + {CB8A8F76-A6F2-436F-A7B9-62D8873A2A01}.Debug|x86.ActiveCfg = Debug|Any CPU + {CB8A8F76-A6F2-436F-A7B9-62D8873A2A01}.Debug|x86.Build.0 = Debug|Any CPU + {CB8A8F76-A6F2-436F-A7B9-62D8873A2A01}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CB8A8F76-A6F2-436F-A7B9-62D8873A2A01}.Release|Any CPU.Build.0 = Release|Any CPU + {CB8A8F76-A6F2-436F-A7B9-62D8873A2A01}.Release|x64.ActiveCfg = Release|Any CPU + {CB8A8F76-A6F2-436F-A7B9-62D8873A2A01}.Release|x64.Build.0 = Release|Any CPU + {CB8A8F76-A6F2-436F-A7B9-62D8873A2A01}.Release|x86.ActiveCfg = Release|Any CPU + {CB8A8F76-A6F2-436F-A7B9-62D8873A2A01}.Release|x86.Build.0 = Release|Any CPU + {3F50E96B-2F22-4E02-9D3C-CFF4F5727B7F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3F50E96B-2F22-4E02-9D3C-CFF4F5727B7F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3F50E96B-2F22-4E02-9D3C-CFF4F5727B7F}.Debug|x64.ActiveCfg = Debug|Any CPU + {3F50E96B-2F22-4E02-9D3C-CFF4F5727B7F}.Debug|x64.Build.0 = Debug|Any CPU + {3F50E96B-2F22-4E02-9D3C-CFF4F5727B7F}.Debug|x86.ActiveCfg = Debug|Any CPU + {3F50E96B-2F22-4E02-9D3C-CFF4F5727B7F}.Debug|x86.Build.0 = Debug|Any CPU + {3F50E96B-2F22-4E02-9D3C-CFF4F5727B7F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3F50E96B-2F22-4E02-9D3C-CFF4F5727B7F}.Release|Any CPU.Build.0 = Release|Any CPU + {3F50E96B-2F22-4E02-9D3C-CFF4F5727B7F}.Release|x64.ActiveCfg = Release|Any CPU + {3F50E96B-2F22-4E02-9D3C-CFF4F5727B7F}.Release|x64.Build.0 = Release|Any CPU + {3F50E96B-2F22-4E02-9D3C-CFF4F5727B7F}.Release|x86.ActiveCfg = Release|Any CPU + {3F50E96B-2F22-4E02-9D3C-CFF4F5727B7F}.Release|x86.Build.0 = Release|Any CPU + {116DEF82-D989-4CC4-868E-6D3FF6897F09}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {116DEF82-D989-4CC4-868E-6D3FF6897F09}.Debug|Any CPU.Build.0 = Debug|Any CPU + {116DEF82-D989-4CC4-868E-6D3FF6897F09}.Debug|x64.ActiveCfg = Debug|Any CPU + {116DEF82-D989-4CC4-868E-6D3FF6897F09}.Debug|x64.Build.0 = Debug|Any CPU + {116DEF82-D989-4CC4-868E-6D3FF6897F09}.Debug|x86.ActiveCfg = Debug|Any CPU + {116DEF82-D989-4CC4-868E-6D3FF6897F09}.Debug|x86.Build.0 = Debug|Any CPU + {116DEF82-D989-4CC4-868E-6D3FF6897F09}.Release|Any CPU.ActiveCfg = Release|Any CPU + {116DEF82-D989-4CC4-868E-6D3FF6897F09}.Release|Any CPU.Build.0 = Release|Any CPU + {116DEF82-D989-4CC4-868E-6D3FF6897F09}.Release|x64.ActiveCfg = Release|Any CPU + {116DEF82-D989-4CC4-868E-6D3FF6897F09}.Release|x64.Build.0 = Release|Any CPU + {116DEF82-D989-4CC4-868E-6D3FF6897F09}.Release|x86.ActiveCfg = Release|Any CPU + {116DEF82-D989-4CC4-868E-6D3FF6897F09}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/ColumnHelper.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/ColumnHelper.cs new file mode 100644 index 0000000000..b2e950cdd6 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/ColumnHelper.cs @@ -0,0 +1,18 @@ +using System.Data; +using EdFi.Ods.Common.Models.Domain; +using EdFi.Ods.Generator.Database.DataTypes; +using EdFi.Ods.Generator.Database.NamingConventions; +using EdFi.Ods.Generator.Database.TemplateModelProviders; + +namespace EdFi.Ods.Generator.Database +{ + public static class ColumnHelper + { + public static Column CreateDiscriminatorColumn(IDatabaseNamingConvention databaseNamingConvention, IDatabaseTypeTranslator databaseTypeTranslator) => new Column + { + ColumnName = databaseNamingConvention.ColumnName("Discriminator"), + DataType = databaseTypeTranslator.GetSqlType(new PropertyType(DbType.String, 128)), + IsNullable = true, + }; + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/Conventions/ColumnConventions.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/Conventions/ColumnConventions.cs new file mode 100644 index 0000000000..21849a179f --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/Conventions/ColumnConventions.cs @@ -0,0 +1,25 @@ +using System; +using EdFi.Ods.Common.Models.Domain; + +namespace EdFi.Ods.Generator.Database.Conventions +{ + public static class ColumnConventions + { + public static bool IsBoilerplate(this EntityProperty property) + { + return IsBoilerplate(property.PropertyName); + } + + public static bool IsBoilerplate(this string propertyName) + { + return (Enum.TryParse(typeof(BoilerplateColumn), propertyName, out object value)); + } + + public enum BoilerplateColumn + { + CreateDate, + LastModifiedDate, + Id, + } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/DataTypes/DatabaseTypeTranslatorFactory.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/DataTypes/DatabaseTypeTranslatorFactory.cs new file mode 100644 index 0000000000..5f08981130 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/DataTypes/DatabaseTypeTranslatorFactory.cs @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using Autofac.Features.Indexed; + +namespace EdFi.Ods.Generator.Database.DataTypes +{ + public class DatabaseTypeTranslatorFactory : IDatabaseTypeTranslatorFactory + { + private readonly IIndex _translatorByDatabaseEngine; + + public DatabaseTypeTranslatorFactory(IIndex translatorByDatabaseEngine) + { + _translatorByDatabaseEngine = translatorByDatabaseEngine; + } + + public IDatabaseTypeTranslator CreateTranslator(string databaseEngine) + { + return _translatorByDatabaseEngine[databaseEngine]; + } + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/DataTypes/IDatabaseTypeTranslator.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/DataTypes/IDatabaseTypeTranslator.cs new file mode 100644 index 0000000000..027629bd83 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/DataTypes/IDatabaseTypeTranslator.cs @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System.Data; +using EdFi.Ods.Common.Models.Domain; + +namespace EdFi.Ods.Generator.Database.DataTypes +{ + /// + /// Defines methods for converting from database physical data types to various code generation output formats + /// for artifacts based on database views. + /// + public interface IDatabaseTypeTranslator + { + /// + /// Gets the C# .NET type associated with the supplied database data type. + /// + /// The raw data type used by the reference database. + /// The corresponding C# .NET type. + /// This supports the code generation process for database views read by the DatabaseSchemaReader library which + /// only provides the data type from the data view in the reference database. + /// + string GetSysType(string sqlType); + + /// + /// Gets the NHibernate mapping type associated with the supplied database data type. + /// + /// The raw data type used by the reference database. + /// The corresponding NHibernate mapping type. + /// This supports the code generation process for database views read by the DatabaseSchemaReader library which + /// only provides the data type from the data view in the reference database. + /// + string GetNHType(string sqlType); + + /// + /// Gets the enumeration value associated with the supplied database data type. + /// + /// The raw data type used by the reference database. + /// The corresponding enumeration value. + DbType GetDbType(string sqlType); + + string GetSqlType(PropertyType propertyType); + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/DataTypes/IDatabaseTypeTranslatorFactory.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/DataTypes/IDatabaseTypeTranslatorFactory.cs new file mode 100644 index 0000000000..0c79f92905 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/DataTypes/IDatabaseTypeTranslatorFactory.cs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using EdFi.Common.Configuration; + +namespace EdFi.Ods.Generator.Database.DataTypes +{ + public interface IDatabaseTypeTranslatorFactory + { + IDatabaseTypeTranslator CreateTranslator(string databaseEngine); + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/DatabaseEngine.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/DatabaseEngine.cs new file mode 100644 index 0000000000..5ed94829d5 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/DatabaseEngine.cs @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +namespace EdFi.Ods.Generator.Database +{ + public static class DatabaseEngine + { + public const string PostgreSql = "PostgreSql"; + public const string SqlServer = "SqlServer"; + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/DatabaseRenderingPlugin.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/DatabaseRenderingPlugin.cs new file mode 100644 index 0000000000..926141c833 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/DatabaseRenderingPlugin.cs @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System.Reflection; +using Autofac; +using EdFi.Ods.Generator.Database.DataTypes; +using EdFi.Ods.Generator.Database.Domain; +using EdFi.Ods.Generator.Database.NamingConventions; +using EdFi.Ods.Generator.Database.TemplateModelProviders; +using EdFi.Ods.Generator.Rendering; +using EdFi.Ods.Generator.Templating; + +namespace EdFi.Ods.Generator.Database +{ + public class DatabaseRenderingPlugin : IRenderingPlugin + { + public void Initialize(ContainerBuilder containerBuilder) + { + // Register reusable database template model provider + containerBuilder.RegisterType() + .As(); + + // Register database-aware factories + containerBuilder.RegisterType() + .As(); + + containerBuilder.RegisterType() + .As(); + + // Render Property enhancement + containerBuilder.RegisterType() + .As(); + + // Domain model components + containerBuilder.RegisterType() + .As(); + + // Register enhancers for Database artifacts generation + containerBuilder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()) + .AssignableTo() + .AsImplementedInterfaces(); + + containerBuilder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()) + .AssignableTo() + .AsImplementedInterfaces(); + } + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/DatabaseRenderingPropertiesEnhancer.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/DatabaseRenderingPropertiesEnhancer.cs new file mode 100644 index 0000000000..7a7031b4cb --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/DatabaseRenderingPropertiesEnhancer.cs @@ -0,0 +1,24 @@ +using System.Collections.Generic; +using EdFi.Ods.Generator.Database.NamingConventions; + +namespace EdFi.Ods.Generator.Database +{ + public class DatabaseRenderingPropertiesEnhancer : IRenderingPropertiesEnhancer + { + private readonly IDatabaseOptions _databaseOptions; + private readonly IDatabaseNamingConvention _namingConvention; + + public DatabaseRenderingPropertiesEnhancer(IDatabaseOptions databaseOptions, IDatabaseNamingConventionFactory databaseNamingConventionFactory) + { + _databaseOptions = databaseOptions; + _namingConvention = databaseNamingConventionFactory.CreateNamingConvention(databaseOptions.DatabaseEngine); + } + + public void EnhanceProperties(IDictionary properties) + { + properties["DatabaseEngine"] = _databaseOptions.DatabaseEngine; + properties["SchemaFilter"] = _databaseOptions.SchemaFilter; + properties["DatabaseEngineCode"] = _namingConvention.DatabaseEngineCode; + } + } +} \ No newline at end of file diff --git a/Application/EdFi.Ods.Api/Infrastructure/Pipelines/IGetDeletedResourceIds.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/Domain/IDomainModelDefinitionsProviderSource.cs similarity index 60% rename from Application/EdFi.Ods.Api/Infrastructure/Pipelines/IGetDeletedResourceIds.cs rename to Utilities/Generator/EdFi.Ods.Generator/Database/Domain/IDomainModelDefinitionsProviderSource.cs index 1cff636e90..28f7540971 100644 --- a/Application/EdFi.Ods.Api/Infrastructure/Pipelines/IGetDeletedResourceIds.cs +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/Domain/IDomainModelDefinitionsProviderSource.cs @@ -4,13 +4,12 @@ // See the LICENSE and NOTICES files in the project root for more information. using System.Collections.Generic; -using EdFi.Ods.Common; using EdFi.Ods.Common.Models; -namespace EdFi.Ods.Api.Infrastructure.Pipelines +namespace EdFi.Ods.Generator.Database.Domain { - public interface IGetDeletedResourceIds + public interface IDomainModelDefinitionsProviderSource { - IReadOnlyList Execute(string schema, string resource, IQueryParameters queryParameters); + IEnumerable GetDomainModelDefinitionProviders(); } } diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/Domain/ModelPathsDomainDefinitionsProviderSource.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/Domain/ModelPathsDomainDefinitionsProviderSource.cs new file mode 100644 index 0000000000..5eebef4182 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/Domain/ModelPathsDomainDefinitionsProviderSource.cs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using EdFi.Ods.Common.Models; + +namespace EdFi.Ods.Generator.Database.Domain +{ + public class ModelPathsDomainDefinitionsProviderSource : IDomainModelDefinitionsProviderSource + { + private readonly IEnumerable _modelPaths; + + public ModelPathsDomainDefinitionsProviderSource(IModelOptions options) + { + _modelPaths = options.ModelPaths; + } + + public IEnumerable GetDomainModelDefinitionProviders() + { + var executionPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + + foreach (string modelPath in _modelPaths) + { + string resolveModelPath = Path.IsPathRooted(modelPath) + ? modelPath + : Path.Combine(executionPath, modelPath); + + if (!File.Exists(resolveModelPath)) + { + throw new FileNotFoundException("Model file not found.", resolveModelPath); + } + + yield return new DomainModelDefinitionsJsonFileSystemProvider(modelPath); + } + } + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/Engines/PostgreSql/PostgreSqlDatabaseNamingConvention.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/Engines/PostgreSql/PostgreSqlDatabaseNamingConvention.cs new file mode 100644 index 0000000000..04c645a34a --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/Engines/PostgreSql/PostgreSqlDatabaseNamingConvention.cs @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using EdFi.Ods.Generator.Database.NamingConventions; + +namespace EdFi.Ods.Generator.Database.Engines.PostgreSql +{ + public class PostgreSqlDatabaseNamingConvention : DatabaseNamingConventionBase + { + protected override int MaximumNameLength => 63; + + protected override bool LowerCaseNames => true; + + public override string DefaultDateConstraintValue() => "now()"; + + public override string DefaultGuidConstraintValue() => "uuid_generate_v4()"; + + public override string DatabaseEngineCode => "PgSql"; + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/Engines/PostgreSql/PostgreSqlDatabaseTypeTranslator.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/Engines/PostgreSql/PostgreSqlDatabaseTypeTranslator.cs new file mode 100644 index 0000000000..16d9209b25 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/Engines/PostgreSql/PostgreSqlDatabaseTypeTranslator.cs @@ -0,0 +1,322 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System; +using System.Data; +using EdFi.Ods.Common.Models.Domain; +using EdFi.Ods.Generator.Database.DataTypes; + +namespace EdFi.Ods.Generator.Database.Engines.PostgreSql +{ + public class PostgreSqlDatabaseTypeTranslator : IDatabaseTypeTranslator + { + public string GetSysType(string sqlType) + { + switch (sqlType) + { + case "smallint": + case "int2": + case "smallserial": + case "serial2": + return "short"; + + case "int": + case "integer": + case "int4": + case "serial": + case "serial4": + return "int"; + + case "bigint": + case "int8": + case "bigserial": + case "serial8": + case "bit varying": + case "varbit": + return "long"; + + case "uuid": + return "Guid"; + + case "date": + case "timestamp": + case "timestamptz": + return "DateTime"; + + case "time": + case "timetz": + case "interval": + return "TimeSpan"; + + case "double precision": + case "float8": + return "double"; + + case "real": + case "float4": + case "numeric": + case "decimal": + case "money": + return "decimal"; + + case "bool": + case "boolean": + return "bool"; + + case "bytea": + return "byte[]"; + + case "text": + case "varchar": + case "character varying": + case "char": + case "character": + case "bpchar": + case "line": + return "string"; + + default: + throw new NotSupportedException($".NET system type mapping from database type '{sqlType}' is not supported."); + } + } + + public string GetNHType(string sqlType) + { + switch (sqlType) + { + case "smallint": + case "int2": + case "serial2": + case "smallserial": + return "short"; + + case "int": + case "integer": + case "int4": + case "serial": + case "serial4": + return "int"; + + case "bigint": + case "int8": + case "bigserial": + case "serial8": + case "bit varying": + case "varbit": + return "long"; + + case "uuid": + return "Guid"; + + case "date": + return "date"; + + case "timestamp": + return "timestamp"; + // Should we consider changing this to "DateTime"? + // See: https://nhibernate.jira.com/browse/NH-2520?focusedCommentId=55412 + + case "timestamptz": + return "UtcDateTime"; + + case "time": + case "timetz": + case "interval": + return "TimeAsTimeSpan"; + + case "double precision": + case "float8": + return "double"; + + case "real": + case "float4": + case "numeric": + case "decimal": + return "decimal"; + + case "money": + return "Currency"; + + case "bool": + case "boolean": + return "bool"; + + case "bytea": + return "byte[]"; // Should this really be "BinaryBlob"? + + case "char": + case "character": + case "varchar": + case "character varying": + case "bpchar": + case "line": + return "string"; + + default: + throw new NotSupportedException($"NHibernate type mapping from database type '{sqlType}' is not supported."); + } + } + + public DbType GetDbType(string sqlType) + { + switch (sqlType) + { + case "smallint": + case "int2": + case "smallserial": + case "serial2": + return DbType.Int16; + + case "int": + case "integer": + case "int4": + case "serial": + case "serial4": + return DbType.Int32; + + case "bigint": + case "int8": + case "bigserial": + case "serial8": + case "bit varying": + case "varbit": + return DbType.Int64; + + case "uuid": + return DbType.Guid; + + case "date": + return DbType.Date; + + case "timestamp": + case "timestamptz": + return DbType.Binary; // This seems wrong -- DbType.DateTime? + + case "time": + case "timetz": + case "interval": + return DbType.Time; + + case "double precision": + case "float8": + return DbType.Double; + + case "real": + case "float4": + return DbType.Single; + + case "decimal": + case "numeric": + return DbType.Decimal; + + case "money": + return DbType.Currency; + + case "bool": + case "boolean": + return DbType.Boolean; + + case "bytea": + return DbType.Binary; + + case "text": + case "varchar": + case "character varying": + case "line": + case "bpchar": + return DbType.String; + + case "char": + case "character": + return DbType.AnsiStringFixedLength; + + case "xml": + return DbType.Xml; + + default: + throw new NotSupportedException($"DbType mapping from PostgreSQL type '{sqlType}' is not supported."); + } + } + + public string GetSqlType(PropertyType propertyType) + { + switch (propertyType.DbType) + { + case DbType.Int64: + return "int8"; + + case DbType.Binary: + return "bytea"; + + case DbType.Boolean: + return "boolean"; + + case DbType.AnsiStringFixedLength: + case DbType.StringFixedLength: + + if (propertyType.MaxLength > 0) + { + return $"char({propertyType.MaxLength})"; + } + + return "text"; + + case DbType.AnsiString: + case DbType.String: + + if (propertyType.MaxLength > 0) + { + return $"varchar({propertyType.MaxLength})"; + } + + return "text"; + + case DbType.Date: + return "date"; + + case DbType.DateTime: + return "timestamp"; + + case DbType.DateTime2: + return "timestamp"; + + // case DbType.DateTimeOffset: + // return "datetimeoffset"; + + case DbType.Time: + return "time"; + + case DbType.Currency: + return "money"; + + case DbType.Decimal: + return $"decimal({propertyType.Precision},{propertyType.Scale})"; + + // or money, smallmoney + + case DbType.Double: + return "double precision"; + + case DbType.Int32: + return "integer"; + + case DbType.Int16: + case DbType.Byte: + return "smallint"; + + case DbType.Guid: + return "uuid"; + + case DbType.Xml: + return "xml"; + + default: + + throw new NotSupportedException( + $"PostgreSQL type mapping from 'DbType.{propertyType.DbType}' is not supported."); + } + } + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/Engines/PostgreSql/PostgresRenderingPlugin.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/Engines/PostgreSql/PostgresRenderingPlugin.cs new file mode 100644 index 0000000000..90ddd05afa --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/Engines/PostgreSql/PostgresRenderingPlugin.cs @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using Autofac; +using EdFi.Ods.Generator.Database.DataTypes; +using EdFi.Ods.Generator.Database.NamingConventions; +using EdFi.Ods.Generator.Rendering; + +namespace EdFi.Ods.Generator.Database.Engines.PostgreSql +{ + public class PostgresRenderingPlugin : IRenderingPlugin + { + public void Initialize(ContainerBuilder containerBuilder) + { + containerBuilder.RegisterType() + .Keyed(DatabaseEngine.PostgreSql); + + containerBuilder.RegisterType() + .Keyed(DatabaseEngine.PostgreSql); + } + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/Engines/SqlServer/SqlServerDatabaseNamingConvention.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/Engines/SqlServer/SqlServerDatabaseNamingConvention.cs new file mode 100644 index 0000000000..c391439784 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/Engines/SqlServer/SqlServerDatabaseNamingConvention.cs @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using EdFi.Ods.Generator.Database.NamingConventions; + +namespace EdFi.Ods.Generator.Database.Engines.SqlServer +{ + public class SqlServerDatabaseNamingConvention : DatabaseNamingConventionBase + { + protected override int MaximumNameLength => 128; + + protected override bool LowerCaseNames => false; + + public override string DefaultDateConstraintValue() => "GETUTCDATE()"; + + public override string DefaultGuidConstraintValue() => "NEWID()"; + + public override string DatabaseEngineCode => "MsSql"; + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/Engines/SqlServer/SqlServerDatabaseTypeTranslator.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/Engines/SqlServer/SqlServerDatabaseTypeTranslator.cs new file mode 100644 index 0000000000..4697ae6937 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/Engines/SqlServer/SqlServerDatabaseTypeTranslator.cs @@ -0,0 +1,330 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System; +using System.Data; +using EdFi.Ods.Common.Models.Domain; +using EdFi.Ods.Generator.Database.DataTypes; + +namespace EdFi.Ods.Generator.Database.Engines.SqlServer +{ + public class SqlServerDatabaseTypeTranslator : IDatabaseTypeTranslator + { + public string GetSysType(string sqlType) + { + switch (sqlType) + { + case "tinyint": + case "smallint": + return "short"; + + case "int": + return "int"; + + case "bigint": + return "long"; + + case "uniqueidentifier": + return "Guid"; + + case "smalldatetime": + case "datetime": + case "date": + case "datetime2": + return "DateTime"; + + case "float": + return "double"; + + case "real": + case "numeric": + case "smallmoney": + case "decimal": + case "money": + return "decimal"; + + case "bit": + return "bool"; + + case "image": + case "binary": + case "varbinary": + return "byte[]"; + + case "time": + return "TimeSpan"; + + case "text": + case "ntext": + case "varchar": + case "nvarchar": + return "string"; + + default: + throw new NotSupportedException($".NET system type mapping from SQL Server type '{sqlType}' is not supported."); + } + } + + public string GetNHType(string sqlType) + { + switch (sqlType) + { + case "bigint": + return "long"; + + case "tinyint": + case "smallint": + return "short"; + + case "int": + return "int"; + + case "uniqueidentifier": + return "Guid"; + + case "datetimeoffset": + return "datetimeoffset"; + + case "smalldatetime": + case "datetime": + return "timestamp"; //"datetime"; + + case "datetime2": + return "UtcDateTime"; + + case "date": + return "date"; + + case "float": + return "double"; + + case "real": + case "numeric": + case "smallmoney": + case "decimal": + case "money": + return "decimal"; + + case "bit": + return "bool"; + + case "image": + case "binary": + case "varbinary": + return "byte[]"; // Should this really be "BinaryBlob"? + + case "time": + return "TimeAsTimeSpan"; + + case "text": + case "varchar": + return "AnsiString"; + + case "ntext": + case "nvarchar": + return "string"; + + default: + throw new NotSupportedException($"NHibernate type mapping from SQL Server type '{sqlType}' is not supported."); + } + } + + public DbType GetDbType(string sqlType) + { + switch (sqlType) + { + case "varchar": + return DbType.AnsiString; + + case "nvarchar": + return DbType.String; + + case "int": + return DbType.Int32; + + case "uniqueidentifier": + return DbType.Guid; + + case "datetime": + return DbType.DateTime; + + case "datetime2": + return DbType.DateTime2; + + case "time": + return DbType.Time; + + case "date": + return DbType.Date; + + case "bigint": + return DbType.Int64; + + case "binary": + return DbType.Binary; + + case "bit": + return DbType.Boolean; + + case "char": + return DbType.AnsiStringFixedLength; + + case "decimal": + return DbType.Decimal; + + case "float": + return DbType.Double; + + case "image": + return DbType.Binary; + + case "money": + return DbType.Currency; + + case "nchar": + return DbType.String; + + case "ntext": + return DbType.String; + + case "numeric": + return DbType.Decimal; + + case "real": + return DbType.Single; + + case "smalldatetime": + return DbType.DateTime; + + case "smallint": + return DbType.Int16; + + case "smallmoney": + return DbType.Currency; + + case "sql_variant": + return DbType.String; + + case "sysname": + return DbType.String; + + case "text": + return DbType.AnsiString; + + case "timestamp": + return DbType.Binary; + + case "tinyint": + return DbType.Byte; + + case "varbinary": + return DbType.Binary; + + case "xml": + return DbType.Xml; + + default: + throw new NotSupportedException($"DbType mapping from SQL Server type '{sqlType}' is not supported."); + } + } + + public string GetSqlType(PropertyType propertyType) + { + switch (propertyType.DbType) + { + case DbType.Int64: + return "bigint"; + + case DbType.Binary: + return "varbinary"; // or binary, timestamp, rowversion, image + + case DbType.Boolean: + return "bit"; + + case DbType.AnsiStringFixedLength: + + return string.Format( + "char({0})", + propertyType.MaxLength > 0 + ? propertyType.MaxLength.ToString() + : "Max"); + + case DbType.String: + + return string.Format( + "nvarchar({0})", + propertyType.MaxLength > 0 + ? propertyType.MaxLength.ToString() + : "Max"); + + // or ntext, text, varchar + + case DbType.Date: + return "date"; + + case DbType.DateTime: + return "datetime"; + + case DbType.DateTime2: + return "datetime2"; + + case DbType.DateTimeOffset: + return "datetimeoffset"; + + case DbType.Time: + return "time"; + + case DbType.Currency: + return "money"; + + case DbType.Decimal: + return string.Format("decimal({0},{1})", propertyType.Precision, propertyType.Scale); + + // or money, smallmoney + + case DbType.Double: + return "float"; + + case DbType.Int32: + return "int"; + + case DbType.Int16: + return "smallint"; + + case DbType.StringFixedLength: + + return string.Format( + "nchar({0})", + propertyType.MaxLength > 0 + ? propertyType.MaxLength.ToString() + : "Max"); + + case DbType.Byte: + return "tinyint"; + + case DbType.Guid: + return "uniqueidentifier"; + + case DbType.AnsiString: + + return string.Format( + "varchar({0})", + propertyType.MaxLength > 0 + ? propertyType.MaxLength.ToString() + : "Max"); + + case DbType.Xml: + return "xml"; + + default: + + throw new NotSupportedException( + string.Format( + "SQL Server type mapping from 'DbType.{0}' is not supported.", + propertyType.DbType)); + } + } + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/Engines/SqlServer/SqlServerRenderingPlugin.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/Engines/SqlServer/SqlServerRenderingPlugin.cs new file mode 100644 index 0000000000..46dd6ff64b --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/Engines/SqlServer/SqlServerRenderingPlugin.cs @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using Autofac; +using EdFi.Ods.Generator.Database.DataTypes; +using EdFi.Ods.Generator.Database.NamingConventions; +using EdFi.Ods.Generator.Rendering; + +namespace EdFi.Ods.Generator.Database.Engines.SqlServer +{ + public class SqlServerRenderingPlugin : IRenderingPlugin + { + public void Initialize(ContainerBuilder containerBuilder) + { + containerBuilder.RegisterType() + .Keyed(DatabaseEngine.SqlServer); + + containerBuilder.RegisterType() + .Keyed(DatabaseEngine.SqlServer); + } + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/NamingConventions/DatabaseNamingConventionBase.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/NamingConventions/DatabaseNamingConventionBase.cs new file mode 100644 index 0000000000..3a0aab97a7 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/NamingConventions/DatabaseNamingConventionBase.cs @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System; +using EdFi.Ods.Common.Models.Domain; +using EdFi.Ods.Generator.Extensions; + +namespace EdFi.Ods.Generator.Database.NamingConventions +{ + public abstract class DatabaseNamingConventionBase : IDatabaseNamingConvention + { + // Convention constants + private const string PrimaryKeyNameSuffix = "_PK"; + private const string AlternateKeyNameSuffix = "_AK"; + private const string ForeignKeyNamePrefix = "FK_"; + + private const string UniqueIndexNamePrefix = "UX_"; + private const string IndexNamePrefix = "IX_"; + + private const string DefaultConstraintMidfix = "_DF_"; + + protected abstract int MaximumNameLength { get; } + + protected abstract bool LowerCaseNames { get; } + + public virtual string Schema(Entity entity) => + new PhysicalNameParts(SchemaCore(entity)) + .ApplyLongNameConvention(LowerCaseNames, MaximumNameLength); + + private static string SchemaCore(Entity entity) => entity?.Schema; + + public virtual string TableName(Entity entity) => + new PhysicalNameParts(TableNameCore(entity)) + .ApplyLongNameConvention(LowerCaseNames, MaximumNameLength); + + private static string TableNameCore(Entity entity) => entity?.Name; + + public virtual string ColumnName(EntityProperty property, string contextualSuffix = null) => + new PhysicalNameParts(ColumnNameCore(property?.PropertyName), suffix: contextualSuffix) + .ApplyLongNameConvention(LowerCaseNames, MaximumNameLength); + + public virtual string ColumnName(string name, string contextualSuffix) => + new PhysicalNameParts(ColumnNameCore(name), suffix: contextualSuffix) + .ApplyLongNameConvention(LowerCaseNames, MaximumNameLength); + + private static string ColumnNameCore(string name) => name; + + public virtual string PrimaryKeyConstraintName(Entity entity) => + new PhysicalNameParts(PrimaryKeyConstraintNameCore(entity), suffix: PrimaryKeyNameSuffix) + .ApplyLongNameConvention(LowerCaseNames, MaximumNameLength); + + private static string PrimaryKeyConstraintNameCore(Entity entity) => $"{TableNameCore(entity)}"; + + public virtual string ForeignKeyConstraintName(AssociationView association, string context = null) => + new PhysicalNameParts(ForeignKeyConstraintNameCore(association, context), prefix: ForeignKeyNamePrefix) + .ApplyLongNameConvention(LowerCaseNames, MaximumNameLength); + + private static string ForeignKeyConstraintNameCore(AssociationView association, string context = null) + { + if (association == null) + { + return null; + } + + switch (association.AssociationType) + { + case AssociationViewType.ToDerived: + case AssociationViewType.ToExtension: + case AssociationViewType.OneToMany: + case AssociationViewType.OneToOneOutgoing: + throw new ArgumentException("AssociationView must represent the incoming side of the association to be used for naming a foreign key."); + } + + return $"{TableNameCore(association.ThisEntity)}_{TableNameCore(association.OtherEntity)}{context}"; + } + + public virtual string ForeignKeyIndexName(AssociationView association, string context = null) => + new PhysicalNameParts(ForeignKeyIndexNameCore(association, context), prefix: IndexNamePrefix) + .ApplyLongNameConvention(LowerCaseNames, MaximumNameLength); + + private static string ForeignKeyIndexNameCore(AssociationView association, string context = null) => + $"{TableNameCore(association.ThisEntity)}_{association.RoleName}{TableNameCore(association.OtherEntity)}{context}"; + + public virtual string DefaultConstraintName(EntityProperty property) => + new PhysicalNameParts(DefaultConstraintNameCore(property)) + .ApplyLongNameConvention(LowerCaseNames, MaximumNameLength); + + private static string DefaultConstraintNameCore(EntityProperty property) => + $"{TableNameCore(property.Entity)}{DefaultConstraintMidfix}{ColumnNameCore(property.PropertyName)}"; + + public virtual string GetUniqueIndexName(Entity entity, string contextualSuffix = null) => + new PhysicalNameParts(GetUniqueIndexNameCore(entity), prefix: UniqueIndexNamePrefix, suffix: contextualSuffix) + .ApplyLongNameConvention(LowerCaseNames, MaximumNameLength); + + private static string GetUniqueIndexNameCore(Entity entity) => TableNameCore(entity); + + public virtual string GetAlternateKeyConstraintName(Entity entity) => + new PhysicalNameParts(GetAlternateKeyConstraintNameCore(entity), prefix: UniqueIndexNamePrefix, suffix: AlternateKeyNameSuffix) + .ApplyLongNameConvention(LowerCaseNames, MaximumNameLength); + + public virtual string IdentifierName(string coreName, string prefix = null, string suffix = null) + { + return new PhysicalNameParts(coreName, prefix, suffix) + .ApplyLongNameConvention(LowerCaseNames, MaximumNameLength); + } + + private static string GetAlternateKeyConstraintNameCore(Entity entity) => TableNameCore(entity); + + public abstract string DefaultDateConstraintValue(); + + public abstract string DefaultGuidConstraintValue(); + + /// + /// Gets a short code representing the database engine. + /// + public abstract string DatabaseEngineCode { get; } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/NamingConventions/DatabaseNamingConventionFactory.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/NamingConventions/DatabaseNamingConventionFactory.cs new file mode 100644 index 0000000000..086781638f --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/NamingConventions/DatabaseNamingConventionFactory.cs @@ -0,0 +1,20 @@ +using Autofac.Features.Indexed; +using EdFi.Common.Configuration; + +namespace EdFi.Ods.Generator.Database.NamingConventions +{ + public class DatabaseNamingConventionFactory : IDatabaseNamingConventionFactory + { + private readonly IIndex _conventionByDatabaseEngine; + + public DatabaseNamingConventionFactory(IIndex conventionByDatabaseEngine) + { + _conventionByDatabaseEngine = conventionByDatabaseEngine; + } + + public IDatabaseNamingConvention CreateNamingConvention(string databaseEngine) + { + return _conventionByDatabaseEngine[databaseEngine]; + } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/NamingConventions/IDatabaseNamingConvention.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/NamingConventions/IDatabaseNamingConvention.cs new file mode 100644 index 0000000000..fde3d08c3e --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/NamingConventions/IDatabaseNamingConvention.cs @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using EdFi.Ods.Common.Models.Domain; + +namespace EdFi.Ods.Generator.Database.NamingConventions +{ + public interface IDatabaseNamingConvention + { + string Schema(Entity entity); + + string TableName(Entity entity); + + string ColumnName(EntityProperty property, string contextualSuffix = null); + + string ColumnName(string name, string contextualSuffix = null); + + string PrimaryKeyConstraintName(Entity entity); + + string ForeignKeyConstraintName(AssociationView association, string context = null); + + string ForeignKeyIndexName(AssociationView association, string context); + + string DefaultConstraintName(EntityProperty property); + + string DefaultDateConstraintValue(); + + string DefaultGuidConstraintValue(); + + string GetUniqueIndexName(Entity entity, string contextualSuffix = null); + + string GetAlternateKeyConstraintName(Entity entity); + + string IdentifierName(string coreName, string prefix = null, string suffix = null); + + /// + /// Gets a short code representing the database engine. + /// + string DatabaseEngineCode { get; } + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/NamingConventions/IDatabaseNamingConventionFactory.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/NamingConventions/IDatabaseNamingConventionFactory.cs new file mode 100644 index 0000000000..50b744f252 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/NamingConventions/IDatabaseNamingConventionFactory.cs @@ -0,0 +1,9 @@ +using EdFi.Common.Configuration; + +namespace EdFi.Ods.Generator.Database.NamingConventions +{ + public interface IDatabaseNamingConventionFactory + { + IDatabaseNamingConvention CreateNamingConvention(string databaseEngine); + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/NamingConventions/PhysicalNameParts.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/NamingConventions/PhysicalNameParts.cs new file mode 100644 index 0000000000..2d2ecfa91a --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/NamingConventions/PhysicalNameParts.cs @@ -0,0 +1,32 @@ +namespace EdFi.Ods.Generator.Database.NamingConventions +{ + public class PhysicalNameParts + { + public PhysicalNameParts(string name, string prefix = null, string suffix = null) + { + Prefix = prefix; + Name = name; + Suffix = suffix; + } + + /// + /// Gets or sets the physical naming convention's applied prefix. + /// + public string Prefix { get; set; } + + /// + /// The core physical name of the object. + /// + public string Name { get; set; } + + /// + /// Gets or sets the physical naming convention's applied suffix. + /// + public string Suffix { get; set; } + + public override string ToString() + { + return $"{Prefix}{Name}{Suffix}"; + } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/Column.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/Column.cs new file mode 100644 index 0000000000..79a7ba5f76 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/Column.cs @@ -0,0 +1,66 @@ +using EdFi.Ods.Common.Models.Dynamic; + +namespace EdFi.Ods.Generator.Database.TemplateModelProviders +{ + public class Column : DynamicModel + { + public string ColumnName { get; set; } + + public string DataType { get; set; } + + public bool IsNullable { get; set; } + + public bool? IsFirst { get; set; } + + public string DefaultConstraintName { get; set; } + public string DefaultValue { get; set; } + + public bool IsString + { + get => DataType.StartsWith("nvarchar"); // TODO: Need to add support for Postgres. + } + + public bool IsGuid + { + get => DataType == "uniqueidentifier"; + } + + public bool IsNumber + { + get => + DataType == "bit" || DataType == "decimal" || DataType == "int" || DataType == "money" || DataType == "smallint"; + } + + public bool IsDate + { + get => DataType == "datetime" || DataType == "datetime2" || DataType == "date"; + } + + public bool IsTime + { + get => DataType == "time"; + } + + public bool IsUnsupportedType => !IsString && !IsGuid && !IsNumber && !IsDate && !IsTime; + + public bool? IsLast { get; set; } + + public bool IsServerAssigned { get; set; } + + public int Index { get; set; } + + public bool IsConcreteDescriptorId { get; set; } + + /// + /// Indicates whether the column represents an identifier (i.e the USI) for a specific type of person (e.g. Student/Staff/Parent). + /// + public bool IsPersonUSIUsage { get; set; } + + public string PersonType { get; set; } + + /// + /// For primary key columns on derived entities/tables, gets or sets the name of the corresponding column in the base table. + /// + public string BaseColumnName { get; set; } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/DatabaseTemplateModel.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/DatabaseTemplateModel.cs new file mode 100644 index 0000000000..420ab36ce6 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/DatabaseTemplateModel.cs @@ -0,0 +1,12 @@ +using System.Collections.Generic; +using EdFi.Ods.Common.Models.Dynamic; + +namespace EdFi.Ods.Generator.Database.TemplateModelProviders +{ + public class DatabaseTemplateModel : DynamicModel + { + public IEnumerable Schemas { get; set; } + + public IEnumerable Tables { get; set; } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/DatabaseTemplateModelProvider.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/DatabaseTemplateModelProvider.cs new file mode 100644 index 0000000000..d337352dae --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/DatabaseTemplateModelProvider.cs @@ -0,0 +1,427 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using EdFi.Common; +using EdFi.Ods.Common.Models; +using EdFi.Ods.Common.Models.Domain; +using EdFi.Ods.Common.Models.Dynamic; +using EdFi.Ods.Common.Specifications; +using EdFi.Ods.Generator.Database.Conventions; +using EdFi.Ods.Generator.Database.DataTypes; +using EdFi.Ods.Generator.Database.Domain; +using EdFi.Ods.Generator.Database.NamingConventions; +using EdFi.Ods.Generator.Database.TemplateModelProviders; +using EdFi.Ods.Generator.Models; +using EdFi.Ods.Generator.Rendering; +using EdFi.Ods.Generator.Templating; +using log4net; + +namespace EdFi.Ods.Generator.Database.TemplateModelProviders +{ + public class DatabaseTemplateModelProvider : ITemplateModelProvider + { + private readonly IList _tableEnhancers; + private readonly IList _columnEnhancers; + private readonly ILog _logger = LogManager.GetLogger(typeof(DatabaseTemplateModelProvider)); + + private readonly IDatabaseTypeTranslatorFactory _databaseTypeTranslatorFactory; + private readonly IDatabaseNamingConventionFactory _databaseNamingConventionFactory; + private readonly Lazy _domainModel; + + private readonly string _databaseEngine; + private readonly string _schemaFilter; + + private bool ShouldRenderEntityForSchema(Entity entity) => entity.Schema.Equals(_schemaFilter, StringComparison.OrdinalIgnoreCase); + + public DatabaseTemplateModelProvider( + IDatabaseTypeTranslatorFactory databaseTypeTranslatorFactory, + IDatabaseNamingConventionFactory databaseNamingConventionFactory, + IDomainModelDefinitionsProviderSource domainModelDefinitionsProviderSource, + IList domainModelDefinitionsTransformers, + IList tableEnhancers, + IList columnEnhancers, + IDatabaseOptions databaseOptions, + IGeneratorOptions generatorOptions) + { + _tableEnhancers = tableEnhancers; + _columnEnhancers = columnEnhancers; + _databaseTypeTranslatorFactory = Preconditions.ThrowIfNull(databaseTypeTranslatorFactory, nameof(databaseTypeTranslatorFactory)); + _databaseNamingConventionFactory = Preconditions.ThrowIfNull(databaseNamingConventionFactory, nameof(databaseNamingConventionFactory)); + + _renderingContext = generatorOptions.PropertyByName; + + var domainModelDefinitionProviders = new Lazy>( + () => domainModelDefinitionsProviderSource.GetDomainModelDefinitionProviders() + .ToList()); + + var domainModelProvider = new Lazy( + () => new DomainModelProvider(domainModelDefinitionProviders.Value, domainModelDefinitionsTransformers.ToArray())); + + _domainModel = new Lazy(() => + { + var domainModel = domainModelProvider.Value.GetDomainModel(); + + _logger.Debug($"Domain model contains the following {domainModel.Schemas.Count} schema(s): {string.Join(", ", domainModel.Schemas.Select(s => s.PhysicalName))}"); + + return domainModel; + }); + + _databaseEngine = databaseOptions.DatabaseEngine; + _schemaFilter = databaseOptions.SchemaFilter; + } + + private readonly IDictionary> _updatableAncestorsByEntity + = new Dictionary>(); + + private IDictionary _renderingContext; + + public object GetTemplateModel(IDictionary properties) + { + var databaseEngine = _databaseEngine; + + var databaseNamingConvention = _databaseNamingConventionFactory.CreateNamingConvention(databaseEngine); + var databaseTypeTranslator = _databaseTypeTranslatorFactory.CreateTranslator(databaseEngine); + + var domainModel = _domainModel.Value; + + var model = new DatabaseTemplateModel + { + Schemas = domainModel.Entities + .Where(ShouldRenderEntityForSchema) + .Select(e => databaseNamingConvention.Schema(e)) + .Distinct() + .Select(s => new SchemaInfo { Schema = s}), + Tables = domainModel.Entities + .Where(ShouldRenderEntityForSchema) + .OrderBy(e => e.FullName.Name) + .Select(CreateTable) + }; + + var dynamicModel = model as IDynamicModel; + + // Add the properties supplied via the command-line to the template + foreach (var kvp in properties) + { + dynamicModel.DynamicProperties.Add(kvp.Key, kvp.Value); + } + + return model; + + Table CreateTable(Entity entity) + { + dynamic entityAsDynamic = entity; + + var table = new Table + { + IsAggregateRoot = entity.IsAggregateRoot, + IsDerived = entity.IsDerived, + IsBase = entity.IsBase, + BaseTableSchema = entity.IsDerived ? databaseNamingConvention.Schema(entity.BaseEntity) : null, + BaseTableName = entity.IsDerived ? databaseNamingConvention.TableName(entity.BaseEntity) : null, + BaseAlternateKeyConstraintName = entity.IsDerived ? databaseNamingConvention.GetAlternateKeyConstraintName(entity.BaseEntity) : null, + BaseAlternateKeyColumns = entity.IsDerived ? entity.BaseEntity?.AlternateIdentifiers.FirstOrDefault()?.Properties.Select( + (p, i) => CreateColumn(p, i, entity.BaseEntity.AlternateIdentifiers.First().Properties)) + : null, + IsDescriptorTable = entity.IsDescriptorEntity, + IsDescriptorBaseTable = entity.IsDescriptorBaseEntity(), + IsPersonTypeTable = entity.IsPersonEntity(), + Schema = databaseNamingConvention.Schema(entity), + TableName = databaseNamingConvention.TableName(entity), + FullName = entity.FullName, + + // TODO: Move LDS plugin + HashKey = new HashKey + { + ColumnName = databaseNamingConvention.ColumnName(entity.Name, "HashKey"), + IndexName = databaseNamingConvention.GetUniqueIndexName(entity, "HashKey") + }, + + PrimaryKeyConstraintName = databaseNamingConvention.PrimaryKeyConstraintName(entity), + PrimaryKeyColumns = entity.Identifier.Properties.Select( + (p, i) => CreateColumn(p, i, entity.Identifier.Properties)), + ContextualPrimaryKeyColumns = entity.Identifier.Properties + .Where(p => !entity.IsAggregateRoot) + .Where(p => !p.IsFromParent) + .Where(p => !entity.Aggregate.AggregateRoot.Identifier.Properties.Any(p2 => p2.PropertyName == p.PropertyName)) + .Where(p => !p.IncomingAssociations.Any()) + .Select((p, i) => CreateColumn(p, i)), + HasServerAssignedSurrogateId = entity.Identifier.IsSurrogateIdentifierDefinition(), + SurrogateIdColumn = entity.Identifier.Properties + .Where(p => p.IsServerAssigned) + .Select((p, i) => CreateColumn(p, i)) + .SingleOrDefault(), + HasAlternateKey = entity.AlternateIdentifiers.Any(), + AlternateKeyConstraintName = databaseNamingConvention.GetAlternateKeyConstraintName(entity), + AlternateKeyColumns = entity.AlternateIdentifiers.FirstOrDefault()?.Properties.Select( + (p, i) => CreateColumn(p, i, entity.AlternateIdentifiers.First().Properties)), + + // TODO: Move LDS plugin + IdentifyingReferences = entity.IncomingAssociations + .Where(a => a.IsIdentifying && a.OtherEntity != entity.Parent) + .Select(CreateHashReference), + + // TODO: Move LDS plugin + References = entity.IncomingAssociations + .Where(a => !a.IsIdentifying) + .Select(CreateHashReference), + + // TODO: Move LDS plugin + AllReferences = entity.IncomingAssociations + .Select(CreateHashReference), + // ForeignKeyColumns = entity.IncomingAssociations + // .Where(a => !a.IsNavigable) + // .SelectMany(a => a.ThisProperties.Select(p => new Column + // { + // ColumnName = _databaseNamingConvention.CreateArtifactName(p.PropertyName), + // DataType = p.PropertyType.ToSql().ToMetaEdPluginDataType(), + // IsNullable = p.PropertyType.IsNullable, + // })), + // Non-PK and Non-FK columns + NonPrimaryOrForeignKeyColumns = entity.Properties + .Where(p => !p.IsIdentifying && !p.IncomingAssociations.Any()) + .Where(p => !p.IsBoilerplate()) + .Select( (p, i) => CreateColumn(p, i)), + // Non-PK columns + NonPrimaryKeyColumns = entity.Properties + .Where(p => !p.IsIdentifying && !p.IsBoilerplate()) + .Select( (p, i) => CreateColumn(p, i)), + // TODO: Think about whether and where this should be applied to the model through a transform. + DiscriminatorColumn = entity.HasDiscriminator() ? ColumnHelper.CreateDiscriminatorColumn(databaseNamingConvention, databaseTypeTranslator) : null, + BoilerplateColumns = GetBoilerplateColumns(ordered: true), + // TODO: Review usage of this property and consider removal + BoilerplateColumnsUnsorted = GetBoilerplateColumns(), + ForeignKeys = entity.IncomingAssociations + .GroupBy(association => databaseNamingConvention.ForeignKeyConstraintName(association), a => a) + .OrderBy(g => g.Key) + .SelectMany(g => g + .Select((a, associationIndex) => new ForeignKey + { + ConstraintName = databaseNamingConvention.ForeignKeyConstraintName(a, (associationIndex == 0 ? string.Empty : associationIndex.ToString())), + ThisSchema = databaseNamingConvention.Schema(a.ThisEntity), + ThisTableName = databaseNamingConvention.TableName(a.ThisEntity), + ThisColumns = a.ThisProperties.Select((p, i) => new Column + { + ColumnName = databaseNamingConvention.ColumnName(p), + DataType = databaseTypeTranslator.GetSqlType(p.PropertyType), + IsNullable = p.PropertyType.IsNullable, + IsConcreteDescriptorId = p.IsDescriptorUsage || (p.IsIdentifying && p.Entity.IsDescriptorEntity()), + IsFirst = i == 0, + Index = i, + }), + OtherSchema = databaseNamingConvention.Schema(a.OtherEntity), + OtherTableName = databaseNamingConvention.TableName(a.OtherEntity), + OtherColumns = a.OtherProperties.Select((p, i) => + CreateColumn(p, i, a.OtherProperties)), + IsFromBase = a.AssociationType == AssociationViewType.FromBase, + IsOneToOne = a.AssociationType == AssociationViewType.OneToOneIncoming, + // IsIdentifying = a.IsIdentifying, + IsNavigable = a.IsNavigable, + IsUpdatable = IsAssociationUpdatable(a), + })), + IdIndexName = databaseNamingConvention.GetUniqueIndexName(entity, "Id"), + // TODO: Move to ChangeQueries plugin as dynamic enhancement? + KeyValuesCanChange = entity.Identifier.IsUpdatable || (entity.IncomingAssociations.Any(a => a.IsIdentifying && IsAssociationUpdatable(a))), + // TODO: Move to LDS plugin as dynamic enhancement + IsTemporal = (entityAsDynamic.ReadHistory == true), + }; + + // Enhance the table + var enhancedTable = table; + + foreach (var tableEnhancer in _tableEnhancers.Where(e => RenderingHelper.ShouldRunEnhancer(e, _renderingContext))) + { + enhancedTable = tableEnhancer.EnhanceTable(entity, enhancedTable, enhancedTable); + } + + return enhancedTable; + + bool IsAssociationUpdatable(AssociationView association) + { + var sb = new StringBuilder(); + + var updatableAncestors = GetAncestorsWithUpdatableIdentifier(association.OtherEntity, sb).ToArray(); + + if (updatableAncestors.Any()) + { + // _logger.Debug($"Starting probe for updatable identifier on association '{association.Association.FullName}'."); + // _logger.Debug(sb.ToString()); + + var sb2 = new StringBuilder(); + + // Get other incoming associations + var otherIncomingAssociationsWithSameUpdatableAncestor = association.ThisEntity.IncomingAssociations + .Where(a => a != association) + .Select( + a => new + { + Association = a, + UpdatableAncestors = GetAncestorsWithUpdatableIdentifier(a.OtherEntity, sb2) + }) + .Where(x => x.UpdatableAncestors.Intersect(updatableAncestors).Any()) + .Select(x => x.Association) + .ToArray(); + + if (!otherIncomingAssociationsWithSameUpdatableAncestor.Any()) + { + return true; + } + + var chosenAssociation = otherIncomingAssociationsWithSameUpdatableAncestor + .Concat(new[] {association}) + .OrderBy(a => a.Association.FullName.ToString(), StringComparer.OrdinalIgnoreCase) + .First(); + + return (chosenAssociation == association); + } + + return false; + } + + IEnumerable GetAncestorsWithUpdatableIdentifier(Entity subjectEntity, StringBuilder sb) + { + if (_updatableAncestorsByEntity.TryGetValue(subjectEntity.FullName, out var entityUpdatableAncestors)) + { + return entityUpdatableAncestors; + } + + var updatableAncestors = new List(); + + sb.AppendLine($"Probing entity '{subjectEntity.Name}' for updatable identifier."); + + if (subjectEntity.Identifier.IsUpdatable) + { + sb.AppendLine($"Identifier for '{subjectEntity.Name}' is updatable."); + + updatableAncestors.Add(subjectEntity.FullName); + } + + foreach (var association in subjectEntity.IncomingAssociations.Where(a => a.IsIdentifying && !a.IsSelfReferencing)) + { + sb.AppendLine($"Probing association '{association.Name}' for updatable identifier."); + + var ancestorsWithUpdatableIdentifier = GetAncestorsWithUpdatableIdentifier(association.OtherEntity, sb); + + updatableAncestors.AddRange(ancestorsWithUpdatableIdentifier); + } + + _updatableAncestorsByEntity[subjectEntity.FullName] = updatableAncestors; + + return updatableAncestors; + } + + // string GetHashKeyIndexName(string thisTableName, string otherTableName = null, string roleName = null) + // { + // string indexName; + // + // if (otherTableName == null) + // { + // indexName = $"UX_{thisTableName}_HashKey"; + // } + // else + // { + // indexName = $"IX_{roleName}{thisTableName}_{otherTableName}_HashKey"; + // } + // + // if (indexName.Length > 128) + // return indexName.Substring(0, 128); + // + // return indexName; + // } + + // TODO: Move to LDS plugin + HashReference CreateHashReference(AssociationView association, int index = 0) + { + if (association == null) + { + return null; + } + + return new HashReference + { + ReferencedTableSchema = databaseNamingConvention.Schema(association.OtherEntity), + ReferencedTableName = databaseNamingConvention.TableName(association.OtherEntity), + ReferenceMemberName = association.Name, + // TODO: REMOVE -- ConstraintName = databaseNamingConvention.ConstraintName(entity, association.OtherEntity, association.RoleName), + ConstraintName = databaseNamingConvention.ForeignKeyConstraintName(association), + IndexName = databaseNamingConvention.ForeignKeyIndexName(association, "HashKey"), + Column = new Column + { + ColumnName = databaseNamingConvention.ColumnName($"{association.Name}HashKey"), + DataType = databaseTypeTranslator.GetSqlType(new PropertyType(DbType.Guid)), + IsNullable = !association.IsRequired, + }, + ReferenceColumns = association.ThisProperties + .Select((p, i) => CreateColumn(p, i, association.ThisProperties)), + IsFirst = index == 0 + }; + } + + IEnumerable GetBoilerplateColumns(bool ordered = false) + { + var boilerplateProperties = entity.Properties + .Where(p => !p.IsIdentifying) + .Where(p => p.IsBoilerplate()); + + if (ordered) + { + boilerplateProperties = boilerplateProperties.OrderBy(p => Enum.Parse(p.PropertyName)); + } + + return boilerplateProperties + .Select((p, i) => new Column + { + ColumnName = databaseNamingConvention.ColumnName(p.PropertyName), + DataType = databaseTypeTranslator.GetSqlType(p.PropertyType), + IsNullable = p.PropertyType.IsNullable, + DefaultValue = p.PropertyType.DbType == DbType.DateTime2 + ? databaseNamingConvention.DefaultDateConstraintValue() + : (p.PropertyType.DbType == DbType.Guid + ? databaseNamingConvention.DefaultGuidConstraintValue() + : null), + DefaultConstraintName = databaseNamingConvention.DefaultConstraintName(p), + IsFirst = i == 0, + }); + } + } + + Column CreateColumn(EntityProperty property, int index, IReadOnlyList contextualPropertySet = null) + { + var column = new Column + { + ColumnName = databaseNamingConvention.ColumnName(property), + DataType = databaseTypeTranslator.GetSqlType(property.PropertyType), + IsNullable = property.PropertyType.IsNullable, + IsServerAssigned = property.IsServerAssigned, + BaseColumnName = property.BaseProperty != null ? databaseNamingConvention.ColumnName(property.BaseProperty) : null, + IsFirst = index == 0, + IsLast = contextualPropertySet == null ? (bool?) null : (index == contextualPropertySet.Count - 1), + Index = index, + + // Ed-Fi-specific properties + IsConcreteDescriptorId = property.IsDescriptorUsage || (property.IsIdentifying && property.Entity.IsDescriptorEntity()), + IsPersonUSIUsage = property.DefiningProperty.Entity != property.Entity + && property.DefiningProperty.IsIdentifying + && property.DefiningProperty.Entity.IsPersonEntity(), + PersonType = UniqueIdSpecification.GetUSIPersonType(property.DefiningProperty.PropertyName), + }; + + // Enhance the table + var enhancedColumn = column; + + foreach (var columnEnhancer in _columnEnhancers.Where(e => RenderingHelper.ShouldRunEnhancer(e, _renderingContext))) + { + enhancedColumn = columnEnhancer.EnhanceColumn(property, enhancedColumn, enhancedColumn); + } + + return enhancedColumn; + } + } + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/ForeignKey.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/ForeignKey.cs new file mode 100644 index 0000000000..0e575e183e --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/ForeignKey.cs @@ -0,0 +1,26 @@ +using System.Collections.Generic; + +namespace EdFi.Ods.Generator.Database.TemplateModelProviders +{ + public class ForeignKey + { + public string ConstraintName { get; set; } + + public string ThisSchema { get; set; } + public string ThisTableName { get; set; } + public IEnumerable ThisColumns { get; set; } + public string OtherSchema { get; set; } + public string OtherTableName { get; set; } + public IEnumerable OtherColumns { get; set; } + + public bool IsFromBase { get; set; } + + // public bool IsIdentifying { get; set; } + + public bool IsNavigable { get; set; } + + public bool IsUpdatable { get; set; } + + public bool IsOneToOne { get; set; } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/HashKey.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/HashKey.cs new file mode 100644 index 0000000000..8be538f513 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/HashKey.cs @@ -0,0 +1,10 @@ +namespace EdFi.Ods.Generator.Database.TemplateModelProviders +{ + // TODO: Move to NDE plugin, add as dynamic + public class HashKey + { + public string ColumnName { get; set; } + + public string IndexName { get; set; } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/HashReference.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/HashReference.cs new file mode 100644 index 0000000000..e76936b85c --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/HashReference.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; + +namespace EdFi.Ods.Generator.Database.TemplateModelProviders +{ + // TODO: Move to NDE plugin, add as dynamic + public class HashReference + { + public string ReferencedTableSchema { get; set; } + + public string ReferencedTableName { get; set; } + + public Column Column { get; set; } + + public string ConstraintName { get; set; } + + public string ReferenceMemberName { get; set; } // TODO: This needs to be processed for Postgres naming limitations + + /// + /// The physical columns whose values are composed into the hash key. + /// + public IEnumerable ReferenceColumns { get; set; } + + public bool IsFirst { get; set; } + + public string IndexName { get; set; } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/IColumnEnhancer.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/IColumnEnhancer.cs new file mode 100644 index 0000000000..ec5e0cffb0 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/IColumnEnhancer.cs @@ -0,0 +1,9 @@ +using EdFi.Ods.Common.Models.Domain; + +namespace EdFi.Ods.Generator.Database.TemplateModelProviders +{ + public interface IColumnEnhancer + { + Column EnhanceColumn(EntityProperty property, Column column, dynamic columnProps); + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/ITableEnhancer.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/ITableEnhancer.cs new file mode 100644 index 0000000000..27566d79f1 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/ITableEnhancer.cs @@ -0,0 +1,9 @@ +using EdFi.Ods.Common.Models.Domain; + +namespace EdFi.Ods.Generator.Database.TemplateModelProviders +{ + public interface ITableEnhancer + { + Table EnhanceTable(Entity entity, Table table, dynamic tableProps); + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/SchemaInfo.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/SchemaInfo.cs new file mode 100644 index 0000000000..f8d9babd93 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/SchemaInfo.cs @@ -0,0 +1,7 @@ +namespace EdFi.Ods.Generator.Database.TemplateModelProviders +{ + public class SchemaInfo + { + public string Schema { get; set; } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/Table.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/Table.cs new file mode 100644 index 0000000000..39e65f7d4f --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/TemplateModelProviders/Table.cs @@ -0,0 +1,143 @@ +using System.Collections.Generic; +using System.Linq; +using EdFi.Ods.Common.Models.Domain; +using EdFi.Ods.Common.Models.Dynamic; + +namespace EdFi.Ods.Generator.Database.TemplateModelProviders +{ + public class Table : DynamicModel + { + public string Schema { get; set; } + + public string TableName { get; set; } + + public bool HasPrimaryKeyColumns + { + get => PrimaryKeyColumns.Any(); + } + + public IEnumerable PrimaryKeyColumns { get; set; } + + public bool HasContextualPrimaryKeyColumns + { + get => ContextualPrimaryKeyColumns.Any(); + } + + public IEnumerable ContextualPrimaryKeyColumns { get; set; } + + public IEnumerable ParentPrimaryKeyColumns + { + get => + PrimaryKeyColumns.Where(pkc => !ContextualPrimaryKeyColumns.Any(c => c.ColumnName == pkc.ColumnName)) + .Select( + (pkc, i) => new Column + { + ColumnName = pkc.ColumnName, + DataType = pkc.DataType, + IsNullable = pkc.IsNullable, + IsFirst = i == 0, + }); + } + + public bool IsAggregateRoot { get; set; } + + public bool HasNonPrimaryOrForeignKeyColumns + { + get => NonPrimaryOrForeignKeyColumns.Any(); + } + + public bool HasNonPrimaryOrForeignKeyColumnsOrReferences + { + get => NonPrimaryOrForeignKeyColumns.Any() || References.Any(); + } + + /// + /// Gets the columns that are not part of any primary or foreign key. + /// + public IEnumerable NonPrimaryOrForeignKeyColumns { get; set; } + + public bool HasBoilerplateColumns + { + get => BoilerplateColumns.Any(); + } + + public bool HasDiscriminatorColumn => DiscriminatorColumn != null; + + public Column DiscriminatorColumn { get; set; } + + public IEnumerable BoilerplateColumns { get; set; } + public IEnumerable BoilerplateColumnsUnsorted { get; set; } + + public bool HasReferences + { + get => References.Any(); + } + + /// + /// Gets non-identifying references. + /// + public IEnumerable References { get; set; } + + public IEnumerable IdentifyingReferences { get; set; } + + public string PrimaryKeyConstraintName { get; set; } + + public bool HasNonPrimaryKeyColumns => NonPrimaryKeyColumns.Any(); + + /// + /// Gets all columns that are not part of the primary key, but are also not the boilerplate columns. + /// + public IEnumerable NonPrimaryKeyColumns { get; set; } + + public IEnumerable ForeignKeys { get; set; } + + public string IdIndexName { get; set; } + + public bool IsDerived { get; set; } + + public bool IsBase { get; set; } + + public bool HasAllReferences => AllReferences.Any(); + + /// + /// Gets all references, identifying and non-identifying. + /// + public IEnumerable AllReferences { get; set; } + + public HashKey HashKey { get; set; } + + public bool HasAlternateKey { get; set; } + + public string AlternateKeyConstraintName { get; set; } + + public bool HasServerAssignedSurrogateId { get; set; } + + public Column SurrogateIdColumn { get; set; } + + public IEnumerable AlternateKeyColumns { get; set; } + + public bool IsDescriptorTable { get; set; } + + public bool IsDescriptorBaseTable { get; set; } + + public FullName FullName { get; set; } + + public bool IsPersonTypeTable { get; set; } + + // TODO: Move to LDS plugin + public bool IsTemporal { get; set; } + + // TODO: Move to ChangeQueries plugin + public bool KeyValuesCanChange { get; set; } + + public string BaseTableSchema { get; set; } + public string BaseTableName { get; set; } + public string BaseAlternateKeyConstraintName { get; set; } + public IEnumerable BaseAlternateKeyColumns { get; set; } + + // /// + // /// Gets the reference back to the parent. + // /// + // public HashReference ParentReference { get; set; } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.Generator/Database/Transformers/IdAlternateIdentifierStripper.cs b/Utilities/Generator/EdFi.Ods.Generator/Database/Transformers/IdAlternateIdentifierStripper.cs new file mode 100644 index 0000000000..c82a7375a2 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Database/Transformers/IdAlternateIdentifierStripper.cs @@ -0,0 +1,31 @@ +using System.Collections.Generic; +using System.Linq; +using EdFi.Ods.Common.Models; +using EdFi.Ods.Common.Models.Definitions; + +namespace EdFi.Ods.Generator.Database.Transformers +{ + public class IdAlternateIdentifierStripper : IDomainModelDefinitionsTransformer + { + public IEnumerable TransformDefinitions(IEnumerable definitions) + { + foreach (DomainModelDefinitions domainModelDefinitions in definitions) + { + foreach (var entityDefinition in domainModelDefinitions.EntityDefinitions) + { + // entityDefinition.LocallyDefinedProperties = entityDefinition.LocallyDefinedProperties + // .Where(p => !p.PropertyName.IsBoilerplate()) + // .ToArray(); + + // Remove the alternate identifier provided for boilerplate "Id" property + entityDefinition.Identifiers = entityDefinition.Identifiers.Where( + i => i.IsPrimary + || !(i.IdentifyingPropertyNames.Length == 1 && i.IdentifyingPropertyNames.Single() == "Id")) + .ToArray(); + } + + yield return domainModelDefinitions; + } + } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.Generator/EdFi.Ods.Generator.csproj b/Utilities/Generator/EdFi.Ods.Generator/EdFi.Ods.Generator.csproj new file mode 100644 index 0000000000..a26ed60147 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/EdFi.Ods.Generator.csproj @@ -0,0 +1,31 @@ + + + + Exe + netcoreapp3.1 + + + + + + + + + + + + + + + + + + + + + + Always + + + + diff --git a/Utilities/Generator/EdFi.Ods.Generator/Extensions/StringExtensions.cs b/Utilities/Generator/EdFi.Ods.Generator/Extensions/StringExtensions.cs new file mode 100644 index 0000000000..73bb8a044b --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Extensions/StringExtensions.cs @@ -0,0 +1,128 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System; +using System.Collections.Concurrent; +using System.Security.Cryptography; +using System.Text; +using EdFi.Ods.Generator.Database.NamingConventions; + +namespace EdFi.Ods.Generator.Extensions +{ + public static class StringExtensions + { + private static readonly SHA256 Hasher = SHA256.Create(); + + public static string Truncate(this string text, int length) + { + if (text.Length > length) + { + return text.Substring(0, length); + } + + return text; + } + + public static string ApplyPrefix(this string text, string prefix) + { + // If text is empty/null, or is already prefixed with the supplied prefix, return now + if (string.IsNullOrEmpty(text) || text.StartsWith(prefix)) + { + return text; + } + + return prefix + text; + } + + public static string ApplyLongNameConvention(this PhysicalNameParts physicalNameParts, bool lowerCaseNames = false, int maxLength = 128) + { + if (string.IsNullOrEmpty(physicalNameParts?.Name)) + { + return null; + } + + string rawName = physicalNameParts.ToString(); + + if (rawName.Length <= maxLength) + { + return lowerCaseNames ? rawName.ToLower() : rawName; + } + + return FinalNameByArgs.GetOrAdd( + (rawName, lowerCaseNames, maxLength), + tuple => + { + var (rn, toLower, length) = tuple; + + var truncatedHash = GetTruncatedHash(physicalNameParts.Name); + + var hashPart = + $"_{truncatedHash}{(string.IsNullOrEmpty(physicalNameParts.Suffix) || physicalNameParts.Suffix.StartsWith("_") ? string.Empty : "_")}"; + + int shortenedNameLength = maxLength + - (physicalNameParts.Prefix?.Length ?? 0) + - (physicalNameParts.Suffix?.Length ?? 0) + - hashPart.Length; + + var shortenedNamePart = physicalNameParts.Name.Substring(0, shortenedNameLength); + + var finalName = $"{physicalNameParts.Prefix}{shortenedNamePart}{hashPart}{physicalNameParts.Suffix}"; + + return toLower ? finalName.ToLower() : finalName; + }); + } + + public static string GetTruncatedHash(this string text) + { + var hash = Hasher.ComputeHash(Encoding.UTF8.GetBytes(text)); + + var truncatedHash = BitConverter.ToString(hash).Replace("-", string.Empty).Substring(0, 6).ToLower(); + + return truncatedHash; + } + + private static readonly ConcurrentDictionary<(string, bool, int), string> FinalNameByArgs = + new ConcurrentDictionary<(string, bool, int), string>(); + + public static bool TryTrimSuffix(this string text, string suffix, out string trimmedText) + { + trimmedText = null; + + if (text == null) + { + return false; + } + + int pos = text.LastIndexOf(suffix); + + if (pos < 0) + { + return false; + } + + if (text.Length - pos == suffix.Length) + { + trimmedText = text.Substring(0, pos); + return true; + } + + ; + + return false; + } + + public static string TrimSuffix(this string text, string suffix) + { + string trimmedText; + + if (TryTrimSuffix(text, suffix, out trimmedText)) + { + return trimmedText; + } + + return text; + } + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Helpers/ConfigurationHelper.cs b/Utilities/Generator/EdFi.Ods.Generator/Helpers/ConfigurationHelper.cs new file mode 100644 index 0000000000..b5349d075e --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Helpers/ConfigurationHelper.cs @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System; +using System.IO; +using Microsoft.Extensions.Configuration; + +namespace EdFi.Ods.Generator.Helpers +{ + public static class ConfigurationHelper + { + public static IConfigurationRoot BuildConfiguration() + { + var configRoot = new ConfigurationBuilder() + .SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName) + .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); + + return configRoot.Build(); + } + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Models/CapabilityStatement.cs b/Utilities/Generator/EdFi.Ods.Generator/Models/CapabilityStatement.cs new file mode 100644 index 0000000000..7d9a2f82e1 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Models/CapabilityStatement.cs @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +namespace EdFi.Ods.Generator.Models +{ + public class CapabilityStatement + { + public Rest[] rest { get; set; } + } + + public class Rest + { + public Mode mode { get; set; } + public Resource[] resource { get; set; } + } + + public enum Mode + { + // client, + server + } + + public class Resource + { + public string type { get; set; } + + public bool readHistory { get; set; } + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Modules/GeneratorModule.cs b/Utilities/Generator/EdFi.Ods.Generator/Modules/GeneratorModule.cs new file mode 100644 index 0000000000..49c6182fc6 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Modules/GeneratorModule.cs @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using Autofac; +using EdFi.Ods.Generator.Rendering; +using EdFi.Ods.Generator.Templating; + +namespace EdFi.Ods.Generator.Modules +{ + public class GeneratorModule : Module + { + protected override void Load(ContainerBuilder builder) + { + builder.RegisterType().As(); + + builder.RegisterType().As(); + + builder.RegisterType().As(); + } + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Options.cs b/Utilities/Generator/EdFi.Ods.Generator/Options.cs new file mode 100644 index 0000000000..cac20acbd4 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Options.cs @@ -0,0 +1,114 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using CommandLine; +using EdFi.Ods.Generator.Database; + +namespace EdFi.Ods.Generator +{ + public interface IGeneratorOptions + { + string OutputPath { get; set; } + IEnumerable Properties { get; set; } + IEnumerable Plugins { get; set; } + IDictionary PropertyByName { get; } + // IDictionary ContextValueByName { get; } + } + + public interface IModelOptions + { + IEnumerable ModelPaths { get; set; } + string CapabilityStatementPath { get; set; } + } + + public interface IDatabaseOptions + { + string DatabaseEngine { get; set; } + + string SchemaFilter { get; set; } + } + + public interface IRenderingPropertiesEnhancer + { + void EnhanceProperties(IDictionary properties); + } + + public class Options : IGeneratorOptions, IModelOptions, IDatabaseOptions + { + private readonly Lazy> _propertyByName; + // private readonly Lazy> _contextValueByName; + + public Options() + { + _propertyByName = new Lazy>( + () => + { + return Properties.Select(p => p.Split('=')) + .Where(x => x.Length == 2) + .ToDictionary(x => x[0], x => x[1], StringComparer.OrdinalIgnoreCase); + }); + + // _contextValueByName = new Lazy>( + // () => + // { + // var generalContextValues = Context.Select(p => p.Split('=')) + // .Where(x => x.Length == 2); + // + // var argsContextValues = this.GetType().GetInterfaces().Where(i => i.Name.EndsWith("Options")) + // .SelectMany(i => i.GetProperties().Where(p => p.GetCustomAttribute() != null && p.PropertyType == typeof(string))) + // .Select(p => new[] { p.Name, (string) p.GetValue(this)}) + // .Where(x => !string.IsNullOrEmpty(x[1])); + // + // return generalContextValues + // .Concat(argsContextValues) + // .ToDictionary(x => x[0], x => x[1], StringComparer.OrdinalIgnoreCase); + // }); + } + + [Option('o', "outputPath", Required = true, HelpText = "The base path for rendered output files.")] + public string OutputPath { get; set; } + + [Option('p', "property", HelpText = "Provides a named value to a template for rendering.")] + public IEnumerable Properties { get; set; } + + [Option('c', "context", HelpText = "Provides a named context value for determining which templates should be rendered.")] + public IEnumerable Context { get; set; } + + [Option('p', "plugin")] + public IEnumerable Plugins { get; set; } + + public IDictionary PropertyByName + { + get => _propertyByName.Value; + } + + // public IDictionary ContextValueByName + // { + // get => _contextValueByName.Value; + // } + + // IDatabaseOptions + [Option("databaseEngine", Required = false, HelpText = "The target database engine (e.g. SqlServer or PostgreSql).", Default = "SqlServer")] + public string DatabaseEngine { get; set; } + + [Option("schemaFilter", Required = false, HelpText = "The schema whose artifacts should be included in code generation.", Default = "edfi")] + public string SchemaFilter { get; set; } + + // IModelOptions + [Option("model", HelpText = "The path to the API model file from MetaEd.")] + public IEnumerable ModelPaths { get; set; } + + [Option("capabilities", Required = false, HelpText = "Path to the capability statement to use for model-based generation.")] + public string CapabilityStatementPath { get; set; } + } + + // [AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)] + // sealed class RenderingContextAttribute : Attribute { } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Program.cs b/Utilities/Generator/EdFi.Ods.Generator/Program.cs new file mode 100644 index 0000000000..50c4f75f7e --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Program.cs @@ -0,0 +1,186 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +using Autofac; +using CommandLine; +using EdFi.Ods.Generator.Helpers; +using EdFi.Ods.Generator.Modules; +using EdFi.Ods.Generator.Rendering; +using log4net; +using log4net.Config; +using Weikio.PluginFramework.Abstractions; +using Weikio.PluginFramework.Catalogs; + +namespace EdFi.Ods.Generator +{ + public static class ReturnCodes + { + public const int Success = 0; + public const int Failure = 1; + } + + internal class Program + { + private static ILog _logger; + + private static readonly CancellationTokenSource CancellationTokenSource = new CancellationTokenSource(); + + private static async Task Main(string[] args) + { + ConfigureLogging(); + _logger = LogManager.GetLogger(typeof(Program)); + + int result = 0; + + Options options = null; + + new Parser( + config => + { + config.CaseInsensitiveEnumValues = true; + config.CaseSensitive = false; + }).ParseArguments(args) + .WithParsed(opts => options = opts) + .WithNotParsed( + errs => + { + Console.WriteLine("Invalid options were entered."); + Console.WriteLine(errs.ToString()); + result = -1; + }); + + if (result != ReturnCodes.Success) + { + return result; + } + + var container = InitializeContainer(options); + + Console.CancelKeyPress += (o, e) => + { + _logger.Warn("Ctrl-C Pressed. Stopping all threads."); + CancellationTokenSource.Cancel(); + e.Cancel = true; + }; + + var stopwatch = new Stopwatch(); + + try + { + stopwatch.Start(); + + _logger.Info("Starting generation."); + + var cancellationToken = CancellationTokenSource.Token; + + await container.Resolve() + .RenderAllAsync(cancellationToken) + .ConfigureAwait(false); + + stopwatch.Stop(); + + _logger.Info($"Completed generation in {stopwatch.Elapsed.ToString()}."); + + return ReturnCodes.Success; + } + catch (Exception e) + { + _logger.Error(e.ToString()); + + return ReturnCodes.Failure; + } + finally + { + container?.Dispose(); + } + } + + private static void ConfigureLogging() + { + var assembly = typeof(Program).GetTypeInfo().Assembly; + + string configPath = Path.Combine(Path.GetDirectoryName(assembly.Location), "log4net.config"); + + XmlConfigurator.Configure(LogManager.GetRepository(assembly), new FileInfo(configPath)); + } + + private static IContainer InitializeContainer(Options options) + { + // Register components with Autofac + var containerBuilder = new ContainerBuilder(); + containerBuilder.RegisterInstance(options).AsImplementedInterfaces(); + containerBuilder.RegisterModule(new GeneratorModule()); + + // Add the Configuration to the container + var configuration = ConfigurationHelper.BuildConfiguration(); + containerBuilder.RegisterInstance(configuration); + + // Handle plugins with paths through Options / command-line parameter + var pluginCatalogs = GetPluginCatalogs(options.Plugins).ToArray(); + var compositePluginCatalog = new CompositePluginCatalog(pluginCatalogs); + compositePluginCatalog.Initialize(); + + var plugins = compositePluginCatalog.GetPlugins(); + + var pluginTypes = new HashSet(); + + foreach (var plugin in plugins) + { + if (pluginTypes.Add(plugin.Type)) + { + var pluginInstance = (IRenderingPlugin) Activator.CreateInstance(plugin.Type); + pluginInstance?.Initialize(containerBuilder); + + containerBuilder.RegisterInstance(plugin); + } + } + + return containerBuilder.Build(); + } + + private static IEnumerable GetPluginCatalogs(IEnumerable pluginsArgument) + { + // Start with the current assembly's built-in plugins + var builtinAssemblyPluginCatalog = new AssemblyPluginCatalog(Assembly.GetExecutingAssembly(),type => type.Implements()); + yield return builtinAssemblyPluginCatalog; + + // Get the base path for any relative paths supplied + string relativePathBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + + foreach (string pluginArgument in pluginsArgument) + { + string testPath = !Path.IsPathFullyQualified(pluginArgument) && !Path.IsPathRooted(pluginArgument) && relativePathBase != null + ? Path.Combine(relativePathBase, pluginArgument) + : pluginArgument; + + if (File.Exists(testPath)) + { + yield return new AssemblyPluginCatalog(testPath, type => type.Implements()); + } + else if (Directory.Exists(testPath)) + { + yield return new FolderPluginCatalog(testPath, type => type.Implements(), + new FolderPluginCatalogOptions { IncludeSubfolders = false }); + + string binSubfolder = Path.Combine(testPath, "bin"); + + if (Directory.Exists(binSubfolder)) + { + yield return new FolderPluginCatalog(binSubfolder, type => type.Implements(), + new FolderPluginCatalogOptions { IncludeSubfolders = true }); + } + } + else + { + throw new ArgumentException( + $"Plugin '{pluginArgument}' could not be resolved as a relative or full path to an assembly or plugins folder."); + } + } + } + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Properties/launchSettings.json b/Utilities/Generator/EdFi.Ods.Generator/Properties/launchSettings.json new file mode 100644 index 0000000000..9092c2fc5f --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Properties/launchSettings.json @@ -0,0 +1,10 @@ +{ + "profiles": { + "Generate ADVISER LDS": { + "commandName": "Project", + "commandLineArgs": "-o C:\\Temp\\Generated -d SqlServer -m \"C:\\Projects\\EdFi\\Models\\ApiModel-v3.2.0-c.json\" -p ContextSchoolYear=2021", + "environmentVariables": { + } + } + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Rendering/IRenderingManager.cs b/Utilities/Generator/EdFi.Ods.Generator/Rendering/IRenderingManager.cs new file mode 100644 index 0000000000..ab492c602b --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Rendering/IRenderingManager.cs @@ -0,0 +1,10 @@ +using System.Threading; +using System.Threading.Tasks; + +namespace EdFi.Ods.Generator.Rendering +{ + public interface IRenderingManager + { + Task RenderAllAsync(CancellationToken cancellationToken); + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.Generator/Rendering/IRenderingPlugin.cs b/Utilities/Generator/EdFi.Ods.Generator/Rendering/IRenderingPlugin.cs new file mode 100644 index 0000000000..abd7c3a2b5 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Rendering/IRenderingPlugin.cs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using Autofac; + +namespace EdFi.Ods.Generator.Rendering +{ + public interface IRenderingPlugin + { + void Initialize(ContainerBuilder containerBuilder); + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Rendering/IRenderingsManifestProvider.cs b/Utilities/Generator/EdFi.Ods.Generator/Rendering/IRenderingsManifestProvider.cs new file mode 100644 index 0000000000..b626180b26 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Rendering/IRenderingsManifestProvider.cs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System.Collections.Generic; +using System.Reflection; +using System.Threading.Tasks; + +namespace EdFi.Ods.Generator.Rendering +{ + public interface IRenderingsManifestProvider + { + Task> GetRenderingsAsync(Assembly pluginAssembly); + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Rendering/RenderingHelper.cs b/Utilities/Generator/EdFi.Ods.Generator/Rendering/RenderingHelper.cs new file mode 100644 index 0000000000..965291deda --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Rendering/RenderingHelper.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text.RegularExpressions; +using log4net; + +namespace EdFi.Ods.Generator.Rendering +{ + public static class RenderingHelper + { + private static readonly ILog Logger = LogManager.GetLogger(typeof(RenderingHelper)); + + public static string ApplyPropertiesToParameterMarkers(IDictionary propertyByName, string textWithParameterMarkers) + { + string finalOutputFileName = textWithParameterMarkers; + + // Apply properties to parameter markers + foreach (var kvp in propertyByName) + { + string propertyMarker = $"{{{{{kvp.Key}}}}}"; + + if (finalOutputFileName.Contains(propertyMarker)) + { + finalOutputFileName = finalOutputFileName.Replace(propertyMarker, kvp.Value); + } + } + + return finalOutputFileName; + } + + public static bool ShouldRunEnhancer(object enhancer, IDictionary renderingContext) + { + var conditions = enhancer.GetType().GetCustomAttributes(); + + return conditions.All( + rc => + { + if (!renderingContext.TryGetValue(rc.Name, out string contextValue)) + { + Logger.Debug( + $"Condition for '{rc.Name}' of '{rc.Pattern}' on enhancer '{enhancer.GetType().Name}' was not satisfied by the global rendering context."); + + return false; + } + + return Regex.IsMatch(contextValue, rc.Pattern, RegexOptions.IgnoreCase); + }); + } + } + + [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)] + public sealed class RenderConditionAttribute : Attribute + { + public RenderConditionAttribute(string name, string pattern) + { + Name = name; + Pattern = pattern; + } + + public string Name { get; } + public string Pattern { get; } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.Generator/Rendering/RenderingManager.cs b/Utilities/Generator/EdFi.Ods.Generator/Rendering/RenderingManager.cs new file mode 100644 index 0000000000..96fa0c746f --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Rendering/RenderingManager.cs @@ -0,0 +1,199 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using EdFi.Ods.Generator.Templating; +using log4net; +using Stubble.Core; +using Stubble.Core.Builders; +using Stubble.Core.Settings; +using Weikio.PluginFramework.Abstractions; + +namespace EdFi.Ods.Generator.Rendering +{ + public class RenderingManager : IRenderingManager + { + private readonly ILog _logger = LogManager.GetLogger(typeof(RenderingManager)); + + private readonly IList _renderingPlugins; + private readonly ITemplatesProvider _templatesProvider; + private readonly IRenderingsManifestProvider _renderingsManifestProvider; + private readonly IList _templateModelProviders; + private readonly string _outputPath; + + private readonly Lazy _stubbleRender; + private readonly RenderSettings _renderSettings; + + private readonly IDictionary _optionsPropertyByName; + + public RenderingManager( + IList renderingPlugins, + ITemplatesProvider templatesProvider, + IRenderingsManifestProvider renderingsManifestProvider, + IList templateModelProviders, + IGeneratorOptions generatorOptions, + IList renderingPropertiesEnhancers) + { + _renderingPlugins = renderingPlugins; + _templatesProvider = templatesProvider; + _renderingsManifestProvider = renderingsManifestProvider; + _templateModelProviders = templateModelProviders; + + _outputPath = generatorOptions.OutputPath; + + _optionsPropertyByName = generatorOptions.PropertyByName; + + foreach (var enhancer in renderingPropertiesEnhancers) + { + enhancer.EnhanceProperties(_optionsPropertyByName); + } + + _stubbleRender = new Lazy( + () => new StubbleBuilder() + .Configure( + settings => + { + settings.SetMaxRecursionDepth(512); + settings.SetIgnoreCaseOnKeyLookup(true); + } + ) + .Build()); + + _renderSettings = new RenderSettings {SkipHtmlEncoding = true}; + } + + public async Task RenderAllAsync(CancellationToken cancellationToken) + { + if (cancellationToken == null) + { + throw new ArgumentNullException(nameof(cancellationToken)); + } + + bool renderingSuccessful = true; + + _logger.Debug("Generation starting."); + + foreach (var renderingPlugin in _renderingPlugins) + { + // Get the template contents for the plugin, by name + var pluginAssembly = renderingPlugin.Type.Assembly; + var templateContentByName = _templatesProvider.GetTemplates(pluginAssembly); + + var renderings = await _renderingsManifestProvider.GetRenderingsAsync(pluginAssembly); + + if (!renderings.Any()) + { + continue; + } + + _logger.Debug($"Global rendering context: {string.Join(", ", _optionsPropertyByName.Select(kvp => $"{kvp.Key}={kvp.Value}"))}"); + + var matchingRenderings = renderings.Where(r => r.Conditions.All( + c => + { + if (!_optionsPropertyByName.TryGetValue(c.Key, out string optionValue)) + { + _logger.Debug($"Condition for '{c.Key}' of '{c.Value}' on template '{r.Template}' was not satisfied by the global rendering context."); + return false; + } + + return Regex.IsMatch(optionValue, c.Value, RegexOptions.IgnoreCase); + })).ToArray(); + + if (!matchingRenderings.Any()) + { + _logger.Warn($"No renderings matched the supplied context."); + continue; + } + + _logger.Info($"The following templates will be rendered from assembly '{renderingPlugin.Assembly.FullName}':{Environment.NewLine} {string.Join($"{Environment.NewLine} ", matchingRenderings.Select(r => RenderingHelper.ApplyPropertiesToParameterMarkers(_optionsPropertyByName, r.Template)))}"); + + foreach (var rendering in matchingRenderings) + { + string templateName = RenderingHelper.ApplyPropertiesToParameterMarkers( + _optionsPropertyByName, + rendering.Template); + + if (!templateContentByName.TryGetValue(templateName, out string templateContent)) + { + _logger.Error($"Unable to find template '{templateName}' in plugin assembly '{pluginAssembly.FullName}'."); + renderingSuccessful = false; + continue; + } + + // Get the model provider, prioritizing the plugin assembly first + var templateModelProvider = _templateModelProviders.Where(p => p.GetType().Assembly == pluginAssembly) + .Where(p => IsTemplateModelProviderForProviderName(p, rendering.ModelProvider)) + .Concat(_templateModelProviders.Where(p => IsTemplateModelProviderForProviderName(p, rendering.ModelProvider))) + .FirstOrDefault(); + + if (templateModelProvider == null) + { + _logger.Error($@"Unable to find model provider '{rendering.ModelProvider}' for template '{templateName}' in plugin assembly '{pluginAssembly.FullName}'."); + renderingSuccessful = false; + continue; + } + + // Get the template model + var templateModel = templateModelProvider.GetTemplateModel(_optionsPropertyByName); + + // Determine output filename + string outputFileName = Path.IsPathRooted(rendering.OutputPath) + ? rendering.OutputPath + : Path.Combine(_outputPath, rendering.OutputPath); + + outputFileName = RenderingHelper.ApplyPropertiesToParameterMarkers(_optionsPropertyByName, outputFileName); + + // Render the template + _logger.Info($"Rendering content for template '{templateName}'..."); + + // Process all the templates for parameter markers and pass to the rendering process as the partials + var partials = templateContentByName + .Select(kvp => new KeyValuePair(RenderingHelper.ApplyPropertiesToParameterMarkers(_optionsPropertyByName, kvp.Key), kvp.Value)) + .ToDictionary(kvp => kvp.Key, kvp => kvp.Value, StringComparer.OrdinalIgnoreCase); + + string renderedContent = await RenderAsync(templateContent, templateModel, partials); + + string outputFolder = Path.GetDirectoryName(outputFileName); + + if (!Directory.Exists(outputFolder)) + { + _logger.Info($"Creating destination folder '{outputFolder}'..."); + Directory.CreateDirectory(outputFolder); + } + + _logger.Info($"Writing '{outputFileName}'..."); + await using var streamWriter = new StreamWriter(outputFileName); + await streamWriter.WriteAsync(renderedContent).ConfigureAwait(false); + } + } + + _logger.Debug($"Generation complete."); + + return renderingSuccessful; + + bool IsTemplateModelProviderForProviderName(ITemplateModelProvider p, string renderingModelProvider) + { + var result = p.GetType().Name.Equals(renderingModelProvider, StringComparison.OrdinalIgnoreCase) + || p.GetType().Name.Equals(renderingModelProvider + "TemplateModelProvider", StringComparison.OrdinalIgnoreCase); + + _logger.Debug($"Evaluated template model provider '{p.GetType().Name}' against model provider name '{renderingModelProvider}': {result}"); + + return result; + } + } + + private async Task RenderAsync(string templateContent, object templateModel, IDictionary partials) + { + string renderedContent = await _stubbleRender + .Value + .RenderAsync(templateContent, templateModel, partials, _renderSettings) + .ConfigureAwait(false); + + return renderedContent; + } + } +} \ No newline at end of file diff --git a/Utilities/Generator/EdFi.Ods.Generator/Rendering/RenderingsManifest.cs b/Utilities/Generator/EdFi.Ods.Generator/Rendering/RenderingsManifest.cs new file mode 100644 index 0000000000..cee026b654 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Rendering/RenderingsManifest.cs @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System.Collections.Generic; + +namespace EdFi.Ods.Generator.Rendering +{ + public class RenderingsManifest + { + public IList Renderings { get; set; } + } + + public class Rendering + { + public string Template { get; set; } + + public string ModelProvider { get; set; } + + public string OutputPath { get; set; } + + public IDictionary Conditions { get; set; } + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Rendering/RenderingsManifestProvider.cs b/Utilities/Generator/EdFi.Ods.Generator/Rendering/RenderingsManifestProvider.cs new file mode 100644 index 0000000000..fd46ce9407 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Rendering/RenderingsManifestProvider.cs @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Threading.Tasks; +using log4net; +using Newtonsoft.Json; + +namespace EdFi.Ods.Generator.Rendering +{ + public class RenderingsManifestProvider : IRenderingsManifestProvider + { + private readonly ILog _logger = LogManager.GetLogger(typeof(RenderingsManifestProvider)); + + public async Task> GetRenderingsAsync(Assembly pluginAssembly) + { + // Get the renderings manifest + string renderingsManifestResourceName = $"{pluginAssembly.GetName().Name}.renderings.json"; + + var renderingsManifestStream = pluginAssembly.GetManifestResourceStream(renderingsManifestResourceName); + + if (renderingsManifestStream == null) + { + _logger.Debug($@"No 'renderings.settings' file was found in plugin assembly '{pluginAssembly.FullName}'."); + + return new Rendering[0]; + } + + string renderingsManifestContents = await GetStreamContents(renderingsManifestStream); + + var renderingSettings = JsonConvert.DeserializeObject(renderingsManifestContents); + + return renderingSettings.Renderings; + + async Task GetStreamContents(Stream stream) + { + await using (stream) + { + using (StreamReader sr = new StreamReader(stream)) + { + return await sr.ReadToEndAsync(); + } + } + } + } + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Templating/ITemplateModelProvider.cs b/Utilities/Generator/EdFi.Ods.Generator/Templating/ITemplateModelProvider.cs new file mode 100644 index 0000000000..57a8a41196 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Templating/ITemplateModelProvider.cs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System.Collections.Generic; + +namespace EdFi.Ods.Generator.Templating +{ + public interface ITemplateModelProvider + { + object GetTemplateModel(IDictionary properties); + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Templating/ITemplatesProvider.cs b/Utilities/Generator/EdFi.Ods.Generator/Templating/ITemplatesProvider.cs new file mode 100644 index 0000000000..8ea21b3d28 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Templating/ITemplatesProvider.cs @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System.Collections.Generic; +using System.Reflection; + +namespace EdFi.Ods.Generator.Templating +{ + public interface ITemplatesProvider + { + IDictionary GetTemplates(Assembly assembly); + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/Templating/TemplatesProvider.cs b/Utilities/Generator/EdFi.Ods.Generator/Templating/TemplatesProvider.cs new file mode 100644 index 0000000000..88b0a9b890 --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/Templating/TemplatesProvider.cs @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: Apache-2.0 +// Licensed to the Ed-Fi Alliance under one or more agreements. +// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. +// See the LICENSE and NOTICES files in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using EdFi.Common.Extensions; +using EdFi.Ods.Common.Utils.Extensions; +using log4net; + +namespace EdFi.Ods.Generator.Templating +{ + public class TemplatesProvider : ITemplatesProvider + { + private readonly ILog _logger = LogManager.GetLogger(typeof(TemplatesProvider)); + + public IDictionary GetTemplates(Assembly assembly) + { + var templateContentByTemplateName = new Dictionary(); + + string templatesBasePath = $"{assembly.GetName().Name}.Templates."; + + var templateResourceNames = assembly.GetManifestResourceNames() + .Where(rn => rn.StartsWithIgnoreCase(templatesBasePath) + && rn.EndsWithIgnoreCase(".mustache")) + .ToList(); + + foreach (string templateResourceName in templateResourceNames) + { + _logger.Debug($"Loading template '{templateResourceName}'..."); + + string templateContent = assembly.ReadResource(templateResourceName); + + if (string.IsNullOrEmpty(templateContent)) + { + _logger.Error($"Unable to load the template for '{templateResourceName}'."); + throw new ArgumentException($"Unable to load the template for '{templateResourceName}'."); + } + + // get the name of the template for the key + // eg EdFi.CodeGen.Mustache.AggregateLoaders.mustache -> AggregateLoaders + string templateName = templateResourceName + .Replace(templatesBasePath, string.Empty) + .Replace(".mustache", string.Empty); + + _logger.Debug($"Caching template '{templateName}'..."); + + templateContentByTemplateName.Add(templateName, templateContent); + } + + return templateContentByTemplateName; + } + } +} diff --git a/Utilities/Generator/EdFi.Ods.Generator/log4net.config b/Utilities/Generator/EdFi.Ods.Generator/log4net.config new file mode 100644 index 0000000000..1cbee96adc --- /dev/null +++ b/Utilities/Generator/EdFi.Ods.Generator/log4net.config @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests/EdFi.Ods.WebApi.CompositeSpecFlowTests/EdFi.Ods.WebApi.CompositeSpecFlowTests.csproj b/tests/EdFi.Ods.WebApi.CompositeSpecFlowTests/EdFi.Ods.WebApi.CompositeSpecFlowTests.csproj index 58cd8b4292..fa7027f36d 100644 --- a/tests/EdFi.Ods.WebApi.CompositeSpecFlowTests/EdFi.Ods.WebApi.CompositeSpecFlowTests.csproj +++ b/tests/EdFi.Ods.WebApi.CompositeSpecFlowTests/EdFi.Ods.WebApi.CompositeSpecFlowTests.csproj @@ -30,7 +30,7 @@ - + diff --git a/tests/EdFi.Ods.WebApi.IntegrationTests/EdFi.Ods.WebApi.IntegrationTests.csproj b/tests/EdFi.Ods.WebApi.IntegrationTests/EdFi.Ods.WebApi.IntegrationTests.csproj index c36b0f0fa3..f3f28aac24 100644 --- a/tests/EdFi.Ods.WebApi.IntegrationTests/EdFi.Ods.WebApi.IntegrationTests.csproj +++ b/tests/EdFi.Ods.WebApi.IntegrationTests/EdFi.Ods.WebApi.IntegrationTests.csproj @@ -17,7 +17,7 @@ - +