コード例 #1
0
 public abstract void Generate([NotNull] CreateTableOperation createTableOperation, [NotNull] IndentedStringBuilder stringBuilder);
コード例 #2
0
 public virtual void Visit(CreateTableOperation createTableOperation, DatabaseModel databaseModel)
 {
     databaseModel.AddTable(createTableOperation.Table);
 }
コード例 #3
0
        /// <summary>
        /// Generates a migration operation to create a table.
        /// </summary>
        /// <param name="op">The operation that represents creating a table.</param>
        /// <returns>A migration operation to create a table.</returns>
        protected virtual MigrationStatement Generate(CreateTableOperation op)
        {
            StringBuilder sb        = new StringBuilder();
            string        tableName = TrimSchemaPrefix(op.Name);

            primaryKeyCols.Clear();
            autoIncrementCols.Clear();
            if (_generatedTables == null)
            {
                _generatedTables = new List <string>();
            }

            if (!_generatedTables.Contains(tableName))
            {
                _generatedTables.Add(tableName);
            }
            sb.Append("create table " + "`" + tableName + "`" + " (");

            _tableName = op.Name;

            if (op.PrimaryKey != null)
            {
                op.PrimaryKey.Columns.ToList().ForEach(col => primaryKeyCols.Add(col));
            }

            //columns
            sb.Append(string.Join(",", op.Columns.Select(c => "`" + c.Name + "` " + Generate(c))));

            // Determine columns that are GUID & identity
            List <ColumnModel> guidCols = new List <ColumnModel>();
            ColumnModel        guidPK   = null;

            foreach (ColumnModel opCol in op.Columns)
            {
                if (opCol.Type == PrimitiveTypeKind.Guid && opCol.IsIdentity && String.Compare(opCol.StoreType, "CHAR(36) BINARY", true) == 0)
                {
                    if (primaryKeyCols.Contains(opCol.Name))
                    {
                        guidPK = opCol;
                    }
                    guidCols.Add(opCol);
                }
            }

            if (guidCols.Count != 0)
            {
                var createTrigger = new StringBuilder();
                createTrigger.AppendLine(string.Format("DROP TRIGGER IF EXISTS `{0}_IdentityTgr`;", TrimSchemaPrefix(_tableName)));
                createTrigger.AppendLine(string.Format("CREATE TRIGGER `{0}_IdentityTgr` BEFORE INSERT ON `{0}`", TrimSchemaPrefix(_tableName)));
                createTrigger.AppendLine("FOR EACH ROW BEGIN");
                for (int i = 0; i < guidCols.Count; i++)
                {
                    ColumnModel opCol = guidCols[i];
                    createTrigger.AppendLine(string.Format("SET NEW.{0} = UUID();", opCol.Name));
                }
                createTrigger.AppendLine(string.Format("DROP TEMPORARY TABLE IF EXISTS tmpIdentity_{0};", TrimSchemaPrefix(_tableName)));
                createTrigger.AppendLine(string.Format("CREATE TEMPORARY TABLE tmpIdentity_{0} (guid CHAR(36))ENGINE=MEMORY;", TrimSchemaPrefix(_tableName)));
                createTrigger.AppendLine(string.Format("INSERT INTO tmpIdentity_{0} VALUES(New.{1});", TrimSchemaPrefix(_tableName), guidPK.Name));
                createTrigger.AppendLine("END");
                var sqlOp = new SqlOperation(createTrigger.ToString());
                _specialStmts.Add(Generate(sqlOp));
            }

            if (op.PrimaryKey != null)// && !sb.ToString().Contains("primary key"))
            {
                sb.Append(",");
                sb.Append("primary key ( " + string.Join(",", op.PrimaryKey.Columns.Select(c => "`" + c + "`")) + ") ");
            }

            string keyFields = ",";

            autoIncrementCols.ForEach(col => keyFields += (!primaryKeyCols.Contains(col) ? string.Format(" KEY (`{0}`),", col) : ""));
            sb.Append(keyFields.Substring(0, keyFields.LastIndexOf(",")));
            sb.Append(") engine=InnoDb auto_increment=0");

            return(new MigrationStatement()
            {
                Sql = sb.ToString()
            });
        }
コード例 #4
0
        public void CreateTable()
        {
            var operation = new CreateTableOperation
            {
                Name    = "People",
                Columns =
                {
                    new AddColumnOperation
                    {
                    Name       = "Id",
                    Table      = "People",
                    ClrType    = typeof(int),
                    IsNullable = false,
                    [FbAnnotationNames.ValueGenerationStrategy] = FbValueGenerationStrategy.None,
                    },
                    new AddColumnOperation
                    {
                    Name       = "Id_Identity",
                    Table      = "People",
                    ClrType    = typeof(int),
                    IsNullable = false,
                    [FbAnnotationNames.ValueGenerationStrategy] = FbValueGenerationStrategy.IdentityColumn,
                    },
                    new AddColumnOperation
                    {
                    Name       = "Id_Sequence",
                    Table      = "People",
                    ClrType    = typeof(int),
                    IsNullable = false,
                    [FbAnnotationNames.ValueGenerationStrategy] = FbValueGenerationStrategy.SequenceTrigger,
                    },
                    new AddColumnOperation
                    {
                    Name       = "EmployerId",
                    Table      = "People",
                    ClrType    = typeof(int),
                    IsNullable = true,
                    },
                    new AddColumnOperation
                    {
                    Name       = "SSN",
                    Table      = "People",
                    ClrType    = typeof(string),
                    ColumnType = "char(11)",
                    IsNullable = true,
                    },
                    new AddColumnOperation
                    {
                    Name         = "DEF_O",
                    Table        = "People",
                    ClrType      = typeof(string),
                    MaxLength    = 20,
                    DefaultValue = "test",
                    IsNullable   = true,
                    },
                    new AddColumnOperation
                    {
                    Name            = "DEF_S",
                    Table           = "People",
                    ClrType         = typeof(string),
                    MaxLength       = 20,
                    DefaultValueSql = "'x'",
                    IsNullable      = true,
                    },
                },
                PrimaryKey = new AddPrimaryKeyOperation
                {
                    Columns = new[] { "Id" },
                },
                UniqueConstraints =
                {
                    new AddUniqueConstraintOperation
                    {
                        Columns = new[]{ "SSN"                     },
                    },
                },
                ForeignKeys =
                {
                    new AddForeignKeyOperation
                    {
                        Columns          = new[] { "EmployerId" },
                        PrincipalTable   = "Companies",
                        PrincipalColumns = new[]{ "Id"                                      },
                    },
                },
            };
            var expectedCreateTable = @"CREATE TABLE ""People"" (
    ""Id"" INTEGER NOT NULL,
    ""Id_Identity"" INTEGER GENERATED BY DEFAULT AS IDENTITY NOT NULL,
    ""Id_Sequence"" INTEGER NOT NULL,
    ""EmployerId"" INTEGER,
    ""SSN"" char(11),
    ""DEF_O"" VARCHAR(20) DEFAULT _UTF8'test',
    ""DEF_S"" VARCHAR(20) DEFAULT 'x',
    PRIMARY KEY (""Id""),
    UNIQUE (""SSN""),
    FOREIGN KEY (""EmployerId"") REFERENCES ""Companies"" (""Id"") ON UPDATE NO ACTION ON DELETE NO ACTION
);";
            var batch = Generate(new[] { operation });

            Assert.AreEqual(3, batch.Count());
            Assert.AreEqual(NewLineEnd(expectedCreateTable), batch[0].CommandText);
            StringAssert.Contains("rdb$generator_name = ", batch[1].CommandText);
            StringAssert.StartsWith("CREATE TRIGGER ", batch[2].CommandText);
        }
コード例 #5
0
 /// <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, nameof(createTableOperation));
     this._createTableOperation = createTableOperation;
     this._migration            = migration;
 }
コード例 #6
0
        /// <summary>
        /// Creates a table named Posts
        /// and columns int PostId, string Title, string Body
        /// </summary>
        /// <returns></returns>

        private CreateTableOperation CreateTableOperation()
        {
            TypeUsage tu;
            TypeUsage result;

            if (ProviderManifest == null)
            {
                ProviderManifest = new MySqlProviderManifest(Version.ToString());
            }

            var createTableOperation = new CreateTableOperation("Posts");

            //Column model for int IdPost
            tu     = TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32));
            result = ProviderManifest.GetStoreType(tu);

            var intColumn = new ColumnModel(PrimitiveTypeKind.Int32, result)
            {
                Name       = "PostId",
                IsNullable = false,
                IsIdentity = true
            };

            createTableOperation.Columns.Add(intColumn);

            //Column model for string
            tu     = TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));
            result = ProviderManifest.GetStoreType(tu);

            var stringColumnTitle = new ColumnModel(PrimitiveTypeKind.String, result)
            {
                Name       = "Title",
                IsNullable = false
            };

            var stringColumnBody = new ColumnModel(PrimitiveTypeKind.String, result)
            {
                Name       = "Body",
                IsNullable = true
            };

            createTableOperation.Columns.Add(stringColumnTitle);
            createTableOperation.Columns.Add(stringColumnBody);

            //Column model for binary
            tu     = TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Binary));
            result = ProviderManifest.GetStoreType(tu);

            var binaryColumn = new ColumnModel(PrimitiveTypeKind.Binary, result)
            {
                Name      = "Password",
                MaxLength = 10,
                StoreType = "binary"
            };

            createTableOperation.Columns.Add(binaryColumn);

            var primaryKey = new AddPrimaryKeyOperation();

            primaryKey.Columns.Add("PostId");

            createTableOperation.PrimaryKey = primaryKey;

            return(createTableOperation);
        }
コード例 #7
0
        protected override void Generate(CreateTableOperation operation, IndentedStringBuilder builder)
        {
            builder.AppendLine(".CreateTable(");

            using (builder.Indent())
            {
                builder
                .Append("name: ")
                .Append(Code.Literal(operation.Name));

                if (operation.Schema != null)
                {
                    builder
                    .AppendLine(",")
                    .Append("schema: ")
                    .Append(Code.Literal(operation.Schema));
                }

                builder
                .AppendLine(",")
                .AppendLine("columns: table => new")
                .AppendLine("{");

                var map = new Dictionary <string, string>();
                using (builder.Indent())
                {
                    var scope = new List <string>();
                    for (var i = 0; i < operation.Columns.Count; i++)
                    {
                        var column       = operation.Columns[i];
                        var propertyName = Code.Identifier(column.Name, scope);
                        map.Add(column.Name, propertyName);

                        builder
                        .Append(propertyName)
                        .Append(" = table.Column<")
                        .Append(Code.Reference(column.ClrType))
                        .Append(">(");

                        if (propertyName != column.Name)
                        {
                            builder
                            .Append("name: ")
                            .Append(Code.Literal(column.Name))
                            .Append(", ");
                        }

                        if (column.ColumnType != null)
                        {
                            builder
                            .Append("type: ")
                            .Append(Code.Literal(column.ColumnType))
                            .Append(", ");
                        }

                        if (column.IsUnicode == false)
                        {
                            builder.Append("unicode: false, ");
                        }

                        if (column.IsFixedLength == true)
                        {
                            builder.Append("fixedLength: true, ");
                        }

                        if (column.MaxLength.HasValue)
                        {
                            builder
                            .Append("maxLength: ")
                            .Append(Code.Literal(column.MaxLength.Value))
                            .Append(", ");
                        }

                        if (column.IsRowVersion)
                        {
                            builder.Append("rowVersion: true, ");
                        }

                        builder.Append("nullable: ")
                        .Append(Code.Literal(column.IsNullable));

                        if (column.DefaultValueSql != null)
                        {
                            builder
                            .Append(", defaultValueSql: ")
                            .Append(Code.Literal(column.DefaultValueSql));
                        }
                        else if (column.ComputedColumnSql != null)
                        {
                            builder
                            .Append(", computedColumnSql: ")
                            .Append(Code.Literal(column.ComputedColumnSql));
                        }
                        else if (column.DefaultValue != null)
                        {
                            builder
                            .Append(", defaultValue: ")
                            .Append(Code.UnknownLiteral(column.DefaultValue));
                        }

                        if (column.Comment != null)
                        {
                            builder
                            .Append(", comment: ")
                            .Append(Code.Literal(column.Comment));
                        }

                        builder.Append(")");

                        using (builder.Indent())
                        {
                            Annotations(column.GetAnnotations(), builder);
                        }

                        if (i != operation.Columns.Count - 1)
                        {
                            builder.Append(",");
                        }

                        builder.AppendLine();
                    }
                }

                builder
                .AppendLine("},")
                .AppendLine("constraints: table =>")
                .AppendLine("{");

                using (builder.Indent())
                {
                    if (operation.PrimaryKey != null)
                    {
                        builder
                        .Append("table.PrimaryKey(")
                        .Append(Code.Literal(operation.PrimaryKey.Name))
                        .Append(", ")
                        .Append(Code.Lambda(operation.PrimaryKey.Columns.Select(c => map[c]).ToList()))
                        .Append(")");

                        using (builder.Indent())
                        {
                            Annotations(operation.PrimaryKey.GetAnnotations(), builder);
                        }

                        builder.AppendLine(";");
                    }

                    foreach (var uniqueConstraint in operation.UniqueConstraints)
                    {
                        builder
                        .Append("table.UniqueConstraint(")
                        .Append(Code.Literal(uniqueConstraint.Name))
                        .Append(", ")
                        .Append(Code.Lambda(uniqueConstraint.Columns.Select(c => map[c]).ToList()))
                        .Append(")");

                        using (builder.Indent())
                        {
                            Annotations(uniqueConstraint.GetAnnotations(), builder);
                        }

                        builder.AppendLine(";");
                    }

                    foreach (var checkConstraints in operation.CheckConstraints)
                    {
                        builder
                        .Append("table.CheckConstraint(")
                        .Append(Code.Literal(checkConstraints.Name))
                        .Append(", ")
                        .Append(Code.Literal(checkConstraints.Sql))
                        .Append(")");

                        using (builder.Indent())
                        {
                            Annotations(checkConstraints.GetAnnotations(), builder);
                        }

                        builder.AppendLine(";");
                    }

                    foreach (var foreignKey in operation.ForeignKeys)
                    {
                        builder.AppendLine("table.ForeignKey(");

                        using (builder.Indent())
                        {
                            builder
                            .Append("name: ")
                            .Append(Code.Literal(foreignKey.Name))
                            .AppendLine(",")
                            .Append(
                                foreignKey.Columns.Length == 1
                                        ? "column: "
                                        : "columns: ")
                            .Append(Code.Lambda(foreignKey.Columns.Select(c => map[c]).ToList()));

                            if (foreignKey.PrincipalSchema != null)
                            {
                                builder
                                .AppendLine(",")
                                .Append("principalSchema: ")
                                .Append(Code.Literal(foreignKey.PrincipalSchema));
                            }

                            builder
                            .AppendLine(",")
                            .Append("principalTable: ")
                            .Append(Code.Literal(foreignKey.PrincipalTable))
                            .AppendLine(",");

                            if (foreignKey.PrincipalColumns.Length == 1)
                            {
                                builder
                                .Append("principalColumn: ")
                                .Append(Code.Literal(foreignKey.PrincipalColumns[0]));
                            }
                            else
                            {
                                builder
                                .Append("principalColumns: ")
                                .Append(Code.Literal(foreignKey.PrincipalColumns));
                            }

                            if (foreignKey.OnUpdate != ReferentialAction.NoAction)
                            {
                                builder
                                .AppendLine(",")
                                .Append("onUpdate: ")
                                .Append(Code.Literal(foreignKey.OnUpdate));
                            }

                            if (foreignKey.OnDelete != ReferentialAction.NoAction)
                            {
                                builder
                                .AppendLine(",")
                                .Append("onDelete: ")
                                .Append(Code.Literal(foreignKey.OnDelete));
                            }

                            builder.Append(")");

                            Annotations(foreignKey.GetAnnotations(), builder);
                        }

                        builder.AppendLine(";");
                    }
                }

                builder.Append("}");

                if (operation.Comment != null)
                {
                    builder
                    .AppendLine(",")
                    .Append("comment: ")
                    .Append(Code.Literal(operation.Comment));
                }

                builder.Append(")");

                Annotations(operation.GetAnnotations(), builder);
            }
        }
コード例 #8
0
 protected virtual void GenerateTableConstraints([NotNull] CreateTableOperation createTableOperation, [NotNull] IndentedStringBuilder stringBuilder)
 {
 }
        public void Generate_can_output_create_table_statement()
        {
            var createTableOperation = new CreateTableOperation("Customers");
            var idColumn             = new ColumnModel(PrimitiveTypeKind.Int32)
            {
                Name       = "I.d",
                IsNullable = true,
                IsIdentity = true
            };

            createTableOperation.Columns.Add(idColumn);
            createTableOperation.Columns.Add(
                new ColumnModel(PrimitiveTypeKind.String)
            {
                Name       = "Name",
                IsNullable = false
            });
            createTableOperation.PrimaryKey = new AddPrimaryKeyOperation
            {
                Name = "MyPK"
            };
            createTableOperation.PrimaryKey.Columns.Add(idColumn.Name);

            var codeGenerator = new CSharpMigrationCodeGenerator();

            var addForeignKeyOperation = new AddForeignKeyOperation
            {
                DependentTable = "Customers",
                PrincipalTable = "Blogs",
                CascadeDelete  = true
            };

            addForeignKeyOperation.DependentColumns.Add("Blog.Id");
            addForeignKeyOperation.PrincipalColumns.Add("Id");

            var generatedMigration
                = codeGenerator.Generate(
                      "Migration",
                      new MigrationOperation[]
            {
                createTableOperation,
                addForeignKeyOperation,
                addForeignKeyOperation.CreateCreateIndexOperation()
            },
                      "Source",
                      "Target",
                      "Foo",
                      "Bar");

            Assert.Equal(
                @"namespace Foo
{
    using System;
    using System.Data.Entity.Migrations;
    
    public partial class Bar : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                ""Customers"",
                c => new
                    {
                        Id = c.Int(name: ""I.d"", identity: true),
                        Name = c.String(nullable: false),
                    })
                .PrimaryKey(t => t.Id, name: ""MyPK"")
                .ForeignKey(""Blogs"", t => t.BlogId, cascadeDelete: true)
                .Index(t => t.BlogId);
            
        }
        
        public override void Down()
        {
            DropIndex(""Customers"", new[] { ""Blog.Id"" });
            DropForeignKey(""Customers"", ""Blog.Id"", ""Blogs"");
            DropTable(""Customers"");
        }
    }
}
",
                generatedMigration.UserCode);

            Assert.Equal(
                @"// <auto-generated />
namespace Foo
{
    using System.CodeDom.Compiler;
    using System.Data.Entity.Migrations;
    using System.Data.Entity.Migrations.Infrastructure;
    using System.Resources;
    
    [GeneratedCode(""EntityFramework.Migrations"", """ + typeof(DbContext).Assembly().GetInformationalVersion() + @""")]
    public sealed partial class Bar : IMigrationMetadata
    {
        private readonly ResourceManager Resources = new ResourceManager(typeof(Bar));
        
        string IMigrationMetadata.Id
        {
            get { return ""Migration""; }
        }
        
        string IMigrationMetadata.Source
        {
            get { return Resources.GetString(""Source""); }
        }
        
        string IMigrationMetadata.Target
        {
            get { return Resources.GetString(""Target""); }
        }
    }
}
",
                generatedMigration.DesignerCode);

            Assert.Equal("cs", generatedMigration.Language);
            Assert.Equal(2, generatedMigration.Resources.Count);
            Assert.Equal("Source", generatedMigration.Resources["Source"]);
            Assert.Equal("Target", generatedMigration.Resources["Target"]);
        }
コード例 #10
0
 public override void Visit(CreateTableOperation operation, IndentedStringBuilder builder)
 {
     builder.Append("Create").Append(operation.Table.Name).Append("Sql");
 }
コード例 #11
0
 protected override void Generate(CreateTableOperation operation, IModel model, MigrationCommandListBuilder builder)
 {
     RemoveForeignKeysHelper.ExecuForeignKeys(operation);
     base.Generate(operation, model, builder);
 }
コード例 #12
0
ファイル: TempDBContext.cs プロジェクト: skyclub66/EntityDB
        public MigrationOperation[] CheckOperations(List <MigrationOperation> operations, IDatabaseService invokingDB)
        {
            //sqlite 不支持column的修改
            bool   isCreateTable = operations.Any(m => m is CreateTableOperation);
            string tableName     = null;

            foreach (var o in operations)
            {
                if (o is DropColumnOperation)
                {
                    tableName = ((DropColumnOperation)o).Table;
                    break;
                }
                else if (o is RenameColumnOperation)
                {
                    tableName = ((RenameColumnOperation)o).Table;
                    break;
                }
                else if (o is AlterColumnOperation)
                {
                    tableName = ((AlterColumnOperation)o).Table;
                    break;
                }
            }
            _newTableName = tableName;
            List <EJ.DBColumn>          nowColumns           = null;
            List <EJ.DBColumn>          originalColumns      = null;
            List <IndexInfo>            nowIndexes           = null;
            List <CreateIndexOperation> newIndexOperations   = new List <CreateIndexOperation>();
            List <AddColumnOperation>   newColumnsOperations = new List <AddColumnOperation>();

            if (tableName != null)
            {
                _reCreateTable = true;
                var dbDesignService = DBHelper.CreateDatabaseDesignService(invokingDB.DBContext.DatabaseType);
                //取出目前数据库所有字段描述
                nowColumns      = dbDesignService.GetCurrentColumns(invokingDB, tableName);
                originalColumns = new List <EJ.DBColumn>();
                originalColumns.AddRange(nowColumns);
                nowIndexes = dbDesignService.GetCurrentIndexes(invokingDB, tableName);
            }

            foreach (var o in operations)
            {
                if (o is DropColumnOperation)
                {
                    var op = o as DropColumnOperation;

                    var column = nowColumns.FirstOrDefault(m => m.Name == op.Name);
                    if (column != null)
                    {
                        nowColumns.Remove(column);
                        originalColumns.Remove(column);
                    }
                }
                else if (o is RenameColumnOperation)
                {
                    var op = o as RenameColumnOperation;

                    var column = nowColumns.FirstOrDefault(m => m.Name == op.Name);
                    if (column != null)
                    {
                        column.BackupChangedProperties["copyfrom"] = new DataValueChangedItem()
                        {
                            OriginalValue = column.Name
                        };
                        column.Name = op.NewName;
                    }
                }
                else if (o is AlterColumnOperation)
                {
                    var op = o as AlterColumnOperation;

                    var column = nowColumns.FirstOrDefault(m => m.Name == op.Name);
                    if (column != null)
                    {
                        column.dbType       = op.ColumnType;
                        column.defaultValue = (string)op.DefaultValue;
                        column.CanNull      = op.IsNullable;
                    }
                }
                else if (o is DropIndexOperation)
                {
                    var op = o as DropIndexOperation;
                    if (nowIndexes != null)
                    {
                        var item = nowIndexes.FirstOrDefault(m => m.Name == op.Name);
                        if (item != null)
                        {
                            nowIndexes.Remove(item);
                        }
                    }
                }
                else if (o is CreateIndexOperation)
                {
                    newIndexOperations.Add((CreateIndexOperation)o);
                }
                else if (o is AddColumnOperation)
                {
                    newColumnsOperations.Add((AddColumnOperation)o);
                }
                else if (o is RenameTableOperation)
                {
                    _newTableName = ((RenameTableOperation)o).NewName;
                }
            }

            if (tableName != null)
            {
                //获取原来所有字段
                _newfields = new StringBuilder();
                _oldfields = new StringBuilder();
                foreach (var o in originalColumns)
                {
                    if (_oldfields.Length > 0)
                    {
                        _oldfields.Append(',');
                        _newfields.Append(',');
                    }
                    if (o.BackupChangedProperties["copyfrom"] != null)
                    {
                        _oldfields.Append($"[{o.BackupChangedProperties["copyfrom"]}]");
                        _newfields.Append($"[{o.Name}]");
                    }
                    else
                    {
                        _oldfields.Append($"[{o.Name}]");
                        _newfields.Append($"[{o.Name}]");
                    }
                }


                //需要重新建表
                operations.Clear();

                var _CreateTableOperation = new CreateTableOperation();
                operations.Add(_CreateTableOperation);
                _CreateTableOperation.Name = _newTableName;
                var pkColumns = nowColumns.Where(m => m.IsPKID == true).Select(m => m.Name.ToLower()).ToArray();
                if (pkColumns.Length > 0)
                {
                    _CreateTableOperation.PrimaryKey         = new AddPrimaryKeyOperation();
                    _CreateTableOperation.PrimaryKey.Columns = pkColumns;
                }


                foreach (var column in nowColumns)
                {
                    var _AddColumnOperation = new AddColumnOperation()
                    {
                        Table        = _CreateTableOperation.Name,
                        ClrType      = EF_CreateTable_Action.GetCSharpType(column.dbType),
                        ColumnType   = column.dbType,
                        DefaultValue = column.defaultValue,
                        IsUnicode    = true,
                        IsNullable   = column.CanNull.GetValueOrDefault(),
                        Name         = column.Name.ToLower(),
                    };
                    if (!string.IsNullOrEmpty(column.length))
                    {
                        //借用ComputedColumnSql字段存放length
                        _AddColumnOperation.ComputedColumnSql = column.length;
                    }
                    _CreateTableOperation.Columns.Add(_AddColumnOperation);
                }
                _CreateTableOperation.Columns.AddRange(newColumnsOperations);
                operations.AddRange(newIndexOperations);

                var idColumns = nowColumns.Where(m => m.IsAutoIncrement == true).Select(m => m.Name.ToLower()).ToArray();
                if (idColumns.Length > 0)
                {
                    foreach (var idc in idColumns)
                    {
                        var _CreateSequenceOperation = new CreateSequenceOperation()
                        {
                            StartValue = 1,
                            Name       = idc,
                        };
                        operations.Add(_CreateSequenceOperation);
                    }
                }

                foreach (var indexCfg in nowIndexes)
                {
                    var keynames = indexCfg.ColumnNames;
                    var _CreateIndexOperation = new CreateIndexOperation();
                    _CreateIndexOperation.Table    = _CreateTableOperation.Name;
                    _CreateIndexOperation.Name     = indexCfg.Name;
                    _CreateIndexOperation.Columns  = keynames.Select(m => m.ToLower()).ToArray();
                    _CreateIndexOperation.IsUnique = indexCfg.IsUnique;

                    operations.Add(_CreateIndexOperation);
                }
            }
            return(operations.ToArray());
        }
コード例 #13
0
        protected override IEnumerable <MigrationOperation> Diff(TableMapping source,
                                                                 TableMapping target, DiffContext diffContext)
        {
            if (source.Schema != target.Schema ||
                source.Name != target.Name)
            {
                // 如果是创建分表操作
                var entityType = target.EntityTypes[0];
                if (entityType.ClrType.IsDefined <ShardableAttribute>())
                {
                    // 不使用 Add 方法创建表操作,会添加重复的索引导致异常
                    var createTableOperation = new CreateTableOperation
                    {
                        Schema  = target.Schema,
                        Name    = target.Name,
                        Comment = target.GetComment()
                    };
                    createTableOperation.AddAnnotations(MigrationsAnnotations.For(entityType));

                    createTableOperation.Columns.AddRange
                        (GetSortedProperties(target)
                        .SelectMany(p => Add(p, diffContext, inline: true))
                        .Cast <AddColumnOperation>());

                    var primaryKey = entityType.FindPrimaryKey();
                    if (primaryKey != null)
                    {
                        createTableOperation.PrimaryKey = Add(primaryKey, diffContext).Cast <AddPrimaryKeyOperation>().Single();
                    }

                    createTableOperation.UniqueConstraints.AddRange(
                        target.GetKeys().Where(k => !k.IsPrimaryKey()).SelectMany(k => Add(k, diffContext))
                        .Cast <AddUniqueConstraintOperation>());

                    createTableOperation.CheckConstraints.AddRange(
                        target.GetCheckConstraints().SelectMany(c => Add(c, diffContext))
                        .Cast <CreateCheckConstraintOperation>());

                    foreach (var targetEntityType in target.EntityTypes)
                    {
                        diffContext.AddCreate(targetEntityType, createTableOperation);
                    }

                    yield return(createTableOperation);

                    yield break; // 跳出迭代,防止出现重复的添加主键、索引等相关操作
                }
                else
                {
                    yield return(new RenameTableOperation
                    {
                        Schema = source.Schema,
                        Name = source.Name,
                        NewSchema = target.Schema,
                        NewName = target.Name
                    });
                }
            }

            // Validation should ensure that all the relevant annotations for the collocated entity types are the same
            var sourceMigrationsAnnotations = MigrationsAnnotations.For(source.EntityTypes[0]).ToList();
            var targetMigrationsAnnotations = MigrationsAnnotations.For(target.EntityTypes[0]).ToList();

            if (source.GetComment() != target.GetComment() ||
                HasDifferences(sourceMigrationsAnnotations, targetMigrationsAnnotations))
            {
                var alterTableOperation = new AlterTableOperation
                {
                    Name     = target.Name,
                    Schema   = target.Schema,
                    Comment  = target.GetComment(),
                    OldTable = { Comment = source.GetComment() }
                };

                alterTableOperation.AddAnnotations(targetMigrationsAnnotations);
                alterTableOperation.OldTable.AddAnnotations(sourceMigrationsAnnotations);

                yield return(alterTableOperation);
            }

            var operations = Diff(source.GetProperties(), target.GetProperties(), diffContext)
                             .Concat(Diff(source.GetKeys(), target.GetKeys(), diffContext))
                             .Concat(Diff(source.GetIndexes(), target.GetIndexes(), diffContext))
                             .Concat(Diff(source.GetCheckConstraints(), target.GetCheckConstraints(), diffContext));

            foreach (var operation in operations)
            {
                yield return(operation);
            }

            DiffData(source, target, diffContext);
        }
コード例 #14
0
        protected virtual void Generate([NotNull] CreateTableOperation operation, [NotNull] IndentedStringBuilder builder)
        {
            Check.NotNull(operation, nameof(operation));
            Check.NotNull(builder, nameof(builder));

            builder.AppendLine(".CreateTable(");

            using (builder.Indent())
            {
                builder
                .Append("name: ")
                .Append(_code.Literal(operation.Name));

                if (operation.Schema != null)
                {
                    builder
                    .AppendLine(",")
                    .Append("schema: ")
                    .Append(_code.Literal(operation.Schema));
                }

                builder
                .AppendLine(",")
                .AppendLine("columns: table => new")
                .AppendLine("{");

                var map = new Dictionary <string, string>();
                using (builder.Indent())
                {
                    var scope = new List <string>();
                    for (var i = 0; i < operation.Columns.Count; i++)
                    {
                        var column       = operation.Columns[i];
                        var propertyName = _code.Identifier(column.Name, scope);
                        map.Add(column.Name, propertyName);

                        builder
                        .Append(propertyName)
                        .Append(" = table.Column(");

                        if (propertyName != column.Name)
                        {
                            builder
                            .Append("name: ")
                            .Append(_code.Literal(column.Name))
                            .Append(", ");
                        }

                        builder
                        .Append("type: ")
                        .Append(_code.Literal(column.Type))
                        .Append(", nullable: ")
                        .Append(_code.Literal(column.IsNullable));

                        if (column.DefaultExpression != null)
                        {
                            builder
                            .Append(", defaultExpression: ")
                            .Append(_code.Literal(column.DefaultExpression));
                        }
                        else if (column.DefaultValue != null)
                        {
                            builder
                            .Append(", defaultValue: ")
                            .Append(_code.UnknownLiteral(column.DefaultValue));
                        }

                        builder.Append(")");

                        using (builder.Indent())
                        {
                            Annotations(column.Annotations, builder);
                        }

                        if (i != operation.Columns.Count - 1)
                        {
                            builder.Append(",");
                        }

                        builder.AppendLine();
                    }
                }

                builder
                .AppendLine("},")
                .AppendLine("constraints: table =>")
                .AppendLine("{");

                using (builder.Indent())
                {
                    if (operation.PrimaryKey != null)
                    {
                        builder
                        .Append("table.PrimaryKey(")
                        .Append(_code.Literal(operation.PrimaryKey.Name))
                        .Append(", ")
                        .Append(_code.Lambda(operation.PrimaryKey.Columns.Select(c => map[c]).ToList()))
                        .Append(")");

                        using (builder.Indent())
                        {
                            Annotations(operation.PrimaryKey.Annotations, builder);
                        }

                        builder.AppendLine(";");
                    }

                    foreach (var uniqueConstraint in operation.UniqueConstraints)
                    {
                        builder
                        .Append("table.Unique(")
                        .Append(_code.Literal(uniqueConstraint.Name))
                        .Append(", ")
                        .Append(_code.Lambda(uniqueConstraint.Columns.Select(c => map[c]).ToList()))
                        .Append(")");

                        using (builder.Indent())
                        {
                            Annotations(uniqueConstraint.Annotations, builder);
                        }

                        builder.AppendLine(";");
                    }

                    foreach (var foreignKey in operation.ForeignKeys)
                    {
                        builder.AppendLine("table.ForeignKey(");

                        using (builder.Indent())
                        {
                            builder
                            .Append("name: ")
                            .Append(_code.Literal(foreignKey.Name))
                            .AppendLine(",")
                            .Append("columns: ")
                            .Append(_code.Lambda(foreignKey.Columns.Select(c => map[c]).ToList()));

                            if (foreignKey.ReferencedSchema != null)
                            {
                                builder
                                .AppendLine(",")
                                .Append("referencedSchema: ")
                                .Append(_code.Literal(foreignKey.ReferencedSchema));
                            }

                            builder
                            .AppendLine(",")
                            .Append("referencedTable: ")
                            .Append(_code.Literal(foreignKey.ReferencedTable));

                            if (foreignKey.ReferencedColumns != null)
                            {
                                builder
                                .AppendLine(",")
                                .Append(
                                    foreignKey.ReferencedColumns.Length == 1
                                            ? "referencedColumn: "
                                            : "referencedColumns: ")
                                .Append(_code.Literal(foreignKey.ReferencedColumns));
                            }

                            if (foreignKey.OnUpdate != ReferentialAction.NoAction)
                            {
                                builder
                                .AppendLine(",")
                                .Append("onUpdate: ")
                                .Append(_code.Literal(foreignKey.OnUpdate));
                            }

                            if (foreignKey.OnDelete != ReferentialAction.NoAction)
                            {
                                builder
                                .AppendLine(",")
                                .Append("onDelete: ")
                                .Append(_code.Literal(foreignKey.OnDelete));
                            }

                            builder.Append(")");

                            Annotations(foreignKey.Annotations, builder);
                        }

                        builder.AppendLine(";");
                    }
                }

                builder.Append("})");

                Annotations(operation.Annotations, builder);
            }
        }
コード例 #15
0
 //AddColumnOperation  在添加表触发
 protected override void Generate(CreateTableOperation createTableOperation)
 {
     SetCreatedColumns(createTableOperation.Columns);
     base.Generate(createTableOperation);
 }
コード例 #16
0
        protected override void Generate(CreateTableOperation operation, IModel model, MigrationCommandListBuilder builder)
        {
            var memoryOptimized = operation[SqlServerAnnotationNames.MemoryOptimized] as bool? == true;
            var temporal        = operation[SystemVersioningConstants.SqlServerSystemVersioning] as bool? == true;

            builder
            .Append("CREATE TABLE ")
            .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name, operation.Schema))
            .AppendLine(" (");

            var schema = operation.Schema ?? "dbo";

            using (builder.Indent())
            {
                for (var i = 0; i < operation.Columns.Count; i++)
                {
                    var column = operation.Columns[i];
                    ColumnDefinition(column, model, builder);

                    if (i != operation.Columns.Count - 1)
                    {
                        builder.AppendLine(",");
                    }
                }

                if (operation.PrimaryKey != null)
                {
                    builder.AppendLine(",");
                    PrimaryKeyConstraint(operation.PrimaryKey, model, builder);
                }

                foreach (var uniqueConstraint in operation.UniqueConstraints)
                {
                    builder.AppendLine(",");
                    UniqueConstraint(uniqueConstraint, model, builder);
                }

                foreach (var foreignKey in operation.ForeignKeys)
                {
                    builder.AppendLine(",");
                    ForeignKeyConstraint(foreignKey, model, builder);
                }

                if (temporal)
                {
                    builder.AppendLine(",");
                    builder.Append(
                        @"[SysStartTime] datetime2 GENERATED ALWAYS AS ROW START HIDDEN NOT NULL,
			            [SysEndTime] datetime2 GENERATED ALWAYS AS ROW END HIDDEN NOT NULL,  
			            PERIOD FOR SYSTEM_TIME([SysStartTime], [SysEndTime])"                        );
                }

                builder.AppendLine();
            }

            builder.Append(")");


            if (memoryOptimized || temporal)
            {
                builder.AppendLine();
                using (builder.Indent())
                {
                    builder.AppendLine("WITH (");
                    using (builder.Indent())
                    {
                        if (memoryOptimized)
                        {
                            builder.Append("MEMORY_OPTIMIZED = ON");
                        }

                        if (temporal)
                        {
                            builder.Append($"SYSTEM_VERSIONING = ON (HISTORY_TABLE = [{schema}].[{operation.Name}History])");
                        }
                    }
                    builder.AppendLine(")");
                }
            }

            builder
            .AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator)
            .EndCommand(suppressTransaction: memoryOptimized);
        }
コード例 #17
0
 /// <summary>
 /// 初始化类<see cref="CreateTableBuilder{TColumns}"/>
 /// </summary>
 /// <param name="operation">新建表格的操作实例。</param>
 public CreateTableBuilder(
     CreateTableOperation operation)
     : base(operation)
 {
     _entity = typeof(TEntity).GetEntityType();
 }
コード例 #18
0
        public void Generate_can_output_create_table_statement()
        {
            var createTableOperation = new CreateTableOperation("Customers");
            var idColumn             = new ColumnModel(PrimitiveTypeKind.Int32)
            {
                Name       = "Id",
                IsNullable = true,
                IsIdentity = true
            };

            createTableOperation.Columns.Add(idColumn);
            createTableOperation.Columns.Add(
                new ColumnModel(PrimitiveTypeKind.String)
            {
                Name       = "Name",
                IsNullable = false
            });
            createTableOperation.PrimaryKey = new AddPrimaryKeyOperation
            {
                Name = "MyPK"
            };
            createTableOperation.PrimaryKey.Columns.Add(idColumn.Name);

            var codeGenerator = new VisualBasicMigrationCodeGenerator();

            var addForeignKeyOperation = new AddForeignKeyOperation
            {
                DependentTable = "Customers",
                PrincipalTable = "Blogs",
                CascadeDelete  = true
            };

            addForeignKeyOperation.DependentColumns.Add("Blog_Id");
            addForeignKeyOperation.PrincipalColumns.Add("Id");

            var generatedMigration
                = codeGenerator.Generate(
                      "Migration",
                      new MigrationOperation[]
            {
                createTableOperation,
                addForeignKeyOperation,
                addForeignKeyOperation.CreateCreateIndexOperation()
            },
                      "Source",
                      "Target",
                      "Foo",
                      "Bar");

            Assert.Equal(
                @"Imports System
Imports System.Data.Entity.Migrations
Imports Microsoft.VisualBasic

Namespace Foo
    Public Partial Class Bar
        Inherits DbMigration
    
        Public Overrides Sub Up()
            CreateTable(
                ""Customers"",
                Function(c) New With
                    {
                        .Id = c.Int(identity := True),
                        .Name = c.String(nullable := False)
                    }) _
                .PrimaryKey(Function(t) t.Id, name := ""MyPK"") _
                .ForeignKey(""Blogs"", Function(t) t.Blog_Id, cascadeDelete := True) _
                .Index(Function(t) t.Blog_Id)
            
        End Sub
        
        Public Overrides Sub Down()
            DropIndex(""Customers"", New String() { ""Blog_Id"" })
            DropForeignKey(""Customers"", ""Blog_Id"", ""Blogs"")
            DropTable(""Customers"")
        End Sub
    End Class
End Namespace
",
                generatedMigration.UserCode);

            Assert.Equal(
                @"' <auto-generated />
Imports System.CodeDom.Compiler
Imports System.Data.Entity.Migrations
Imports System.Data.Entity.Migrations.Infrastructure
Imports System.Resources

Namespace Foo
    <GeneratedCode(""EntityFramework.Migrations"", """ + typeof(DbContext).Assembly.GetInformationalVersion() + @""")>
    Public NotInheritable Partial Class Bar
        Implements IMigrationMetadata
    
        Private ReadOnly Resources As New ResourceManager(GetType(Bar))
        
        Private ReadOnly Property IMigrationMetadata_Id() As String Implements IMigrationMetadata.Id
            Get
                Return ""Migration""
            End Get
        End Property
        
        Private ReadOnly Property IMigrationMetadata_Source() As String Implements IMigrationMetadata.Source
            Get
                Return Resources.GetString(""Source"")
            End Get
        End Property
        
        Private ReadOnly Property IMigrationMetadata_Target() As String Implements IMigrationMetadata.Target
            Get
                Return Resources.GetString(""Target"")
            End Get
        End Property
    End Class
End Namespace
",
                generatedMigration.DesignerCode);

            Assert.Equal("vb", generatedMigration.Language);
            Assert.Equal(2, generatedMigration.Resources.Count);
            Assert.Equal("Source", generatedMigration.Resources["Source"]);
            Assert.Equal("Target", generatedMigration.Resources["Target"]);
        }
コード例 #19
0
ファイル: Configuration.cs プロジェクト: alexeylipaev/ACS
 protected override void Generate(CreateTableOperation createTableOperation)
 {
     SetAnnotatedColumns(createTableOperation.Columns, createTableOperation.Name);
     base.Generate(createTableOperation);
 }
コード例 #20
0
        public void When_Create_Table_With_Different_KeyTypes_Then_CQL_Is_Returned()
        {
            Action <ModelBuilder> firstModelBuilderCallback = (modelBuilder) =>
            {
                var entity = modelBuilder.Entity <Applicant>()
                             .ToTable("applicants");
                entity.HasKey(p => p.Id);
            };
            Action <ModelBuilder> secondModelBuilderCallback = (modelBuilder) =>
            {
                var entity = modelBuilder.Entity <Applicant>()
                             .ToTable("applicants");
                entity.HasKey(p => p.Id);
                entity.ForCassandraSetClusterColumns(new[] { "lastname" });
            };
            Action <ModelBuilder> thirdModelBuilderCallback = (modelBuilder) =>
            {
                var entity = modelBuilder.Entity <Applicant>()
                             .ToTable("applicants");
                entity.HasKey(p => p.Id);
                entity.ForCassandraSetClusterColumns(new[] { "lastname" });
                entity.ForCassandraSetStaticColumns(new[] { "applicationname" });
            };
            var createTable = new CreateTableOperation
            {
                Name    = "applicants",
                Schema  = "cv",
                Columns =
                {
                    new AddColumnOperation
                    {
                        Name    = "id",
                        ClrType = typeof(Guid),
                        Table   = "applicants"
                    },
                    new AddColumnOperation
                    {
                        Name    = "lastname",
                        ClrType = typeof(string),
                        Table   = "applicants"
                    },
                    new AddColumnOperation
                    {
                        Name    = "applicationname",
                        ClrType = typeof(string),
                        Table   = "applicants"
                    },
                    new AddColumnOperation
                    {
                        Name    = "lst",
                        ClrType = typeof(List <string>),
                        Table   = "applicants"
                    },
                    new AddColumnOperation
                    {
                        Name    = "dic",
                        ClrType = typeof(Dictionary <string, string>),
                        Table   = "applicants"
                    }
                },
                PrimaryKey = new AddPrimaryKeyOperation
                {
                    Columns = new[] { "id" },
                    Table   = "applicants"
                }
            };
            var firstSql  = BuildSql(firstModelBuilderCallback, createTable);
            var secondSql = BuildSql(secondModelBuilderCallback, createTable);
            var thirdSql  = BuildSql(thirdModelBuilderCallback, createTable);

            Assert.Equal("CREATE TABLE \"cv\".\"applicants\" (\r\n    \"id\" uuid,\r\n    \"lastname\" text,\r\n    \"applicationname\" text,\r\n    \"lst\" list<text>,\r\n    \"dic\" map<text,text>,\r\n    PRIMARY KEY ((\"id\"))\r\n);\r\n", firstSql);
            Assert.Equal("CREATE TABLE \"cv\".\"applicants\" (\r\n    \"id\" uuid,\r\n    \"lastname\" text,\r\n    \"applicationname\" text,\r\n    \"lst\" list<text>,\r\n    \"dic\" map<text,text>,\r\n    PRIMARY KEY ((\"id\"),\"lastname\")\r\n);\r\n", secondSql);
            Assert.Equal("CREATE TABLE \"cv\".\"applicants\" (\r\n    \"id\" uuid,\r\n    \"lastname\" text,\r\n    \"applicationname\" text STATIC,\r\n    \"lst\" list<text>,\r\n    \"dic\" map<text,text>,\r\n    PRIMARY KEY ((\"id\"),\"lastname\")\r\n);\r\n", thirdSql);
        }
コード例 #21
0
 protected override void CreateTableForeignKeys(CreateTableOperation operation, IModel model, MigrationCommandListBuilder builder)
 {
     //base.CreateTableForeignKeys(operation, model, builder);
 }
コード例 #22
0
 public virtual void AddCreate([NotNull] IEntityType target, [NotNull] CreateTableOperation operation)
 => _createTableOperations.Add(target, operation);
コード例 #23
0
        /// <summary>
        ///     Constructs a builder for the given <see cref="CreateTableOperation" />.
        /// </summary>
        /// <param name="createTableOperation"> The operation. </param>
        public ColumnsBuilder([NotNull] CreateTableOperation createTableOperation)
        {
            Check.NotNull(createTableOperation, nameof(createTableOperation));

            _createTableOperation = createTableOperation;
        }
コード例 #24
0
 protected virtual void Generate(
     [NotNull] CreateTableOperation operation,
     [CanBeNull] IModel model,
     [NotNull] MigrationCommandListBuilder builder)
 => Generate(operation, model, builder, terminate: true);