示例#1
0
        private HistoryRepository SetupHistoryRepositoryForOrderingTest()
        {
            ResetDatabase();

            using (var context = CreateContext <ShopContext_v1>())
            {
                var model = new VersionedModel(context.GetModel());

                var clonedConnection = DbProviderServices.GetProviderFactory(context.Database.Connection).CreateConnection();
                clonedConnection.ConnectionString = context.Database.Connection.ConnectionString;

                using (var historyContext = new HistoryContext(clonedConnection, defaultSchema: null))
                {
                    context.InternalContext.MarkDatabaseInitialized();

                    context.Database.ExecuteSqlCommand(
                        ((IObjectContextAdapter)historyContext).ObjectContext.CreateDatabaseScript());

                    historyContext.History.Add(
                        new HistoryRow
                    {
                        MigrationId    = "227309030010001_Migration1",
                        ContextKey     = "MyKey",
                        Model          = new ModelCompressor().Compress(model.Model),
                        ProductVersion = "",
                    });

                    historyContext.History.Add(
                        new HistoryRow
                    {
                        MigrationId    = "227209030010001_Migration2",
                        ContextKey     = "MyKey",
                        Model          = new ModelCompressor().Compress(model.Model),
                        ProductVersion = "",
                    });

                    historyContext.SaveChanges();
                }
            }

            return(new HistoryRepository(Mock.Of <InternalContextForMock>(), ConnectionString, ProviderFactory, "MyKey", null, HistoryContext.DefaultFactory));
        }
示例#2
0
        public HistoryRepository(
            InternalContext usersContext,
            string connectionString,
            DbProviderFactory providerFactory,
            string contextKey,
            int?commandTimeout,
            Func <DbConnection, string, HistoryContext> historyContextFactory,
            IEnumerable <string> schemas            = null,
            DbContext contextForInterception        = null,
            DatabaseExistenceState initialExistence = DatabaseExistenceState.Unknown)
            : base(usersContext, connectionString, providerFactory)
        {
            this._initialExistence    = initialExistence;
            this._commandTimeout      = commandTimeout;
            this._existingTransaction = usersContext.TryGetCurrentStoreTransaction();
            this._schemas             = ((IEnumerable <string>) new string[1]
            {
                "dbo"
            }).Concat <string>(schemas ?? Enumerable.Empty <string>()).Distinct <string>();
            this._contextForInterception = contextForInterception;
            this._historyContextFactory  = historyContextFactory;
            DbConnection connection = (DbConnection)null;

            try
            {
                connection = this.CreateConnection();
                using (HistoryContext context = this.CreateContext(connection, (string)null))
                {
                    EntityType entityType = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace.GetItems <EntityType>(DataSpace.CSpace).Single <EntityType>((Func <EntityType, bool>)(et => EntityTypeExtensions.GetClrType(et) == typeof(HistoryRow)));
                    int?       maxLength  = entityType.Properties.Single <EdmProperty>((Func <EdmProperty, bool>)(p => p.GetClrPropertyInfo().IsSameAs(HistoryRepository.MigrationIdProperty))).MaxLength;
                    this._migrationIdMaxLength = maxLength.HasValue ? maxLength.Value : 150;
                    maxLength = entityType.Properties.Single <EdmProperty>((Func <EdmProperty, bool>)(p => p.GetClrPropertyInfo().IsSameAs(HistoryRepository.ContextKeyProperty))).MaxLength;
                    this._contextKeyMaxLength = maxLength.HasValue ? maxLength.Value : 300;
                }
            }
            finally
            {
                this.DisposeConnection(connection);
            }
            this._contextKey = contextKey.RestrictTo(this._contextKeyMaxLength);
        }
示例#3
0
        public virtual XDocument GetLastModel(
            out string migrationId,
            out string productVersion,
            string contextKey = null)
        {
            migrationId    = (string)null;
            productVersion = (string)null;
            if (!this.Exists(contextKey))
            {
                return((XDocument)null);
            }
            DbConnection connection = (DbConnection)null;

            try
            {
                connection = this.CreateConnection();
                using (HistoryContext context = this.CreateContext(connection, (string)null))
                {
                    using (new TransactionScope(TransactionScopeOption.Suppress))
                    {
                        var data = this.CreateHistoryQuery(context, contextKey).OrderByDescending <HistoryRow, string>((Expression <Func <HistoryRow, string> >)(h => h.MigrationId)).Select(s => new
                        {
                            MigrationId    = s.MigrationId,
                            Model          = s.Model,
                            ProductVersion = s.ProductVersion
                        }).FirstOrDefault();
                        if (data == null)
                        {
                            return((XDocument)null);
                        }
                        migrationId    = data.MigrationId;
                        productVersion = data.ProductVersion;
                        return(new ModelCompressor().Decompress(data.Model));
                    }
                }
            }
            finally
            {
                this.DisposeConnection(connection);
            }
        }
示例#4
0
        public virtual bool HasMigrations()
        {
            if (!this.Exists((string)null))
            {
                return(false);
            }
            if (!this._contextKeyColumnExists)
            {
                return(true);
            }
            DbConnection connection = (DbConnection)null;

            try
            {
                connection = this.CreateConnection();
                using (HistoryContext context = this.CreateContext(connection, (string)null))
                    return(context.History.Count <HistoryRow>((Expression <Func <HistoryRow, bool> >)(hr => hr.ContextKey == this._contextKey)) > 0);
            }
            finally
            {
                this.DisposeConnection(connection);
            }
        }
示例#5
0
        public virtual IEnumerable <string> GetMigrationsSince(string migrationId)
        {
            bool         flag       = this.Exists((string)null);
            DbConnection connection = (DbConnection)null;

            try
            {
                connection = this.CreateConnection();
                using (HistoryContext context = this.CreateContext(connection, (string)null))
                {
                    IQueryable <HistoryRow> source = this.CreateHistoryQuery(context, (string)null);
                    migrationId = migrationId.RestrictTo(this._migrationIdMaxLength);
                    if (migrationId != "0")
                    {
                        if (flag)
                        {
                            if (source.Any <HistoryRow>((Expression <Func <HistoryRow, bool> >)(h => h.MigrationId == migrationId)))
                            {
                                source = source.Where <HistoryRow>((Expression <Func <HistoryRow, bool> >)(h => string.Compare(h.MigrationId, migrationId, StringComparison.Ordinal) > 0));
                                goto label_9;
                            }
                        }
                        throw Error.MigrationNotFound((object)migrationId);
                    }
                    if (!flag)
                    {
                        return(Enumerable.Empty <string>());
                    }
label_9:
                    return((IEnumerable <string>)source.OrderByDescending <HistoryRow, string>((Expression <Func <HistoryRow, string> >)(h => h.MigrationId)).Select <HistoryRow, string>((Expression <Func <HistoryRow, string> >)(h => h.MigrationId)).ToList <string>());
                }
            }
            finally
            {
                this.DisposeConnection(connection);
            }
        }
示例#6
0
        public void Generate_can_output_delete_history_statement()
        {
            var migrationSqlGenerator = new SqlCeMigrationSqlGenerator();

            using (var historyContext = new HistoryContext())
            {
                var historyRow
                    = new HistoryRow
                          {
                              MigrationId = "House Lannister",
                              ContextKey = "The pointy end"
                          };

                historyContext.History.Attach(historyRow);
                historyContext.History.Remove(historyRow);

                using (var commandTracer = new CommandTracer(historyContext))
                {
                    historyContext.SaveChanges();

                    var deleteHistoryOperation
                        = new HistoryOperation(commandTracer.CommandTrees.OfType<DbModificationCommandTree>().ToList());

                    var sql
                        = migrationSqlGenerator
                            .Generate(new[] { deleteHistoryOperation }, "4.0")
                            .Single();

                    Assert.Equal(@"DELETE [__MigrationHistory]
WHERE (([MigrationId] = N'House Lannister') AND ([ContextKey] = N'The pointy end'))", sql.Sql.Trim());
                }
            }
        }
示例#7
0
        public void Generate_can_output_insert_history_statement()
        {
            var migrationSqlGenerator = new SqlCeMigrationSqlGenerator();

            using (var historyContext = new HistoryContext())
            {
                historyContext.History.Add(
                    new HistoryRow
                        {
                            MigrationId = "House Lannister",
                            ContextKey = "The pointy end",
                            Model = new byte[0],
                            ProductVersion = "Awesomeness"
                        });

                using (var commandTracer = new CommandTracer(historyContext))
                {
                    historyContext.SaveChanges();

                    var insertHistoryOperation
                        = new HistoryOperation(commandTracer.CommandTrees.OfType<DbModificationCommandTree>().ToList());

                    var sql
                        = migrationSqlGenerator
                            .Generate(new[] { insertHistoryOperation }, "4.0")
                            .Single();

                    Assert.Equal(@"INSERT [__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion])
VALUES (N'House Lannister', N'The pointy end',  0x , N'Awesomeness')", sql.Sql.Trim());
                }
            }
        }
        private HistoryRepository SetupHistoryRepositoryForOrderingTest()
        {
            ResetDatabase();

            using (var context = CreateContext<ShopContext_v1>())
            {
                var model = context.GetModel();

                var clonedConnection = DbProviderServices.GetProviderFactory(context.Database.Connection).CreateConnection();
                clonedConnection.ConnectionString = context.Database.Connection.ConnectionString;

                using (var historyContext = new HistoryContext(clonedConnection, defaultSchema: null))
                {
                    context.InternalContext.MarkDatabaseInitialized();

                    context.Database.ExecuteSqlCommand(
                        ((IObjectContextAdapter)historyContext).ObjectContext.CreateDatabaseScript());

                    historyContext.History.Add(
                        new HistoryRow
                            {
                                MigrationId = "227309030010001_Migration1",
                                ContextKey = "MyKey",
                                Model = new ModelCompressor().Compress(model),
                                ProductVersion = "",
                            });

                    historyContext.History.Add(
                        new HistoryRow
                            {
                                MigrationId = "227209030010001_Migration2",
                                ContextKey = "MyKey",
                                Model = new ModelCompressor().Compress(model),
                                ProductVersion = "",
                            });

                    historyContext.SaveChanges();
                }
            }

            return new HistoryRepository(ConnectionString, ProviderFactory, "MyKey", null);
        }
        private static MigrationOperation[] Create_operations_to_upgrade_primary_key_of_history_table()
        {
            const string tableName = "dbo." + HistoryContext.DefaultTableName;

            CreateTableOperation createTableOperation;
            using (var context = new HistoryContext())
            {
                var emptyModel = new DbModelBuilder()
                    .Build(context.Database.Connection).GetModel();
                createTableOperation = (CreateTableOperation)
                                       new EdmModelDiffer().Diff(emptyModel, context.GetModel()).Single();
            }

            var addColumnOperation =
                new AddColumnOperation(
                    tableName,
                    new ColumnModel(PrimitiveTypeKind.String)
                        {
                            MaxLength = 512,
                            Name = "ContextKey",
                            IsNullable = false,
                            DefaultValue = "DefaultContextKey"
                        });

            var dropPrimaryKeyOperation
                = new DropPrimaryKeyOperation
                      {
                          Table = tableName,
                          CreateTableOperation = createTableOperation
                      };

            dropPrimaryKeyOperation.Columns.Add("MigrationId");

            var alterColumnOperation
                = new AlterColumnOperation(
                    tableName,
                    new ColumnModel(PrimitiveTypeKind.String)
                        {
                            MaxLength = 150,
                            Name = "MigrationId",
                            IsNullable = false
                        },
                    isDestructiveChange: false);

            var addPrimaryKeyOperation
                = new AddPrimaryKeyOperation
                      {
                          Table = tableName
                      };

            addPrimaryKeyOperation.Columns.Add("MigrationId");
            addPrimaryKeyOperation.Columns.Add("ContextKey");

            return
                new MigrationOperation[]
                    {
                        addColumnOperation,
                        dropPrimaryKeyOperation,
                        alterColumnOperation,
                        addPrimaryKeyOperation
                    };
        }
        private IQueryable<HistoryRow> CreateHistoryQuery(HistoryContext context, string contextKey = null)
        {
            IQueryable<HistoryRow> q = context.History;

            contextKey
                = !string.IsNullOrWhiteSpace(contextKey)
                    ? contextKey.RestrictTo(_contextKeyMaxLength)
                    : _contextKey;

            if (_contextKeyColumnExists)
            {
                q = q.Where(h => h.ContextKey == contextKey);
            }

            return q;
        }
        private IQueryable<HistoryRow> CreateHistoryQuery(HistoryContext context, string contextKey = null)
        {
            IQueryable<HistoryRow> q = context.History;

            contextKey = contextKey ?? _contextKey;

            if (_contextKeyColumnExists)
            {
                q = q.Where(h => h.ContextKey == contextKey);
            }

            return q;
        }
示例#12
0
        public virtual IEnumerable <MigrationOperation> GetUpgradeOperations()
        {
            if (this.Exists((string)null))
            {
                DbConnection connection = (DbConnection)null;
                try
                {
                    connection = this.CreateConnection();
                    string             tableName = "dbo.__MigrationHistory";
                    DbProviderManifest providerManifest;
                    if (connection.GetProviderInfo(out providerManifest).IsSqlCe())
                    {
                        tableName = "__MigrationHistory";
                    }
                    using (LegacyHistoryContext context = new LegacyHistoryContext(connection))
                    {
                        bool createdOnExists = false;
                        try
                        {
                            this.InjectInterceptionContext((DbContext)context);
                            using (new TransactionScope(TransactionScopeOption.Suppress))
                                context.History.Select <LegacyHistoryRow, DateTime>((Expression <Func <LegacyHistoryRow, DateTime> >)(h => h.CreatedOn)).FirstOrDefault <DateTime>();
                            createdOnExists = true;
                        }
                        catch (EntityException ex)
                        {
                        }
                        if (createdOnExists)
                        {
                            yield return((MigrationOperation) new DropColumnOperation(tableName, "CreatedOn", (object)null));
                        }
                    }
                    using (HistoryContext context = this.CreateContext(connection, (string)null))
                    {
                        if (!this._contextKeyColumnExists)
                        {
                            if (this._historyContextFactory != HistoryContext.DefaultFactory)
                            {
                                throw Error.UnableToUpgradeHistoryWhenCustomFactory();
                            }
                            string      table1       = tableName;
                            ColumnModel columnModel1 = new ColumnModel(PrimitiveTypeKind.String);
                            columnModel1.MaxLength    = new int?(this._contextKeyMaxLength);
                            columnModel1.Name         = "ContextKey";
                            columnModel1.IsNullable   = new bool?(false);
                            columnModel1.DefaultValue = (object)this._contextKey;
                            ColumnModel column1 = columnModel1;
                            yield return((MigrationOperation) new AddColumnOperation(table1, column1, (object)null));

                            XDocument               emptyModel           = new DbModelBuilder().Build(connection).GetModel();
                            CreateTableOperation    createTableOperation = (CreateTableOperation) new EdmModelDiffer().Diff(emptyModel, context.GetModel(), (Lazy <ModificationCommandTreeGenerator>)null, (MigrationSqlGenerator)null, (string)null, (string)null).Single <MigrationOperation>();
                            DropPrimaryKeyOperation primaryKeyOperation1 = new DropPrimaryKeyOperation((object)null);
                            primaryKeyOperation1.Table = tableName;
                            primaryKeyOperation1.CreateTableOperation = createTableOperation;
                            DropPrimaryKeyOperation dropPrimaryKeyOperation = primaryKeyOperation1;
                            dropPrimaryKeyOperation.Columns.Add("MigrationId");
                            yield return((MigrationOperation)dropPrimaryKeyOperation);

                            string      table2       = tableName;
                            ColumnModel columnModel2 = new ColumnModel(PrimitiveTypeKind.String);
                            columnModel2.MaxLength  = new int?(this._migrationIdMaxLength);
                            columnModel2.Name       = "MigrationId";
                            columnModel2.IsNullable = new bool?(false);
                            ColumnModel column2 = columnModel2;
                            yield return((MigrationOperation) new AlterColumnOperation(table2, column2, false, (object)null));

                            AddPrimaryKeyOperation primaryKeyOperation2 = new AddPrimaryKeyOperation((object)null);
                            primaryKeyOperation2.Table = tableName;
                            AddPrimaryKeyOperation addPrimaryKeyOperation = primaryKeyOperation2;
                            addPrimaryKeyOperation.Columns.Add("MigrationId");
                            addPrimaryKeyOperation.Columns.Add("ContextKey");
                            yield return((MigrationOperation)addPrimaryKeyOperation);
                        }
                    }
                }
                finally
                {
                    this.DisposeConnection(connection);
                }
            }
        }
示例#13
0
        private bool QueryExists(string contextKey)
        {
            if (this._initialExistence == DatabaseExistenceState.DoesNotExist)
            {
                return(false);
            }
            DbConnection connection = (DbConnection)null;

            try
            {
                connection = this.CreateConnection();
                if (this._initialExistence == DatabaseExistenceState.Unknown)
                {
                    using (HistoryContext context = this.CreateContext(connection, (string)null))
                    {
                        if (!context.Database.Exists())
                        {
                            return(false);
                        }
                    }
                }
                foreach (string schema in this._schemas.Reverse <string>())
                {
                    using (HistoryContext context = this.CreateContext(connection, schema))
                    {
                        this._currentSchema          = schema;
                        this._contextKeyColumnExists = true;
                        try
                        {
                            using (new TransactionScope(TransactionScopeOption.Suppress))
                            {
                                contextKey = contextKey.RestrictTo(this._contextKeyMaxLength);
                                if (context.History.Count <HistoryRow>((Expression <Func <HistoryRow, bool> >)(hr => hr.ContextKey == contextKey)) > 0)
                                {
                                    return(true);
                                }
                            }
                        }
                        catch (EntityException ex)
                        {
                            this._contextKeyColumnExists = false;
                        }
                        if (!this._contextKeyColumnExists)
                        {
                            try
                            {
                                using (new TransactionScope(TransactionScopeOption.Suppress))
                                    context.History.Count <HistoryRow>();
                            }
                            catch (EntityException ex)
                            {
                                this._currentSchema = (string)null;
                            }
                        }
                    }
                }
            }
            finally
            {
                this.DisposeConnection(connection);
            }
            return(!string.IsNullOrWhiteSpace(this._currentSchema));
        }
        protected string GetMigrationHistory(DbMigrationsConfiguration migrationConfiguration, string migrationName)
        {
            // I would rather not use reflection to get the needed DbConnection but the alternative is requiring 
            // more configuraton or hardcoding to SQL Server. This looks to be the lesser of multiple evils

            MigratorBase migrator = CreateMigrator(migrationConfiguration);
            MethodInfo method = migrator.GetType().GetMethod("CreateConnection", BindingFlags.NonPublic | BindingFlags.Instance);

            using (DbConnection dbConnection = (DbConnection)method.Invoke(migrator, null))
            {
                dbConnection.Open();

                using (HistoryContext historyContext = new HistoryContext(dbConnection, null))
                {
                    HistoryRow history = historyContext.History.SingleOrDefault(x => x.MigrationId == migrationName);
                    if (history != null)
                    {
                        using (MemoryStream stream = new MemoryStream(history.Model))
                        {
                            using (GZipStream gzip = new GZipStream(stream, CompressionMode.Decompress))
                            {
                                return XDocument.Load(gzip).ToString();
                            }
                        }
                    }
                    else
                    {
                        return "Migration name not found";
                    }
                }
            }
        }
示例#15
0
        private XDocument GetInitialHistoryModel()
        {
            var initialHistoryModel
                = (from migrationId in _migrationAssembly.MigrationIds
                   let migrationMetadata = (IMigrationMetadata)_migrationAssembly.GetMigration(migrationId)
                   select new ModelCompressor().Decompress(Convert.FromBase64String(migrationMetadata.Target)))
                    .FirstOrDefault();

            if (initialHistoryModel == null)
            {
                using (var historyContext = new HistoryContext(CreateConnection(), true, null))
                {
                    initialHistoryModel = historyContext.GetModel();

                    initialHistoryModel
                        .Descendants()
                        .Each(a => a.SetAttributeValue(EdmXNames.IsSystemName, true));
                }
            }

            return initialHistoryModel;
        }