private void DiagnoseKeyCollision(UpdateCompiler compiler, PropagatorResult change, CompositeKey key, PropagatorResult other)
        {
            KeyManager   keyManager = compiler.m_translator.KeyManager;
            CompositeKey otherKey   = new CompositeKey(GetKeyConstants(other));

            // determine if the conflict is due to shared principal key values
            bool sharedPrincipal = true;

            for (int i = 0; sharedPrincipal && i < key.KeyComponents.Length; i++)
            {
                int identifier1 = key.KeyComponents[i].Identifier;
                int identifier2 = otherKey.KeyComponents[i].Identifier;

                if (!keyManager.GetPrincipals(identifier1).Intersect(keyManager.GetPrincipals(identifier2)).Any())
                {
                    sharedPrincipal = false;
                }
            }

            if (sharedPrincipal)
            {
                // if the duplication is due to shared principals, there is a duplicate key exception
                var stateEntries = SourceInterpreter.GetAllStateEntries(change, compiler.m_translator, m_table)
                                   .Concat(SourceInterpreter.GetAllStateEntries(other, compiler.m_translator, m_table));
                throw EntityUtil.Update(Strings.Update_DuplicateKeys, null, stateEntries);
            }
            else
            {
                // if there are no shared principals, it implies that common dependents are the problem
                HashSet <IEntityStateEntry> commonDependents = null;
                foreach (PropagatorResult keyValue in key.KeyComponents.Concat(otherKey.KeyComponents))
                {
                    var dependents = new HashSet <IEntityStateEntry>();
                    foreach (int dependentId in keyManager.GetDependents(keyValue.Identifier))
                    {
                        PropagatorResult dependentResult;
                        if (keyManager.TryGetIdentifierOwner(dependentId, out dependentResult) &&
                            null != dependentResult.StateEntry)
                        {
                            dependents.Add(dependentResult.StateEntry);
                        }
                    }
                    if (null == commonDependents)
                    {
                        commonDependents = new HashSet <IEntityStateEntry>(dependents);
                    }
                    else
                    {
                        commonDependents.IntersectWith(dependents);
                    }
                }

                // to ensure the exception shape is consistent with constraint violations discovered while processing
                // commands (a more conventional scenario in which different tables are contributing principal values)
                // wrap a DataConstraintException in an UpdateException
                throw EntityUtil.Update(Strings.Update_GeneralExecutionException,
                                        EntityUtil.Constraint(Strings.Update_ReferentialConstraintIntegrityViolation), commonDependents);
            }
        }
Example #2
0
        /// <summary>
        /// Builds an update command.
        /// </summary>
        /// <param name="oldRow">Old value of the row being updated.</param>
        /// <param name="newRow">New value for the row being updated.</param>
        /// <param name="processor">Context for the table containing row.</param>
        /// <returns>Update command.</returns>
        internal UpdateCommand BuildUpdateCommand(PropagatorResult oldRow,
                                                  PropagatorResult newRow, TableChangeProcessor processor)
        {
            // If we're updating a row, the row may not need to be touched (e.g., no concurrency validation required)
            bool rowMustBeTouched = false;

            DbExpressionBinding target = GetTarget(processor);

            // Create set clauses and returning parameter
            Dictionary <int, string>    outputIdentifiers;
            DbExpression                returning;
            List <DbModificationClause> setClauses = new List <DbModificationClause>();

            foreach (DbModificationClause clause in BuildSetClauses(
                         target, newRow, oldRow, processor, /* insertMode */ false, out outputIdentifiers, out returning,
                         ref rowMustBeTouched))
            {
                setClauses.Add(clause);
            }

            // Construct predicate identifying the row to modify
            DbExpression predicate = BuildPredicate(target, oldRow, newRow, processor, ref rowMustBeTouched);

            if (0 == setClauses.Count)
            {
                if (rowMustBeTouched)
                {
                    List <IEntityStateEntry> stateEntries = new List <IEntityStateEntry>();
                    stateEntries.AddRange(SourceInterpreter.GetAllStateEntries(
                                              oldRow, m_translator, processor.Table));
                    stateEntries.AddRange(SourceInterpreter.GetAllStateEntries(
                                              newRow, m_translator, processor.Table));
                    if (stateEntries.All(it => (it.State == EntityState.Unchanged)))
                    {
                        rowMustBeTouched = false;
                    }
                }

                // Determine if there is nothing to do (i.e., no values to set,
                // no computed columns, and no concurrency validation required)
                if (!rowMustBeTouched)
                {
                    return(null);
                }
            }

            // Initialize DML command tree
            DbUpdateCommandTree commandTree =
                new DbUpdateCommandTree(m_translator.MetadataWorkspace, DataSpace.SSpace, target, predicate, setClauses.AsReadOnly(), returning);

            // Create command
            UpdateCommand command = new DynamicUpdateCommand(processor, m_translator, ModificationOperator.Update, oldRow, newRow, commandTree, outputIdentifiers);

            return(command);
        }
Example #3
0
        /// <summary>
        /// Finds all markup associated with the given source.
        /// </summary>
        /// <param name="source">Source expression. Must not be null.</param>
        /// <param name="translator">Translator containing session information.</param>
        /// <param name="sourceTable">Table from which the exception was thrown (must not be null).</param>
        /// <returns>Markup.</returns>
        internal static ReadOnlyCollection<IEntityStateEntry> GetAllStateEntries(PropagatorResult source, UpdateTranslator translator,
            EntitySet sourceTable)
        {
            Debug.Assert(null != source);
            Debug.Assert(null != translator);
            Debug.Assert(null != sourceTable);

            SourceInterpreter interpreter = new SourceInterpreter(translator, sourceTable);
            interpreter.RetrieveResultMarkup(source);

            return new ReadOnlyCollection<IEntityStateEntry>(interpreter.m_stateEntries);
        }
Example #4
0
        /// <summary>
        /// Finds all markup associated with the given source.
        /// </summary>
        /// <param name="source">Source expression. Must not be null.</param>
        /// <param name="translator">Translator containing session information.</param>
        /// <param name="sourceTable">Table from which the exception was thrown (must not be null).</param>
        /// <returns>Markup.</returns>
        internal static ReadOnlyCollection <IEntityStateEntry> GetAllStateEntries(PropagatorResult source, UpdateTranslator translator,
                                                                                  EntitySet sourceTable)
        {
            Debug.Assert(null != source);
            Debug.Assert(null != translator);
            Debug.Assert(null != sourceTable);

            SourceInterpreter interpreter = new SourceInterpreter(translator, sourceTable);

            interpreter.RetrieveResultMarkup(source);

            return(new ReadOnlyCollection <IEntityStateEntry>(interpreter.m_stateEntries));
        }
        internal override IList <IEntityStateEntry> GetStateEntries(UpdateTranslator translator)
        {
            List <IEntityStateEntry> stateEntries = new List <IEntityStateEntry>(2);

            if (null != this.OriginalValues)
            {
                foreach (IEntityStateEntry stateEntry in SourceInterpreter.GetAllStateEntries(
                             this.OriginalValues, translator, this.Table))
                {
                    stateEntries.Add(stateEntry);
                }
            }

            if (null != this.CurrentValues)
            {
                foreach (IEntityStateEntry stateEntry in SourceInterpreter.GetAllStateEntries(
                             this.CurrentValues, translator, this.Table))
                {
                    stateEntries.Add(stateEntry);
                }
            }
            return(stateEntries);
        }
Example #6
0
            /// <summary>
            /// Propagate all changes associated with a particular join key.
            /// </summary>
            /// <param name="key">Key.</param>
            /// <param name="result">Resulting changes are added to this result.</param>
            private void Propagate(CompositeKey key, ChangeNode result, JoinDictionary leftDeletes, JoinDictionary leftInserts,
                                   JoinDictionary rightDeletes, JoinDictionary rightInserts)
            {
                // Retrieve changes associates with this join key
                Tuple <CompositeKey, PropagatorResult> leftInsert  = null;
                Tuple <CompositeKey, PropagatorResult> leftDelete  = null;
                Tuple <CompositeKey, PropagatorResult> rightInsert = null;
                Tuple <CompositeKey, PropagatorResult> rightDelete = null;

                Ops input = Ops.Nothing;

                if (leftInserts.TryGetValue(key, out leftInsert))
                {
                    input |= Ops.LeftInsert;
                }
                if (leftDeletes.TryGetValue(key, out leftDelete))
                {
                    input |= Ops.LeftDelete;
                }
                if (rightInserts.TryGetValue(key, out rightInsert))
                {
                    input |= Ops.RightInsert;
                }
                if (rightDeletes.TryGetValue(key, out rightDelete))
                {
                    input |= Ops.RightDelete;
                }

                // Get propagation rules for the changes
                Ops insertRule = m_insertRules[input];
                Ops deleteRule = m_deleteRules[input];

                if (Ops.Unsupported == insertRule || Ops.Unsupported == deleteRule)
                {
                    // If no propagation rules are defined, it suggests an invalid workload (e.g.
                    // a required entity or relationship is missing). In general, such exceptions
                    // should be caught by the RelationshipConstraintValidator, but we defensively
                    // check for problems here regardless. For instance, a 0..1:1..1 self-assocation
                    // implied a stronger constraint that cannot be checked by RelationshipConstraintValidator.

                    // First gather state entries contributing to the problem
                    List <IEntityStateEntry> stateEntries = new List <IEntityStateEntry>();
                    Action <Tuple <CompositeKey, PropagatorResult> > addStateEntries = (r) =>
                    {
                        if (r != null)
                        {
                            stateEntries.AddRange(SourceInterpreter.GetAllStateEntries(r.Item2, this.m_parent.m_updateTranslator,
                                                                                       this.m_parent.m_table));
                        }
                    };
                    addStateEntries(leftInsert);
                    addStateEntries(leftDelete);
                    addStateEntries(rightInsert);
                    addStateEntries(rightDelete);

                    throw EntityUtil.Update(Strings.Update_InvalidChanges, null, stateEntries);
                }

                // Where needed, substitute null/unknown placeholders. In some of the join propagation
                // rules, we handle the case where a side of the join is 'unknown', or where one side
                // of a join is comprised of an record containing only nulls. For instance, we may update
                // only one extent appearing in a row of a table (unknown), or; we may insert only
                // the left hand side of a left outer join, in which case the right hand side is 'null'.
                if (0 != (Ops.LeftUnknown & insertRule))
                {
                    leftInsert = Tuple.Create(key, LeftPlaceholder(key, PopulateMode.Unknown));
                }
                if (0 != (Ops.LeftUnknown & deleteRule))
                {
                    leftDelete = Tuple.Create(key, LeftPlaceholder(key, PopulateMode.Unknown));
                }
                if (0 != (Ops.RightNullModified & insertRule))
                {
                    rightInsert = Tuple.Create(key, RightPlaceholder(key, PopulateMode.NullModified));
                }
                else if (0 != (Ops.RightNullPreserve & insertRule))
                {
                    rightInsert = Tuple.Create(key, RightPlaceholder(key, PopulateMode.NullPreserve));
                }
                else if (0 != (Ops.RightUnknown & insertRule))
                {
                    rightInsert = Tuple.Create(key, RightPlaceholder(key, PopulateMode.Unknown));
                }

                if (0 != (Ops.RightNullModified & deleteRule))
                {
                    rightDelete = Tuple.Create(key, RightPlaceholder(key, PopulateMode.NullModified));
                }
                else if (0 != (Ops.RightNullPreserve & deleteRule))
                {
                    rightDelete = Tuple.Create(key, RightPlaceholder(key, PopulateMode.NullPreserve));
                }
                else if (0 != (Ops.RightUnknown & deleteRule))
                {
                    rightDelete = Tuple.Create(key, RightPlaceholder(key, PopulateMode.Unknown));
                }

                // Populate elements in join output
                if (null != leftInsert && null != rightInsert)
                {
                    result.Inserted.Add(CreateResultTuple(leftInsert, rightInsert, result));
                }
                if (null != leftDelete && null != rightDelete)
                {
                    result.Deleted.Add(CreateResultTuple(leftDelete, rightDelete, result));
                }
            }
        // Processes all insert and delete requests in the table's <see cref="ChangeNode" />. Inserts
        // and deletes with the same key are merged into updates.
        internal List <UpdateCommand> CompileCommands(ChangeNode changeNode, UpdateCompiler compiler)
        {
            Set <CompositeKey> keys = new Set <CompositeKey>(compiler.m_translator.KeyComparer);

            // Retrieve all delete results (original values) and insert results (current values) while
            // populating a set of all row keys. The set contains a single key per row.
            Dictionary <CompositeKey, PropagatorResult> deleteResults = ProcessKeys(compiler, changeNode.Deleted, keys);
            Dictionary <CompositeKey, PropagatorResult> insertResults = ProcessKeys(compiler, changeNode.Inserted, keys);

            List <UpdateCommand> commands = new List <UpdateCommand>(deleteResults.Count + insertResults.Count);

            // Examine each row key to see if the row is being deleted, inserted or updated
            foreach (CompositeKey key in keys)
            {
                PropagatorResult deleteResult;
                PropagatorResult insertResult;

                bool hasDelete = deleteResults.TryGetValue(key, out deleteResult);
                bool hasInsert = insertResults.TryGetValue(key, out insertResult);

                Debug.Assert(hasDelete || hasInsert, "(update/TableChangeProcessor) m_keys must not contain a value " +
                             "if there is no corresponding insert or delete");

                try
                {
                    if (!hasDelete)
                    {
                        // this is an insert
                        commands.Add(compiler.BuildInsertCommand(insertResult, this));
                    }
                    else if (!hasInsert)
                    {
                        // this is a delete
                        commands.Add(compiler.BuildDeleteCommand(deleteResult, this));
                    }
                    else
                    {
                        // this is an update because it has both a delete result and an insert result
                        UpdateCommand updateCommand = compiler.BuildUpdateCommand(deleteResult, insertResult, this);
                        if (null != updateCommand)
                        {
                            // if null is returned, it means it is a no-op update
                            commands.Add(updateCommand);
                        }
                    }
                }
                catch (Exception e)
                {
                    if (UpdateTranslator.RequiresContext(e))
                    {
                        // collect state entries in scope for the current compilation
                        List <IEntityStateEntry> stateEntries = new List <IEntityStateEntry>();
                        if (null != deleteResult)
                        {
                            stateEntries.AddRange(SourceInterpreter.GetAllStateEntries(
                                                      deleteResult, compiler.m_translator, m_table));
                        }
                        if (null != insertResult)
                        {
                            stateEntries.AddRange(SourceInterpreter.GetAllStateEntries(
                                                      insertResult, compiler.m_translator, m_table));
                        }

                        throw EntityUtil.Update(System.Data.Entity.Strings.Update_GeneralExecutionException,
                                                e, stateEntries);
                    }
                    throw;
                }
            }

            return(commands);
        }