Esempio n. 1
0
        internal override void RevertMigration(
            string migrationId,
            DbMigration migration,
            XDocument targetModel)
        {
            IEnumerable <MigrationOperation> systemOperations = Enumerable.Empty <MigrationOperation>();
            string    defaultSchema = DbMigrator.GetDefaultSchema(migration);
            XDocument historyModel1 = this.GetHistoryModel(defaultSchema);

            if (object.ReferenceEquals((object)targetModel, (object)this._emptyModel.Value) && !this._historyRepository.IsShared())
            {
                systemOperations = (IEnumerable <MigrationOperation>) this._modelDiffer.Diff(historyModel1, this._emptyModel.Value, (Lazy <ModificationCommandTreeGenerator>)null, (MigrationSqlGenerator)null, (string)null, (string)null);
            }
            else
            {
                string lastDefaultSchema = this.GetLastDefaultSchema(migrationId);
                if (!string.Equals(lastDefaultSchema, defaultSchema, StringComparison.Ordinal))
                {
                    XDocument historyModel2 = this.GetHistoryModel(lastDefaultSchema);
                    systemOperations = (IEnumerable <MigrationOperation>) this._modelDiffer.Diff(historyModel1, historyModel2, (Lazy <ModificationCommandTreeGenerator>)null, (MigrationSqlGenerator)null, (string)null, (string)null);
                }
            }
            migration.Down();
            this.ExecuteOperations(migrationId, new VersionedModel(targetModel, (string)null), migration.Operations, systemOperations, true, false);
        }
Esempio n. 2
0
        internal override void ApplyMigration(DbMigration migration, DbMigration lastMigration)
        {
            IMigrationMetadata migrationMetadata = (IMigrationMetadata)migration;
            VersionedModel     sourceModel1      = this.GetLastModel(lastMigration, migrationMetadata.Id);
            VersionedModel     sourceModel2      = migration.GetSourceModel();
            VersionedModel     targetModel       = migration.GetTargetModel();

            if (sourceModel2 != null && this.IsModelOutOfDate(sourceModel2.Model, lastMigration))
            {
                base.AutoMigrate(migrationMetadata.Id.ToAutomaticMigrationId(), sourceModel1, sourceModel2, false);
                sourceModel1 = sourceModel2;
            }
            string    defaultSchema = DbMigrator.GetDefaultSchema(migration);
            XDocument historyModel  = this.GetHistoryModel(defaultSchema);
            IEnumerable <MigrationOperation> systemOperations = Enumerable.Empty <MigrationOperation>();

            if (object.ReferenceEquals((object)sourceModel1.Model, (object)this._emptyModel.Value) && !base.HistoryExists())
            {
                systemOperations = (IEnumerable <MigrationOperation>) this._modelDiffer.Diff(this._emptyModel.Value, historyModel, (Lazy <ModificationCommandTreeGenerator>)null, (MigrationSqlGenerator)null, (string)null, (string)null);
            }
            else
            {
                string lastDefaultSchema = this.GetLastDefaultSchema(migrationMetadata.Id);
                if (!string.Equals(lastDefaultSchema, defaultSchema, StringComparison.Ordinal))
                {
                    systemOperations = (IEnumerable <MigrationOperation>) this._modelDiffer.Diff(this.GetHistoryModel(lastDefaultSchema), historyModel, (Lazy <ModificationCommandTreeGenerator>)null, (MigrationSqlGenerator)null, (string)null, (string)null);
                }
            }
            migration.Up();
            this.ExecuteOperations(migrationMetadata.Id, targetModel, migration.Operations, systemOperations, false, false);
        }
Esempio n. 3
0
        public DbMigrator CreateMigrator <TContext>(
            DbMigration migration,
            IEnumerable <Tuple <string, MigrationSqlGenerator> > sqlGenerators = null,
            bool automaticDataLossEnabled = false)
            where TContext : DbContext
        {
            using (var context = CreateContext <TContext>())
            {
                var operations = migration.GetOperations();

                var generatedMigration
                    = CodeGenerator
                      .Generate(
                          GenerateUniqueMigrationName(migration.GetType().Name),
                          operations,
                          Convert.ToBase64String(CompressModel(GetModel(context))),
                          Convert.ToBase64String(CompressModel(GetModel(context))),
                          "System.Data.Entity.Migrations",
                          migration.GetType().Name);

                return(new DbMigrator(CreateMigrationsConfiguration <TContext>(
                                          scaffoldedMigrations: generatedMigration,
                                          sqlGenerators: sqlGenerators,
                                          automaticDataLossEnabled: automaticDataLossEnabled)));
            }
        }
Esempio n. 4
0
        internal override void RevertMigration(
            string migrationId, DbMigration migration, XDocument targetModel)
        {
            var systemOperations = Enumerable.Empty <MigrationOperation>();

            var migrationSchema = GetDefaultSchema(migration);
            var historyModel    = GetHistoryModel(migrationSchema);

            if (ReferenceEquals(targetModel, _emptyModel.Value) &&
                !_historyRepository.IsShared())
            {
                systemOperations = _modelDiffer.Diff(historyModel, targetModel);
            }
            else
            {
                var lastMigrationSchema = GetLastDefaultSchema(migrationId);

                if (!string.Equals(lastMigrationSchema, migrationSchema, StringComparison.Ordinal))
                {
                    var lastHistoryModel = GetHistoryModel(lastMigrationSchema);

                    systemOperations = _modelDiffer.Diff(historyModel, lastHistoryModel);
                }
            }

            migration.Down();

            ExecuteOperations(migrationId, targetModel, migration.Operations, systemOperations, downgrading: true);
        }
Esempio n. 5
0
        private bool IsModelOutOfDate(XDocument model, DbMigration lastMigration)
        {
            DebugCheck.NotNull(model);

            var sourceModel = GetLastModel(lastMigration);

            return(_modelDiffer.Diff(sourceModel, model).Any());
        }
Esempio n. 6
0
        public static IList <MigrationOperation> GetOperations(this DbMigration migration)
        {
            var migrationOperations = (IList <MigrationOperation>)_operationsProperty.GetValue(migration, null);

            if (!migrationOperations.Any())
            {
                migration.Up();
            }

            return(migrationOperations);
        }
Esempio n. 7
0
        internal override void Upgrade(
            IEnumerable <string> pendingMigrations, string targetMigrationId, string lastMigrationId)
        {
            DbMigration lastMigration = null;

            if (lastMigrationId != null)
            {
                lastMigration = _migrationAssembly.GetMigration(lastMigrationId);
            }

            foreach (var pendingMigration in pendingMigrations)
            {
                var migration = _migrationAssembly.GetMigration(pendingMigration);

                base.ApplyMigration(migration, lastMigration);

                lastMigration = migration;

                _emptyMigrationNeeded = false;

                if (pendingMigration.EqualsIgnoreCase(targetMigrationId))
                {
                    break;
                }
            }

            if (string.IsNullOrWhiteSpace(targetMigrationId) &&
                ((_emptyMigrationNeeded && _configuration.AutomaticMigrationsEnabled) ||
                 IsModelOutOfDate(_currentModel, lastMigration)))
            {
                if (!_configuration.AutomaticMigrationsEnabled)
                {
                    throw Error.AutomaticDisabledException();
                }

                base.AutoMigrate(
                    MigrationAssembly.CreateMigrationId(
                        _calledByCreateDatabase
                            ? Strings.InitialCreate
                            : Strings.AutomaticMigration),
                    _calledByCreateDatabase
                        ? _emptyModel.Value
                        : GetLastModel(lastMigration),
                    _currentModel,
                    false);
            }

            // Context may not be constructable when Migrations is being called by DbContext CreateDatabase
            // and the config cannot have Seed data anyway, so avoid doing model diff and creating the context to seed.
            if (!_calledByCreateDatabase && !IsModelOutOfDate(_currentModel, lastMigration))
            {
                base.SeedDatabase();
            }
        }
Esempio n. 8
0
        internal override void ApplyMigration(DbMigration migration, DbMigration lastMigration)
        {
            DebugCheck.NotNull(migration);

            var migrationMetadata = (IMigrationMetadata)migration;
            var compressor        = new ModelCompressor();

            var lastModel   = GetLastModel(lastMigration, migrationMetadata.Id);
            var targetModel = compressor.Decompress(Convert.FromBase64String(migrationMetadata.Target));

            if (migrationMetadata.Source != null)
            {
                var sourceModel
                    = compressor.Decompress(Convert.FromBase64String(migrationMetadata.Source));

                if (IsModelOutOfDate(sourceModel, lastMigration))
                {
                    base.AutoMigrate(
                        migrationMetadata.Id.ToAutomaticMigrationId(),
                        lastModel,
                        sourceModel,
                        downgrading: false);

                    lastModel = sourceModel;
                }
            }

            var migrationSchema = GetDefaultSchema(migration);
            var historyModel    = GetHistoryModel(migrationSchema);

            var systemOperations = Enumerable.Empty <MigrationOperation>();

            if (ReferenceEquals(lastModel, _emptyModel.Value) &&
                !base.HistoryExists())
            {
                systemOperations = _modelDiffer.Diff(lastModel, historyModel);
            }
            else
            {
                var lastMigrationSchema = GetLastDefaultSchema(migrationMetadata.Id);

                if (!string.Equals(lastMigrationSchema, migrationSchema, StringComparison.Ordinal))
                {
                    var lastHistoryModel = GetHistoryModel(lastMigrationSchema);

                    systemOperations = _modelDiffer.Diff(lastHistoryModel, historyModel);
                }
            }

            migration.Up();

            ExecuteOperations(migrationMetadata.Id, targetModel, migration.Operations, systemOperations, false);
        }
Esempio n. 9
0
 private static string GetDefaultSchema(DbMigration migration)
 {
     try
     {
         string str = new ResourceManager(migration.GetType()).GetString("DefaultSchema");
         return(!string.IsNullOrWhiteSpace(str) ? str : "dbo");
     }
     catch (MissingManifestResourceException ex)
     {
         return("dbo");
     }
 }
Esempio n. 10
0
        internal override void Upgrade(
            IEnumerable <string> pendingMigrations, string targetMigrationId, string lastMigrationId)
        {
            DbMigration lastMigration = null;

            if (lastMigrationId != null)
            {
                lastMigration = _migrationAssembly.GetMigration(lastMigrationId);
            }

            foreach (var pendingMigration in pendingMigrations)
            {
                var migration = _migrationAssembly.GetMigration(pendingMigration);

                base.ApplyMigration(migration, lastMigration);

                lastMigration = migration;

                _emptyMigrationNeeded = false;

                if (pendingMigration.EqualsIgnoreCase(targetMigrationId))
                {
                    break;
                }
            }

            if (string.IsNullOrWhiteSpace(targetMigrationId) &&
                ((_emptyMigrationNeeded && _configuration.AutomaticMigrationsEnabled) ||
                 IsModelOutOfDate(_currentModel, lastMigration)))
            {
                if (!_configuration.AutomaticMigrationsEnabled)
                {
                    throw Error.AutomaticDisabledException();
                }

                base.AutoMigrate(
                    MigrationAssembly.CreateMigrationId(
                        _calledByCreateDatabase
                            ? Strings.InitialCreate
                            : Strings.AutomaticMigration),
                    _calledByCreateDatabase
                        ? _emptyModel.Value
                        : GetLastModel(lastMigration),
                    _currentModel,
                    false);
            }

            if (!IsModelOutOfDate(_currentModel, lastMigration))
            {
                base.SeedDatabase();
            }
        }
        public static void CreateFullTextIndex(
            this DbMigration migration,
            string table,
            string index,
            string[] columns)
        {
            var op = new CreateFullTextIndexOperation
            {
                Table   = table,
                Index   = index,
                Columns = columns
            };

            ((IDbMigration)migration).AddOperation(op);
        }
Esempio n. 12
0
        private static string GetDefaultSchema(DbMigration migration)
        {
            DebugCheck.NotNull(migration);

            try
            {
                var defaultSchema = new ResourceManager(migration.GetType()).GetString(DefaultSchemaResourceKey);

                return(!string.IsNullOrWhiteSpace(defaultSchema) ? defaultSchema : EdmModelExtensions.DefaultSchema);
            }
            catch (MissingManifestResourceException)
            {
                // Upgrade scenario, no default schema resource found
                return(EdmModelExtensions.DefaultSchema);
            }
        }
Esempio n. 13
0
        internal override void ApplyMigration(DbMigration migration, DbMigration lastMigration)
        {
            var migrationMetadata = (IMigrationMetadata)migration;
            var compressor        = new ModelCompressor();

            var lastModel   = GetLastModel(lastMigration, migrationMetadata.Id);
            var targetModel = compressor.Decompress(Convert.FromBase64String(migrationMetadata.Target));

            if (migrationMetadata.Source != null)
            {
                var sourceModel
                    = compressor.Decompress(Convert.FromBase64String(migrationMetadata.Source));

                if (IsModelOutOfDate(sourceModel, lastMigration))
                {
                    base.AutoMigrate(
                        migrationMetadata.Id.ToAutomaticMigrationId(),
                        lastModel,
                        sourceModel,
                        downgrading: false);

                    lastModel = sourceModel;
                }
            }

            bool?includeSystemOps = null;
            var  isFirstMigration = ReferenceEquals(lastModel, _emptyModel.Value);

            if (isFirstMigration && !_historyRepository.IsShared())
            {
                includeSystemOps = true;

                if (!targetModel.HasSystemOperations())
                {
                    // upgrade scenario, inject the history model
                    AttachHistoryModel(targetModel);
                }
            }

            var systemOperations
                = _modelDiffer.Diff(lastModel, targetModel, includeSystemOps)
                  .Where(o => o.IsSystem);

            migration.Up();

            ExecuteOperations(migrationMetadata.Id, targetModel, migration.Operations.Concat(systemOperations), false);
        }
Esempio n. 14
0
        public DbMigrator CreateMigrator <TContext>(DbMigration migration)
            where TContext : DbContext
        {
            var modelCompressor = new ModelCompressor();

            var generatedMigration
                = CodeGenerator
                  .Generate(
                      UtcNowGenerator.UtcNowAsMigrationIdTimestamp() + "_" + migration.GetType().Name,
                      migration.GetOperations(),
                      Convert.ToBase64String(modelCompressor.Compress(CreateContext <TContext>().GetModel())),
                      Convert.ToBase64String(modelCompressor.Compress(CreateContext <TContext>().GetModel())),
                      "System.Data.Entity.Migrations",
                      migration.GetType().Name);

            return(new DbMigrator(CreateMigrationsConfiguration <TContext>(scaffoldedMigrations: generatedMigration)));
        }
Esempio n. 15
0
        public DbMigrator CreateMigrator <TContext>(DbMigration migration)
            where TContext : DbContext
        {
            using (var context = CreateContext <TContext>())
            {
                var generatedMigration
                    = CodeGenerator
                      .Generate(
                          GenerateUniqueMigrationName(migration.GetType().Name),
                          migration.GetOperations(),
                          Convert.ToBase64String(CompressModel(GetModel(context))),
                          Convert.ToBase64String(CompressModel(GetModel(context))),
                          "System.Data.Entity.Migrations",
                          migration.GetType().Name);

                return(new DbMigrator(CreateMigrationsConfiguration <TContext>(scaffoldedMigrations: generatedMigration)));
            }
        }
Esempio n. 16
0
        private VersionedModel GetLastModel(
            DbMigration lastMigration,
            string currentMigrationId = null)
        {
            if (lastMigration != null)
            {
                return(lastMigration.GetTargetModel());
            }
            string    migrationId;
            string    productVersion;
            XDocument lastModel = this._historyRepository.GetLastModel(out migrationId, out productVersion, (string)null);

            if (lastModel != null && (currentMigrationId == null || string.CompareOrdinal(migrationId, currentMigrationId) < 0))
            {
                return(new VersionedModel(lastModel, productVersion));
            }
            return(new VersionedModel(this._emptyModel.Value, (string)null));
        }
Esempio n. 17
0
        private XDocument GetLastModel(DbMigration lastMigration, string currentMigrationId = null)
        {
            if (lastMigration != null)
            {
                var migrationMetadata = (IMigrationMetadata)lastMigration;

                return(new ModelCompressor().Decompress(Convert.FromBase64String(migrationMetadata.Target)));
            }

            string migrationId;
            var    lastModel = _historyRepository.GetLastModel(out migrationId);

            if (lastModel != null &&
                (currentMigrationId == null || string.CompareOrdinal(migrationId, currentMigrationId) < 0))
            {
                return(lastModel);
            }

            return(_emptyModel.Value);
        }
Esempio n. 18
0
 internal override void Downgrade(IEnumerable <string> pendingMigrations)
 {
     for (int index = 0; index < pendingMigrations.Count <string>() - 1; ++index)
     {
         string      migrationId1    = pendingMigrations.ElementAt <string>(index);
         DbMigration migration       = this._migrationAssembly.GetMigration(migrationId1);
         string      migrationId2    = pendingMigrations.ElementAt <string>(index + 1);
         string      productVersion1 = (string)null;
         XDocument   xdocument       = migrationId2 != "0" ? this._historyRepository.GetModel(migrationId2, out productVersion1) : this._emptyModel.Value;
         string      productVersion2;
         XDocument   model = this._historyRepository.GetModel(migrationId1, out productVersion2);
         if (migration == null)
         {
             base.AutoMigrate(migrationId1, new VersionedModel(model, (string)null), new VersionedModel(xdocument, productVersion1), true);
         }
         else
         {
             base.RevertMigration(migrationId1, migration, xdocument);
         }
     }
 }
Esempio n. 19
0
        internal override void RevertMigration(string migrationId, DbMigration migration, XDocument sourceModel, XDocument targetModel)
        {
            bool?includeSystemOps = null;

            if (ReferenceEquals(targetModel, _emptyModel.Value) &&
                !_historyRepository.IsShared())
            {
                includeSystemOps = true;

                if (!sourceModel.HasSystemOperations())
                {
                    // upgrade scenario, inject the history model
                    AttachHistoryModel(sourceModel);
                }
            }

            var systemOperations
                = _modelDiffer.Diff(sourceModel, targetModel, includeSystemOps)
                  .Where(o => o.IsSystem);

            migration.Down();

            ExecuteOperations(migrationId, targetModel, migration.Operations.Concat(systemOperations), downgrading: true);
        }
Esempio n. 20
0
        internal override void Upgrade(
            IEnumerable <string> pendingMigrations,
            string targetMigrationId,
            string lastMigrationId)
        {
            DbMigration lastMigration = (DbMigration)null;

            if (lastMigrationId != null)
            {
                lastMigration = this._migrationAssembly.GetMigration(lastMigrationId);
            }
            foreach (string pendingMigration in pendingMigrations)
            {
                DbMigration migration = this._migrationAssembly.GetMigration(pendingMigration);
                base.ApplyMigration(migration, lastMigration);
                lastMigration = migration;
                this._emptyMigrationNeeded = false;
                if (pendingMigration.EqualsIgnoreCase(targetMigrationId))
                {
                    break;
                }
            }
            if (string.IsNullOrWhiteSpace(targetMigrationId) && (this._emptyMigrationNeeded && this._configuration.AutomaticMigrationsEnabled || this.IsModelOutOfDate(this._currentModel, lastMigration)))
            {
                if (!this._configuration.AutomaticMigrationsEnabled)
                {
                    throw Error.AutomaticDisabledException();
                }
                base.AutoMigrate(MigrationAssembly.CreateMigrationId(this._calledByCreateDatabase ? Strings.InitialCreate : Strings.AutomaticMigration), this._calledByCreateDatabase ? new VersionedModel(this._emptyModel.Value, (string)null) : this.GetLastModel(lastMigration, (string)null), new VersionedModel(this._currentModel, (string)null), false);
            }
            if (this._calledByCreateDatabase || this.IsModelOutOfDate(this._currentModel, lastMigration))
            {
                return;
            }
            base.SeedDatabase();
        }
Esempio n. 21
0
 /// <summary>
 /// Create a new computed column
 /// </summary>
 /// <param name="migration">The DBMigration</param>
 /// <param name="tableName">The name of table for create computed column</param>
 /// <param name="columnName">The name of computed column to drop</param>
 public static void DropComputedColumn(this DbMigration migration, string tableName, string columnName)
 {
     ((IDbMigration)migration)
     .AddOperation(new DropComputedColumnOperation(tableName, columnName));
 }
Esempio n. 22
0
 /// <summary>
 /// Remove table permission to specified user
 /// </summary>
 /// <param name="migration">The DbMigration</param>
 /// <param name="table">The table you remove the permission</param>
 /// <param name="user">The user you remove the permission</param>
 /// <param name="permission">The permission to revoke</param>
 public static void RevokeTablePermission(this DbMigration migration, string table, string user, TablePermission permission)
 {
     ((IDbMigration)migration)
     .AddOperation(new RevokeTablePermissionOperation(table, user, permission));
 }
Esempio n. 23
0
 /// <summary>
 /// Change the collation to specified database
 /// </summary>
 /// <param name="migration">The DbMigration</param>
 /// <param name="databaseName">The name of database you change the collation.</param>
 /// <param name="collation">The collation to set.</param>
 public static void SetDatabaseCollation(this DbMigration migration, string databaseName, string collation)
 {
     ((IDbMigration)migration)
     .AddOperation(new DatabaseCollationOperation(databaseName, collation));
 }
Esempio n. 24
0
        internal virtual bool IsModelOutOfDate(XDocument model, DbMigration lastMigration)
        {
            VersionedModel lastModel = this.GetLastModel(lastMigration, (string)null);

            return(this._modelDiffer.Diff(lastModel.Model, model, (Lazy <ModificationCommandTreeGenerator>)null, (MigrationSqlGenerator)null, lastModel.Version, (string)null).Any <MigrationOperation>());
        }
Esempio n. 25
0
 /// <summary>
 /// Create a new view
 /// </summary>
 /// <param name="migration">The DBMigration</param>
 /// <param name="viewName">The name of view to create</param>
 /// <param name="bodySql">The sql body of view to create</param>
 public static void CreateView(this DbMigration migration, string viewName, string bodySql)
 {
     ((IDbMigration)migration)
     .AddOperation(new CreateViewOperation(viewName, bodySql));
 }
Esempio n. 26
0
 /// <summary>
 /// Drop existing view
 /// </summary>
 /// <param name="migration">the DBMigration</param>
 /// <param name="viewName">the name of view to drop</param>
 public static void DropView(this DbMigration migration, string viewName)
 {
     ((IDbMigration)migration)
     .AddOperation(new DropViewOperation(viewName));
 }
Esempio n. 27
0
 /// <summary>
 /// Add a new computed column
 /// </summary>
 /// <param name="migration">The DBMigration</param>
 /// <param name="columnName">The name of computed column to create</param>
 /// <param name="bodySql">The sql body of view to create</param>
 /// <param name="tableName">The name of table for create computed column</param>
 public static void AddComputedColumn(this DbMigration migration, string tableName, string columnName, string bodySql)
 {
     ((IDbMigration)migration)
     .AddOperation(new AddComputedColumnOperation(tableName, columnName, bodySql));
 }
Esempio n. 28
0
 /// <summary>
 /// Execute sql scripts from existing sql file.
 /// </summary>
 /// <param name="migration">the DBMigration.</param>
 /// <param name="sqlFilePath">The sql file path with scripts to be executed.</param>
 public static void SqlFile(this DbMigration migration, string sqlFilePath)
 {
     ((IDbMigration)migration)
     .AddOperation(new SqlFileOperation(sqlFilePath));
 }
Esempio n. 29
0
 /// <summary>
 /// Execute sql scripts from existing stream.
 /// </summary>
 /// <param name="migration">The DBMigration</param>
 /// <param name="sqlFileStream">The stream with sql scripts to be executed.</param>
 public static void SqlFile(this DbMigration migration, Stream sqlFileStream)
 {
     ((IDbMigration)migration)
     .AddOperation(new SqlFileOperation(sqlFileStream));
 }
Esempio n. 30
0
        /// <summary>
        /// Execute sql scripts from existing resource.
        /// </summary>
        /// <param name="migration">The DbMigration</param>
        /// <param name="assembly">The assembly that contain the resource.</param>
        /// <param name="resourceName">The resource name.</param>

        public static void SqlResource(this DbMigration migration, Assembly assembly, string resourceName)
        {
            ((IDbMigration)migration)
            .AddOperation(new SqlResourceOperation(assembly, resourceName));
        }