/// <summary> /// 修改表注释迁移代码生成。 /// </summary> /// <param name="alterTableOperation">表注释模型对象。</param> /// <param name="writer">写入器</param> protected override void Generate(AlterTableOperation alterTableOperation, IndentedTextWriter writer) { if (alterTableOperation == null || writer == null) { return; } //是否只设置了表注释 bool hasCommentOnly = alterTableOperation.Annotations.HasCommentOnly(); //如果有AnonymousArguments就认为不走设置表注释 if (hasCommentOnly && alterTableOperation.AnonymousArguments != null && alterTableOperation.AnonymousArguments.Count > 0) { hasCommentOnly = false; } alterTableOperation.Annotations.WriteComment(() => { if (!hasCommentOnly) { base.Generate(alterTableOperation, writer); } }, o => { //不管如何,都设置一下表注释,除非前后注释一样。 writer.Write($"this.TableComment({base.Quote(alterTableOperation.Name.TrimSchemaPrefix())}, {base.Quote(o)});"); writer.WriteLine(); }); }
/// <inheritdoc /> protected override void Generate(AlterTableOperation operation, IModel model, MigrationCommandListBuilder builder) { base.Generate(operation, model, builder); System.Diagnostics.Debugger.Launch(); var oldComment = GetComment(operation.OldTable); var comment = GetComment(operation); if (oldComment != comment) { builder.AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator); var dropDescription = oldComment != null; if (dropDescription) { DropDescription(builder, operation.Schema, operation.Name); } if (comment != null) { AddDescription( builder, comment, operation.Schema, operation.Name, omitSchemaVariable: dropDescription); } builder.EndCommand(suppressTransaction: IsMemoryOptimized(operation, model, operation.Schema, operation.Name)); } }
public static string SQLGenerateAlterTable(this TableTemplate template, string tableName) { SqlServerMigrationSqlGenerator gen = new SqlServerMigrationSqlGenerator(); ColumnBuilder columnBuilder = new ColumnBuilder(); //columnBuilder.Int(name:"sysid",identity:true); //System.Data.Entity.Migrations.DbMigration var operations = new List <MigrationOperation>(); var dict = new Dictionary <string, AnnotationValues>(); dict.Add("dddddd", new AnnotationValues(1, 2)); var alter = new AlterTableOperation("dddd", dict); //alter.Columns.Add(new ColumnModel(PrimitiveTypeKind.String) { Name="dd" }); //operations.Add(alter); operations.Add(new AddColumnOperation(tableName, columnBuilder.String(name: "dd"))); operations.Add(new AlterColumnOperation(tableName, new ColumnModel(PrimitiveTypeKind.String) { Name = "dd3", MaxLength = 20 }, false)); operations.Add(new AlterColumnOperation(tableName, new ColumnModel(PrimitiveTypeKind.String) { Name = "dd2", MaxLength = 50 }, false)); operations.Add(new RenameColumnOperation(tableName, "dd3", "ee3")); var sqls = gen.Generate(operations, "2008").Select <MigrationStatement, string>(ms => ms.Sql).ToArray(); var sql = string.Join("\r\n\r\n", sqls); return(sql); }
protected virtual void Generate([NotNull] AlterTableOperation operation, [NotNull] IndentedStringBuilder builder) { Check.NotNull(operation, nameof(operation)); Check.NotNull(builder, nameof(builder)); builder.AppendLine(".AlterTable("); 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.Append(")"); Annotations(operation.GetAnnotations(), builder); OldAnnotations(operation.OldTable.GetAnnotations(), builder); } }
private string GenerateSqlStatementConcrete(AlterTableOperation migrationOperation) { /* * SQLite does not support alter table * We should rename old table, create the new table, copy old data to new table and drop old table */ throw new NotSupportedException("Alter column not supported by SQLite"); }
/// <summary> /// Override this method to generate SQL when the definition of a table or its attributes are changed. /// The default implementation of this method does nothing. /// </summary> /// <param name="alterTableOperation">The operation describing changes to the table. </param> protected override void Generate(AlterTableOperation alterTableOperation) { base.Generate(alterTableOperation); AnnotationAction <string>( alterTableOperation.Annotations, TableDescriptionAnnotationConvention.AnnotationName, s => AddDescription(s, alterTableOperation.Name, null)); }
protected override void Generate(AlterTableOperation operation) { foreach (var column in operation.Columns) { SetColumnValue(column); } base.Generate(operation); }
protected override void Generate(AlterTableOperation operation, IModel model, MigrationCommandListBuilder builder) { if (IsMemoryOptimized(operation) ^ IsMemoryOptimized(operation.OldTable)) { throw new InvalidOperationException(SqlServerStrings.AlterMemoryOptimizedTable); } base.Generate(operation, model, builder); }
/// <summary> /// 修改表格。 /// </summary> /// <param name="table">表格名称。</param> /// <returns>返回迁移实例。</returns> public virtual AlterOperationBuilder <AlterTableOperation> AlterTable(string table) { var operation = new AlterTableOperation { Table = table }; Operations.Add(operation); return(new AlterOperationBuilder <AlterTableOperation>(operation)); }
protected override void Generate(AlterTableOperation alterTableOperation) { base.Generate(alterTableOperation); // If the tables you want to reseed have an Id primary key... if (alterTableOperation.Columns.Any(c => c.Name == "Id")) { string sqlSeedReset = string.Format("DBCC CHECKIDENT ({0}, RESEED, 1000) ", alterTableOperation.Name.Replace("dbo.", "")); base.Generate(new SqlOperation(sqlSeedReset)); } }
protected override void Generate(AlterTableOperation alterTableOperation) { base.Generate(alterTableOperation); // Retrieve table name. var tableName = alterTableOperation.Name; // Retrieve table annotations. var tableAnnotations = alterTableOperation.Annotations; // Generate table description. GenerateTableDescription(tableAnnotations, tableName); }
protected override void Generate(AlterTableOperation operation, IModel model, MigrationCommandListBuilder builder) { base.Generate(operation, model, builder); foreach (var extendedProperty in operation.OldTable.GetExtendedProperties()) { Generate(new RemoveExtendedPropertyOperation(new SchemaTableColumn(operation.Schema, operation.Name, null), extendedProperty), builder); } foreach (var extendedProperty in operation.GetExtendedProperties()) { Generate(new AddExtendedPropertyOperation(new SchemaTableColumn(operation.Schema, operation.Name, null), extendedProperty), builder); } }
public virtual AlterOperationBuilder <AlterTableOperation> AlterTable(string name, string schema = null) { Check.NotEmpty(name, nameof(name)); var operation = new AlterTableOperation { Schema = schema, Name = name }; Operations.Add(operation); return(new AlterOperationBuilder <AlterTableOperation>(operation)); }
protected override void Generate(AlterTableOperation operation, IModel model, MigrationCommandListBuilder builder) { var oldStorageParameters = GetStorageParameters(operation.OldTable); var newStorageParameters = GetStorageParameters(operation); var newOrChanged = newStorageParameters.Where(p => !oldStorageParameters.ContainsKey(p.Key) || oldStorageParameters[p.Key] != p.Value ).ToList(); if (newOrChanged.Count > 0) { builder .Append("ALTER TABLE ") .Append(SqlGenerationHelper.DelimitIdentifier(operation.Name, operation.Schema)); builder .Append(" SET (") .Append(string.Join(", ", newOrChanged.Select(p => $"{p.Key}={p.Value}"))) .Append(")"); builder.AppendLine(SqlGenerationHelper.StatementTerminator); EndStatement(builder); } var removed = oldStorageParameters .Select(p => p.Key) .Where(pn => !newStorageParameters.ContainsKey(pn)) .ToList(); if (removed.Count > 0) { builder .Append("ALTER TABLE ") .Append(SqlGenerationHelper.DelimitIdentifier(operation.Name, operation.Schema)); builder .Append(" RESET (") .Append(string.Join(", ", removed)) .Append(")"); builder.AppendLine(SqlGenerationHelper.StatementTerminator); EndStatement(builder); } base.Generate(operation, model, builder); }
protected override void Generate(AlterTableOperation operation, IModel model, MigrationCommandListBuilder builder) { base.Generate(operation, model, builder); IAnnotation comment = operation.GetAnnotations().FirstOrDefault(x => x.Name == CommentAnnotationName); if (comment is null) { comment = operation.OldTable.GetAnnotation(CommentAnnotationName); if (comment != null) { DropTableComment(builder, operation.Schema, operation.Name); } } else { UpdateTableComment(builder, operation.Schema, operation.Name, comment.Value); } }
protected override void Generate( AlterTableOperation operation, IModel model, MigrationCommandListBuilder builder) { base.Generate(operation, model, builder); var autoIncrementValue = operation[CustomMySqlAnnotationProvider.AutoincrementAnnotation]; if (autoIncrementValue is not null && (autoIncrementValue.GetType().Equals(typeof(int)) | autoIncrementValue.GetType().Equals(typeof(long)))) { builder.Append("ALTER TABLE ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name, operation.Schema)) .Append(" AUTO_INCREMENT ") .Append(autoIncrementValue.ToString() !); builder.AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator); EndStatement(builder); } }
protected override void Generate(AlterTableOperation alterTableOperation) { Action <AlterTableOperation, string, Action <AnnotationValues, Action <AnnotationValues, IndentedTextWriter> >, Action <AnnotationValues, IndentedTextWriter> > func = (alter, annotationName, funcwriter, act) => { AnnotationValues annoValues; if (alterTableOperation.Annotations.TryGetValue(annotationName, out annoValues)) { funcwriter(annoValues, act); } }; Action <AnnotationValues, Action <AnnotationValues, IndentedTextWriter> > funcIndentedTextWriter = (annoValues, action) => { using (IndentedTextWriter writer = Writer()) { action(annoValues, writer); Statement(writer); } }; Action <AnnotationValues, IndentedTextWriter> funcChangeTracking = (anoVals, wr) => { string[] settingOpts = { "ENABLE", "DISABLE", "True" }; var setting = anoVals.NewValue != null ? (anoVals.NewValue.ToString() == settingOpts[2] ? settingOpts[0] : settingOpts[1]) : settingOpts[1]; wr.WriteLine($"exec sp_executesql N'ALTER TABLE [{alterTableOperation.Name}] {setting} CHANGE_TRACKING';"); }; Func <AnnotationValues, string[]> funcNeedSplit = anoVals => anoVals.NewValue.ToString().Split('|'); Action <AnnotationValues, IndentedTextWriter> funcView = (anoVals, wr) => { string[] newValues = funcNeedSplit(anoVals); wr.WriteLine($"exec sp_executesql N'CREATE VIEW {newValues[0]} AS {newValues[1]}'; "); }; Action <AnnotationValues, IndentedTextWriter> funcStorePorcedures = (anoVals, wr) => { string[] newValues = funcNeedSplit(anoVals); for (int i = 1; i < newValues.Length; i += 2) { wr.WriteLine($"exec sp_executesql N'CREATE PROCEDURE {newValues[i - 1]} {newValues[i]}'; "); } }; func(alterTableOperation, "TrackDatabaseChanges", funcIndentedTextWriter, funcChangeTracking); func(alterTableOperation, "View", funcIndentedTextWriter, funcView); func(alterTableOperation, "StoredProcedures", funcIndentedTextWriter, funcStorePorcedures); }
protected override void Generate(AlterTableOperation alterTableOperation) { _tableCollation = alterTableOperation.Annotations.ContainsKey(CollationAttribute.AnnotationName) ? (CollationAttribute)alterTableOperation.Annotations[CollationAttribute.AnnotationName].NewValue : null; if (_tableCollation != null) { // Need to alter any column that doesn't have explicitly set collation foreach (var column in alterTableOperation.Columns.Where( c => c.ClrType == typeof(string) && !c.Annotations.ContainsKey(CollationAttribute.AnnotationName))) { Generate(new AlterColumnOperation(alterTableOperation.Name, column, false)); } } _tableCollation = null; }
protected override void Generate(AlterTableOperation operation, IModel model, MigrationCommandListBuilder builder) { var changeTrackingEnabled = operation.IsChangeTrackingEnabled(); var changeTrackingWasEnabled = operation.OldTable.IsChangeTrackingEnabled(); if (!changeTrackingEnabled && !changeTrackingWasEnabled) { base.Generate(operation, model, builder); return; } if (changeTrackingEnabled) { Generate(new EnableChangeTrackingForTableOperation(operation.Name, operation.Schema, operation.ChangeTrackingTrackColumns()), model, builder); } else { Generate(new DisableChangeTrackingForTableOperation(operation.Name, operation.Schema), model, builder); } }
protected virtual IEnumerable <MigrationOperation> PostFilterOperations(IEnumerable <MigrationOperation> migrationOperations) { foreach (var migrationOperation in migrationOperations) { var resultOperation = migrationOperation switch { AlterDatabaseOperation operation => PostFilterOperation(operation), CreateTableOperation operation => PostFilterOperation(operation), AlterTableOperation operation => PostFilterOperation(operation), AddColumnOperation operation => PostFilterOperation(operation), AlterColumnOperation operation => PostFilterOperation(operation), _ => migrationOperation }; if (resultOperation != null) { yield return(resultOperation); } } }
private string GenerateSqlStatementConcrete(AlterTableOperation migrationOperation) { JetDdlBuilder ddlBuilder = new JetDdlBuilder(); foreach (ColumnModel column in migrationOperation.Columns) { ddlBuilder.AppendSql("ALTER TABLE "); ddlBuilder.AppendIdentifier(migrationOperation.Name); ddlBuilder.AppendSql(" ALTER COLUMN "); ddlBuilder.AppendIdentifier(column.Name); ddlBuilder.AppendSql(" "); TypeUsage storeType = JetProviderManifest.Instance.GetStoreType(column.TypeUsage); ddlBuilder.AppendType(storeType, column.IsNullable ?? true, column.IsIdentity); ddlBuilder.AppendSql(BATCHTERMINATOR); } return(ddlBuilder.GetCommandText()); }
protected virtual AlterTableOperation PostFilterOperation(AlterTableOperation operation) { HandleCharSetDelegation(operation, DelegationModes.ApplyToTables); HandleCollationDelegation(operation, DelegationModes.ApplyToTables); // Ensure, that no properties have been added by the EF Core team in the meantime. // If they have, they need to be checked below. AssertMigrationOperationProperties( operation, new[] { nameof(AlterTableOperation.OldTable), nameof(AlterTableOperation.Name), nameof(AlterTableOperation.Schema), nameof(AlterTableOperation.Comment), }); // Ensure, that this hasn't become an empty operation. // We do not check Name and Schema, because changes would have resulted in a RenameTableOperation already. return(operation.Comment != operation.OldTable.Comment || HasDifferences(operation.GetAnnotations(), operation.OldTable.GetAnnotations()) ? operation : null); }
protected override void Generate(AlterTableOperation operation, IModel model, MigrationCommandListBuilder builder) { var madeChanges = false; // Storage parameters var oldStorageParameters = GetStorageParameters(operation.OldTable); var newStorageParameters = GetStorageParameters(operation); var newOrChanged = newStorageParameters.Where(p => !oldStorageParameters.ContainsKey(p.Key) || oldStorageParameters[p.Key] != p.Value ).ToList(); if (newOrChanged.Count > 0) { builder .Append("ALTER TABLE ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name, operation.Schema)); builder .Append(" SET (") .Append(string.Join(", ", newOrChanged.Select(p => $"{p.Key}={p.Value}"))) .Append(")"); builder.AppendLine(';'); madeChanges = true; } var removed = oldStorageParameters .Select(p => p.Key) .Where(pn => !newStorageParameters.ContainsKey(pn)) .ToList(); if (removed.Count > 0) { builder .Append("ALTER TABLE ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name, operation.Schema)); builder .Append(" RESET (") .Append(string.Join(", ", removed)) .Append(")"); builder.AppendLine(';'); madeChanges = true; } // Comment var oldComment = operation.OldTable[NpgsqlAnnotationNames.Comment] as string; var newComment = operation[NpgsqlAnnotationNames.Comment] as string; if (oldComment != newComment) { var stringTypeMapping = Dependencies.TypeMappingSource.GetMapping(typeof(string)); builder .Append("COMMENT ON TABLE ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name, operation.Schema)) .Append(" IS ") .Append(stringTypeMapping.GenerateSqlLiteral(newComment)); builder.AppendLine(';'); madeChanges = true; } if (madeChanges) { EndStatement(builder); } }
protected override void Generate(AlterTableOperation alterTableOperation) { SetAnnotatedColumns(alterTableOperation.Columns, alterTableOperation.Name); base.Generate(alterTableOperation); }
protected virtual IEnumerable <MigrationStatement> Generate(AlterTableOperation operation) { // Nothing to do since there is no inherent semantics associated with annotations yield break; }
/// <summary> /// 修改表格。 /// </summary> /// <param name="operation">操作实例。</param> /// <param name="builder"><see cref="MigrationCommandListBuilder"/>实例对象。</param> protected virtual void Generate( AlterTableOperation operation, MigrationCommandListBuilder builder) { }
/// <summary> /// Override this method to generate SQL when the definition of a table or its attributes are changed. /// The default implementation of this method does nothing. /// </summary> /// <param name="alterTableOperation"> The operation describing changes to the table. </param> protected internal virtual void Generate(AlterTableOperation alterTableOperation) { Check.NotNull(alterTableOperation, "alterTableOperation"); // Nothing to do since there is no inherent semantics associated with annotations }
protected override void Generate(AlterTableOperation operation, IModel model, MigrationCommandListBuilder builder) => base.Generate(operation, model, builder);
protected override void Generate(AlterTableOperation alterTableOperation, IndentedTextWriter writer) { SetAnnotatedColumns(alterTableOperation.Columns, writer); base.Generate(alterTableOperation, writer); }
protected virtual void Generate( [NotNull] AlterTableOperation operation, [CanBeNull] IModel model, [NotNull] MigrationCommandListBuilder builder) { }