protected override void VisitDefaultConstraint(DefaultConstraint item)
 {
     if (item.Value != null)
     {
         int?defaultVal = null;
         ((IVisitableBuilder)item.Value).Accept(this);
         if (CurrentNumericLiteralValue != null)
         {
             defaultVal = Convert.ToInt32(CurrentNumericLiteralValue);
             CurrentNumericLiteralValue = null;
         }
         if (defaultVal.HasValue)
         {
             if (defaultVal == 1)
             {
                 CurrentDefaultBooleanAttributeValue = true;
             }
             else if (defaultVal == 0)
             {
                 CurrentDefaultBooleanAttributeValue = false;
             }
         }
     }
     base.VisitDefaultConstraint(item);
 }
예제 #2
0
 /// <summary>
 /// Enumerates the SQL commands that are necessary to drop
 /// the specified <paramref name="defaultConstraint"/>.
 /// </summary>
 /// <param name="defaultConstraint">The default constraint.</param>
 /// <returns>The SQL commands.</returns>
 protected virtual IEnumerable <string> DropDefaultConstraint(DefaultConstraint defaultConstraint)
 {
     yield return(string.Format("ALTER TABLE {0} ALTER COLUMN {1} DROP DEFAULT;",
                                EscapeTableName(defaultConstraint.Table.Name),
                                EscapeConstraintName(defaultConstraint.Name)
                                ));
 }
예제 #3
0
        /// <summary>
        /// Enumerates the SQL commands that are necessary to drop
        /// the specified <paramref name="defaultConstraint"/>.
        /// </summary>
        /// <param name="defaultConstraint">The default constraint.</param>
        /// <returns>The SQL commands.</returns>
        protected override IEnumerable <string> DropDefaultConstraint(DefaultConstraint defaultConstraint)
        {
            IEnumerable <string> sql = null;

            if (string.IsNullOrEmpty(defaultConstraint.Name))
            {
                sql = new string[]
                {
                    string.Format("DECLARE @{0}DefaultName VARCHAR(MAX);", defaultConstraint.ColumnName) +
                    Environment.NewLine +
                    string.Format("SELECT @{0}DefaultName = o2.name " +
                                  "FROM syscolumns c " +
                                  "JOIN sysobjects o ON c.id = o.id " +
                                  "JOIN sysobjects o2 ON c.cdefault = o2.id " +
                                  "WHERE o.name = {1} AND c.name = {2};",
                                  defaultConstraint.ColumnName,
                                  FormatValue(defaultConstraint.Table.Name),
                                  FormatValue(defaultConstraint.ColumnName)
                                  ) +
                    Environment.NewLine +
                    string.Format("EXEC('ALTER TABLE {0} DROP CONSTRAINT ' + @{1}DefaultName);",
                                  EscapeTableName(string.Format(defaultConstraint.Table.Name)),
                                  defaultConstraint.ColumnName
                                  )
                };
            }
            else
            {
                sql = base.DropDefaultConstraint(defaultConstraint);
            }

            return(sql);
        }
예제 #4
0
        public IEnumerable <string> RenameColumn(string tableName, string oldName, string newName)
        {
            Table table  = GetTable(tableName);
            var   column = new Microsoft.SqlServer.Management.Smo.Column(table, oldName);

            // rename default constraint
            string            oldDefaultConstraintName = ObjectNameHelper.GetObjectName(tableName, "DF", MaximumDbObjectNameLength, oldName);
            string            constraintName           = oldDefaultConstraintName;
            DefaultConstraint defaultConstraint        = column.AddDefaultConstraint(constraintName);

            defaultConstraint.Rename(ObjectNameHelper.GetObjectName(tableName, "DF", MaximumDbObjectNameLength, newName));

            // rename column
            table.Columns.Add(column);
            column.Rename(newName);

            // script changes
            IEnumerable <string> commandTexts         = ScriptChanges(table.Parent.Parent);
            string renameDefaultConstraintCommandText = string.Format(CultureInfo.InvariantCulture, "IF OBJECT_ID('{0}') IS NOT NULL ", oldDefaultConstraintName) + commandTexts.First();

            yield return(Regex.Replace(renameDefaultConstraintCommandText, @"EXEC \[\w+\]\.dbo\.sp_rename", @"EXEC dbo.sp_rename")); // for some reason SMO is putting the server name in front of dbo.sp_rename which we do not have in the SqlServerProvider

            foreach (string commandText in commandTexts.Skip(1))
            {
                yield return(commandText);
            }
        }
예제 #5
0
        public IEnumerable <string> AlterColumn(string tableName, Column column)
        {
            // drop (possibly) existing default constraint
            Table table = GetTable(tableName);
            var   c     = new Microsoft.SqlServer.Management.Smo.Column(table, column.Name)
            {
                Nullable = column.IsNullable,
                DataType = Convert(column.DataType),
            };
            DefaultConstraint defaultConstraint = AddDefaultConstraint(c, tableName, "dummy");

            defaultConstraint.Drop();
            foreach (string command in ScriptChanges(table.Parent.Parent))
            {
                yield return(string.Format(CultureInfo.InvariantCulture, "IF OBJECT_ID('{0}') IS NOT NULL ", defaultConstraint.Name) + command);
            }

            // alter column
            table = GetTable(tableName);
            c     = new Microsoft.SqlServer.Management.Smo.Column(table, column.Name)
            {
                Nullable = column.IsNullable,
                DataType = Convert(column.DataType),
            };
            if (column.DefaultValue != null)
            {
                AddDefaultConstraint(c, tableName, column.DefaultValue);
            }
            c.Alter();
            foreach (string command in ScriptChanges(table.Parent.Parent))
            {
                yield return(command);
            }
        }
예제 #6
0
 /// <summary>
 /// Devuelve el schema de la columna en formato SQL.
 /// </summary>
 public string ToSql(Boolean sqlConstraint)
 {
     string sql = "";
     sql += "[" + Name + "] ";
     if (!IsComputed)
     {
         if (this.IsUserDefinedType)
             sql += Type;
         else
             sql += "[" + Type + "]";
         if (Type.Equals("binary") || Type.Equals("varbinary") || Type.Equals("varchar") || Type.Equals("char") || Type.Equals("nchar") || Type.Equals("nvarchar"))
         {
             if (Size == -1)
                 sql += " (max)";
             else
             {
                 if (Type.Equals("nchar") || Type.Equals("nvarchar"))
                     sql += " (" + (Size / 2).ToString(CultureInfo.InvariantCulture) + ")";
                 else
                     sql += " (" + Size.ToString(CultureInfo.InvariantCulture) + ")";
             }
         }
         if (Type.Equals("xml"))
         {
             if (!String.IsNullOrEmpty(XmlSchema))
             {
                 if (IsXmlDocument)
                     sql += "(DOCUMENT " + XmlSchema + ")";
                 else
                     sql += "(CONTENT " + XmlSchema + ")";
             }
         }
         if (Type.Equals("numeric") || Type.Equals("decimal")) sql += " (" + Precision.ToString(CultureInfo.InvariantCulture) + "," + Scale.ToString(CultureInfo.InvariantCulture) + ")";
         if (((Database)Parent.Parent).Info.Version >= DatabaseInfo.VersionTypeEnum.SQLServer2008)
         {
             if (Type.Equals("datetime2") || Type.Equals("datetimeoffset") || Type.Equals("time")) sql += "(" + Scale.ToString(CultureInfo.InvariantCulture) + ")";
         }
         if ((!String.IsNullOrEmpty(Collation)) && (!IsUserDefinedType)) sql += " COLLATE " + Collation;
         if (IsIdentity) sql += " IDENTITY (" + IdentitySeed.ToString(CultureInfo.InvariantCulture) + "," + IdentityIncrement.ToString(CultureInfo.InvariantCulture) + ")";
         if (IsIdentityForReplication) sql += " NOT FOR REPLICATION";
         if (IsSparse) sql += " SPARSE";
         if (IsFileStream) sql += " FILESTREAM";
         if (IsNullable)
             sql += " NULL";
         else
             sql += " NOT NULL";
         if (IsRowGuid) sql += " ROWGUIDCOL";
     }
     else
     {
         sql += "AS " + ComputedFormula;
         if (IsPersisted) sql += " PERSISTED";
     }
     if ((sqlConstraint) && (DefaultConstraint != null))
     {
         if (DefaultConstraint.Status != ObjectStatus.Drop)
             sql += " " + DefaultConstraint.ToSql().Replace("\t", "").Trim();
     }
     return sql;
 }
예제 #7
0
        public void ConstraintAndSinglePoint()
        {
            Constraint c = new DefaultConstraint(new double[] { 0, 0, 0 }, new double[] { 1, 1, 1 });

            Assert.IsTrue(c.ContainsSubspace(new double[] { 0.5, 0.5, 0.5 }));
            Assert.IsTrue(c.ContainsSubspace(new double[] { -0.5, -0.5, -0.5 }));
            Assert.IsFalse(c.ContainsSubspace(new double[] { 1, 1, 2 }));
        }
예제 #8
0
        public virtual void AddDefaultConstraint(SchemaQualifiedName tableName, [NotNull] string columnName,
                                                 DefaultConstraint defaultConstraint)
        {
            Check.NotEmpty(columnName, "columnName");

            AddOperation(new AddDefaultConstraintOperation(tableName, columnName,
                                                           defaultConstraint.GetValue(), defaultConstraint.GetSql()));
        }
예제 #9
0
        private static DefaultConstraint AddDefaultConstraint(Microsoft.SqlServer.Management.Smo.Column column, string tableName, object value)
        {
            string            constraintName    = ObjectNameHelper.GetObjectName(tableName, "DF", MaximumDbObjectNameLength, column.Name);
            DefaultConstraint defaultConstraint = column.AddDefaultConstraint(constraintName);

            defaultConstraint.Text = GetDefaultValueAsString(value);
            return(defaultConstraint);
        }
예제 #10
0
 public static string ScriptDefault(
     DefaultConstraint defaultConstraint,
     string tableSchema,
     string tableName,
     string columnName
     )
 {
     return("ALTER TABLE [" + tableSchema + "].[" + tableName + "] ADD CONSTRAINT [" + defaultConstraint.Name +
            "] DEFAULT " + defaultConstraint.Text + " FOR [" + columnName + "];");
 }
예제 #11
0
 public SQLScriptList RebuildConstraint(Boolean Check)
 {
     SQLScriptList list = new SQLScriptList();
     if (DefaultConstraint != null)
     {
         if ((!Check) || (DefaultConstraint.CanCreate)) list.Add(DefaultConstraint.Create());
         list.Add(DefaultConstraint.Drop());
     }
     return list;
 }
예제 #12
0
 /// <summary>
 /// Enumerates the SQL commands that are necessary to create
 /// the specified <paramref name="defaultConstraint"/>.
 /// </summary>
 /// <param name="defaultConstraint">The default constraint.</param>
 /// <returns>The SQL commands.</returns>
 protected virtual IEnumerable <string> AddDefaultConstraint(DefaultConstraint defaultConstraint)
 {
     yield return(string.Format(
                      "ALTER TABLE {0} ADD CONSTRAINT {1} DEFAULT({2}) FOR {3};",
                      EscapeTableName(defaultConstraint.Table.Name),
                      EscapeConstraintName(defaultConstraint.Name),
                      FormatValue(defaultConstraint.Value),
                      EscapeColumnName(defaultConstraint.ColumnName)
                      ));
 }
        public void Equals_Object_SameInstance_True()
        {
            // Arrange
            var instance = new DefaultConstraint("a", "b", "c", "d");

            // Act
            var equals = instance.Equals((object)instance);

            // Assert
            Assert.IsTrue(equals);
        }
        public void Equals_Object_Null_False()
        {
            // Arrange
            var instance = new DefaultConstraint("a", "b", "c", "d");

            // Act
            var equals = instance.Equals(null as object);

            // Assert
            Assert.IsFalse(equals);
        }
        public void Equals_Object_DifferentType_False()
        {
            // Arrange
            var instance = new DefaultConstraint("a", "b", "c", "d");

            // Act
            var equals = instance.Equals(new Version(1, 0));

            // Assert
            Assert.IsFalse(equals);
        }
예제 #16
0
 public static SubSpace FromPoint(params double[] coordinates)
 {
     //foreach coordinate, one constraint x[i]=coordinate[y], and the term??
     Constraint[] constraints=new Constraint[coordinates.Length];
     for (int i = 0; i < coordinates.Length; i++)
     {
         double[] constraintCoeffs=new double[coordinates.Length];
         constraintCoeffs[i] = coordinates[i];
         constraints[i] = new DefaultConstraint(constraintCoeffs);
     }
     return new SubSpace(constraints);
 }
        public void Equals_Typed_TwoInstances(string tableSchema, string tableName, string columnName, string constraintName, bool expectedEquals)
        {
            // Arrange
            var instance1 = new DefaultConstraint("a", "b", "c", "d");
            var instance2 = new DefaultConstraint(tableSchema, tableName, columnName, constraintName);

            // Act
            var equals = instance1.Equals(instance2);

            // Assert
            Assert.AreEqual(expectedEquals, equals);
        }
        public void InequalityOperator(string tableSchema, string tableName, string columnName, string constraintName, bool expectedInequality)
        {
            // Arrange
            var instance1 = new DefaultConstraint("a", "b", "c", "d");
            var instance2 = new DefaultConstraint(tableSchema, tableName, columnName, constraintName);

            // Act
            var inequality = instance1 != instance2;

            // Assert
            Assert.AreEqual(expectedInequality, inequality);
        }
예제 #19
0
 public static SubSpace FromPoint(params double[] coordinates)
 {
     //foreach coordinate, one constraint x[i]=coordinate[y], and the term??
     Constraint[] constraints = new Constraint[coordinates.Length];
     for (int i = 0; i < coordinates.Length; i++)
     {
         double[] constraintCoeffs = new double[coordinates.Length];
         constraintCoeffs[i] = coordinates[i];
         constraints[i]      = new DefaultConstraint(constraintCoeffs);
     }
     return(new SubSpace(constraints));
 }
예제 #20
0
        public IEnumerable <string> DropDefault(string tableName, Column column)
        {
            Table table = GetTable(tableName);
            var   c     = new Microsoft.SqlServer.Management.Smo.Column(table, column.Name)
            {
                DataType = Convert(column.DataType),
                Nullable = column.IsNullable,
            };
            DefaultConstraint defaultConstraint = AddDefaultConstraint(c, tableName, column.DefaultValue);

            defaultConstraint.Drop();
            return(ScriptChanges(table.Parent.Parent));
        }
        public void GetHashCode_HashCodeComparison(string tableSchema, string tableName, string columnName, string constraintName, bool expectedSameHashCode)
        {
            // Arrange
            var instance1 = new DefaultConstraint("a", "b", "c", "d");
            var instance2 = new DefaultConstraint(tableSchema, tableName, columnName, constraintName);

            // Act
            var i1HashCode   = instance1.GetHashCode();
            var i2HashCode   = instance2.GetHashCode();
            var sameHashCode = i1HashCode == i2HashCode;

            // Assert
            Assert.AreEqual(expectedSameHashCode, sameHashCode);
        }
예제 #22
0
        private void AddDefaultItem(DefaultConstraint defaultItem)
        {
            builder.AppendLine(ScriptHelper.KeyIsNull(defaultItem.Name));
            builder.Begin();
            var foreignScripts = defaultItem.Script();

            foreach (string script in foreignScripts)
            {
                builder.AppendLine(script);
            }

            builder.AddEndGo();
            builder.NewLine();
        }
예제 #23
0
        public void AddDefaultConstraint_adds_operation()
        {
            var builder = new MigrationBuilder();

            builder.AddDefaultConstraint("dbo.MyTable", "Foo", DefaultConstraint.Value(5));

            Assert.Equal(1, builder.Operations.Count);
            Assert.IsType <AddDefaultConstraintOperation>(builder.Operations[0]);

            var operation = (AddDefaultConstraintOperation)builder.Operations[0];

            Assert.Equal("dbo.MyTable", operation.TableName);
            Assert.Equal("Foo", operation.ColumnName);
            Assert.Equal(5, operation.DefaultValue);
        }
        public void Constructor_CorrectInitialization(string constraintName)
        {
            // Arrange
            const string tableSchema = "dbo";
            const string tableName   = "Author";
            const string columnName  = "Name";

            // Act
            var dc = new DefaultConstraint(tableSchema, tableName, columnName, constraintName);

            // Assert
            Assert.AreEqual(tableSchema, dc.TableSchema);
            Assert.AreEqual(tableName, dc.TableName);
            Assert.AreEqual(columnName, dc.ColumnName);
            Assert.AreEqual(constraintName, dc.ConstraintName);
            Assert.AreEqual($"[dbo].[Author].[Name].[{(constraintName ?? "<UNNAMED>")}]", dc.DisplayName);
        }
예제 #25
0
        public static string CreateColumn(IColumn c, DefaultConstraint constraint)
        {
            string fullType = GetColumnType(c);

            var generatedAlways = c is SystemVersionedInfo.Column svc ?
                                  $"GENERATED ALWAYS AS ROW {(svc.SystemVersionColumnType == SystemVersionedInfo.ColumnType.Start ? "START" : "END")} HIDDEN" :
                                  null;

            var defaultConstraint = constraint != null ? $"CONSTRAINT {constraint.Name} DEFAULT " + constraint.QuotedDefinition : null;

            return($" ".CombineIfNotEmpty(
                       c.Name.SqlEscape(),
                       fullType,
                       c.Identity ? "IDENTITY " : null,
                       generatedAlways,
                       c.Collation != null ? ("COLLATE " + c.Collation) : null,
                       c.Nullable.ToBool() ? "NULL" : "NOT NULL",
                       defaultConstraint
                       ));
        }
예제 #26
0
        //----------------------------------------------------------------------------------------------------
        public static DefaultConstraint DefaultConstraint__Get(Column column)
        {
            AjaxService.ASPdatabaseService.GetSetVal();
            var    dict = new Dictionary <string, DefaultConstraint>();
            string sql  = SQLServer_SQLBuilders.BuildSql__DefaultConstraint_Select(column);

            using (DbConnectionCommand command = UniversalADO.OpenConnectionCommand(column.ConnectionId, sql))
            {
                using (DbReaderWrapper reader = command.ExecuteReaderWrapper())
                {
                    while (reader.Read())
                    {
                        string columnName   = reader.Get("ColumnName", "");
                        string columnName_L = columnName.ToLower();

                        var defaultConstraint = new DefaultConstraint()
                        {
                            ConnectionId          = column.ConnectionId,
                            Schema                = column.Schema,
                            TableName             = column.TableName,
                            ColumnName            = reader.Get("ColumnName", ""),
                            DefaultConstraintName = reader.Get("DefaultConstraintName", ""),
                            DefaultDefinition     = reader.Get("DefaultDefinition", "")
                        };

                        if (!dict.ContainsKey(columnName_L))
                        {
                            dict.Add(columnName_L, defaultConstraint);
                        }
                    }
                }
            }
            if (dict.ContainsKey(column.ColumnName.ToLower()))
            {
                return(dict[column.ColumnName.ToLower()]);
            }
            else
            {
                return(null);
            }
        }
예제 #27
0
        public void CreateDefaultConstraint(
            Dictionary <string, UserTable> userTables,
            IDataRecord reader)
        {
            var schemaName = Convert.ToString(reader[SchemaNameOrdinal]);
            var tableName  = Convert.ToString(reader[TableNameOrdinal]);

            var userTableNamespaceBuilder = new StringBuilder(schemaName.Length + tableName.Length + 1);

            userTableNamespaceBuilder.Append(schemaName).
            Append(Constants.Dot).
            Append(tableName);

            var userTableNamespace = userTableNamespaceBuilder.ToString();

            if (!userTables.ContainsKey(userTableNamespace))
            {
                return;
            }

            var userTable = userTables[userTableNamespace];

            if (userTable == null)
            {
                return;
            }

            var defaultConstraint = new DefaultConstraint
            {
                UserTable     = userTable,
                ColumnName    = Convert.ToString(reader[ColumnNameOrdinal]),
                ObjectName    = Convert.ToString(reader[ObjectNameOrdinal]),
                Definition    = Convert.ToString(reader[DefinitionOrdinal]),
                IsSystemNamed = Convert.ToBoolean(reader[IsSystemNamedOrdinal])
            };

            userTable.DefaultConstraints.Add(defaultConstraint);
        }
예제 #28
0
        protected string TranslateExecDropDefaultConstraint(SqlCompilerContext context, SqlAlterTable node, DefaultConstraint defaultConstraint)
        {
            var resultBuilder = new StringBuilder();
            var column        = defaultConstraint.Column;
            var table         = defaultConstraint.Table;
            var schema        = defaultConstraint.Column.DataTable.Schema;
            var gettingNameOfDefaultConstraintScript = GetCurentNameOfDefaultConstraintScript();

            var sqlVariableName = RemoveFromStringInvalidCharacters(string.Format("var_{0}_{1}_{2}", schema.DbName,
                                                                                  table.DbName,
                                                                                  column.DbName));

            resultBuilder.Append(string.Format(gettingNameOfDefaultConstraintScript,
                                               sqlVariableName,
                                               QuoteIdentifier(schema.Catalog.DbName),
                                               schema.DbName,
                                               table.DbName,
                                               column.DbName));
            resultBuilder.Append(" ");
            resultBuilder.Append("Exec(N'");
            resultBuilder.Append(Translate(context, node, AlterTableSection.Entry));
            resultBuilder.Append(Translate(context, node, AlterTableSection.DropConstraint));
            resultBuilder.AppendFormat(" CONSTRAINT [' + @{0} + N']')", sqlVariableName);
            return(resultBuilder.ToString());
        }
예제 #29
0
 public virtual string Translate(SqlCompilerContext context, SqlAlterTable node, DefaultConstraint constraint)
 {
     return(TranslateExecDropDefaultConstraint(context, node, constraint));
 }
예제 #30
0
        /// <summary>
        /// Enumerates the SQL commands that are necessary to drop
        /// the specified <paramref name="defaultConstraint"/>.
        /// </summary>
        /// <param name="defaultConstraint">The default constraint.</param>
        /// <returns>The SQL commands.</returns>
        protected override IEnumerable<string> DropDefaultConstraint(DefaultConstraint defaultConstraint)
        {
            IEnumerable<string> sql = null;
            if (string.IsNullOrEmpty(defaultConstraint.Name))
            {
                sql = new string[]
                {
                    string.Format("DECLARE @{0}DefaultName VARCHAR(MAX);", defaultConstraint.ColumnName) +
                    Environment.NewLine +
                    string.Format("SELECT @{0}DefaultName = o2.name " +
                        "FROM syscolumns c " +
                        "JOIN sysobjects o ON c.id = o.id " +
                        "JOIN sysobjects o2 ON c.cdefault = o2.id " +
                        "WHERE o.name = {1} AND c.name = {2};",
                        defaultConstraint.ColumnName,
                        FormatValue(defaultConstraint.Table.Name),
                        FormatValue(defaultConstraint.ColumnName)
                    ) +
                    Environment.NewLine +
                    string.Format("EXEC('ALTER TABLE {0} DROP CONSTRAINT ' + @{1}DefaultName);",
                        EscapeTableName(string.Format(defaultConstraint.Table.Name)),
                        defaultConstraint.ColumnName
                    )
                };
            }
            else
            {
                sql = base.DropDefaultConstraint(defaultConstraint);
            }

            return sql;
        }
예제 #31
0
파일: Cases.cs 프로젝트: daszat/zetbox
 private bool WriteDefaultValue(TableRef tblName, string colName, DefaultConstraint def, IEnumerable<string> discriminatorFilter)
 {
     if (def is NewGuidDefaultConstraint)
     {
         db.WriteGuidDefaultValue(tblName, colName, discriminatorFilter);
         return true;
     }
     else if (def is DateTimeDefaultConstraint)
     {
         if (((DateTimeDefaultConstraint)def).Precision == DateTimeDefaultConstraintPrecision.Date)
             db.WriteDefaultValue(tblName, colName, DateTime.Today, discriminatorFilter);
         else
             db.WriteDefaultValue(tblName, colName, DateTime.Now, discriminatorFilter);
         return true;
     }
     else if (def is BoolDefaultConstraint)
     {
         db.WriteDefaultValue(tblName, colName, ((BoolDefaultConstraint)def).Value, discriminatorFilter);
         return true;
     }
     else if (def is IntDefaultConstraint)
     {
         db.WriteDefaultValue(tblName, colName, ((IntDefaultConstraint)def).Value, discriminatorFilter);
         return true;
     }
     else if (def is DecimalDefaultConstraint)
     {
         db.WriteDefaultValue(tblName, colName, ((DecimalDefaultConstraint)def).Value, discriminatorFilter);
         return true;
     }
     return false;
 }
예제 #32
0
 /// <summary>
 /// Drops the <see cref="DefaultConstraint"/> of the specified <paramref name="columnName"/>.
 /// </summary>
 /// <param name="columnName">Name of the column.</param>
 /// <returns>The constraint.</returns>
 public DefaultConstraint DropDefaultConstraintByColumnName(string columnName)
 {
     var c = new DefaultConstraint(this, null, Modifier.Drop)
     {
         ColumnName = columnName
     };
     Database.MigrationSteps.EnqueueBefore(c, (e => e == this));
     return c;
 }
예제 #33
0
        public override string CreateDefaultConstraint(DataContext sourceDataContext, DataContext targetDataContext, DefaultConstraint defaultConstraint)
        {
            var builder = new StringBuilder();

            builder.Append("ALTER TABLE ");
            builder.Append(CreateIdentifier(defaultConstraint.UserTable));
            builder.Append(" ADD CONSTRAINT `");
            builder.Append(defaultConstraint.ObjectName);
            builder.Append("`  DEFAULT ");
            builder.Append(defaultConstraint.Definition);
            builder.Append(" FOR `");
            builder.Append(defaultConstraint.ColumnName);
            builder.Append("`");
            return(builder.ToString());
        }
예제 #34
0
 /// <summary>
 /// Enumerates the SQL commands that are necessary to create
 /// the specified <paramref name="defaultConstraint"/>.
 /// </summary>
 /// <param name="defaultConstraint">The default constraint.</param>
 /// <returns>The SQL commands.</returns>
 protected virtual IEnumerable<string> AddDefaultConstraint(DefaultConstraint defaultConstraint)
 {
     yield return string.Format(
         "ALTER TABLE {0} ADD CONSTRAINT {1} DEFAULT({2}) FOR {3};",
         EscapeTableName(defaultConstraint.Table.Name),
         EscapeConstraintName(defaultConstraint.Name),
         FormatValue(defaultConstraint.Value),
         EscapeColumnName(defaultConstraint.ColumnName)
     );
 }
예제 #35
0
 /// <summary>
 /// Enumerates the SQL commands that are necessary to drop
 /// the specified <paramref name="defaultConstraint"/>.
 /// </summary>
 /// <param name="defaultConstraint">The default constraint.</param>
 /// <returns>The SQL commands.</returns>
 protected virtual IEnumerable<string> DropDefaultConstraint(DefaultConstraint defaultConstraint)
 {
     yield return string.Format("ALTER TABLE {0} ALTER COLUMN {1} DROP DEFAULT;",
         EscapeTableName(defaultConstraint.Table.Name),
         EscapeConstraintName(defaultConstraint.Name)
     );
 }
예제 #36
0
        private void CheckColumn(TableRef tblName, string colName, System.Data.DbType type, int size, int scale, bool isNullable, DefaultConstraint defConstr)
        {
            if (db.CheckColumnExists(tblName, colName))
            {
                // TODO: Add DataType Check
                {
                    var colIsNullable = db.GetIsColumnNullable(tblName, colName);
                    if (colIsNullable != isNullable)
                    {
                        Log.WarnFormat("Column '{0}'.'{1}' nullable mismatch. Column is {2} but should be {3}", tblName, colName,
                            colIsNullable ? "NULLABLE" : "NOT NULLABLE",
                            isNullable ? "NULLABLE" : "NOT NULLABLE");

                        if (repair)
                        {
                            if (isNullable || (!isNullable && !db.CheckColumnContainsNulls(tblName, colName)))
                            {
                                db.AlterColumn(tblName, colName, type, size, scale, isNullable, defConstr);
                                Log.Info("Fixed");
                            }
                            else if (!isNullable && db.CheckColumnContainsNulls(tblName, colName))
                            {
                                Log.WarnFormat("Column '{0}.{1}' contains NULL values, cannot set NOT NULLABLE", tblName, colName);
                            }
                        }
                    }
                }
                if (type == System.Data.DbType.String)
                {
                    int colSize = db.GetColumnMaxLength(tblName, colName);
                    // TODO: Introduce TextProperty
                    if (size == int.MaxValue)
                    {
                        // TODO: Check if nvarchar(max) or text
                    }
                    else if (colSize != size)
                    {
                        Log.WarnFormat("Column '{0}'.'{1}' length mismatch. Columns length is {2} but should be {3}", tblName, colName, colSize, size);
                    }
                }
                {
                    bool colHasDefValue = db.GetHasColumnDefaultValue(tblName, colName);
                    bool hasDefValue = defConstr != null;
                    if (colHasDefValue != hasDefValue)
                    {
                        Log.WarnFormat("Column '{0}'.'{1}' default value mismatch. Column {2} a default value but should {3}have one", tblName, colName,
                            colHasDefValue ? "has" : "does not have",
                            hasDefValue ? string.Empty : "not ");

                        if (repair)
                        {
                            db.AlterColumn(tblName, colName, type, size, scale, isNullable, defConstr);
                        }
                    }
                }
            }
            else
            {
                Log.WarnFormat("Column '{0}'.'{1}' is missing", tblName, colName);
                if (repair)
                {
                    Log.Info("Fixing");
                    if (!isNullable && db.CheckTableContainsData(tblName))
                    {
                        Log.WarnFormat("Table '{0}' contains data, cannot create NOT NULLABLE column '{1}'", tblName, colName);
                        db.CreateColumn(tblName, colName, type, size, scale, true, defConstr);
                    }
                    else
                    {
                        db.CreateColumn(tblName, colName, type, size, scale, isNullable, defConstr);
                    }
                }
            }
        }
예제 #37
0
        /// <summary>
        /// Adds the default <see cref="Constraint"/> to this <see cref="Table"/>.
        /// </summary>
        /// <param name="name">The constraint name.</param>
        /// <param name="columnName">The name of the column that has the defaul constraint.</param>
        /// <param name="value">The default value.</param>
        /// <returns>The default constraint.</returns>
        public DefaultConstraint AddDefaultConstraint(string name, string columnName, object value)
        {
            var c = new DefaultConstraint(this, name, Modifier.Add)
            {
                ColumnName = columnName,
                Value = value
            };

            Database.MigrationSteps.Enqueue(c);
            return c;
        }
예제 #38
0
        public override string DropDefaultConstraint(DataContext sourceDataContext, DataContext targetDataContext, DefaultConstraint defaultConstraint)
        {
            var builder = new StringBuilder();

            builder.Append("ALTER TABLE ");
            builder.Append(CreateIdentifier(defaultConstraint.UserTable));
            builder.Append(" DROP CONSTRAINT `");
            builder.Append(defaultConstraint.ObjectName);
            builder.Append("`");
            return(builder.ToString());
        }
예제 #39
0
 /// <summary>
 /// Drops the <see cref="DefaultConstraint"/> with the specified <paramref name="name"/>.
 /// </summary>
 /// <param name="name">The constraint's name.</param>
 /// <returns>The constraint.</returns>
 public DefaultConstraint DropDefaultConstraint(string name)
 {
     var c = new DefaultConstraint(this, name, Modifier.Drop);
     Database.MigrationSteps.EnqueueBefore(c, (e => e == this));
     return c;
 }