public DropForeignKeyOperation(AddForeignKeyOperation inverse, object anonymousArguments = null) : base(anonymousArguments) { //Contract.Requires(inverse != null); _inverse = inverse; }
public void Inverse_should_return_add_foreign_key_operation() { var addForeignKeyOperation = new AddForeignKeyOperation(); var dropForeignKeyOperation = new DropForeignKeyOperation(addForeignKeyOperation); Assert.Same(addForeignKeyOperation, dropForeignKeyOperation.Inverse); }
public DropForeignKeyOperation(AddForeignKeyOperation inverse, object anonymousArguments = null) : base(anonymousArguments) { Check.NotNull(inverse, "inverse"); _inverse = inverse; }
protected override void Generate(AddForeignKeyOperation addForeignKeyOperation, IndentedTextWriter writer) { var isReadonly = ReadonlyEntities.Contains(addForeignKeyOperation.PrincipalTable) || ReadonlyEntities.Contains(addForeignKeyOperation.DependentTable); ; //if (!isReadonly) { base.Generate(addForeignKeyOperation, writer); } }
public void DefaultName_is_restricted_to_128_chars() { var addForeignKeyOperation = new AddForeignKeyOperation { PrincipalTable = "P", DependentTable = "D" }; addForeignKeyOperation.DependentColumns.Add(new string('c', 150)); Assert.Equal(128, addForeignKeyOperation.DefaultName.Length); }
public void CreateCreateIndexOperation_should_return_corresponding_create_index_operation() { var addForeignKeyOperation = new AddForeignKeyOperation { PrincipalTable = "P", DependentTable = "D", Name = "Foo" }; addForeignKeyOperation.DependentColumns.Add("fk"); var createIndexOperation = addForeignKeyOperation.CreateCreateIndexOperation(); Assert.Equal(createIndexOperation.DefaultName, createIndexOperation.Name); Assert.Equal("D", createIndexOperation.Table); Assert.Equal("fk", createIndexOperation.Columns.Single()); }
public void Inverse_should_produce_drop_foreign_key_operation() { var addForeignKeyOperation = new AddForeignKeyOperation { PrincipalTable = "P", DependentTable = "D", Name = "Foo" }; addForeignKeyOperation.PrincipalColumns.Add("pk"); addForeignKeyOperation.DependentColumns.Add("fk"); var dropForeignKeyOperation = (DropForeignKeyOperation)addForeignKeyOperation.Inverse; Assert.Equal("P", dropForeignKeyOperation.PrincipalTable); Assert.Equal("D", dropForeignKeyOperation.DependentTable); Assert.Equal("fk", dropForeignKeyOperation.DependentColumns.Single()); Assert.Equal("Foo", dropForeignKeyOperation.Name); Assert.Equal("FK_D_P_fk", dropForeignKeyOperation.DefaultName); }
public void Can_get_and_set_properties() { var addForeignKeyOperation = new AddForeignKeyOperation { PrincipalTable = "P", DependentTable = "D", CascadeDelete = true, Name = "Foo" }; addForeignKeyOperation.PrincipalColumns.Add("pk"); addForeignKeyOperation.DependentColumns.Add("fk"); Assert.Equal("P", addForeignKeyOperation.PrincipalTable); Assert.Equal("D", addForeignKeyOperation.DependentTable); Assert.Equal("pk", addForeignKeyOperation.PrincipalColumns.Single()); Assert.Equal("fk", addForeignKeyOperation.DependentColumns.Single()); Assert.True(addForeignKeyOperation.CascadeDelete); Assert.Equal("Foo", addForeignKeyOperation.Name); Assert.Equal("FK_D_P_fk", addForeignKeyOperation.DefaultName); Assert.False(addForeignKeyOperation.HasDefaultName); }
public void Inverse_should_produce_drop_foreign_key_operation() { var addForeignKeyOperation = new AddForeignKeyOperation { PrincipalTable = "P", DependentTable = "D", Name = "Foo", IsSystem = true }; addForeignKeyOperation.PrincipalColumns.Add("pk"); addForeignKeyOperation.DependentColumns.Add("fk"); var dropForeignKeyOperation = (DropForeignKeyOperation)addForeignKeyOperation.Inverse; Assert.Equal("P", dropForeignKeyOperation.PrincipalTable); Assert.Equal("D", dropForeignKeyOperation.DependentTable); Assert.Equal("fk", dropForeignKeyOperation.DependentColumns.Single()); Assert.Equal("Foo", dropForeignKeyOperation.Name); Assert.Equal("FK_D_P_fk", dropForeignKeyOperation.DefaultName); Assert.True(dropForeignKeyOperation.IsSystem); }
public void CreateDropIndexOperation_should_return_corresponding_drop_index_operation() { var addForeignKeyOperation = new AddForeignKeyOperation { DependentTable = "D" }; addForeignKeyOperation.DependentColumns.Add("fk"); var dropForeignKeyOperation = new DropForeignKeyOperation(addForeignKeyOperation) { DependentTable = "D" }; dropForeignKeyOperation.DependentColumns.Add("fk"); var dropIndexOperation = dropForeignKeyOperation.CreateDropIndexOperation(); Assert.Equal("D", dropIndexOperation.Table); Assert.NotNull(dropIndexOperation.Inverse); Assert.Equal("fk", dropIndexOperation.Columns.Single()); }
protected virtual MigrationStatement Generate(AddForeignKeyOperation op) { StringBuilder sb = new StringBuilder(); string fkName = op.Name; if (fkName.Length > 64) { fkName = "FK_" + Guid.NewGuid().ToString().Replace("-", ""); } sb.Append("alter table `" + TrimSchemaPrefix(op.DependentTable) + "` add constraint `" + TrimSchemaPrefix(fkName) + "` " + " foreign key "); sb.Append("(" + string.Join(",", op.DependentColumns.Select(c => "`" + c + "`")) + ") "); sb.Append("references `" + TrimSchemaPrefix(op.PrincipalTable) + "` ( " + string.Join(",", op.PrincipalColumns.Select(c => "`" + c + "`")) + ") "); if (op.CascadeDelete) { sb.Append(" on update cascade on delete cascade "); } return new MigrationStatement { Sql = sb.ToString() }; }
protected override void GenerateInline(AddForeignKeyOperation addForeignKeyOperation, IndentedTextWriter writer) { writer.WriteLine(); writer.Write(".ForeignKey(\"" + TrimSchemaPrefix(addForeignKeyOperation.PrincipalTable) + "\", "); Generate(addForeignKeyOperation.DependentColumns, writer); writer.Write(addForeignKeyOperation.CascadeDelete ? ", cascadeDelete: true)" : ")"); }
protected virtual MigrationStatement Generate(AddForeignKeyOperation op) { StringBuilder sb = new StringBuilder(); sb.Append("alter table `" + op.DependentTable + "` add constraint `" + op.Name + "` " + " foreign key "); sb.Append("(" + string.Join(",", op.DependentColumns.Select(c => "`" + c + "`")) + ") "); sb.Append("references `" + op.PrincipalTable + "` ( " + string.Join(",", op.PrincipalColumns.Select(c => "`" + c + "`")) + ") "); if (op.CascadeDelete) { sb.Append(" on update cascade on delete cascade "); } return new MigrationStatement { Sql = sb.ToString() }; }
/// <summary> /// Generates code to perform an <see cref="AddForeignKeyOperation" /> as part of a <see cref="CreateTableOperation" />. /// </summary> /// <param name="addForeignKeyOperation"> The operation to generate code for. </param> /// <param name="writer"> Text writer to add the generated code to. </param> protected virtual void GenerateInline(AddForeignKeyOperation addForeignKeyOperation, IndentedTextWriter writer) { Check.NotNull(addForeignKeyOperation, "addForeignKeyOperation"); Check.NotNull(writer, "writer"); writer.WriteLine(" _"); writer.Write(".ForeignKey(" + Quote(addForeignKeyOperation.PrincipalTable) + ", "); Generate(addForeignKeyOperation.DependentColumns, writer); if (addForeignKeyOperation.CascadeDelete) { writer.Write(", cascadeDelete := True"); } writer.Write(")"); }
public void Generate_can_output_add_fk_statement() { var addForeignKeyOperation = new AddForeignKeyOperation { PrincipalTable = "Customers", DependentTable = "Orders", CascadeDelete = true }; addForeignKeyOperation.PrincipalColumns.Add("CustomerId"); addForeignKeyOperation.DependentColumns.Add("CustomerId"); var migrationSqlGenerator = new SqlCeMigrationSqlGenerator(); var sql = migrationSqlGenerator.Generate(new[] { addForeignKeyOperation }, "4.0").Join(s => s.Sql, Environment.NewLine); Assert.Contains( @"ALTER TABLE [Orders] ADD CONSTRAINT [FK_Orders_Customers_CustomerId] FOREIGN KEY ([CustomerId]) REFERENCES [Customers] ([CustomerId]) ON DELETE CASCADE", sql); }
public void Generate_can_output_composite_add_foreign_key() { var codeGenerator = new VisualBasicMigrationCodeGenerator(); var addForeignKeyOperation = new AddForeignKeyOperation { DependentTable = "Orders", PrincipalTable = "Customers" }; addForeignKeyOperation.DependentColumns.Add("CustomerId1"); addForeignKeyOperation.DependentColumns.Add("CustomerId2"); addForeignKeyOperation.PrincipalColumns.Add("Id1"); addForeignKeyOperation.PrincipalColumns.Add("Id2"); var generatedMigration = codeGenerator.Generate( "Migration", new MigrationOperation[] { addForeignKeyOperation }, "Source", "Target", "Foo", "Bar"); Assert.Equal( @"Imports System Imports System.Data.Entity.Migrations Namespace Foo Public Partial Class Bar Inherits DbMigration Public Overrides Sub Up() AddForeignKey(""Orders"", New String() { ""CustomerId1"", ""CustomerId2"" }, ""Customers"", New String() { ""Id1"", ""Id2"" }) End Sub Public Overrides Sub Down() DropForeignKey(""Orders"", New String() { ""CustomerId1"", ""CustomerId2"" }, ""Customers"") End Sub End Class End Namespace ", generatedMigration.UserCode); }
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"]); }
public void CreateForeignKeyOperation() { var migrationOperations = new List<MigrationOperation>(); // create dependant table Posts var createTableOperation = CreateTableOperation(); migrationOperations.Add(createTableOperation); // Add column BlogId to create the constraints if (ProviderManifest == null) ProviderManifest = new MySqlProviderManifest(Version.ToString()); TypeUsage tu = TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32)); TypeUsage result = ProviderManifest.GetStoreType(tu); var intColumn = new ColumnModel(PrimitiveTypeKind.Int32, result) { Name = "BlogId", IsNullable = false }; var addColumnMigratioOperation = new AddColumnOperation("Posts", intColumn); migrationOperations.Add(addColumnMigratioOperation); // create constrain object var createForeignkeyOperation = new AddForeignKeyOperation(); createForeignkeyOperation.Name = "FKBlogs"; createForeignkeyOperation.DependentTable = "Posts"; createForeignkeyOperation.DependentColumns.Add("BlogId"); createForeignkeyOperation.CascadeDelete = true; createForeignkeyOperation.PrincipalTable = "Blogs"; createForeignkeyOperation.PrincipalColumns.Add("BlogId"); //create index to use migrationOperations.Add(createForeignkeyOperation.CreateCreateIndexOperation()); migrationOperations.Add(createForeignkeyOperation); using (BlogContext context = new BlogContext()) { if (context.Database.Exists()) context.Database.Delete(); context.Database.Create(); Assert.AreEqual(true, GenerateAndExecuteMySQLStatements(migrationOperations)); using (var conn = new MySqlConnection(context.Database.Connection.ConnectionString)) { if (conn.State == System.Data.ConnectionState.Closed) conn.Open(); // check for foreign key creation MySqlCommand query = new MySqlCommand("select Count(*) from information_schema.table_constraints where constraint_type = 'foreign key' and constraint_schema = '" + conn.Database + "' and constraint_name = 'FKBlogs'", conn); int rows = Convert.ToInt32(query.ExecuteScalar()); Assert.AreEqual(1, rows); // check for table creation query = new MySqlCommand("select Count(*) from information_schema.Tables WHERE `table_name` = 'Posts' and `table_schema` = '" + conn.Database + "' ", conn); rows = Convert.ToInt32(query.ExecuteScalar()); Assert.AreEqual(1, rows); conn.Close(); } // Test fix for MySqlConnection con = GetConnectionFromContext(context); con.Open(); try { MySqlCommand cmd = new MySqlCommand("show create table `posts`", con); using (MySqlDataReader r = cmd.ExecuteReader()) { r.Read(); string sql = r.GetString(1); Assert.IsTrue(sql.IndexOf( " CONSTRAINT `FKBlogs` FOREIGN KEY (`BlogId`) REFERENCES `blogs` (`BlogId`) ON DELETE CASCADE ON UPDATE CASCADE", StringComparison.OrdinalIgnoreCase) != -1); } } finally { con.Close(); } } }
public void CreateForeignKeyOperation() { var migrationOperations = new List<MigrationOperation>(); // create dependant table Posts var createTableOperation = CreateTableOperation(); migrationOperations.Add(createTableOperation); // Add column BlogId to create the constraints if (ProviderManifest == null) ProviderManifest = new MySqlProviderManifest(Version.ToString()); TypeUsage tu = TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32)); TypeUsage result = ProviderManifest.GetStoreType(tu); var intColumn = new ColumnModel(PrimitiveTypeKind.Int32, result) { Name = "BlogId", IsNullable = false }; var addColumnMigratioOperation = new AddColumnOperation("Posts", intColumn); migrationOperations.Add(addColumnMigratioOperation); // create constrain object var createForeignkeyOperation = new AddForeignKeyOperation(); createForeignkeyOperation.Name = "FKBlogs"; createForeignkeyOperation.DependentTable = "Posts"; createForeignkeyOperation.DependentColumns.Add("BlogId"); createForeignkeyOperation.CascadeDelete = true; createForeignkeyOperation.PrincipalTable = "Blogs"; createForeignkeyOperation.PrincipalColumns.Add("BlogId"); //create index to use migrationOperations.Add(createForeignkeyOperation.CreateCreateIndexOperation()); migrationOperations.Add(createForeignkeyOperation); using (BlogContext context = new BlogContext()) { if (context.Database.Exists()) context.Database.Delete(); context.Database.Create(); Assert.AreEqual(true, GenerateAndExecuteMySQLStatements(migrationOperations)); using (var conn = new MySqlConnection(context.Database.Connection.ConnectionString)) { if (conn.State == System.Data.ConnectionState.Closed) conn.Open(); // check for foreign key creation MySqlCommand query = new MySqlCommand("select Count(*) from information_schema.table_constraints where constraint_type = 'foreign key' and constraint_schema = '" + conn.Database + "' and constraint_name = 'FKBlogs'", conn); int rows = Convert.ToInt32(query.ExecuteScalar()); Assert.AreEqual(1, rows); // check for table creation query = new MySqlCommand("select Count(*) from information_schema.Tables WHERE `table_name` = 'Posts' and `table_schema` = '" + conn.Database + "' ", conn); rows = Convert.ToInt32(query.ExecuteScalar()); Assert.AreEqual(1, rows); conn.Close(); } } }
/// <summary> /// Generates code to perform an <see cref = "AddForeignKeyOperation" />. /// </summary> /// <param name = "addForeignKeyOperation">The operation to generate code for.</param> /// <param name = "writer">Text writer to add the generated code to.</param> protected virtual void Generate(AddForeignKeyOperation addForeignKeyOperation, IndentedTextWriter writer) { Contract.Requires(addForeignKeyOperation != null); Contract.Requires(writer != null); writer.Write("AddForeignKey("); writer.Write(Quote(addForeignKeyOperation.DependentTable)); writer.Write(", "); var compositeKey = addForeignKeyOperation.DependentColumns.Count() > 1; if (compositeKey) { writer.Write("new[] { "); } writer.Write(addForeignKeyOperation.DependentColumns.Join(Quote)); if (compositeKey) { writer.Write(" }"); } writer.Write(", "); writer.Write(Quote(addForeignKeyOperation.PrincipalTable)); if (addForeignKeyOperation.PrincipalColumns.Any()) { writer.Write(", "); if (compositeKey) { writer.Write("new[] { "); } writer.Write(addForeignKeyOperation.PrincipalColumns.Join(Quote)); if (compositeKey) { writer.Write(" }"); } } if (addForeignKeyOperation.CascadeDelete) { writer.Write(", cascadeDelete: true"); } if (!addForeignKeyOperation.HasDefaultName) { writer.Write(", name: "); writer.Write(Quote(addForeignKeyOperation.Name)); } writer.WriteLine(");"); }
private void Convert(AddForeignKeyOperation addForeignKeyOperation) { StringBuilder sql = new StringBuilder(); sql.Append("ALTER TABLE "); AppendTableName(addForeignKeyOperation.DependentTable, sql); sql.Append(" ADD CONSTRAINT \""); sql.Append(addForeignKeyOperation.Name); sql.Append("\" FOREIGN KEY ("); foreach (var column in addForeignKeyOperation.DependentColumns) { sql.Append('"'); sql.Append(column); sql.Append("\","); } sql.Remove(sql.Length - 1, 1); sql.Append(") REFERENCES "); AppendTableName(addForeignKeyOperation.PrincipalTable, sql); sql.Append(" ("); foreach (var column in addForeignKeyOperation.PrincipalColumns) { sql.Append('"'); sql.Append(column); sql.Append("\","); } sql.Remove(sql.Length - 1, 1); sql.Append(")"); if (addForeignKeyOperation.CascadeDelete) { sql.Append(" ON DELETE CASCADE"); } AddStatment(sql); }
public void Generate_can_output_composite_add_foreign_key() { var codeGenerator = new CSharpMigrationCodeGenerator(); var addForeignKeyOperation = new AddForeignKeyOperation { DependentTable = "Orders", PrincipalTable = "Customers" }; addForeignKeyOperation.DependentColumns.Add("CustomerId1"); addForeignKeyOperation.DependentColumns.Add("CustomerId2"); addForeignKeyOperation.PrincipalColumns.Add("Id1"); addForeignKeyOperation.PrincipalColumns.Add("Id2"); var generatedMigration = codeGenerator.Generate( "Migration", new MigrationOperation[] { addForeignKeyOperation }, "Source", "Target", "Foo", "Bar"); Assert.Equal( @"namespace Foo { using System; using System.Data.Entity.Migrations; public partial class Bar : DbMigration { public override void Up() { AddForeignKey(""Orders"", new[] { ""CustomerId1"", ""CustomerId2"" }, ""Customers"", new[] { ""Id1"", ""Id2"" }); } public override void Down() { DropForeignKey(""Orders"", new[] { ""CustomerId1"", ""CustomerId2"" }, ""Customers""); } } } ", generatedMigration.UserCode); }
/// <summary> /// Generates SQL for a <see cref="AddForeignKeyOperation" />. /// Generated SQL should be added using the Statement method. /// </summary> /// <param name="addForeignKeyOperation"> The operation to produce SQL for. </param> protected virtual void Generate(AddForeignKeyOperation addForeignKeyOperation) { Check.NotNull(addForeignKeyOperation, "addForeignKeyOperation"); using (var writer = Writer()) { writer.Write("ALTER TABLE "); writer.Write(Name(addForeignKeyOperation.DependentTable)); writer.Write(" ADD CONSTRAINT "); writer.Write(Quote(addForeignKeyOperation.Name)); writer.Write(" FOREIGN KEY ("); writer.Write(addForeignKeyOperation.DependentColumns.Select(Quote).Join()); writer.Write(") REFERENCES "); writer.Write(Name(addForeignKeyOperation.PrincipalTable)); writer.Write(" ("); writer.Write(addForeignKeyOperation.PrincipalColumns.Select(Quote).Join()); writer.Write(")"); if (addForeignKeyOperation.CascadeDelete) { writer.Write(" ON DELETE CASCADE"); } Statement(writer); } }
protected override void Generate(AddForeignKeyOperation addForeignKeyOperation) { using (var writer = Writer()) { writer.WriteLine("IF NOT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE CONSTRAINT_NAME = '{0}')\r\nBEGIN", addForeignKeyOperation.Name); writer.Indent++; writer.Write("ALTER TABLE "); writer.Write(Name(addForeignKeyOperation.DependentTable)); writer.Write(" ADD CONSTRAINT "); writer.Write(Quote(addForeignKeyOperation.Name)); writer.Write(" FOREIGN KEY ("); writer.Write(string.Join(", ", addForeignKeyOperation.DependentColumns.Select(Quote))); writer.Write(") REFERENCES "); writer.Write(Name(addForeignKeyOperation.PrincipalTable)); writer.Write(" ("); writer.Write(string.Join(", ", addForeignKeyOperation.PrincipalColumns.Select(Quote))); writer.Write(")"); if (addForeignKeyOperation.CascadeDelete) writer.Write(" ON DELETE CASCADE"); writer.Indent--; writer.Write("\r\nEND"); Statement(writer); } }
/// <summary> /// Generates code to perform an <see cref="AddForeignKeyOperation" />. /// </summary> /// <param name="addForeignKeyOperation"> The operation to generate code for. </param> /// <param name="writer"> Text writer to add the generated code to. </param> protected virtual void Generate(AddForeignKeyOperation addForeignKeyOperation, IndentedTextWriter writer) { Check.NotNull(addForeignKeyOperation, "addForeignKeyOperation"); Check.NotNull(writer, "writer"); writer.Write("AddForeignKey("); writer.Write(Quote(addForeignKeyOperation.DependentTable)); writer.Write(", "); var compositeKey = addForeignKeyOperation.DependentColumns.Count() > 1; if (compositeKey) { writer.Write("New String() { "); } writer.Write(addForeignKeyOperation.DependentColumns.Join(Quote)); if (compositeKey) { writer.Write(" }"); } writer.Write(", "); writer.Write(Quote(addForeignKeyOperation.PrincipalTable)); if (addForeignKeyOperation.PrincipalColumns.Any()) { writer.Write(", "); if (compositeKey) { writer.Write("New String() { "); } writer.Write(addForeignKeyOperation.PrincipalColumns.Join(Quote)); if (compositeKey) { writer.Write(" }"); } } if (addForeignKeyOperation.CascadeDelete) { writer.Write(", cascadeDelete := True"); } if (!addForeignKeyOperation.HasDefaultName) { writer.Write(", name := "); writer.Write(Quote(addForeignKeyOperation.Name)); } writer.WriteLine(")"); }
/// <summary> /// Generates code to perform an <see cref = "AddForeignKeyOperation" /> as part of a <see cref = "CreateTableOperation" />. /// </summary> /// <param name = "addForeignKeyOperation">The operation to generate code for.</param> /// <param name = "writer">Text writer to add the generated code to.</param> protected virtual void GenerateInline(AddForeignKeyOperation addForeignKeyOperation, IndentedTextWriter writer) { Contract.Requires(addForeignKeyOperation != null); Contract.Requires(writer != null); writer.WriteLine(" _"); writer.Write(".ForeignKey(" + Quote(addForeignKeyOperation.PrincipalTable) + ", "); Generate(addForeignKeyOperation.DependentColumns, writer); if (addForeignKeyOperation.CascadeDelete) { writer.Write(", cascadeDelete := True"); } writer.Write(")"); }
protected override void Generate(AddForeignKeyOperation addForeignKeyOperation, IndentedTextWriter writer) { addForeignKeyOperation.PrincipalTable = TrimSchemaPrefix(addForeignKeyOperation.PrincipalTable); addForeignKeyOperation.DependentTable = TrimSchemaPrefix(addForeignKeyOperation.DependentTable); base.Generate(addForeignKeyOperation, writer); }
public void TestAddForeignKeyOperationCascadeDelete() { var operations = new List<MigrationOperation>(); var operation = new AddForeignKeyOperation(); operation.Name = "someFK"; operation.PrincipalTable = "somePrincipalTable"; operation.DependentTable = "someDependentTable"; operation.DependentColumns.Add("column1"); operation.DependentColumns.Add("column2"); operation.DependentColumns.Add("column3"); operation.CascadeDelete = true; operations.Add(operation); var statments = new NpgsqlMigrationSqlGenerator().Generate(operations, BackendVersion.ToString()); Assert.AreEqual(1, statments.Count()); Assert.AreEqual("ALTER TABLE \"someDependentTable\" ADD CONSTRAINT \"someFK\" FOREIGN KEY (\"column1\",\"column2\",\"column3\") REFERENCES \"somePrincipalTable\" ) ON DELETE CASCADE", statments.ElementAt(0).Sql); }
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 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.Data.Entity.Migrations Imports System.Data.Entity.Migrations.Infrastructure Imports System.Resources Namespace Foo 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"]); }
public void GenerateCanOutputAddFkStatement() { var addForeignKeyOperation = new AddForeignKeyOperation { PrincipalTable = "Customers", DependentTable = "Orders", CascadeDelete = true }; addForeignKeyOperation.PrincipalColumns.Add("CustomerId"); addForeignKeyOperation.DependentColumns.Add("CustomerId"); var migrationSqlGenerator = new PostgreSqlMigrationSqlGenerator(); var sql = migrationSqlGenerator.Generate(new[] { addForeignKeyOperation }, "9.2").Join(s => s.Sql, Environment.NewLine); Assert.True( sql.Contains( "ALTER TABLE \"Orders\" ADD CONSTRAINT \"FK_Orders_Customers_CustomerId\" FOREIGN KEY (\"CustomerId\") REFERENCES \"Customers\" (\"CustomerId\") ON DELETE CASCADE")); }
protected virtual IEnumerable<MigrationStatement> Generate(AddForeignKeyOperation operation) { using (var writer = SqlWriter()) { writer.Write("ALTER TABLE "); writer.Write(Quote(operation.DependentTable)); writer.Write(" ADD FOREIGN KEY ("); WriteColumns(writer, operation.DependentColumns.Select(Quote)); writer.Write(") REFERENCES "); writer.Write(Quote(operation.PrincipalTable)); writer.Write(" ("); WriteColumns(writer, operation.PrincipalColumns.Select(Quote)); writer.Write(")"); if (operation.CascadeDelete) { writer.Write(" ON DELETE CASCADE"); } yield return Statement(writer); } }
public DropForeignKeyOperation(AddForeignKeyOperation inverse, object anonymousArguments = null) : base(anonymousArguments) { Check.NotNull <AddForeignKeyOperation>(inverse, nameof(inverse)); this._inverse = inverse; }