/// <summary>Implements the visitor pattern for the delete command tree.</summary>
 /// <param name="deleteTree">The delete command tree.</param>
 protected virtual void VisitDeleteCommandTree(DbDeleteCommandTree deleteTree)
 {
     Check.NotNull(deleteTree, "deleteTree");
     VisitExpressionBindingPre(deleteTree.Target);
     VisitExpression(deleteTree.Predicate);
     VisitExpressionBindingPost(deleteTree.Target);
 }
 protected virtual void VisitDeleteCommandTree(DbDeleteCommandTree deleteTree)
 {
     Contract.Requires(deleteTree != null);
     VisitExpressionBindingPre(deleteTree.Target);
     VisitExpression(deleteTree.Predicate);
     VisitExpressionBindingPost(deleteTree.Target);
 }
 /// <summary>Implements the visitor pattern for the delete command tree.</summary>
 /// <param name="deleteTree">The delete command tree.</param>
 protected virtual void VisitDeleteCommandTree(DbDeleteCommandTree deleteTree)
 {
     Check.NotNull <DbDeleteCommandTree>(deleteTree, nameof(deleteTree));
     this.VisitExpressionBindingPre(deleteTree.Target);
     this.VisitExpression(deleteTree.Predicate);
     this.VisitExpressionBindingPost(deleteTree.Target);
 }
 /// <summary>Implements the visitor pattern for the delete command tree.</summary>
 /// <param name="deleteTree">The delete command tree.</param>
 protected virtual void VisitDeleteCommandTree(DbDeleteCommandTree deleteTree)
 {
     Check.NotNull(deleteTree, "deleteTree");
     VisitExpressionBindingPre(deleteTree.Target);
     VisitExpression(deleteTree.Predicate);
     VisitExpressionBindingPost(deleteTree.Target);
 }
        private void GetAffectedEntitySets(System.Data.Entity.Core.Common.CommandTrees.DbCommandTree commandTree)
        {
            System.Data.Entity.Core.Common.CommandTrees.DbExpressionVisitor visitor   = new FindAffectedEntitySetsVisitor(this.affectedEntitySets, this.functionsUsed);
            System.Data.Entity.Core.Common.CommandTrees.DbQueryCommandTree  queryTree = commandTree as System.Data.Entity.Core.Common.CommandTrees.DbQueryCommandTree;
            if (queryTree != null)
            {
                queryTree.Query.Accept(visitor);
                return;
            }

            System.Data.Entity.Core.Common.CommandTrees.DbFunctionCommandTree fxnTree = commandTree as System.Data.Entity.Core.Common.CommandTrees.DbFunctionCommandTree;
            if (fxnTree != null)
            {
                this.IsStoredProcedure = true;
                return;
            }

            System.Data.Entity.Core.Common.CommandTrees.DbUpdateCommandTree updateTree = commandTree as System.Data.Entity.Core.Common.CommandTrees.DbUpdateCommandTree;
            if (updateTree != null)
            {
                this.IsModification = true;
                updateTree.Target.Expression.Accept(visitor);
                updateTree.Predicate.Accept(visitor);
                if (updateTree.Returning != null)
                {
                    updateTree.Returning.Accept(visitor);
                }

                return;
            }

            System.Data.Entity.Core.Common.CommandTrees.DbInsertCommandTree insertTree = commandTree as System.Data.Entity.Core.Common.CommandTrees.DbInsertCommandTree;
            if (insertTree != null)
            {
                this.IsModification = true;
                insertTree.Target.Expression.Accept(visitor);
                if (insertTree.Returning != null)
                {
                    insertTree.Returning.Accept(visitor);
                }

                return;
            }

            System.Data.Entity.Core.Common.CommandTrees.DbDeleteCommandTree deleteTree = commandTree as System.Data.Entity.Core.Common.CommandTrees.DbDeleteCommandTree;
            if (deleteTree != null)
            {
                this.IsModification = true;
                deleteTree.Target.Expression.Accept(visitor);
                if (deleteTree.Predicate != null)
                {
                    deleteTree.Predicate.Accept(visitor);
                }

                return;
            }

            throw new NotSupportedException("Command tree type " + commandTree.GetType() + " is not supported.");
        }
    internal static string GenerateDeleteSql(DbDeleteCommandTree tree, out List<DbParameter> parameters)
    {
      StringBuilder commandText = new StringBuilder(s_commandTextBuilderInitialCapacity);
      ExpressionTranslator translator = new ExpressionTranslator(commandText, tree, false, "DeleteFunction");

      // delete [schemaName].[tableName]
      commandText.Append("DELETE FROM ");
      tree.Target.Expression.Accept(translator);
      commandText.AppendLine();

      // where c1 = ... AND c2 = ...
      commandText.Append("WHERE ");
      tree.Predicate.Accept(translator);

      parameters = translator.Parameters;

      commandText.AppendLine(";");
      return commandText.ToString();
    }
        /// <summary>
        ///     Builds a delete command.
        /// </summary>
        /// <param name="oldRow"> Value of the row being deleted. </param>
        /// <param name="processor"> Context for the table containing row. </param>
        /// <returns> Delete command. </returns>
        internal UpdateCommand BuildDeleteCommand(PropagatorResult oldRow, TableChangeProcessor processor)
        {
            // If we're deleting a row, the row must always be touched
            var rowMustBeTouched = true;

            // Initialize DML command tree
            var target = GetTarget(processor);

            // Create delete predicate
            var predicate = BuildPredicate(target, oldRow, null, processor, ref rowMustBeTouched);
            var commandTree = new DbDeleteCommandTree(m_translator.MetadataWorkspace, DataSpace.SSpace, target, predicate);

            // Set command
            // Initialize delete command
            UpdateCommand command = new DynamicUpdateCommand(
                processor, m_translator, ModificationOperator.Delete, oldRow, null, commandTree, null);

            return command;
        }
        internal static string GenerateDeleteSql(DbDeleteCommandTree tree, SqlVersion sqlVersion, out List<SqlParameter> parameters)
        {
            var commandText = new StringBuilder(s_commandTextBuilderInitialCapacity);
            var translator = new ExpressionTranslator(commandText, tree, false, sqlVersion);

            // delete [schemaName].[tableName]
            commandText.Append("delete ");
            tree.Target.Expression.Accept(translator);
            commandText.AppendLine();

            // where c1 = ... AND c2 = ...
            commandText.Append("where ");
            tree.Predicate.Accept(translator);

            parameters = translator.Parameters;
            return commandText.ToString();
        }
        internal static string GenerateDeleteSql(
            DbDeleteCommandTree tree,
            SqlGenerator sqlGenerator,
            out List<SqlParameter> parameters,
            bool upperCaseKeywords = true,
            bool createParameters = true)
        {
            var commandText
                = new SqlStringBuilder(CommandTextBuilderInitialCapacity)
                      {
                          UpperCaseKeywords = upperCaseKeywords
                      };

            var translator 
                = new ExpressionTranslator(
                    commandText, 
                    tree, 
                    false, 
                    sqlGenerator,
                    createParameters: createParameters);

            // delete [schemaName].[tableName]
            commandText.AppendKeyword("delete ");
            tree.Target.Expression.Accept(translator);
            commandText.AppendLine();

            // where c1 = ... AND c2 = ...
            commandText.AppendKeyword("where ");
            tree.Predicate.Accept(translator);

            parameters = translator.Parameters;
            return commandText.ToString();
        }
        internal static string[] GenerateDeleteSql(DbDeleteCommandTree tree, out List<DbParameter> parameters, bool isLocalProvider)
        {
            var commandTexts = new List<String>();
            var commandText = new StringBuilder(s_commandTextBuilderInitialCapacity);
            var translator = new ExpressionTranslator(commandText, tree, false, isLocalProvider);

            // delete [schemaName].[tableName]
            commandText.Append("delete ");
            tree.Target.Expression.Accept(translator);
            commandText.AppendLine();

            // where c1 = ... AND c2 = ...
            commandText.Append("where ");
            tree.Predicate.Accept(translator);

            commandTexts.Add(commandText.ToString());
            commandText.Length = 0;

            parameters = translator.Parameters;
            return commandTexts.ToArray();
        }
        /// <summary>
        /// In case of a delete command we always filter based on the userId
        /// </summary>
        static void InterceptDeleteCommand(DbCommandTreeInterceptionContext interceptionContext)
        {
            var deleteCommand = interceptionContext.Result as DbDeleteCommandTree;
            if (deleteCommand != null)
            {
                var column = UserAwareAttribute.GetUserColumnName(deleteCommand.Target.VariableType.EdmType);
                if (!string.IsNullOrEmpty(column))
                {
                    // Get the userId (throw an exception if there is none)
                    var userId = GetCurrentUserId();

                    // Create the variable reference in order to create the property
                    var variableReference = DbExpressionBuilder.Variable(deleteCommand.Target.VariableType,
                        deleteCommand.Target.VariableName);
                    // Create the property to which will assign the correct value
                    var userProperty = DbExpressionBuilder.Property(variableReference, column);
                    var userIdWherePredicate = DbExpressionBuilder.Equal(userProperty, DbExpression.FromInt32(userId));

                    // The initial predicate is the sql where statement
                    var initialPredicate = deleteCommand.Predicate;
                    // Add to the initial statement the userId statement which translates in sql AND userId = 'value'
                    var finalPredicate = initialPredicate.And(userIdWherePredicate);

                    var newDeleteCommand = new DbDeleteCommandTree(
                        deleteCommand.MetadataWorkspace,
                        deleteCommand.DataSpace,
                        deleteCommand.Target,
                        finalPredicate);

                    interceptionContext.Result = newDeleteCommand;
                }
            }
        }
        private IEnumerable<CreateProcedureOperation> BuildCreateProcedureOperations(
            StorageAssociationSetModificationFunctionMapping modificationFunctionMapping,
            ModificationCommandTreeGenerator modificationCommandTreeGenerator,
            MigrationSqlGenerator migrationSqlGenerator)
        {
            DebugCheck.NotNull(modificationFunctionMapping);

            var insertCommandTrees = new DbInsertCommandTree[0];
            var deleteCommandTrees = new DbDeleteCommandTree[0];

            if (modificationCommandTreeGenerator != null)
            {
                var dynamicToFunctionModificationCommandConverter
                    = new DynamicToFunctionModificationCommandConverter(
                        modificationFunctionMapping,
                        _target.StorageEntityContainerMapping);

                insertCommandTrees
                    = dynamicToFunctionModificationCommandConverter
                        .Convert(
                            modificationCommandTreeGenerator
                                .GenerateAssociationInsert(modificationFunctionMapping.AssociationSet.ElementType.Identity))
                        .ToArray();

                deleteCommandTrees
                    = dynamicToFunctionModificationCommandConverter
                        .Convert(
                            modificationCommandTreeGenerator
                                .GenerateAssociationDelete(modificationFunctionMapping.AssociationSet.ElementType.Identity))
                        .ToArray();
            }

            string insertBodySql = null, deleteBodySql = null;

            if (migrationSqlGenerator != null)
            {
                var providerManifestToken
                    = _target.ProviderInfo.ProviderManifestToken;

                insertBodySql
                    = migrationSqlGenerator
                        .GenerateProcedureBody(insertCommandTrees, null, providerManifestToken);

                deleteBodySql
                    = migrationSqlGenerator.GenerateProcedureBody(
                        deleteCommandTrees,
                        modificationFunctionMapping.DeleteFunctionMapping.RowsAffectedParameterName,
                        providerManifestToken);
            }

            yield return BuildCreateProcedureOperation(
                modificationFunctionMapping.InsertFunctionMapping.Function,
                insertBodySql);

            yield return BuildCreateProcedureOperation(
                modificationFunctionMapping.DeleteFunctionMapping.Function,
                deleteBodySql);
        }