public void Can_get_default_for_name()
        {
            var addPrimaryKeyOperation = new AddPrimaryKeyOperation { Table = "T" };

            Assert.Equal("PK_T", addPrimaryKeyOperation.Name);
            Assert.True(addPrimaryKeyOperation.HasDefaultName);
        }
        public void Can_set_and_get_primary_key()
        {
            var addPrimaryKeyOperation = new AddPrimaryKeyOperation();
            var table = new CreateTableOperation("T") { PrimaryKey = addPrimaryKeyOperation };

            Assert.Same(addPrimaryKeyOperation, table.PrimaryKey);
            Assert.Equal("T", addPrimaryKeyOperation.Table);
        }
        public void DefaultName_is_restricted_to_128_chars()
        {
            var addPrimaryKeyOperation = new AddPrimaryKeyOperation
            {
                Table = new string('t', 150)
            };

            Assert.Equal(128, addPrimaryKeyOperation.DefaultName.Length);
        }
        public void DefaultName_is_restricted_to_128_chars()
        {
            var addPrimaryKeyOperation = new AddPrimaryKeyOperation
                                             {
                                                 Table = new string('t', 150)
                                             };

            Assert.Equal(128, addPrimaryKeyOperation.DefaultName.Length);
        }
        public void Can_get_default_for_name()
        {
            var addPrimaryKeyOperation = new AddPrimaryKeyOperation
            {
                Table = "T"
            };

            Assert.Equal("PK_T", addPrimaryKeyOperation.Name);
            Assert.True(addPrimaryKeyOperation.HasDefaultName);
        }
        public void Can_set_and_get_primary_key()
        {
            var addPrimaryKeyOperation = new AddPrimaryKeyOperation();
            var table = new CreateTableOperation("T")
            {
                PrimaryKey = addPrimaryKeyOperation
            };

            Assert.Same(addPrimaryKeyOperation, table.PrimaryKey);
            Assert.Equal("T", addPrimaryKeyOperation.Table);
        }
        public void Can_get_and_set_table_and_name_and_columns()
        {
            var addPrimaryKeyOperation = new AddPrimaryKeyOperation { Table = "T", Name = "Pk" };

            addPrimaryKeyOperation.Columns.Add("pk2");

            Assert.Equal("T", addPrimaryKeyOperation.Table);
            Assert.Equal("Pk", addPrimaryKeyOperation.Name);
            Assert.Equal("pk2", addPrimaryKeyOperation.Columns.Single());
            Assert.False(addPrimaryKeyOperation.HasDefaultName);
        }
        public void Inverse_should_return_drop_operation()
        {
            var addPrimaryKeyOperation = new AddPrimaryKeyOperation { Table = "T", Name = "Pk" };

            addPrimaryKeyOperation.Columns.Add("pk2");

            var inverse = (DropPrimaryKeyOperation)addPrimaryKeyOperation.Inverse;

            Assert.Equal("T", inverse.Table);
            Assert.Equal("Pk", inverse.Name);
            Assert.Equal("pk2", inverse.Columns.Single());
        }
        public void Can_get_and_set_table_and_name_and_columns()
        {
            var addPrimaryKeyOperation = new AddPrimaryKeyOperation
            {
                Table = "T",
                Name  = "Pk"
            };

            addPrimaryKeyOperation.Columns.Add("pk2");

            Assert.Equal("T", addPrimaryKeyOperation.Table);
            Assert.Equal("Pk", addPrimaryKeyOperation.Name);
            Assert.Equal("pk2", addPrimaryKeyOperation.Columns.Single());
            Assert.False(addPrimaryKeyOperation.HasDefaultName);
        }
        public void Inverse_should_return_drop_operation()
        {
            var addPrimaryKeyOperation = new AddPrimaryKeyOperation
            {
                Table = "T",
                Name  = "Pk"
            };

            addPrimaryKeyOperation.Columns.Add("pk2");

            var inverse = (DropPrimaryKeyOperation)addPrimaryKeyOperation.Inverse;

            Assert.Equal("T", inverse.Table);
            Assert.Equal("Pk", inverse.Name);
            Assert.Equal("pk2", inverse.Columns.Single());
        }
        protected override void Generate(AddPrimaryKeyOperation addPrimaryKeyOperation)
        {
            if (addPrimaryKeyOperation == null)
            {
                throw new ArgumentNullException("addPrimaryKeyOperation");
            }

            // turn off clustered index for all PKs (except for migration history)
            if (!addPrimaryKeyOperation.Table.Contains("__MigrationHistory"))
            {
                addPrimaryKeyOperation.IsClustered = false;
            }


            base.Generate(addPrimaryKeyOperation);
        }
        public virtual IEnumerable<MigrationOperation> GetUpgradeOperations()
        {
            if (!Exists())
            {
                yield break;
            }

            DbConnection connection = null;
            try
            {
                connection = CreateConnection();

                var tableName = "dbo." + HistoryContext.DefaultTableName;

                DbProviderManifest providerManifest;
                if (connection.GetProviderInfo(out providerManifest).IsSqlCe())
                {
                    tableName = HistoryContext.DefaultTableName;
                }

                using (var context = new LegacyHistoryContext(connection))
                {
                    var createdOnExists = false;

                    try
                    {
                        InjectInterceptionContext(context);

                        using (new TransactionScope(TransactionScopeOption.Suppress))
                        {
                            context.History
                                .Select(h => h.CreatedOn)
                                .FirstOrDefault();
                        }

                        createdOnExists = true;
                    }
                    catch (EntityException)
                    {
                    }

                    if (createdOnExists)
                    {
                        yield return new DropColumnOperation(tableName, "CreatedOn");
                    }
                }

                using (var context = CreateContext(connection))
                {
                    if (!_contextKeyColumnExists)
                    {
                        if (_historyContextFactory != HistoryContext.DefaultFactory)
                        {
                            throw Error.UnableToUpgradeHistoryWhenCustomFactory();
                        }

                        yield return new AddColumnOperation(
                            tableName,
                            new ColumnModel(PrimitiveTypeKind.String)
                                {
                                    MaxLength = _contextKeyMaxLength,
                                    Name = "ContextKey",
                                    IsNullable = false,
                                    DefaultValue = _contextKey
                                });

                        var emptyModel = new DbModelBuilder().Build(connection).GetModel();
                        var createTableOperation = (CreateTableOperation)
                            new EdmModelDiffer().Diff(emptyModel, context.GetModel()).Single();

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

                        dropPrimaryKeyOperation.Columns.Add("MigrationId");

                        yield return dropPrimaryKeyOperation;

                        yield return new AlterColumnOperation(
                            tableName,
                            new ColumnModel(PrimitiveTypeKind.String)
                                {
                                    MaxLength = _migrationIdMaxLength,
                                    Name = "MigrationId",
                                    IsNullable = false
                                },
                            isDestructiveChange: false);

                        var addPrimaryKeyOperation
                            = new AddPrimaryKeyOperation
                                {
                                    Table = tableName
                                };

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

                        yield return addPrimaryKeyOperation;
                    }
                }
            }
            finally
            {
                DisposeConnection(connection);
            }
        }
        private static IEnumerable<PrimaryKeyOperation> BuildChangePrimaryKeyOperations(
            string oldTable, string newTable, XElement oldKey, XElement newKey)
        {
            var dropPrimaryKeyOperation = new DropPrimaryKeyOperation
                                              {
                                                  Table = oldTable
                                              };

            oldKey.Descendants(EdmXNames.Ssdl.PropertyRefNames).Each(
                pr => dropPrimaryKeyOperation.Columns.Add(pr.NameAttribute()));

            yield return dropPrimaryKeyOperation;

            var addPrimaryKeyOperation = new AddPrimaryKeyOperation
                                             {
                                                 Table = newTable
                                             };

            newKey.Descendants(EdmXNames.Ssdl.PropertyRefNames).Each(
                pr => addPrimaryKeyOperation.Columns.Add(pr.NameAttribute()));

            yield return addPrimaryKeyOperation;
        }
		protected override void Generate(AddPrimaryKeyOperation addPrimaryKeyOperation)
		{
			addPrimaryKeyOperation.IsClustered = false;
			base.Generate(addPrimaryKeyOperation);
		}
Exemple #15
0
        public void Generate_can_output_non_clustered_add_primary_key_operation()
        {
            var migrationSqlGenerator = new SqlCeMigrationSqlGenerator();

            var addPrimaryKeyOperation = new AddPrimaryKeyOperation
                                             {
                                                 Table = "T",
                                                 IsClustered = false
                                             };

            addPrimaryKeyOperation.Columns.Add("c1");
            addPrimaryKeyOperation.Columns.Add("c2");

            var sql = migrationSqlGenerator.Generate(new[] { addPrimaryKeyOperation }, "4.0").Join(s => s.Sql, Environment.NewLine);

            Assert.Contains("ALTER TABLE [T] ADD CONSTRAINT [PK_T] PRIMARY KEY NONCLUSTERED ([c1], [c2])", sql);
        }
 protected override void Generate(AddPrimaryKeyOperation addPrimaryKeyOperation, IndentedTextWriter writer)
 {
     addPrimaryKeyOperation.Table = TrimSchemaPrefix(addPrimaryKeyOperation.Table);
       base.Generate(addPrimaryKeyOperation, writer);
 }
        /// <summary>
        /// Generates code to perform an <see cref="AddPrimaryKeyOperation" />.
        /// </summary>
        /// <param name="addPrimaryKeyOperation"> The operation to generate code for. </param>
        /// <param name="writer"> Text writer to add the generated code to. </param>
        protected virtual void Generate(AddPrimaryKeyOperation addPrimaryKeyOperation, IndentedTextWriter writer)
        {
            Check.NotNull(addPrimaryKeyOperation, "addPrimaryKeyOperation");
            Check.NotNull(writer, "writer");

            writer.Write("AddPrimaryKey(");
            writer.Write(Quote(addPrimaryKeyOperation.Table));
            writer.Write(", ");

            var compositeIndex = addPrimaryKeyOperation.Columns.Count() > 1;

            if (compositeIndex)
            {
                writer.Write("New String() { ");
            }

            writer.Write(addPrimaryKeyOperation.Columns.Join(Quote));

            if (compositeIndex)
            {
                writer.Write(" }");
            }

            if (!addPrimaryKeyOperation.HasDefaultName)
            {
                writer.Write(", name := ");
                writer.Write(Quote(addPrimaryKeyOperation.Name));
            }

            if (!addPrimaryKeyOperation.IsClustered)
            {
                writer.Write(", clustered := False");
            }

            writer.WriteLine(")");
        }
        /// <summary>
        /// Generates SQL for a <see cref="AddPrimaryKeyOperation" />.
        /// Generated SQL should be added using the Statement method.
        /// </summary>
        /// <param name="addPrimaryKeyOperation"> The operation to produce SQL for. </param>
        protected virtual void Generate(AddPrimaryKeyOperation addPrimaryKeyOperation)
        {
            Check.NotNull(addPrimaryKeyOperation, "addPrimaryKeyOperation");

            using (var writer = Writer())
            {
                writer.Write("ALTER TABLE ");
                writer.Write(Name(addPrimaryKeyOperation.Table));
                writer.Write(" ADD CONSTRAINT ");
                writer.Write(Quote(addPrimaryKeyOperation.Name));
                writer.Write(" PRIMARY KEY ");

                if (!addPrimaryKeyOperation.IsClustered)
                {
                    writer.Write("NONCLUSTERED ");
                }

                writer.Write("(");
                writer.Write(addPrimaryKeyOperation.Columns.Select(Quote).Join());
                writer.Write(")");

                Statement(writer);
            }
        }
        /*protected override void Generate(AlterColumnOperation alterColumnOperation)
        {
            string schema, objectName;
            this.GetNameParts(alterColumnOperation.Table, out schema, out objectName);
            using (var writer = Writer())
            {
                writer.WriteLine("IF NOT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE CONSTRAINT_TYPE = 'Primary Key' AND TABLE_SCHEMA = '{0}' AND TABLE_NAME = '{2}')\r\nBEGIN", alterColumnOperation.Table);
                writer.Indent++;
                writer.Write("ALTER TABLE ");
                writer.Write(this.Name(alterColumnOperation.Table));
                writer.Write(" ALTER COLUMN ");
                this.AddColumnDefinition(alterColumnOperation.Column, writer);
                writer.Indent--;
                writer.Write("\r\nEND");

                this.Statement(writer);
            }
        }

        protected override void Generate(DropTableOperation dropTableOperation)
        {
            string schema, objectName;
            this.GetNameParts(dropTableOperation.Name, out schema, out objectName);
            using (var writer = Writer())
            {
                writer.WriteLine("IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{0}' AND TABLE_NAME = '{1}')\r\nBEGIN", schema, objectName);
                writer.Indent++;
                writer.WriteLine("DROP TABLE ");
                writer.Write(this.Name(dropTableOperation.Name));
                writer.Indent--;
                writer.Write("\r\nEND");
            }
        }

        protected override void Generate(RenameColumnOperation renameColumnOperation)
        {
            string schema, objectName;
            this.GetNameParts(renameColumnOperation.Table, out schema, out objectName);
            using (var writer = Writer())
            {
                writer.WriteLine("IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = '{0}' AND TABLE_SCHEMA = '{1}' AND TABLE_NAME = '{2}')\r\nBEGIN", renameColumnOperation.Name, schema, objectName);
                writer.Indent++;
                writer.Write("EXEC sys.sp_rename @objname = N'");
                writer.Write(this.Name(renameColumnOperation.Table));
                writer.Write(".");
                writer.Write(string.Format("{0}', @newname = '{1}', @objtype = 'COLUMN'", renameColumnOperation.Name, renameColumnOperation.NewName));
                writer.Indent--;
                writer.Write("\r\nEND");

                this.Statement(writer);
            }
        }

        protected override void Generate(DropColumnOperation dropColumnOperation)
        {
            base.Generate(dropColumnOperation);
            string schema, objectName;
            this.GetNameParts(dropColumnOperation.Table, out schema, out objectName);
            using (var writer = Writer())
            {
                writer.WriteLine("IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = '{0}' AND TABLE_SCHEMA = '{1}' AND TABLE_NAME = '{2}')\r\nBEGIN", dropColumnOperation.Name, schema, objectName);
                writer.Indent++;
                writer.Write("ALTER TABLE ");
                writer.Write(this.Name(dropColumnOperation.Table));
                writer.Write(" DROP COLUMN ");
                writer.Write(this.Quote(dropColumnOperation.Name));
                writer.Indent--;
                writer.Write("\r\nEND");

                this.Statement(writer);
            }
        }
        */
        protected override void Generate(AddPrimaryKeyOperation addPrimaryKeyOperation)
        {
            string schema, objectName;
            this.GetNameParts(addPrimaryKeyOperation.Table, out schema, out objectName);
            using (var writer = Writer())
            {
                //writer.WriteLine("IF NOT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE CONSTRAINT_TYPE = 'Primary Key' AND TABLE_SCHEMA = '{0}' AND TABLE_NAME = '{1}')\r\nBEGIN", schema, objectName);
                writer.WriteLine("IF NOT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = '{0}' AND TABLE_NAME = '{1}')\r\nBEGIN", schema, objectName);
                writer.Indent++;
                writer.Write("ALTER TABLE ");
                writer.Write(this.Name(addPrimaryKeyOperation.Table));
                writer.Write(" ADD CONSTRAINT ");
                writer.Write(this.Quote(addPrimaryKeyOperation.Name));
                writer.Write(string.Format(" PRIMARY KEY ({0})", addPrimaryKeyOperation.Columns.Concat(",")));
                writer.Indent--;
                writer.Write("\r\nEND");

                this.Statement(writer);
            }
        }
 protected override void Generate( AddPrimaryKeyOperation addPrimaryKeyOperation )
 {
     addPrimaryKeyOperation.Name = addPrimaryKeyOperation.Name.Replace( '.', '_' );
     base.Generate( addPrimaryKeyOperation );
 }
        public void GenerateCanOutputAddPrimaryKeyOperation()
        {
            var migrationSqlGenerator = new PostgreSqlMigrationSqlGenerator();

            var addPrimaryKeyOperation = new AddPrimaryKeyOperation
            {
                Table = "T"
            };

            addPrimaryKeyOperation.Columns.Add("c1");
            addPrimaryKeyOperation.Columns.Add("c2");

            var sql = migrationSqlGenerator.Generate(new[] { addPrimaryKeyOperation }, "9.2").Join(s => s.Sql, Environment.NewLine);

            Assert.True(sql.Contains("ALTER TABLE \"T\" ADD CONSTRAINT \"PK_T\" PRIMARY KEY (\"c1\", \"c2\")"));
        }
        /// <summary>
        ///     Generates code to perform an <see cref="AddPrimaryKeyOperation" />.
        /// </summary>
        /// <param name="addPrimaryKeyOperation"> The operation to generate code for. </param>
        /// <param name="writer"> Text writer to add the generated code to. </param>
        protected virtual void Generate(AddPrimaryKeyOperation addPrimaryKeyOperation, IndentedTextWriter writer)
        {
            Check.NotNull(addPrimaryKeyOperation, "addPrimaryKeyOperation");
            Check.NotNull(writer, "writer");

            writer.Write("AddPrimaryKey(");
            writer.Write(Quote(addPrimaryKeyOperation.Table));
            writer.Write(", ");

            var compositeKey = addPrimaryKeyOperation.Columns.Count() > 1;

            if (compositeKey)
            {
                writer.Write("new[] { ");
            }

            writer.Write(addPrimaryKeyOperation.Columns.Join(Quote));

            if (compositeKey)
            {
                writer.Write(" }");
            }

            if (!addPrimaryKeyOperation.HasDefaultName)
            {
                writer.Write(", name: ");
                writer.Write(Quote(addPrimaryKeyOperation.Name));
            }

            writer.WriteLine(");");
        }
 public void TestAddPrimaryKeyOperationClustered()
 {
     var operations = new List<MigrationOperation>();
     var operation = new AddPrimaryKeyOperation();
     operation.Table = "someTable";
     operation.Name = "somePKName";
     operation.Columns.Add("column1");
     operation.Columns.Add("column2");
     operation.Columns.Add("column3");
     operation.IsClustered = true;
     //TODO: PostgreSQL support something like IsClustered?
     operations.Add(operation);
     var statments = new NpgsqlMigrationSqlGenerator().Generate(operations, BackendVersion.ToString());
     Assert.AreEqual(1, statments.Count());
     Assert.AreEqual("ALTER TABLE \"someTable\" ADD CONSTRAINT \"somePKName\" PRIMARY KEY (\"column1\",\"column2\",\"column3\")", statments.ElementAt(0).Sql);
 }
        private static MigrationOperation[] Create_operations_to_upgrade_primary_key_of_history_table()
        {
            const string tableName = "dbo." + HistoryContext.DefaultTableName;

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

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

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

            dropPrimaryKeyOperation.Columns.Add("MigrationId");

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

            var addPrimaryKeyOperation
                = new AddPrimaryKeyOperation
                      {
                          Table = tableName
                      };

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

            return
                new MigrationOperation[]
                    {
                        addColumnOperation,
                        dropPrimaryKeyOperation,
                        alterColumnOperation,
                        addPrimaryKeyOperation
                    };
        }
        public void Generate_can_output_add_primary_key_with_non_clustered_index()
        {
            var codeGenerator = new CSharpMigrationCodeGenerator();

            var addPrimaryKeyOperation
                = new AddPrimaryKeyOperation
                {
                    Table = "T",
                    Name = "PK",
                    IsClustered = false
                };

            addPrimaryKeyOperation.Columns.Add("c1");
            addPrimaryKeyOperation.Columns.Add("c2");

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

            Assert.Equal(
                @"namespace Foo
{
    using System;
    using System.Data.Entity.Migrations;
    
    public partial class Bar : DbMigration
    {
        public override void Up()
        {
            AddPrimaryKey(""T"", new[] { ""c1"", ""c2"" }, name: ""PK"", clustered: false);
        }
        
        public override void Down()
        {
            DropPrimaryKey(""T"", name: ""PK"");
        }
    }
}
",
                generatedMigration.UserCode);
        }
        private void Convert(AddPrimaryKeyOperation addPrimaryKeyOperation)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append("ALTER TABLE ");
            AppendTableName(addPrimaryKeyOperation.Table, sql);
            sql.Append(" ADD CONSTRAINT \"");
            sql.Append(addPrimaryKeyOperation.Name);
            sql.Append("\" PRIMARY KEY ");

            sql.Append("(");
            foreach (var column in addPrimaryKeyOperation.Columns)
            {
                sql.Append('"');
                sql.Append(column);
                sql.Append("\",");
            }
            sql.Remove(sql.Length - 1, 1);
            sql.Append(")");
            AddStatment(sql);
        }
        private CreateTableOperation BuildCreateTableOperation(
            string entitySetName,
            string tableName,
            string schema,
            string isSystem,
            ModelMetadata modelMetadata)
        {
            Contract.Requires(!string.IsNullOrWhiteSpace(entitySetName));
            Contract.Requires(!string.IsNullOrWhiteSpace(tableName));
            Contract.Requires(!string.IsNullOrWhiteSpace(schema));
            Contract.Requires(modelMetadata != null);

            var createTableOperation = new CreateTableOperation(GetQualifiedTableName(tableName, schema));

            var entityTypeElement = modelMetadata.Model.Descendants(EdmXNames.Ssdl.EntityTypeNames)
                .Single(et => et.NameAttribute().EqualsIgnoreCase(entitySetName));

            entityTypeElement
                .Descendants(EdmXNames.Ssdl.PropertyNames)
                .Each(p => createTableOperation.Columns.Add(BuildColumnModel(p, entitySetName, modelMetadata)));

            var addPrimaryKeyOperation = new AddPrimaryKeyOperation();

            entityTypeElement
                .Descendants(EdmXNames.Ssdl.PropertyRefNames)
                .Each(pr => addPrimaryKeyOperation.Columns.Add(pr.NameAttribute()));

            createTableOperation.PrimaryKey = addPrimaryKeyOperation;
            createTableOperation.IsSystem = isSystem.EqualsIgnoreCase("true");

            return createTableOperation;
        }
        /// <summary>
        /// Generates code to perform an <see cref="AddPrimaryKeyOperation" /> as part of a <see cref="CreateTableOperation" />.
        /// </summary>
        /// <param name="addPrimaryKeyOperation"> The operation to generate code for. </param>
        /// <param name="writer"> Text writer to add the generated code to. </param>
        protected virtual void GenerateInline(AddPrimaryKeyOperation addPrimaryKeyOperation, IndentedTextWriter writer)
        {
            Check.NotNull(writer, "writer");

            if (addPrimaryKeyOperation != null)
            {
                writer.WriteLine(" _");
                writer.Write(".PrimaryKey(");

                Generate(addPrimaryKeyOperation.Columns, writer);

                if (!addPrimaryKeyOperation.HasDefaultName)
                {
                    writer.Write(", name := ");
                    writer.Write(Quote(addPrimaryKeyOperation.Name));
                }

                if (!addPrimaryKeyOperation.IsClustered)
                {
                    writer.Write(", clustered := False");
                }

                writer.Write(")");
            }
        }
        /// <summary>
        ///     Generates code to perform an <see cref = "AddPrimaryKeyOperation" /> as part of a <see cref = "CreateTableOperation" />.
        /// </summary>
        /// <param name = "addPrimaryKeyOperation">The operation to generate code for.</param>
        /// <param name = "writer">Text writer to add the generated code to.</param>
        protected virtual void GenerateInline(AddPrimaryKeyOperation addPrimaryKeyOperation, IndentedTextWriter writer)
        {
            Contract.Requires(writer != null);

            if (addPrimaryKeyOperation != null)
            {
                writer.WriteLine(" _");
                writer.Write(".PrimaryKey(");

                Generate(addPrimaryKeyOperation.Columns, writer);

                if (!addPrimaryKeyOperation.HasDefaultName)
                {
                    writer.Write(", name := ");
                    writer.Write(Quote(addPrimaryKeyOperation.Name));
                }

                writer.Write(")");
            }
        }
        protected virtual MigrationStatement Generate(AddPrimaryKeyOperation op)
        {
            StringBuilder sb = new StringBuilder();
              sb.Append("alter table `" + op.Table + "` add primary key ");
              sb.Append(" `" + op.Name + "` ");

              if (op.Columns.Count > 0)
            sb.Append("( " + string.Join(",", op.Columns.Select(c => "`" + c + "`")) + ") ");

              return new MigrationStatement { Sql = sb.ToString() };
        }
        /// <summary>
        ///     Generates code to perform an <see cref = "AddPrimaryKeyOperation" />.
        /// </summary>
        /// <param name = "addPrimaryKeyOperation">The operation to generate code for.</param>
        /// <param name = "writer">Text writer to add the generated code to.</param>
        protected virtual void Generate(AddPrimaryKeyOperation addPrimaryKeyOperation, IndentedTextWriter writer)
        {
            Contract.Requires(addPrimaryKeyOperation != null);
            Contract.Requires(writer != null);

            writer.Write("AddPrimaryKey(");
            writer.Write(Quote(addPrimaryKeyOperation.Table));
            writer.Write(", ");

            var compositeIndex = addPrimaryKeyOperation.Columns.Count() > 1;

            if (compositeIndex)
            {
                writer.Write("New String() { ");
            }

            writer.Write(addPrimaryKeyOperation.Columns.Join(Quote));

            if (compositeIndex)
            {
                writer.Write(" }");
            }

            if (!addPrimaryKeyOperation.HasDefaultName)
            {
                writer.Write(", name := ");
                writer.Write(Quote(addPrimaryKeyOperation.Name));
            }

            writer.WriteLine(")");
        }
        public void Generate_can_output_add_primary_key_with_implicit_name()
        {
            var codeGenerator = new VisualBasicMigrationCodeGenerator();

            var addPrimaryKeyOperation
                = new AddPrimaryKeyOperation
                      {
                          Table = "T"
                      };

            addPrimaryKeyOperation.Columns.Add("c1");
            addPrimaryKeyOperation.Columns.Add("c2");

            var generatedMigration
                = codeGenerator.Generate(
                    "Migration",
                    new MigrationOperation[] { addPrimaryKeyOperation },
                    "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()
            AddPrimaryKey(""T"", New String() { ""c1"", ""c2"" })
        End Sub
        
        Public Overrides Sub Down()
            DropPrimaryKey(""T"", New String() { ""c1"", ""c2"" })
        End Sub
    End Class
End Namespace
",
                generatedMigration.UserCode);
        }
        public void Generate_can_output_add_primary_key_operation()
        {
            var migrationProvider = new SqlServerMigrationSqlGenerator();

            var addPrimaryKeyOperation = new AddPrimaryKeyOperation { Table = "T" };

            addPrimaryKeyOperation.Columns.Add("c1");
            addPrimaryKeyOperation.Columns.Add("c2");

            var sql = migrationProvider.Generate(new[] { addPrimaryKeyOperation }, "2008").Join(s => s.Sql, Environment.NewLine);

            Assert.True(sql.Contains("ALTER TABLE [T] ADD CONSTRAINT [PK_T] PRIMARY KEY ([c1], [c2])"));
        }
 protected virtual IEnumerable<MigrationStatement> Generate(AddPrimaryKeyOperation operation)
 {
     using (var writer = SqlWriter())
     {
         writer.Write("ALTER TABLE ");
         writer.Write(Quote(operation.Table));
         writer.Write(" ADD CONSTRAINT ");
         writer.Write(Quote(FixName(operation.Name)));
         writer.Write(" PRIMARY KEY ");
         writer.Write("(");
         WriteColumns(writer, operation.Columns.Select(Quote));
         writer.Write(")");
         yield return Statement(writer);
     }
 }
    /// <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);
      var primaryKey = new AddPrimaryKeyOperation();

      primaryKey.Columns.Add("PostId");

      createTableOperation.PrimaryKey = primaryKey;
      
      return createTableOperation;
    
    }