You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Connected.Framework/Connected.Data/Schema/Sql/ColumnAlter.cs

61 lines
1.9 KiB

2 years ago
using System.Text;
namespace Connected.Data.Schema.Sql
{
internal class ColumnAlter : ColumnTransaction
{
public ColumnAlter(ISchemaColumn column, ExistingSchema existing, ISchemaColumn existingColumn) : base(column)
{
Existing = existing;
ExistingColumn = existingColumn;
}
private ExistingSchema Existing { get; }
private ISchemaColumn ExistingColumn { get; }
protected override async Task OnExecute()
{
if (ExistingColumn.Equals(Column))
return;
if (!string.IsNullOrWhiteSpace(ExistingColumn.DefaultValue))
{
var existingDefault = SchemaExtensions.ParseDefaultValue(ExistingColumn.DefaultValue);
var def = SchemaExtensions.ParseDefaultValue(Column.DefaultValue);
if (!string.Equals(existingDefault, def, StringComparison.Ordinal))
await new DefaultDrop(Column).Execute(Context);
}
if (Column.DataType != ExistingColumn.DataType
|| Column.IsNullable != ExistingColumn.IsNullable
|| Column.MaxLength != ExistingColumn.MaxLength
|| Column.IsVersion != ExistingColumn.IsVersion)
await Context.Execute(CommandText);
var ed = SchemaExtensions.ParseDefaultValue(ExistingColumn.DefaultValue);
var nd = SchemaExtensions.ParseDefaultValue(Column.DefaultValue);
if (!string.Equals(ed, nd, StringComparison.Ordinal) && nd is not null)
await new DefaultAdd(Column, Context.Schema.Name).Execute(Context);
if (!ExistingColumn.IsPrimaryKey && Column.IsPrimaryKey)
await new PrimaryKeyAdd(Column).Execute(Context);
else if (ExistingColumn.IsPrimaryKey && !Column.IsPrimaryKey)
await new PrimaryKeyRemove(Existing, ExistingColumn).Execute(Context);
}
private string CommandText
{
get
{
var text = new StringBuilder();
text.AppendLine($"ALTER TABLE {Escape(Context.Schema.SchemaName(), Context.Schema.Name)}");
text.AppendLine($"ALTER COLUMN {CreateColumnCommandText(Column)}");
return text.ToString();
}
}
}
}