Example #1
0
        /// <summary>
        /// 如果用DbMigration自带的CreateTable方法,会造成死循环。
        /// </summary>
        /// <typeparam name="TColumns"></typeparam>
        /// <param name="d"></param>
        /// <param name="name"></param>
        /// <param name="columnsAction"></param>
        /// <param name="annotations"></param>
        /// <param name="anonymousArguments"></param>
        /// <returns></returns>
        private static TableBuilder <TColumns> CreateTableWithComment <TColumns>(this DbMigration d, string name, Func <ColumnBuilder, TColumns> columnsAction, IDictionary <string, object> annotations, object anonymousArguments = null)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new Exception("创建表时必须设置表名。");
            }
            if (columnsAction == null)
            {
                throw new Exception("创建表时必须设置列对象。");
            }
            CreateTableOperation createTableOperation = new CreateTableOperation(name, annotations, anonymousArguments);

            (d as IDbMigration).AddOperation(createTableOperation);
            //添加列
            TColumns columns = columnsAction(new ColumnBuilder());

            columns.GetType().GetNonIndexerProperties().ForEach(p =>
            {
                ColumnModel columnModel = p.GetValue(columns, null) as ColumnModel;
                if (columnModel != null)
                {
                    //columnModel..ApiPropertyInfo = p;
                    columnModel.GetType().GetField("_apiPropertyInfo", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(columnModel, p);
                    if (string.IsNullOrWhiteSpace(columnModel.Name))
                    {
                        columnModel.Name = p.Name;
                    }
                    createTableOperation.Columns.Add(columnModel);
                }
            });
            return(new TableBuilder <TColumns>(createTableOperation, d));
        }
Example #2
0
        /// <summary>
        /// Adds an operation to drop an existing primary key that was created with the default name.
        /// </summary>
        /// <param name="table">The table that contains the primary key column. Schema name is optional, if no schema is specified then dbo is assumed. </param>
        /// <param name="anonymousArguments">Additional arguments that may be processed by providers. Use anonymous type syntax to specify arguments e.g. 'new { SampleArgument = "MyValue" }'. </param>
        public void DropPrimaryKey(string table, object anonymousArguments = null)
        {
            DbMigration dbMigration = new DbMigration();

            dbMigration.DropPrimaryKey(table, anonymousArguments);
            Sql(dbMigration.GetMigrationSql(SqlConnection));
        }
Example #3
0
 public static void TableComment(this DbMigration d, string name, string comment)
 {
     (d as IDbMigration).AddOperation(new SqlOperation($"ALTER TABLE `{name}` COMMENT '{comment}'")
     {
         SuppressTransaction = false
     });
 }
Example #4
0
        /// <summary>
        /// Adds an operation to create a new foreign key constraint.
        /// attacks etc.
        /// </summary>
        /// <param name="dependentTable">The table that contains the foreign key column. Schema name is optional, if no
        ///     schema is specified then dbo is assumed.</param>
        /// <param name="dependentColumns">The foreign key columns.</param>
        /// <param name="principalTable">The table that contains the column this foreign key references. Schema name is
        ///     optional, if no schema is specified then dbo is assumed.</param>
        /// <param name="principalColumns">The columns this foreign key references. If no value is supplied the primary key
        ///     of the principal table will be referenced.</param>
        /// <param name="cascadeDelete">A value indicating if cascade delete should be configured for the foreign key
        ///     relationship. If no value is supplied, cascade delete will be off.</param>
        /// <param name="name">The name of the foreign key constraint in the database. If no value is supplied
        ///     a unique name will be generated.</param>
        /// <param name="anonymousArguments"> Additional arguments that may be processed by providers. Use anonymous type syntax
        ///     to specify arguments e.g. 'new { SampleArgument = "MyValue" }'.</param>
        public void AddForeignKey(string dependentTable, string[] dependentColumns, string principalTable, string[] principalColumns = null, bool cascadeDelete = false, string name = null, object anonymousArguments = null)
        {
            DbMigration dbMigration = new DbMigration();

            dbMigration.AddForeignKey(dependentTable, dependentColumns, principalTable, principalColumns, cascadeDelete, name, anonymousArguments);
            Sql(dbMigration.GetMigrationSql(SqlConnection));
        }
Example #5
0
        /// <summary>
        /// Adds an operation to create an index.
        /// </summary>
        /// <param name="table">The name of the table to create the index on. Schema name is optional, if no
        ///     schema is specified then dbo is assumed.</param>
        /// <param name="columns">The names of the columns to create the index on.</param>
        /// <param name="unique">A value indicating if this is a unique index. If no value is supplied a non-unique
        ///     index will be created.</param>
        /// <param name="name">The name to use for the index in the database. If no value is supplied a unique
        ///     name will be generated.</param>
        /// <param name="clustered">A value indicating whether or not this is a clustered index.</param>
        /// <param name="anonymousArguments">Additional arguments that may be processed by providers. Use anonymous type syntax
        ///     to specify arguments e.g. 'new { SampleArgument = "MyValue" }'.</param>
        public void AddIndex(string table, string[] columns, bool unique = false, string name = null, bool clustered = false, object anonymousArguments = null)
        {
            DbMigration dbMigration = new DbMigration();

            dbMigration.CreateIndex(table, columns, unique, name, clustered, anonymousArguments);
            Sql(dbMigration.GetMigrationSql(SqlConnection));
        }
Example #6
0
        /// <summary>
        /// Adds an operation to create a new primary key.
        /// </summary>
        /// <param name="table">The table that contains the primary key column. Schema name is optional, if no
        ///     schema is specified then dbo is assumed.</param>
        /// <param name="columns">The primary key columns.</param>
        /// <param name="name">The name of the primary key in the database. If no value is supplied a unique
        ///     name will be generated.</param>
        /// <param name="clustered">A value indicating whether or not this is a clustered primary key.</param>
        /// <param name="anonymousArguments">Additional arguments that may be processed by providers. Use anonymous type syntax
        ///     to specify arguments e.g. 'new { SampleArgument = "MyValue" }'.</param>
        public void AddPrimaryKey(string table, string[] columns, string name = null, bool clustered = true, object anonymousArguments = null)
        {
            DbMigration dbMigration = new DbMigration();

            dbMigration.AddPrimaryKey(table, columns, name, clustered, anonymousArguments);
            Sql(dbMigration.GetMigrationSql(SqlConnection));
        }
Example #7
0
        /// <summary>
        /// Adds an operation to create a new table.
        /// </summary>
        /// <typeparam name="TColumns"> The columns in this create table operation. You do not need to specify this type, it will be inferred from the columnsAction parameter you supply. </typeparam>
        /// <param name="name"> The name of the table. Schema name is optional, if no schema is specified then dbo is assumed. </param>
        /// <param name="columnsAction"> An action that specifies the columns to be included in the table. i.e. t => new { Id = t.Int(identity: true), Name = t.String() } </param>
        /// <param name="anonymousArguments"> Additional arguments that may be processed by providers. Use anonymous type syntax to specify arguments e.g. 'new { SampleArgument = "MyValue" }'. </param>
        public void AddTable <TColumns>(string name, Func <ColumnBuilder, TColumns> columnsAction, object anonymousArguments = null)
        {
            var dbMigration = new DbMigration();

            dbMigration.CreateTable(name, columnsAction, anonymousArguments);
            Sql(dbMigration.GetMigrationSql(SqlConnection));
        }
Example #8
0
 internal virtual void RevertMigration(
     string migrationId,
     DbMigration migration,
     XDocument targetModel)
 {
     this._this.RevertMigration(migrationId, migration, targetModel);
 }
Example #9
0
        public Startup(IConfiguration configuration, IWebHostEnvironment env)
        {
            Configuration = configuration;

            BotSettings.GlobalConfiguration = Configuration;
            BotSettings.HostingEnvironment  = env;
            BotSettings.FillSettings();
            Logger.SetupLogger();

            BotSettings.DbConnectionString = Configuration["CommonConfig:ConnectionString"];
            DbMigration.ConnectionString   = BotSettings.DbConnectionString;

            Log.Information($"ProductName: {Configuration["Engines:ProductName"]}");
            Log.Information($"Version: {Configuration["Engines:Version"]}");

            BotSettings.Client = new TelegramBotClient(Configuration["ZiziBot:ApiToken"]);

            // Bot.Clients.Add("zizibot", new TelegramBotClient(Configuration["ZiziBot:ApiToken"]));
            // Bot.Clients.Add("macosbot", new TelegramBotClient(Configuration["MacOsBot:ApiToken"]));

            GlobalConfiguration.Configuration
            .UseSerilogLogProvider()
            .UseColouredConsoleLogProvider();

            DbMigration.RunMySqlMigration();
        }
Example #10
0
        public static void Run <TColumns>(this TableBuilder <TColumns> tableBuilder, Rock.Plugin.Migration migration)
        {
            FieldInfo   fiMigration = tableBuilder.GetType().GetField("_migration", BindingFlags.NonPublic | BindingFlags.Instance);
            DbMigration dbMigration = fiMigration.GetValue(tableBuilder) as DbMigration;

            migration.Sql(GetMigrationSql(dbMigration, migration.SqlConnection));
        }
Example #11
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseHealthChecks("/health");
            loggerFactory.AddSerilog();

            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.RoutePrefix = string.Empty;
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "SmartHouse Gateway API V1");
                c.DisplayRequestDuration();
            });

            DbMigration.Migrate(app.ApplicationServices);
        }
Example #12
0
    private static Action <string, bool, object> GetSqlMethod(this DbMigration migration)
    {
        MethodInfo methodInfo = typeof(DbMigration).GetMethod(
            "Sql", BindingFlags.NonPublic | BindingFlags.Instance);

        return((s, b, arg3) => methodInfo.Invoke(migration, new[] { s, b, arg3 }));
    }
Example #13
0
        /// <summary>
        /// Adds an operation to drop an index based on its name.  This is a wrapper for the default DBMigration DropIndex.
        /// </summary>
        /// <param name="table">The name of the table to drop the index from. Schema name is optional, if no schema is specified then dbo is assumed.</param>
        /// <param name="columns">The columns.</param>
        /// <param name="anonymousArguments">Additional arguments that may be processed by providers. Use anonymous type syntax to specify arguments e.g. 'new { SampleArgument = "MyValue" }'.</param>
        public void DropIndex(string table, string[] columns, object anonymousArguments = null)
        {
            DbMigration dbMigration = new DbMigration();

            dbMigration.DropIndex(table, columns, anonymousArguments);
            Sql(dbMigration.GetMigrationSql(SqlConnection));
        }
        /// <summary>
        /// Initializes a new instance of the TableBuilder class.
        /// </summary>
        /// <param name="createTableOperation"> The table creation operation to be further configured. </param>
        /// <param name="migration"> The migration the table is created in. </param>
        public TableBuilder(CreateTableOperation createTableOperation, DbMigration migration)
        {
            Check.NotNull(createTableOperation, "createTableOperation");

            _createTableOperation = createTableOperation;
            _migration            = migration;
        }
Example #15
0
        /// <summary>
        /// Adds an operation to drop an index based on the columns it targets.  This is a wrapper for the default DBMigration DropTable.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="anonymousArguments">Additional arguments that may be processed by providers. Use anonymous type syntax to specify arguments e.g. 'new { SampleArgument = "MyValue" }'.</param>
        public void DropTable(string name, object anonymousArguments = null)
        {
            DbMigration dbMigration = new DbMigration();

            dbMigration.DropTable(name, anonymousArguments);
            Sql(dbMigration.GetMigrationSql(SqlConnection));
        }
Example #16
0
        /// <summary>
        ///     Adds an operation to add a column to an existing table.  This is a wrapper for the default DBMigration AddColumn.
        /// </summary>
        /// <param name="table"> The name of the table to add the column to. Schema name is optional, if no schema is specified then dbo is assumed. </param>
        /// <param name="name"> The name of the column to be added. </param>
        /// <param name="columnAction"> An action that specifies the column to be added. i.e. c => c.Int(nullable: false, defaultValue: 3) </param>
        /// <param name="anonymousArguments"> Additional arguments that may be processed by providers. Use anonymous type syntax to specify arguments e.g. 'new { SampleArgument = "MyValue" }'. </param>
        public void AddColumn(string table, string name, Func <ColumnBuilder, ColumnModel> columnAction, object anonymousArguments = null)
        {
            DbMigration dbMigration = new DbMigration();

            dbMigration.AddColumn(table, name, columnAction, anonymousArguments);
            Sql(dbMigration.GetMigrationSql(SqlConnection));
        }
Example #17
0
        /// <summary>
        ///     Adds an operation to drop a foreign key constraint based on its name.  This is a wrapper for the default DBMigration DropForeignKey.
        /// </summary>
        /// <param name="dependentTable"> The table that contains the foreign key column. Schema name is optional, if no schema is specified then dbo is assumed. </param>
        /// <param name="name"> The name of the foreign key constraint in the database. </param>
        /// <param name="anonymousArguments"> Additional arguments that may be processed by providers. Use anonymous type syntax to specify arguments e.g. 'new { SampleArgument = "MyValue" }'. </param>
        public void DropForeignKey(string dependentTable, string name, object anonymousArguments = null)
        {
            DbMigration dbMigration = new DbMigration();

            dbMigration.DropForeignKey(dependentTable, name, anonymousArguments);
            Sql(dbMigration.GetMigrationSql(SqlConnection));
        }
Example #18
0
        private void AddOrUpdateMigration(DbMigration migration)
        {
            using (IDbConnection conn = new SqlConnection(Program.ConnectionString))
            {
                conn.Open();
                if (migration.IsNew)
                {
                    conn.Execute(@"
INSERT INTO __Migration 
(Name, Hash, AppliedDateTime, DurationInSeconds, IsOk, Mode, Error)
VALUES (@Name, @Hash, @AppliedDateTime, @DurationInSeconds, @IsOk, @Mode, @Error)", migration);
                }
                else
                {
                    conn.Execute(@"
UPDATE __Migration 
SET Hash = @Hash,
AppliedDateTime = @AppliedDateTime,
DurationInSeconds = @DurationInSeconds,
IsOk = @IsOk,
Mode = @Mode,
Error = @Error
WHERE Name = @Name", migration);
                }
            }
        }
Example #19
0
        /// <summary>
        /// 从历史记录中还原迁移对象
        /// </summary>
        /// <param name="history"></param>
        /// <returns></returns>
        internal DbMigration TryRestore(HistoryItem history)
        {
            Type type = null;

            try
            {
                type = Type.GetType(history.MigrationClass);
            }
            catch (TypeLoadException)
            {
                //如果当前这个类已经不存在了,无法还原,则直接返回 null,跳过该项。
                return(null);
            }

            //如果这个类型已经被变更了,或者找不到,则直接返回 null
            if (type == null)
            {
                return(null);
            }

            DbMigration migration = null;

            if (history.IsGenerated)
            {
                migration = SerializationHelper.XmlDeserialize(type, history.MigrationContent).CastTo <DbMigration>();

                (migration as MigrationOperation).RuntimeTimeId = history.TimeId;
            }
            else
            {
                migration = Activator.CreateInstance(type, true).CastTo <DbMigration>();
            }

            return(migration);
        }
Example #20
0
        public void Initialize()
        {
            try
            {
                Catfish.Tests.Migrations.Configuration config = new Catfish.Tests.Migrations.Configuration();
                var migrator = new DbMigrator(config);

                foreach (string migName in migrator.GetPendingMigrations())
                {
                    Type        migration = config.MigrationsAssembly.GetType(string.Format("{0}.{1}", config.MigrationsNamespace, migName.Substring(16)));
                    DbMigration m         = (DbMigration)Activator.CreateInstance(migration);
                    m.Up();

                    var prop = m.GetType().GetProperty("Operations", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                    if (prop != null)
                    {
                        IEnumerable <MigrationOperation> operations = prop.GetValue(m) as IEnumerable <MigrationOperation>;
                        var generator  = config.GetSqlGenerator("System.Data.SQLite");
                        var statements = generator.Generate(operations, "2008");
                        foreach (MigrationStatement item in statements)
                        {
                            Db.Database.ExecuteSqlCommand(item.Sql);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static async Task Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(Configuration)
                         .Enrich.FromLogContext()
                         .CreateLogger();

            try
            {
                Log.Information("Inicializando a API!");
                var host = CreateHostBuilder(args).Build();

                await DbMigration.EnsureSeedData(host);

                await host.RunAsync().ConfigureAwait(false);;
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Erro ao inicializar!");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
Example #22
0
        public virtual DbMigration GetMigration(string migrationId)
        {
            DbMigration dbMigration = (DbMigration)this._migrations.SingleOrDefault <IMigrationMetadata>((Func <IMigrationMetadata, bool>)(m => m.Id.StartsWith(migrationId, StringComparison.Ordinal)));

            dbMigration?.Reset();
            return(dbMigration);
        }
        internal override void ApplyMigration(DbMigration migration, DbMigration lastMigration)
        {
            DebugCheck.NotNull(migration);

            _logger.Info(Strings.LoggingApplyMigration(((IMigrationMetadata)migration).Id));

            base.ApplyMigration(migration, lastMigration);
        }
Example #24
0
        /// <summary>
        ///     Adds an operation to create a new table.  This is a wrapper for the default DBMigration CreateTable.
        /// </summary>
        /// <typeparam name="TColumns"> The columns in this create table operation. You do not need to specify this type, it will be inferred from the columnsAction parameter you supply. </typeparam>
        /// <param name="name"> The name of the table. Schema name is optional, if no schema is specified then dbo is assumed. </param>
        /// <param name="columnsAction"> An action that specifies the columns to be included in the table. i.e. t => new { Id = t.Int(identity: true), Name = t.String() } </param>
        /// <param name="anonymousArguments"> Additional arguments that may be processed by providers. Use anonymous type syntax to specify arguments e.g. 'new { SampleArgument = "MyValue" }'. </param>
        /// <returns> An object that allows further configuration of the table creation operation. </returns>
        public TableBuilder <TColumns> CreateTable <TColumns>(string name, Func <ColumnBuilder, TColumns> columnsAction, object anonymousArguments = null)
        {
            DbMigration dbMigration = new DbMigration();
            var         table       = dbMigration.CreateTable(name, columnsAction, anonymousArguments);

            Sql(dbMigration.GetMigrationSql(SqlConnection));
            return(table);
        }
        internal override void RevertMigration(string migrationId, DbMigration migration, XDocument targetModel)
        {
            DebugCheck.NotEmpty(migrationId);

            _logger.Info(Strings.LoggingRevertMigration(migrationId));

            base.RevertMigration(migrationId, migration, targetModel);
        }
Example #26
0
 internal override void RevertMigration(
     string migrationId,
     DbMigration migration,
     XDocument targetModel)
 {
     this._logger.Info(Strings.LoggingRevertMigration((object)migrationId));
     base.RevertMigration(migrationId, migration, targetModel);
 }
        public static void DropView(this DbMigration migration, string name)
        {
            var sql = $"DROP VIEW {name}";

            var method = typeof(DbMigration).GetMethod("Sql", BindingFlags.NonPublic | BindingFlags.Instance);

            method?.Invoke(migration, new object[] { sql, false, null });
        }
Example #28
0
        public static void RemoveTriggers(this DbMigration migration)
        {
            var types = migration.GetType().Assembly.GetTypes().Where(t => typeof(InsertTriggerCustomAttribute).IsAssignableFrom(t));

            foreach (var triggerType in types)
            {
                string tt = "";
            }
        }
Example #29
0
        // add custom and logging triggers to DB tables of classes so attributed
        public static void AddTriggers(this DbMigration migration, object anonymousArguments = null)
        {
            //#if DEBUG
            //            if (!System.Diagnostics.Debugger.IsAttached)
            //                System.Diagnostics.Debugger.Launch();
            //#endif

            // get all the types that have been attributed with the InsertTriggerCustomAttribute
            List <Type> types = (from a in AppDomain.CurrentDomain.GetAssemblies()
                                 from t in a.GetTypes()
                                 where t.IsDefined(typeof(InsertTriggerCustomAttribute), false)
                                 select t as Type).ToList();

            // loop those types and create the triggers
            foreach (var triggerType in types)
            {
                // NOTE: triggerType is the type of object that we are aplying a trigger to
                var insertTriggerAttr = triggerType.GetCustomAttributes(typeof(InsertTriggerCustomAttribute), false).FirstOrDefault() as InsertTriggerCustomAttribute;
                if (insertTriggerAttr != null)
                {
                    var triggerSql = GenerateInsertTrigger(triggerType, insertTriggerAttr);
                    ((IDbMigration)migration).AddOperation(new AddTriggerOperation(triggerSql, anonymousArguments));
                }
            }
            // get all the types that have been attributed with the UpdateTriggerCustomAttribute
            types = (from a in AppDomain.CurrentDomain.GetAssemblies()
                     from t in a.GetTypes()
                     where t.IsDefined(typeof(UpdateTriggerCustomAttribute), false)
                     select t as Type).ToList();
            // loop those types and create the triggers
            foreach (var triggerType in types)
            {
                // NOTE: triggerType is the type of object that we are aplying a trigger to
                var updateTriggerAttr = triggerType.GetCustomAttributes(typeof(UpdateTriggerCustomAttribute), false).FirstOrDefault() as UpdateTriggerCustomAttribute;
                if (updateTriggerAttr != null)
                {
                    var triggerSql = GenerateUpdateTrigger(triggerType, updateTriggerAttr);
                    ((IDbMigration)migration).AddOperation(new AddTriggerOperation(triggerSql, anonymousArguments));
                }
            }
            // get all the types that have been attributed with the DeleteTriggerCustomAttribute
            types = (from a in AppDomain.CurrentDomain.GetAssemblies()
                     from t in a.GetTypes()
                     where t.IsDefined(typeof(DeleteTriggerCustomAttribute), false)
                     select t as Type).ToList();
            // loop those types and create the triggers
            foreach (var triggerType in types)
            {
                // NOTE: triggerType is the type of object that we are aplying a trigger to
                var deleteTriggerAttr = triggerType.GetCustomAttributes(typeof(DeleteTriggerCustomAttribute), false).FirstOrDefault() as DeleteTriggerCustomAttribute;
                if (deleteTriggerAttr != null)
                {
                    var triggerSql = GenerateDeleteTrigger(triggerType, deleteTriggerAttr);
                    ((IDbMigration)migration).AddOperation(new AddTriggerOperation(triggerSql, anonymousArguments));
                }
            }
        }
Example #30
0
        internal virtual void RevertMigration(
            string migrationId, DbMigration migration, XDocument targetModel)
        {
            DebugCheck.NotEmpty(migrationId);
            DebugCheck.NotNull(migration);
            DebugCheck.NotNull(targetModel);

            _this.RevertMigration(migrationId, migration, targetModel);
        }
Example #31
0
        /// <summary>
        /// 当某个迁移操作升级完成后,为它添加相应的历史记录。
        /// </summary>
        /// <param name="database"></param>
        /// <param name="migration"></param>
        /// <returns></returns>
        internal Result AddAsExecuted(string database, DbMigration migration)
        {
            var history = new HistoryItem()
            {
                IsGenerated = false,
                TimeId = migration.TimeId,
                Description = migration.Description,
                MigrationClass = migration.GetType().AssemblyQualifiedName,
            };

            if (migration.MigrationType == MigrationType.AutoMigration)
            {
                history.IsGenerated = true;
                history.MigrationContent = SerializationHelper.XmlSerialize(migration);
            }

            return this.AddHistoryCore(database, history);
        }
Example #32
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;

            if (ReferenceEquals(lastModel, _emptyModel.Value))
            {
                includeSystemOps = true;

                if (!targetModel.HasSystemOperations())
                {
                    // upgrade scenario, inject the history model
                    _historyRepository
                        .AppendHistoryModel(
                            targetModel,
                            new DbProviderInfo(_usersContextInfo.ConnectionProviderName, _providerManifestToken));
                }
            }

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

            migration.Up();

            ExecuteOperations(migrationMetadata.Id, targetModel, migration.Operations.Concat(systemOperations), false);
        }
Example #33
0
        internal override void RevertMigration(string migrationId, DbMigration migration, XDocument sourceModel, XDocument targetModel)
        {
            bool? includeSystemOps = null;

            if (ReferenceEquals(targetModel, _emptyModel.Value))
            {
                includeSystemOps = true;

                if (!sourceModel.HasSystemOperations())
                {
                    // upgrade scenario, inject the history model
                    _historyRepository
                        .AppendHistoryModel(
                            sourceModel,
                            new DbProviderInfo(_usersContextInfo.ConnectionProviderName, _providerManifestToken));
                }
            }

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

            migration.Down();

            ExecuteOperations(migrationId, targetModel, migration.Operations.Concat(systemOperations), downgrading: true);
        }
Example #34
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;
        }
Example #35
0
        private bool IsModelOutOfDate(XDocument model, DbMigration lastMigration)
        {
            Contract.Requires(model != null);

            var sourceModel = GetLastModel(lastMigration);

            return _modelDiffer.Diff(sourceModel, model, ReferenceEquals(sourceModel, _emptyModel.Value)).Any();
        }
        internal override void RevertMigration(string migrationId, DbMigration migration, XDocument soureModel, XDocument targetModel)
        {
            _logger.Info(Strings.LoggingRevertMigration(migrationId));

            base.RevertMigration(migrationId, migration, soureModel, targetModel);
        }
        internal override void ApplyMigration(DbMigration migration, DbMigration lastMigration)
        {
            _logger.Info(Strings.LoggingApplyMigration(((IMigrationMetadata)migration).Id));

            base.ApplyMigration(migration, lastMigration);
        }
        internal virtual void ApplyMigration(DbMigration migration, DbMigration lastMigration)
        {
            //Contract.Requires(migration != null);

            _this.ApplyMigration(migration, lastMigration);
        }
        private bool IsModelOutOfDate(XDocument model, DbMigration lastMigration)
        {
            DebugCheck.NotNull(model);

            var sourceModel = GetLastModel(lastMigration);

            return _modelDiffer.Diff(sourceModel, model).Any();
        }
Example #40
0
        private VersionedModel GetLastModel(DbMigration lastMigration, string currentMigrationId = null)
        {
            if (lastMigration != null)
            {
                return lastMigration.GetTargetModel();
            }

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

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

            return new VersionedModel(_emptyModel.Value);
        }
Example #41
0
        internal override void ApplyMigration(DbMigration migration, DbMigration lastMigration)
        {
            DebugCheck.NotNull(migration);

            var migrationMetadata = (IMigrationMetadata)migration;
            var lastModel = GetLastModel(lastMigration, migrationMetadata.Id);
            var sourceModel = migration.GetSourceModel();
            var targetModel = migration.GetTargetModel();

            if (sourceModel != null
                && IsModelOutOfDate(sourceModel.Model, 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.Model, _emptyModel.Value)
                && !base.HistoryExists())
            {
                systemOperations = _modelDiffer.Diff(_emptyModel.Value, 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);
        }
Example #42
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);
        }
        internal override void RevertMigration(string migrationId, DbMigration migration, XDocument targetModel)
        {
            DebugCheck.NotEmpty(migrationId);

            _logger.Info(Strings.LoggingRevertMigration(migrationId));

            base.RevertMigration(migrationId, migration, targetModel);
        }
        internal virtual void RevertMigration(string migrationId, DbMigration migration, XDocument sourceModel, XDocument targetModel)
        {
            //Contract.Requires(!string.IsNullOrWhiteSpace(migrationId));
            //Contract.Requires(migration != null);
            //Contract.Requires(sourceModel != null);
            //Contract.Requires(targetModel != null);

            _this.RevertMigration(migrationId, migration, sourceModel, targetModel);
        }
        internal override void RevertMigration(string migrationId, DbMigration migration, XDocument targetModel)
        {
            migration.Down();

            ExecuteOperations(migrationId, targetModel, migration.Operations.ToList(), downgrading: true);
        }
        private bool IsModelOutOfDate(XDocument model, DbMigration lastMigration)
        {
            Contract.Requires(model != null);

            return _modelDiffer.Diff(GetLastModel(lastMigration), model).Any();
        }
Example #47
0
        internal virtual bool IsModelOutOfDate(XDocument model, DbMigration lastMigration)
        {
            DebugCheck.NotNull(model);

            var sourceModel = GetLastModel(lastMigration);

            return _modelDiffer.Diff(sourceModel.Model, model, sourceModelVersion: sourceModel.Version).Any();
        }
        internal override void ApplyMigration(DbMigration migration, DbMigration lastMigration)
        {
            var migrationMetadata = (IMigrationMetadata)migration;
            var compressor = new ModelCompressor();

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

                if (IsModelOutOfDate(sourceModel, lastMigration))
                {
                    base.AutoMigrate(
                        migrationMetadata.Id + "_" + Strings.AutomaticMigration,
                        GetLastModel(lastMigration, migrationMetadata.Id),
                        sourceModel,
                        downgrading: false);
                }
            }

            migration.Up();

            var targetModel = compressor.Decompress(Convert.FromBase64String(migrationMetadata.Target));

            ExecuteOperations(migrationMetadata.Id, targetModel, migration.Operations.ToList(), false);
        }
Example #49
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, _emptyModel.Value);
            }
            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, new VersionedModel(targetModel), migration.Operations, systemOperations, downgrading: true);
        }
Example #50
0
        internal virtual void ApplyMigration(DbMigration migration, DbMigration lastMigration)
        {
            DebugCheck.NotNull(migration);

            _this.ApplyMigration(migration, lastMigration);
        }
Example #51
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;
            }
        }
Example #52
0
        internal virtual void RevertMigration(
            string migrationId, DbMigration migration, XDocument targetModel)
        {
            DebugCheck.NotEmpty(migrationId);
            DebugCheck.NotNull(migration);
            DebugCheck.NotNull(targetModel);

            _this.RevertMigration(migrationId, migration, targetModel);
        }