Example #1
0
        public RemoveColumn(Table table, string name)
        {
            Unsafe = name == "Document" || name == "Id";

            Table = table;
            Name = name;
        }
Example #2
0
        public RemoveColumn(Table table, string name)
        {
            Unsafe = true;

            Table = table;
            Name = name;
        }
Example #3
0
 protected static IDictionary<Column, object> ConvertAnonymousToProjections(Table table, object projections)
 {
     return projections as IDictionary<Column, object> ??
            (from projection in projections as IDictionary<string, object> ?? ObjectToDictionaryRegistry.Convert(projections)
             let column = table[projection]
             where column != null
             select new KeyValuePair<Column, object>(column, projection.Value)).ToDictionary();
 }
Example #4
0
        public RenameColumn(Table table, string oldColumnName, string newColumnName)
        {
            Unsafe = oldColumnName == "Document";

            Table = table;
            OldColumnName = oldColumnName;
            NewColumnName = newColumnName;
        }
        public void RemovesTempTableColumn(TableMode mode)
        {
            Use(mode);

            var table = new Table("Entities", new Column("FirstColumn", typeof(int)));
            new CreateTable(table).Execute(store.Database);
            new AddColumn("Entities", new Column("SomeColumn", typeof(int))).Execute(store.Database);

            new RemoveColumn(table, "SomeColumn").Execute(store.Database);

            store.Database.QuerySchema()["Entities"]["SomeColumn"].ShouldBe(null);
        }
Example #6
0
        public void RemovesColumn()
        {
            Use(TableMode.UseRealTables);

            var table = new Table("Entities", new Column("FirstColumn", typeof (int)));
            new CreateTable(table).Execute(database);
            new AddColumn("Entities", new Column("SomeColumn", typeof(int))).Execute(database);

            new RemoveColumn(table, "SomeColumn").Execute(database);

            database.QuerySchema()["Entities"]["SomeColumn"].ShouldBe(null);
        }
Example #7
0
        public void RenamesColumn(TableMode mode)
        {
            Use(mode);

            var table = new Table("Entities", new Column("Col1", typeof(int)));

            new CreateTable(table).Execute(database);
            new AddColumn("Entities", new Column("SomeColumn", typeof(int))).Execute(database);

            new RenameColumn(table, "SomeColumn", "SomeNewColumn").Execute(database);

            database.QuerySchema()["Entities"]["SomeColumn"].ShouldBe(null);
            database.QuerySchema()["Entities"]["SomeNewColumn"].ShouldNotBe(null);
        }
        public void RenamesColumn(TableMode mode)
        {
            Use(mode);
            UseTableNamePrefix(Guid.NewGuid().ToString());

            var table = new Table("Entities", new Column("Col1", typeof(int)));

            new CreateTable(table).Execute(store.Database);
            new AddColumn("Entities", new Column("SomeColumn", typeof(int))).Execute(store.Database);

            new RenameColumn(table, "SomeColumn", "SomeNewColumn").Execute(store.Database);

            store.Database.QuerySchema()["Entities"]["SomeColumn"].ShouldBe(null);
            store.Database.QuerySchema()["Entities"]["SomeNewColumn"].ShouldNotBe(null);
        }
Example #9
0
 public EntityKey(Table table, string id)
 {
     Table = table;
     Id = id;
 }
Example #10
0
 public void OnRead(Table table, IDictionary<string, object> projections)
 {
     throw new OperationException();
 }
Example #11
0
        public void Run()
        {
            if (!store.Configuration.RunSchemaMigrationsOnStartup)
                return;

            var requiresReprojection = new List<string>();

            var database = ((DocumentStore)store).Database;
            var configuration = store.Configuration;

            using (var tx = new TransactionScope(TransactionScopeOption.RequiresNew, new TransactionOptions { IsolationLevel = IsolationLevel.Serializable }))
            {
                var metadata = new Table("HybridDb", new Column("SchemaVersion", typeof(int)));
                configuration.Tables.TryAdd(metadata.Name, metadata);

                new CreateTable(metadata).Execute(database);

                var currentSchemaVersion = database.RawQuery<int>(
                    string.Format("select top 1 SchemaVersion from {0} with (tablockx, holdlock)", 
                        database.FormatTableNameAndEscape("HybridDb"))).SingleOrDefault();

                if (currentSchemaVersion > store.Configuration.ConfiguredVersion)
                {
                    throw new InvalidOperationException(string.Format(
                        "Database schema is ahead of configuration. Schema is version {0}, but configuration is version {1}.", 
                        currentSchemaVersion, store.Configuration.ConfiguredVersion));
                }

                if (database is SqlServerUsingRealTables)
                {
                    if (currentSchemaVersion < configuration.ConfiguredVersion)
                    {
                        var migrationsToRun = migrations.OrderBy(x => x.Version).Where(x => x.Version > currentSchemaVersion).ToList();
                        logger.Information("Migrates schema from version {0} to {1}.", currentSchemaVersion, configuration.ConfiguredVersion);

                        foreach (var migration in migrationsToRun)
                        {
                            var migrationCommands = migration.MigrateSchema();
                            foreach (var command in migrationCommands)
                            {
                                requiresReprojection.AddRange(ExecuteCommand(database, command));
                            }

                            currentSchemaVersion++;
                        }
                    }
                }
                else
                {
                    logger.Information("Skips provided migrations when not using real tables.");
                }

                var schema = database.QuerySchema().Values.ToList(); // demeter go home!
                var commands = differ.CalculateSchemaChanges(schema, configuration);

                if (commands.Any())
                {
                    logger.Information("Found {0} differences between current schema and configuration. Migrates schema to get up to date.", commands.Count);

                    foreach (var command in commands)
                    {
                        requiresReprojection.AddRange(ExecuteCommand(database, command));
                    }
                }

                foreach (var tablename in requiresReprojection)
                {
                    // TODO: Only set RequireReprojection on command if it is documenttable - can it be done?
                    var design = configuration.DocumentDesigns.FirstOrDefault(x => x.Table.Name == tablename);
                    if (design == null) continue;

                    database.RawExecute(string.Format("update {0} set [email protected]",
                        database.FormatTableNameAndEscape(tablename)), new { AwaitsReprojection = true });
                }

                database.RawExecute(string.Format(@"
if not exists (select * from {0}) 
    insert into {0} (SchemaVersion) values (@version); 
else
    update {0} set [email protected]",
                    database.FormatTableNameAndEscape("HybridDb")),
                    new { version = currentSchemaVersion });

                tx.Complete();
            }
        }
Example #12
0
 public CreateTable(Table table)
 {
     Table = table;
 }
        public void RunsProvidedSchemaMigrationsInOrderThenDiffed()
        {
            CreateMetadataTable();

            var table = new Table("Testing", new Column("Id", typeof(Guid), isPrimaryKey: true));

            UseMigrations(
                new InlineMigration(2, new AddColumn("Testing", new Column("Noget", typeof(int)))),
                new InlineMigration(1, new CreateTable(table)));

            var runner = new SchemaMigrationRunner(store,
                new FakeSchemaDiffer(new RenameColumn(table, "Noget", "NogetNyt")));

            runner.Run();

            var tables = store.Database.QuerySchema();
            tables.ShouldContainKey("Testing");
            tables["Testing"]["Id"].ShouldNotBe(null);
            tables["Testing"]["NogetNyt"].ShouldNotBe(null);
        }
Example #14
0
 public ColumnAlreadRegisteredException(Table table, Column column)
     : base(string.Format("The table {0} already has a column named {1} and is not of the same type.", table.Name, column.Name)) {}
        public void Run()
        {
            if (!store.Configuration.RunSchemaMigrationsOnStartup)
                return;

            var requiresReprojection = new List<string>();

            var database = ((DocumentStore)store).Database;
            var configuration = store.Configuration;

            using (var tx = new TransactionScope(TransactionScopeOption.RequiresNew, new TransactionOptions { IsolationLevel = IsolationLevel.Serializable }))
            {
                // lock other migrators out while executing
                using (var connection = database.Connect())
                {
                    var parameters = new DynamicParameters();
                    parameters.Add("@Resource", "HybridDb");
                    parameters.Add("@DbPrincipal", "public");
                    parameters.Add("@LockMode", "Exclusive");
                    parameters.Add("@LockOwner", "Transaction");
                    parameters.Add("@LockTimeout", TimeSpan.FromMinutes(1).TotalMilliseconds);
                    parameters.Add("@Result", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);

                    connection.Connection.Execute(@"sp_getapplock", parameters, commandType: CommandType.StoredProcedure);

                    var result = parameters.Get<int>("@Result");

                    if (result < 0)
                    {
                        throw new InvalidOperationException($"sp_getapplock failed with code {result}");
                    }

                    connection.Complete();
                }

                // create metadata table if it does not exist
                var metadata = new Table("HybridDb", new Column("SchemaVersion", typeof(int)));
                configuration.Tables.TryAdd(metadata.Name, metadata);
                new CreateTable(metadata).Execute(database);

                // get schema version
                var currentSchemaVersion = database.RawQuery<int>(
                    $"select top 1 SchemaVersion from {database.FormatTableNameAndEscape("HybridDb")}")
                    .SingleOrDefault();

                if (currentSchemaVersion > store.Configuration.ConfiguredVersion)
                {
                    throw new InvalidOperationException(
                        $"Database schema is ahead of configuration. Schema is version {currentSchemaVersion}, " +
                        $"but configuration is version {store.Configuration.ConfiguredVersion}.");
                }

                // run provided migrations only if we are using real tables
                if (database is SqlServerUsingRealTables)
                {
                    if (currentSchemaVersion < configuration.ConfiguredVersion)
                    {
                        var migrationsToRun = migrations.OrderBy(x => x.Version).Where(x => x.Version > currentSchemaVersion).ToList();
                        logger.Information("Migrates schema from version {0} to {1}.", currentSchemaVersion, configuration.ConfiguredVersion);

                        foreach (var migration in migrationsToRun)
                        {
                            var migrationCommands = migration.MigrateSchema();
                            foreach (var command in migrationCommands)
                            {
                                requiresReprojection.AddRange(ExecuteCommand(database, command));
                            }

                            currentSchemaVersion++;
                        }
                    }
                }
                else
                {
                    logger.Information("Skips provided migrations when not using real tables.");
                }

                // get the diff and run commands to get to configured schema
                var schema = database.QuerySchema().Values.ToList(); // demeter go home!
                var commands = differ.CalculateSchemaChanges(schema, configuration);

                if (commands.Any())
                {
                    logger.Information("Found {0} differences between current schema and configuration. Migrates schema to get up to date.", commands.Count);

                    foreach (var command in commands)
                    {
                        requiresReprojection.AddRange(ExecuteCommand(database, command));
                    }
                }

                // flag each document of tables that need to run a re-projection
                foreach (var tablename in requiresReprojection)
                {
                    // TODO: Only set RequireReprojection on command if it is documenttable - can it be done?
                    var design = configuration.TryGetDesignByTablename(tablename);
                    if (design == null) continue;

                    database.RawExecute(
                        $"update {database.FormatTableNameAndEscape(tablename)} set [email protected]",
                        new { AwaitsReprojection = true });
                }

                // update the schema version
                database.RawExecute(string.Format(@"
            if not exists (select * from {0})
            insert into {0} (SchemaVersion) values (@version);
            else
            update {0} set [email protected]",
                    database.FormatTableNameAndEscape("HybridDb")),
                    new { version = currentSchemaVersion });

                tx.Complete();
            }
        }