示例#1
0
        protected override void ScriptAlteracaoCheckConstraint(Table tbAtual, Table tbNova)
        {
            foreach (object chkc in tbAtual.CheckConstraints)
            {
                CheckConstraint ccdestino = PegarCheckConstraint(((CheckConstraint)chkc).CheckConstraintName, tbNova.CheckConstraints);

                if (ccdestino != null)
                {
                    string relatorio = ScriptAlteracaoCheckConstraint((CheckConstraint)chkc, ccdestino, tbAtual.TableName);
                    lstScriptRelatorio.Add(relatorio);
                    AdicionarScriptSegmentado(tbAtual.TableName, relatorio);
                }
                else
                {
                    string relatorio = ScriptCheckConstraintExcluida((CheckConstraint)chkc, tbAtual.TableName);
                    lstScriptRelatorio.Add(relatorio);
                    AdicionarScriptSegmentado(tbAtual.TableName, relatorio);
                }
            }


            foreach (object chkc in tbNova.CheckConstraints)
            {
                CheckConstraint ccorigem = PegarCheckConstraint(((CheckConstraint)chkc).CheckConstraintName, tbAtual.CheckConstraints);

                if (ccorigem == null)
                {
                    string relatorio = ScriptInclusaoCheckConstraint((CheckConstraint)chkc, tbAtual.TableName);
                    lstScriptRelatorio.Add(relatorio);
                    AdicionarScriptSegmentado(tbAtual.TableName, relatorio);
                }
            }
        }
        public void CreateTableWithMultipleCheckConstraint()
        {
            const string TableName = nameof(CreateTableWithMultipleCheckConstraint);

            Table  table   = new Table(TableName);
            Column column1 = new Column("column1", DataType.Int());
            Column column2 = new Column("column2", DataType.Int());
            Column column3 = new Column("column3", DataType.VarChar(10));

            table.Columns.AddAll(column1, column2, column3);

            CheckExpression expression       = new CheckExpression("([column2]>=(0))");
            CheckConstraint checkConstraint1 = new CheckConstraint("CK_CheckConstraint_1")
            {
                CheckExpression = new CheckExpression(column1, CheckOperator.GreaterThanOrEquals, column2)
                                  .And(expression)
            };
            CheckConstraint checkConstraint2 = new CheckConstraint("CK_CheckConstraint_2")
            {
                CheckExpression = new CheckExpression(column3, CheckOperator.GreaterThanOrEquals, "'a'")
                                  .And(column3, CheckOperator.LessThanOrEquals, "'zzzzzzzzzz'")
                                  .Or(column3, CheckOperator.GreaterThanOrEquals, "'A'")
                                  .And(column3, CheckOperator.LessThanOrEquals, "'ZZZZZZZZZZ'")
            };

            table.Constraints.AddAll(checkConstraint1, checkConstraint2);

            VerifyCheckConstraint(table,
                                  "([column1]>=[column2] AND [column2]>=(0))",
                                  "([column3]>='a' AND [column3]<='zzzzzzzzzz' OR [column3]>='A' AND [column3]<='ZZZZZZZZZZ')");
        }
        public void GetCheckConstraints(Database db, Table t)
        {
            SqlCommand qry = new SqlCommand(
                "select " +
                "  o.name, " +
                "  c.text " +
                "from " +
                "  sysobjects o " +
                "    inner join syscomments c on " +
                "      c.id = o.id " +
                "where " +
                "  o.parent_obj = object_id(@TableName) and " +
                "  o.uid = 1 and " +
                "  o.xtype = 'C' " +
                "order by " +
                "  o.name ", SqlConn);
            SqlDataAdapter dat = new SqlDataAdapter();

            dat.SelectCommand = qry;
            qry.Parameters.Add("@TableName", SqlDbType.VarChar, 200).Value = t.TableName;
            DataSet ds = new DataSet();

            dat.Fill(ds);

            foreach (DataRow r in ds.Tables[0].Rows)
            {
                CheckConstraint ch = new CheckConstraint();
                ch.TableName           = t.TableName;
                ch.CheckConstraintName = (string)r[0];
                ch.Expression          = (string)r[1];
                t.CheckConstraints.Add(ch);
            }
        }
        public override void Initialize()
        {
            m_CheckConstraints =
                Execute(CheckConstraintsCommandText)
                .Select(o => CheckConstraint.CreateFrom(SqlHelper, o))
                .ToList();
            m_ReferenceConstraintsByName =
                Execute(ReferenceConstraintsCommandText)
                .Select(o => ReferenceConstraint.CreateFrom(SqlHelper, o))
                .ToDictionary(x => x.ConstraintName);
            m_RelationConstraintsByName =
                Execute(RelationConstraintsCommandText)
                .Select(o => RelationConstraint.CreateFrom(SqlHelper, o))
                .ToDictionary(x => x.ConstraintName);

            m_ReferenceConstraintsByNameUq = m_ReferenceConstraintsByName.Values
                                             .ToMultiDictionary(x => x.ConstraintNameUq);
            m_ReferenceConstraintsByRelation = m_ReferenceConstraintsByName.Values
                                               .ToMultiDictionary(x => m_RelationConstraintsByName[x.ConstraintName].RelationName);
            m_RelationConstraintsByIndexName = m_RelationConstraintsByName.Values
                                               .Where(x => x.IndexName != null)
                                               .ToDictionary(x => x.IndexName);

            m_RelationConstraintsByRelation = m_RelationConstraintsByName.Values
                                              .ToMultiDictionary(x => x.RelationName);
        }
        /// <summary>
        ///     Finds an <see cref="ICheckConstraint" /> with the given name.
        /// </summary>
        /// <param name="entityType"> The entity type to find the check constraint for. </param>
        /// <param name="name"> The check constraint name. </param>
        /// <returns>
        ///     The <see cref="ICheckConstraint" /> or <see langword="null" /> if no check constraint with the
        ///     given name in the given entity type was found.
        /// </returns>
        public static ICheckConstraint FindCheckConstraint(
            [NotNull] this IEntityType entityType, [NotNull] string name)
        {
            Check.NotEmpty(name, nameof(name));

            return(CheckConstraint.FindCheckConstraint(entityType, name));
        }
示例#6
0
        private string ScriptInclusaoCheckConstraint(CheckConstraint cc, string NomeTabelaOrigem)
        {
            string relatorioAlteracao = "Inclusão CheckConstraint - " + cc.CheckConstraintName + Environment.NewLine;

            relatorioAlteracao += "   Expressão: " + cc.Expression + Environment.NewLine;
            return(relatorioAlteracao);
        }
        public void CreateTableWithMultipleCheckConstraint2()
        {
            const string TableName = nameof(CreateTableWithMultipleCheckConstraint2);

            Table  table   = new Table(TableName);
            Column column1 = new Column("column1", DataType.Int());
            Column column2 = new Column("column2", DataType.Int());
            Column column3 = new Column("column3", DataType.VarChar(10));

            table.Columns.AddAll(column1, column2, column3);

            CheckExpression expression       = new CheckExpression("([column2]>=0)");
            CheckConstraint checkConstraint1 = new CheckConstraint(expression);

            CheckExpression expression2      = new CheckExpression("([column2]!=(666))");
            CheckConstraint checkConstraint2 = new CheckConstraint()
            {
                CheckExpression = new CheckExpression(column3, CheckOperator.Equals, "'a'")
                                  .And(column2, CheckOperator.NotEquals, column1)
                                  .Or(expression2)
                                  .Or(column2, CheckOperator.LessThan, column1)
                                  .And("1=1")
                                  .Or("2=2")
            };

            table.Constraints.AddAll(checkConstraint1, checkConstraint2);

            VerifyCheckConstraint(table,
                                  "([column2]>=(0))",
                                  "([column3]='a' AND [column2]<>[column1] OR [column2]<>(666) OR [column2]<[column1] AND (1)=(1) OR (2)=(2))");
        }
示例#8
0
        /// <summary>
        /// This method is used to parse CheckConstraint objects.
        /// </summary>
        public CheckConstraint ParseCheckConstraint(ref CheckConstraint checkConstraint, XmlNode xmlNode)
        {
            // if the checkConstraint object exists and the xmlNode exists
            if ((checkConstraint != null) && (xmlNode != null))
            {
                // get the full name of this node
                string fullName = xmlNode.GetFullName();

                // Check the name of this node to see if it is mapped to a property
                switch (fullName)
                {
                case "Database.Tables.DataTable.CheckConstraints.CheckConstraint.CheckClause":

                    // Set the value for checkConstraint.CheckClause
                    checkConstraint.CheckClause = xmlNode.FormattedNodeValue;

                    // required
                    break;

                case "Database.Tables.DataTable.CheckConstraints.CheckConstraint.ColumnName":

                    // Set the value for checkConstraint.ColumnName
                    checkConstraint.ColumnName = xmlNode.FormattedNodeValue;

                    // required
                    break;

                case "Database.Tables.DataTable.CheckConstraints.CheckConstraint.ConstraintName":

                    // Set the value for checkConstraint.ConstraintName
                    checkConstraint.ConstraintName = xmlNode.FormattedNodeValue;

                    // required
                    break;

                case "Database.Tables.DataTable.CheckConstraints.CheckConstraint.TableName":

                    // Set the value for checkConstraint.TableName
                    checkConstraint.TableName = xmlNode.FormattedNodeValue;

                    // required
                    break;
                }

                // if there are ChildNodes
                if (xmlNode.HasChildNodes)
                {
                    // iterate the child nodes
                    foreach (XmlNode childNode in xmlNode.ChildNodes)
                    {
                        // append to this CheckConstraint
                        checkConstraint = ParseCheckConstraint(ref checkConstraint, childNode);
                    }
                }
            }

            // return value
            return(checkConstraint);
        }
        public void Creation()
        {
            var TempConstraint = new CheckConstraint("Constraint_Name", "LEN(SomeColumn)>5", null);

            Assert.Equal("Constraint_Name", TempConstraint.Name);
            Assert.Equal("LEN(SomeColumn)>5", TempConstraint.Definition);
            Assert.Null(TempConstraint.ParentTable);
        }
示例#10
0
        /// <summary>
        ///     Removes the <see cref="ICheckConstraint" /> with the given name.
        /// </summary>
        /// <param name="entityType"> The entity type to remove the check constraint from. </param>
        /// <param name="name"> The check constraint name to be removed. </param>
        /// <returns>
        ///     True if the <see cref="ICheckConstraint" /> is successfully found and removed; otherwise, false.
        /// </returns>
        public static bool RemoveCheckConstraint(
            [NotNull] this IMutableEntityType entityType,
            [NotNull] string name)
        {
            Check.NotEmpty(name, nameof(name));

            return(CheckConstraint.RemoveCheckConstraint(entityType, name));
        }
    /// <summary>
    ///     Finds an <see cref="IReadOnlyCheckConstraint" /> with the given name.
    /// </summary>
    /// <param name="entityType">The entity type to find the check constraint for.</param>
    /// <param name="name">The check constraint name.</param>
    /// <returns>
    ///     The <see cref="IReadOnlyCheckConstraint" /> or <see langword="null" /> if no check constraint with the
    ///     given name in the given entity type was found.
    /// </returns>
    public static IReadOnlyCheckConstraint?FindCheckConstraint(
        this IReadOnlyEntityType entityType,
        string name)
    {
        Check.NotEmpty(name, nameof(name));

        return(CheckConstraint.FindCheckConstraint(entityType, name));
    }
示例#12
0
        private string ScriptInclusaoCheckConstraint(CheckConstraint cc, string NomeTabelaOrigem)
        {
            string script = "ALTER TABLE [dbo].[" + NomeTabelaOrigem + "] ADD " + Environment.NewLine;

            script += "CONSTRAINT [" + cc.CheckConstraintName + "] CHECK " + cc.Expression + Environment.NewLine;
            script += "GO " + Environment.NewLine + Environment.NewLine;
            return(script);
        }
        /// <summary>
        ///     Removes the <see cref="ICheckConstraint" /> with the given name.
        /// </summary>
        /// <param name="model"> The model to remove the check constraint from. </param>
        /// <param name="name"> The check constraint name. </param>
        /// <param name="table"> The table that contains the check constraint. </param>
        /// <param name="schema"> The table schema that contains the check constraint. </param>
        /// <returns>
        ///     The removed <see cref="ICheckConstraint" /> or <c>null</c> if no check constraint with the given name in
        ///     the given schema was found.
        /// </returns>
        public static ICheckConstraint RemoveCheckConstraint(
            [NotNull] this IMutableModel model, [NotNull] string name, [NotNull] string table, [CanBeNull] string schema = null)
        {
            Check.NotEmpty(name, nameof(name));
            Check.NotEmpty(table, nameof(table));
            Check.NullButNotEmpty(schema, nameof(schema));

            return(CheckConstraint.RemoveCheckConstraint(model, name, table, schema));
        }
示例#14
0
        void fixCheckConstraints(Database database, DDL withDDL)
        {
            var fieldsWithConstraints = from table in withDDL.statements.OfType <CreateTableStatement>()
                                        from field in table.Fields
                                        from constraint in field.Constraints.OfType <DDL_Parser.CheckConstraint>()
                                        select new {
                Table           = table.SimpleName,
                FieldName       = field.SimpleName,
                Constraintname  = constraint.Field.Name,
                ConstraintRules = constraint.Rules
            };
            int fixes = 0;

            foreach (var field in fieldsWithConstraints)
            {
                // find table
                var table = (Table)database.getTable(field.Table);
                if (table != null)
                {
                    // find field
                    var column = (Column)table.getColumn(field.FieldName);
                    if (column != null)
                    {
                        var checkConstraint = table.constraints.OfType <CheckConstraint>()
                                              .FirstOrDefault(x => x.name.Equals(field.Constraintname, StringComparison.InvariantCultureIgnoreCase));
                        if (checkConstraint == null)
                        {
                            checkConstraint = new CheckConstraint(field.Constraintname, column, field.ConstraintRules);
                            checkConstraint.save();
                            fixes++;
                        }
                        else
                        {
                            if (checkConstraint.rule != field.ConstraintRules)
                            {
                                checkConstraint.rule = field.ConstraintRules;
                                checkConstraint.save();
                                fixes++;
                            }
                        }
                    }
                    else
                    {
                        this.log("WARNING: field " + table.name + "." + field.FieldName + " not found");
                    }
                }
                else
                {
                    this.log("WARNING: table " + field.Table + " not found");
                }
            }
            this.log(string.Format(
                         "RESULT: Fix check constraints: fixed {0}/{1}",
                         fixes, fieldsWithConstraints.Count()
                         ));
        }
示例#15
0
    /// <summary>
    ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
    ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
    ///     any release. You should only use it directly in your code with extreme caution and knowing that
    ///     doing so can result in application failures when updating to a new Entity Framework Core release.
    /// </summary>
    public static void Attach(IConventionEntityType entityType, IConventionCheckConstraint detachedCheckConstraint)
    {
        var newCheckConstraint = new CheckConstraint(
            (IMutableEntityType)entityType,
            detachedCheckConstraint.ModelName,
            detachedCheckConstraint.Sql,
            detachedCheckConstraint.GetConfigurationSource());

        Attach(detachedCheckConstraint, newCheckConstraint);
    }
        /// <summary>
        /// This event is fired AFTER the checkConstraint is parsed.
        /// </summary>
        /// <param name="xmlNode"></param>
        /// <param name="checkConstraint"></param>
        /// <returns>True if cancelled else false if not.</returns>
        public bool Parsed(XmlNode xmlNode, ref CheckConstraint checkConstraint)
        {
            // initial value
            bool cancel = false;

            // Add any post processing code here. Set cancel to true to abort adding this object.

            // return value
            return(cancel);
        }
示例#17
0
        // <Summary>
        // This method is used to export a CheckConstraint object to xml.
        // </Summary>
        public string ExportCheckConstraint(CheckConstraint checkConstraint, int indent = 0)
        {
            // initial value
            string checkConstraintXml = "";

            // locals
            string indentString  = TextHelper.Indent(indent);
            string indentString2 = TextHelper.Indent(indent + 2);

            // If the checkConstraint object exists
            if (NullHelper.Exists(checkConstraint))
            {
                // Create a StringBuilder
                StringBuilder sb = new StringBuilder();

                // Append the indentString
                sb.Append(indentString);

                // Write the open checkConstraint node
                sb.Append("<CheckConstraint>" + Environment.NewLine);

                // Write out each property

                // Write out the value for CheckClause

                sb.Append(indentString2);
                sb.Append("<CheckClause>" + checkConstraint.CheckClause + "</CheckClause>" + Environment.NewLine);

                // Write out the value for ColumnName

                sb.Append(indentString2);
                sb.Append("<ColumnName>" + checkConstraint.ColumnName + "</ColumnName>" + Environment.NewLine);

                // Write out the value for ConstraintName

                sb.Append(indentString2);
                sb.Append("<ConstraintName>" + checkConstraint.ConstraintName + "</ConstraintName>" + Environment.NewLine);

                // Write out the value for TableName

                sb.Append(indentString2);
                sb.Append("<TableName>" + checkConstraint.TableName + "</TableName>" + Environment.NewLine);

                // Append the indentString
                sb.Append(indentString);

                // Write out the close checkConstraint node
                sb.Append("</CheckConstraint>" + Environment.NewLine);

                // set the return value
                checkConstraintXml = sb.ToString();
            }
            // return value
            return(checkConstraintXml);
        }
        static RootedWorld()
        {
            var schemas = new[]
            {
                new Schema(name: "dbo", id: 1),
                new Schema(name: "sys", id: 2)
            };
            var tables = new[]
            {
                // Create tables out of order to make sure proper ordering is happening.
                new Table(name: "Residents", id: 6, schemaId: 1),
                new Table(name: "Nations", id: 3, schemaId: 1),
                new Table(name: "Provinces", id: 4, schemaId: 1)
            };
            var columns = new[]
            {
                new Column(tableId: 6, name: "ID", columnId: 1, isNullable: false, isIdentity: true),
                new Column(tableId: 6, name: "Name", columnId: 2, isNullable: false),
                new Column(tableId: 6, name: "ProvinceID", columnId: 3, isNullable: false),
                new Column(tableId: 3, name: "ID", columnId: 1, isNullable: false, isIdentity: true),
                new Column(tableId: 3, name: "Name", columnId: 2, isNullable: false),
                new Column(tableId: 3, name: "FoundedDate", columnId: 3, isNullable: false),
                new Column(tableId: 4, name: "ID", columnId: 1, isNullable: false, isIdentity: true),
                new Column(tableId: 4, name: "NationID", columnId: 2, isNullable: false),
                new Column(tableId: 4, name: "Name", columnId: 3, isNullable: false),
                new Column(tableId: 4, name: "Motto", columnId: 4, isNullable: false)
            };
            var primaryKeys = new[]
            {
                new PrimaryKey(tableId: 6, name: "PK_Residents"),
                new PrimaryKey(tableId: 3, name: "PK_Nations"),
                new PrimaryKey(tableId: 4, name: "PK_Provinces"),
            };
            var primaryKeyColumns = new[]
            {
                new PrimaryKeyColumn(tableId: 3, columnId: 1),
                new PrimaryKeyColumn(tableId: 4, columnId: 1),
                new PrimaryKeyColumn(tableId: 6, columnId: 1)
            };
            var foreignKeys = new[]
            {
                new ForeignKey(name: "FK_Provinces_NationID_Nations_ID", id: 5, parentTableId: 4, referencedTableId: 3),
                new ForeignKey(name: "FK_Residents_ProvinceID_Provinces_ID", id: 7, parentTableId: 6, referencedTableId: 4)
            };
            var foreignKeyColumns = new[]
            {
                new ForeignKeyColumn(foreignKeyId: 7, parentTableId: 6, parentColumnId: 3, referencedTableId: 4, referencedColumnId: 1),
                new ForeignKeyColumn(foreignKeyId: 5, parentTableId: 4, parentColumnId: 2, referencedTableId: 3, referencedColumnId: 1)
            };
            var checkConstraints = new CheckConstraint[0];

            Catalog = new Catalog(schemas, tables, columns, primaryKeys, primaryKeyColumns, foreignKeys, foreignKeyColumns, checkConstraints);
        }
示例#19
0
        [TestMethod] public void ConstructWithoutName()
        {
            // Arrange
            var mockClause = new Mock <Clause>();

            // Act
            var constraint = new CheckConstraint(mockClause.Object);

            // Assert
            constraint.Name.Should().NotHaveValue();
            constraint.Condition.Should().BeSameAs(mockClause.Object);
            mockClause.VerifyNoOtherCalls();
        }
示例#20
0
        private string ScriptAlteracaoCheckConstraint(CheckConstraint ccAtual, CheckConstraint ccNova, string NomeTabela)
        {
            string relatorioAlteracao = string.Empty;

            if (ccAtual.Expression != ccNova.Expression)
            {
                relatorioAlteracao += "   Expressão: " + ccNova.Expression + Environment.NewLine;
            }

            if (relatorioAlteracao.Length > 0)
            {
                relatorioAlteracao = "Alteração CheckConstraint: " + ccAtual.CheckConstraintName + Environment.NewLine + relatorioAlteracao;
            }

            return(relatorioAlteracao);
        }
        public override void Apply(Database db)
        {
            Table t = db.FindTable(this.CheckConstraint.TableName, false);

            if (t == null)
            {
                throw new DatabaseStatementApplyException("Couldn't find table " + this.CheckConstraint.TableName);
            }
            CheckConstraint cc = t.FindCheckConstraint(this.CheckConstraint.CheckConstraintName);

            if (cc != null)
            {
                throw new DatabaseStatementApplyException("Check constraint " + this.CheckConstraint.CheckConstraintName + " already exists");
            }
            t.CheckConstraints.Add(cc);
        }
示例#22
0
        [TestMethod] public void GenerateDeclarationWithoutName()
        {
            // Arrange
            var mockClause  = new Mock <Clause>();
            var constraint  = new CheckConstraint(mockClause.Object);
            var mockBuilder = new Mock <IConstraintDeclBuilder>();

            // Act
            constraint.GenerateDeclaration(mockBuilder.Object);

            // Assert
            mockClause.Verify(clause => clause.AddDeclarationTo(mockBuilder.Object));
            mockBuilder.Verify(builder => builder.Build());
            mockClause.VerifyNoOtherCalls();
            mockBuilder.VerifyNoOtherCalls();
        }
        public void CreateTableWithSingleCheckConstraint()
        {
            const string ColumnName = "Id";
            const string TableName  = nameof(CreateTableWithSingleCheckConstraint);

            Table  table  = new Table(TableName);
            Column column = new Column(ColumnName, DataType.Int());

            table.Columns.Add(column);

            CheckConstraint checkConstraint = new CheckConstraint()
            {
                CheckExpression = new CheckExpression(column, CheckOperator.GreaterThan, 25)
            };

            table.Constraints.Add(checkConstraint);

            VerifyCheckConstraint(table, "([Id]>(25))");
        }
        public void CreateCheckConstraint(
            Dictionary <string, UserTable> userTables,
            IDataReader 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 checkConstraint = new CheckConstraint
            {
                UserTable           = userTable,
                ColumnName          = Convert.ToString(reader[ColumnNameOrdinal]),
                ObjectName          = Convert.ToString(reader[ObjectNameOrdinal]),
                Definition          = Convert.ToString(reader[DefinitionOrdinal]),
                IsTableConstraint   = Convert.ToBoolean(reader[IsTableConstraintOrdinal]),
                IsDisabled          = Convert.ToBoolean(reader[IsDisabledOrdinal]),
                IsNotForReplication = Convert.ToBoolean(reader[IsNotForReplicationOrdinal]),
                IsNotTrusted        = Convert.ToBoolean(reader[IsNotTrustedOrdinal]),
                IsSystemNamed       = Convert.ToBoolean(reader[IsSystemNamedOrdinal])
            };

            userTable.CheckConstraints.Add(checkConstraint);
        }
    /// <summary>
    ///     Called after an entity type is added to the model.
    /// </summary>
    /// <param name="entityTypeBuilder">The builder for the entity type.</param>
    /// <param name="context">Additional information associated with convention execution.</param>
    public virtual void ProcessEntityTypeAdded(
        IConventionEntityTypeBuilder entityTypeBuilder,
        IConventionContext <IConventionEntityTypeBuilder> context)
    {
        var entityType = entityTypeBuilder.Metadata;

        if (!entityType.HasSharedClrType)
        {
            return;
        }

        List <IConventionCheckConstraint>?constraintsToReattach = null;

        foreach (var checkConstraint in entityType.GetCheckConstraints())
        {
            if (checkConstraint.EntityType == entityType)
            {
                continue;
            }

            constraintsToReattach ??= new List <IConventionCheckConstraint>();

            constraintsToReattach.Add(checkConstraint);
        }

        if (constraintsToReattach == null)
        {
            return;
        }

        foreach (var checkConstraint in constraintsToReattach)
        {
            var removedCheckConstraint = entityType.RemoveCheckConstraint(checkConstraint.ModelName);
            if (removedCheckConstraint != null)
            {
                CheckConstraint.Attach(entityType, removedCheckConstraint);
            }
        }
    }
    private static bool AreCompatible(IConventionCheckConstraint checkConstraint, IConventionCheckConstraint baseCheckConstraint)
    {
        var baseTable = StoreObjectIdentifier.Create(baseCheckConstraint.EntityType, StoreObjectType.Table);

        if (baseTable == null)
        {
            return(true);
        }

        if (checkConstraint.GetName(baseTable.Value) != baseCheckConstraint.GetName(baseTable.Value) &&
            checkConstraint.GetNameConfigurationSource() is ConfigurationSource nameConfigurationSource &&
            !nameConfigurationSource.OverridesStrictly(baseCheckConstraint.GetNameConfigurationSource()))
        {
            return(false);
        }

        return(CheckConstraint.AreCompatible(
                   checkConstraint,
                   baseCheckConstraint,
                   baseTable.Value,
                   shouldThrow: false));
    }
示例#27
0
        static TableTests()
        {
            snippet_ = new SqlSnippet("SQL");

            var mockField0 = new Mock <IField>();

            mockField0.Setup(field => field.Name).Returns(new FieldName("A"));
            mockField0.Setup(field => field.Nullability).Returns(IsNullable.No);
            mockField0.Setup(field => field.DataType).Returns(DBType.Int32);
            mockField0.Setup(field => field.GenerateDeclaration(It.IsAny <IFieldDeclBuilder>())).Returns(snippet_);
            var mockField1 = new Mock <IField>();

            mockField1.Setup(field => field.Name).Returns(new FieldName("B"));
            mockField1.Setup(field => field.Nullability).Returns(IsNullable.No);
            mockField1.Setup(field => field.DataType).Returns(DBType.Guid);
            mockField1.Setup(field => field.GenerateDeclaration(It.IsAny <IFieldDeclBuilder>())).Returns(snippet_);
            var mockField2 = new Mock <IField>();

            mockField2.Setup(field => field.Name).Returns(new FieldName("C"));
            mockField2.Setup(field => field.Nullability).Returns(IsNullable.No);
            mockField2.Setup(field => field.DataType).Returns(DBType.Enumeration);
            mockField2.Setup(field => field.GenerateDeclaration(It.IsAny <IFieldDeclBuilder>())).Returns(snippet_);

            var pkey  = new PrimaryKey(new IField[] { mockField0.Object });
            var ckey  = new CandidateKey(new IField[] { mockField1.Object });
            var check = new CheckConstraint(new Mock <Clause>().Object);

            var mockReferenceTable = new Mock <ITable>();

            mockReferenceTable.Setup(table => table.PrimaryKey).Returns(pkey);
            var fkey = new ForeignKey(mockReferenceTable.Object, pkey.Fields, OnDelete.SetNull, OnUpdate.NoAction);

            table_ = new Table(new TableName("TABLE"),
                               new IField[] { mockField1.Object, mockField2.Object, mockField0.Object }, pkey,
                               new CandidateKey[] { ckey }, new ForeignKey[] { fkey }, new CheckConstraint[] { check });
        }
示例#28
0
		public static void SetDomain(CheckConstraint element, Domain newDomain)
		{
			DslModeling::DomainRoleInfo.SetLinkedElement(element, CheckConstraintDomainRoleId, newDomain);
		}
示例#29
0
		public static Table GetTable(CheckConstraint element)
		{
			return DslModeling::DomainRoleInfo.GetLinkedElement(element, CheckConstraintDomainRoleId) as Table;
		}
示例#30
0
		public static void SetTable(CheckConstraint element, Table newTable)
		{
			DslModeling::DomainRoleInfo.SetLinkedElement(element, CheckConstraintDomainRoleId, newTable);
		}
示例#31
0
		/// <summary>
		/// Constructor
		/// Creates a DomainContainsCheckConstraint link in the same Partition as the given Domain
		/// </summary>
		/// <param name="source">Domain to use as the source of the relationship.</param>
		/// <param name="target">CheckConstraint to use as the target of the relationship.</param>
		public DomainContainsCheckConstraint(Domain source, CheckConstraint target)
			: base((source != null ? source.Partition : null), new DslModeling::RoleAssignment[]{new DslModeling::RoleAssignment(DomainContainsCheckConstraint.DomainDomainRoleId, source), new DslModeling::RoleAssignment(DomainContainsCheckConstraint.CheckConstraintDomainRoleId, target)}, null)
		{
		}
示例#32
0
		public static Domain GetDomain(CheckConstraint element)
		{
			return DslModeling::DomainRoleInfo.GetLinkedElement(element, CheckConstraintDomainRoleId) as Domain;
		}
示例#33
0
 public string GetSQLConstraintAdd(CheckConstraint constraint)
 {
     return string.Format("ALTER TABLE \"{0}\" ADD CONSTRAINT \"{1}\" CHECK ({2})", constraint.Table.Name, constraint.Name, constraint.Expression);
 }
示例#34
0
 /// <summary>
 /// Create a new CheckConstraint object.
 /// </summary>
 /// <param name="id">Initial value of Id.</param>
 /// <param name="name">Initial value of Name.</param>
 /// <param name="isDeferrable">Initial value of IsDeferrable.</param>
 /// <param name="isInitiallyDeferred">Initial value of IsInitiallyDeferred.</param>
 public static CheckConstraint CreateCheckConstraint(string id, string name, bool isDeferrable, bool isInitiallyDeferred)
 {
   CheckConstraint checkConstraint = new CheckConstraint();
   checkConstraint.Id = id;
   checkConstraint.Name = name;
   checkConstraint.IsDeferrable = isDeferrable;
   checkConstraint.IsInitiallyDeferred = isInitiallyDeferred;
   return checkConstraint;
 }
示例#35
0
		public static void SetCheckConstraint(Domain element, CheckConstraint newCheckConstraint)
		{
			DslModeling::DomainRoleInfo.SetLinkedElement(element, DomainDomainRoleId, newCheckConstraint);
		}
示例#36
0
 public string GetSQLConstraintAdd(CheckConstraint constraint)
 {
     throw new NotImplementedException("SQLite doesn't support check constraints. Use trigger.");
 }
示例#37
0
 public string GetSQLConstraintAdd(CheckConstraint constraint)
 {
     return string.Format("ALTER TABLE [{0}] WITH NOCHECK ADD CONSTRAINT [{1}] CHECK ({2})", constraint.Table.Name, constraint.Name, constraint.Expression);
 }
示例#38
0
 private string _CheckConstraintDefinition(CheckConstraint constraint)
 {
     return string.Format(
         "CHECK({0})",
         constraint.condition
     );
 }
 /// <summary>
 ///     Removes the <see cref="IConventionCheckConstraint" /> with the given name.
 /// </summary>
 /// <param name="entityType"> The entity type to remove the check constraint from. </param>
 /// <param name="name"> The check constraint name. </param>
 /// <returns> The removed <see cref="IConventionCheckConstraint" />. </returns>
 public static IConventionCheckConstraint RemoveCheckConstraint(
     [NotNull] this IConventionEntityType entityType,
     [NotNull] string name)
 => CheckConstraint.RemoveCheckConstraint((IMutableEntityType)entityType, Check.NotEmpty(name, nameof(name)));
 /// <summary>
 ///     Returns all <see cref="IMutableCheckConstraint" /> contained in the entity type.
 /// </summary>
 /// <param name="entityType"> The entity type to get the check constraints for. </param>
 public static IEnumerable <IMutableCheckConstraint> GetCheckConstraints([NotNull] this IMutableEntityType entityType)
 => CheckConstraint.GetCheckConstraints(entityType);
 /// <summary>
 ///     Returns all <see cref="IConventionCheckConstraint" /> contained in the entity type.
 /// </summary>
 /// <param name="entityType"> The entity type to get the check constraints for. </param>
 public static IEnumerable <IConventionCheckConstraint> GetCheckConstraints([NotNull] this IConventionEntityType entityType)
 => CheckConstraint.GetCheckConstraints(entityType);
示例#42
0
 public string GetSQLConstraintAdd(CheckConstraint constraint)
 {
     throw new NotImplementedException();
 }