Exemplo n.º 1
0
        protected override Expression VisitIn(InExpression expression)
        {
            if (!ShouldRewrite(expression)) {
                return base.VisitIn(expression);
            }

            Array array = expression.Values.OfType<ConstantExpression>().Select(item => item.Value).Distinct().ToArray();

            var vfpDataXml = new ArrayXmlToCursor(array);
            var tableAlias = new TableAlias();
            var columnType = _language.TypeSystem.GetColumnType(vfpDataXml.ItemType);
            var columnExpression = new ColumnExpression(vfpDataXml.ItemType, columnType, tableAlias, ArrayXmlToCursor.ColumnName);

            var columns = new List<ColumnDeclaration> {
                new ColumnDeclaration(string.Empty, columnExpression, columnType)
            };

            var xml = Expression.Constant(vfpDataXml.Xml);
            var cursorName = Expression.Constant("curTemp_" + DateTime.Now.ToString("ddHHssmm"));
            var check = Expression.GreaterThan(new XmlToCursorExpression(xml, cursorName), Expression.Constant(0));
            var from = Expression.Condition(check, cursorName, Expression.Constant(string.Empty));
            var select = new SelectExpression(tableAlias, columns, from, null);

            return new InExpression(expression.Expression, select);
        }
Exemplo n.º 2
0
 protected internal override Expression VisitIn(InExpression @in)
 {
     if (@in.Select != null)
     {
         AddSingleColumn(@in);
     }
     return base.VisitIn(@in);
 }
        public void Contains_call_on_generic_list_of_int_is_parsed_into_InExpression_with_property_name_and_values()
        {
            var pageCounts = new List<int> { 0, 1 };

            var expression = _parser.Parse<Book>(x => pageCounts.Contains(x.PageCount));

            var expectedExpression = new InExpression(
                new PropertyExpression("PageCount", typeof(int)),
                new ArrayValueExpression(pageCounts));

            Assert.AreEqual(expectedExpression, expression);
        }
        public void Contains_call_on_generic_list_of_string_is_parsed_into_InExpression_with_property_name_and_values()
        {
            IList<string> titles = new List<string> { "Title 1", "Title 2" };

            var expression = _parser.Parse<Book>(x => titles.Contains(x.Title));

            var expectedExpression = new InExpression(
                new PropertyExpression("Title", typeof(string)),
                new ArrayValueExpression(titles));

            Assert.AreEqual(expectedExpression, expression);
        }
Exemplo n.º 5
0
            protected virtual Expression VisitIn(InExpression expression)
            {
                _expressionInProgress.Enqueue(new GroupStartFragment());
                Visit(expression.Subject);

                _expressionInProgress.Enqueue(new StringFragment(" IN "));

                Visit(expression.Target);

                _expressionInProgress.Enqueue(new GroupEndFragment());

                return(expression);
            }
Exemplo n.º 6
0
        protected override Expression VisitIn(InExpression inExpression)
        {
            var parentSearchCondition = _isSearchCondition;

            _isSearchCondition = false;
            var item     = (SqlExpression)Visit(inExpression.Item);
            var subquery = (SelectExpression)Visit(inExpression.Subquery);
            var values   = (SqlExpression)Visit(inExpression.Values);

            _isSearchCondition = parentSearchCondition;

            return(ApplyConversion(inExpression.Update(item, values, subquery), condition: true));
        }
Exemplo n.º 7
0
        public void Contains_call_on_generic_list_of_int_is_parsed_into_InExpression_with_property_name_and_values()
        {
            var pageCounts = new List <int> {
                0, 1
            };

            var expression = _parser.Parse <Book>(x => pageCounts.Contains(x.PageCount));

            var expectedExpression = new InExpression(
                new PropertyExpression("PageCount", typeof(int)),
                new ArrayValueExpression(pageCounts));

            Assert.AreEqual(expectedExpression, expression);
        }
        private void DoTestEvaluate(object value, IReadOnlyCollection <object> list, bool expected)
        {
            // Arrange
            Literal literal = new Literal(value, LiteralType.Value);
            IReadOnlyCollection <Literal> literals = list.Select(item => new Literal(item, LiteralType.Value)).ToList();

            IExpression expression = new InExpression(literal, literals);

            // Act
            bool result = expression.Evaluate(null);

            // Assert
            Assert.AreEqual(expected, result);
        }
Exemplo n.º 9
0
        public void Contains_call_on_generic_list_of_string_is_parsed_into_InExpression_with_property_name_and_values()
        {
            IList <string> titles = new List <string> {
                "Title 1", "Title 2"
            };

            var expression = _parser.Parse <Book>(x => titles.Contains(x.Title));

            var expectedExpression = new InExpression(
                new PropertyExpression("Title", typeof(string)),
                new ArrayValueExpression(titles));

            Assert.AreEqual(expectedExpression, expression);
        }
Exemplo n.º 10
0
        protected override Expression VisitIn(InExpression inExpression)
        {
            Check.NotNull(inExpression, nameof(inExpression));

            var parentOptimize = _optimize;

            _optimize = false;
            var item     = (SqlExpression)Visit(inExpression.Item);
            var subquery = (SelectExpression)Visit(inExpression.Subquery);
            var values   = (SqlExpression)Visit(inExpression.Values);

            _optimize = parentOptimize;

            return(ApplyConversion(inExpression.Update(item, values, subquery), condition: true));
        }
Exemplo n.º 11
0
        public override void VisitInExpression(InExpression inExpression)
        {
            if (inExpression.Values == null)
            {
                throw new SqlErrorException("IN predicate only supports a list of values right now");
            }

            Expression memberExpression;

            if (inExpression.Expression is ColumnReference columnReferenceExpression)
            {
                //Check here if any index can be used aswell

                var identifiers = columnReferenceExpression.Identifiers;

                identifiers      = MemberUtils.RemoveAlias(_previousStage, identifiers);
                memberExpression = MemberUtils.GetMember(_previousStage, identifiers, _visitorMetadata.OperationsProvider, out var property);
                AddUsedProperty(property);
                AddNameToStack(string.Join(".", identifiers));
            }
            else
            {
                throw new SqlErrorException("IN predicate can only be used against column names");
            }

            IList list = ListUtils.GetNewListFunction(memberExpression.Type)();

            foreach (var value in inExpression.Values)
            {
                if (value is Literal literal)
                {
                    list.Add(TypeConvertUtils.ConvertToType(literal.GetValue(), memberExpression.Type));
                }
                else if (value is VariableReference variableReference)
                {
                    var sqlParameter  = _visitorMetadata.Parameters.GetParameter(variableReference.Name);
                    var variableValue = sqlParameter.GetValue(memberExpression.Type);
                    list.Add(variableValue);
                }
                else
                {
                    throw new SqlErrorException("IN predicate only supports literal or parameter values.");
                }
            }
            var inPredicate = _visitorMetadata.OperationsProvider.GetListContains(memberExpression, list);

            AddExpressionToStack(inPredicate);
        }
        public void InBoolean_GivenElementAndSet_CorrectValueReturned(int[] a, int[] b, bool expected)
        {
            Element           lhsValue   = new Element(a.ToList());
            Set               rhsValue   = GetSetWith1DElements(b);
            ElementExpression lhs        = new ElementExpression(null, 0, 0);
            SetExpression     rhs        = GetSetInit();
            InExpression      expression = new InExpression(lhs, rhs, 0, 0);

            IInterpreterBoolean parent = Substitute.For <IInterpreterBoolean>();

            DispatchElementForParent(lhsValue, lhs, parent);
            DispatchSetForParent(rhsValue, rhs, parent);
            BooleanHelper booleanHelper = Utilities.GetBooleanHelper(parent);

            bool res = booleanHelper.InBoolean(expression, new List <object>());

            Assert.AreEqual(expected, res);
        }
Exemplo n.º 13
0
    protected internal virtual Expression VisitIn(InExpression @in)
    {
        var expression = this.Visit(@in.Expression);
        var select     = (SelectExpression?)this.Visit(@in.Select);

        if (expression != @in.Expression || select != @in.Select)
        {
            if (select != null)
            {
                return(new InExpression(expression, select));
            }
            else
            {
                return(InExpression.FromValues(expression, @in.Values !));
            }
        }
        return(@in);
    }
Exemplo n.º 14
0
        public virtual Expression VisitIn(InExpression inExpression)
        {
            if (inExpression.Values != null)
            {
                var inValues        = ProcessInExpressionValues(inExpression.Values);
                var inValuesNotNull = ExtractNonNullExpressionValues(inValues);

                if (inValues.Count != inValuesNotNull.Count)
                {
                    var relationalNullsInExpression
                        = Expression.OrElse(
                              new InExpression(inExpression.Operand, inValuesNotNull),
                              new IsNullExpression(inExpression.Operand));

                    return(Visit(relationalNullsInExpression));
                }

                if (inValuesNotNull.Count > 0)
                {
                    Visit(inExpression.Operand);

                    _relationalCommandBuilder.Append(" IN (");

                    VisitJoin(inValuesNotNull);

                    _relationalCommandBuilder.Append(")");
                }
                else
                {
                    _relationalCommandBuilder.Append("1 = 0");
                }
            }
            else
            {
                Visit(inExpression.Operand);

                _relationalCommandBuilder.Append(" IN ");

                Visit(inExpression.SubQuery);
            }

            return(inExpression);
        }
Exemplo n.º 15
0
        protected virtual Expression VisitNotIn([NotNull] InExpression inExpression)
        {
            if (inExpression.Values != null)
            {
                var inValues        = ProcessInExpressionValues(inExpression.Values);
                var inValuesNotNull = ExtractNonNullExpressionValues(inValues);

                if (inValues.Count != inValuesNotNull.Count)
                {
                    var relationalNullsNotInExpression
                        = Expression.AndAlso(
                              Expression.Not(new InExpression(inExpression.Operand, inValuesNotNull)),
                              Expression.Not(new IsNullExpression(inExpression.Operand)));

                    return(Visit(relationalNullsNotInExpression));
                }

                if (inValues.Count > 0)
                {
                    Visit(inExpression.Operand);

                    _relationalCommandBuilder.Append(" NOT IN (");

                    VisitJoin(inValues);

                    _relationalCommandBuilder.Append(")");
                }
                else
                {
                    _relationalCommandBuilder.Append("1 = 1");
                }
            }
            else
            {
                Visit(inExpression.Operand);

                _relationalCommandBuilder.Append(" NOT IN ");

                Visit(inExpression.SubQuery);
            }

            return(inExpression);
        }
Exemplo n.º 16
0
        public void TestVisitInExpression()
        {
            Mock <ScalarExpression> expMock      = new Mock <ScalarExpression>();
            Mock <ScalarExpression> valueMock    = new Mock <ScalarExpression>();
            InExpression            inExpression = new InExpression()
            {
                Expression = expMock.Object,
                Values     = new List <ScalarExpression>()
                {
                    valueMock.Object
                }
            };

            KoraliumSqlVisitor koraliumSqlVisitor = new KoraliumSqlVisitor();

            koraliumSqlVisitor.Visit(inExpression);

            expMock.Verify(x => x.Accept(koraliumSqlVisitor));
            valueMock.Verify(x => x.Accept(koraliumSqlVisitor));
        }
        protected virtual Expression VisitNotInExpression(InExpression inExpression)
        {
            var inValues = ProcessInExpressionValues(inExpression.Values);

            if (inValues.Count > 0)
            {
                VisitExpression(inExpression.Column);

                _sql.Append(" NOT IN (");

                VisitJoin(inValues);

                _sql.Append(")");
            }
            else
            {
                _sql.Append("1 = 1");
            }

            return(inExpression);
        }
        public virtual Expression VisitInExpression(InExpression inExpression)
        {
            var inValues = ProcessInExpressionValues(inExpression.Values);

            if (inValues.Count > 0)
            {
                VisitExpression(inExpression.Column);

                _sql.Append(" IN (");

                VisitJoin(inValues);

                _sql.Append(")");
            }
            else
            {
                _sql.Append("1 = 0");
            }

            return(inExpression);
        }
Exemplo n.º 19
0
        private static bool ShouldRewrite(InExpression @in)
        {
            if (@in.Values == null || @in.Values.Count == 0 || @in.Values[0].NodeType != ExpressionType.Constant) {
                return false;
            }

            const int MINLENGTH = 250;

            var values = new StringBuilder();

            foreach (var value in @in.Values.Where(value => value != null).Distinct()) {
                values.Append(value);
                values.Append(",");

                if (values.Length > MINLENGTH) {
                    return true;
                }
            }

            return false;
        }
        protected override Expression VisitIn(InExpression inExpression)
        {
            var canOptimize = _canOptimize;

            _canOptimize = false;
            _isNullable  = false;
            var item       = (SqlExpression)Visit(inExpression.Item);
            var isNullable = _isNullable;

            _isNullable = false;
            var subquery = (SelectExpression)Visit(inExpression.Subquery);

            isNullable |= _isNullable;
            _isNullable = false;
            var values = (SqlExpression)Visit(inExpression.Values);

            _isNullable |= isNullable;
            _canOptimize = canOptimize;

            return(inExpression.Update(item, values, subquery));
        }
Exemplo n.º 21
0
        private static IEnumerable <(string Value, ValueTokenType Type)> GetValuesForIn(
            JsonOperationContext context,
            Query query,
            InExpression expression,
            QueryMetadata metadata,
            BlittableJsonReaderObject parameters,
            string fieldName)
        {
            foreach (var val in expression.Values)
            {
                var valueToken = val as ValueExpression;
                if (valueToken == null)
                {
                    ThrowInvalidInValue(query, parameters, val);
                }

                foreach (var(value, type) in GetValues(fieldName, query, metadata, parameters, valueToken))
                {
                    string valueAsString;
                    switch (type)
                    {
                    case ValueTokenType.Long:
                        var valueAsLong = (long)value;
                        valueAsString = valueAsLong.ToString(CultureInfo.InvariantCulture);
                        break;

                    case ValueTokenType.Double:
                        var valueAsDbl = (double)value;
                        valueAsString = valueAsDbl.ToString("G");
                        break;

                    default:
                        valueAsString = value?.ToString();
                        break;
                    }

                    yield return(valueAsString, type);
                }
            }
        }
Exemplo n.º 22
0
            public void Visit(InExpression expression)
            {
                if (expression.ArrayValueExpression.Values.IsEmpty())
                {
                    throw new WeenyMapperException("Can not generate IN constraint from empty collection");
                }

                var columnName = expression.PropertyExpression.PropertyName;

                var newParameters = new List <CommandParameter>();

                foreach (var value in expression.ArrayValueExpression.Values)
                {
                    var commandParameter = _commandParameterFactory.Create(columnName, value);
                    CommandParameters.Add(commandParameter);
                    newParameters.Add(commandParameter);
                }
                var parameterString  = string.Join(", ", newParameters.Select(x => x.ReferenceName));
                var columnNameString = CreateColumnNameString(expression.PropertyExpression.PropertyName);

                ConstraintCommandText = string.Format("({0} IN ({1}))", columnNameString, parameterString);
            }
Exemplo n.º 23
0
        public void Visit(InExpression expression)
        {
            var values = expression.ArrayValueExpression.Values;

            if (values.IsEmpty())
            {
                throw new WeenyMapperException("Can not generate IN constraint from empty collection");
            }

            var columnName  = expression.PropertyExpression.PropertyName;
            var actualValue = _row.GetColumnValue(columnName).Value;

            foreach (var value in values)
            {
                if (Equals(value, actualValue))
                {
                    return;
                }
            }

            _isMatch = false;
        }
Exemplo n.º 24
0
        protected virtual Expression VisitIn(InExpression inExpression)
        {
            Expression expression = Visit(inExpression.Expression);

            if (inExpression.Query != null)
            {
                SelectExpression select = (SelectExpression)Visit(inExpression.Query);
                if (expression != inExpression.Expression || select != inExpression.Query)
                {
                    return(new InExpression(expression, select));
                }
            }
            else
            {
                ReadOnlyCollection <Expression> values = Visit(inExpression.Values);
                if (expression != inExpression.Expression || values != inExpression.Values)
                {
                    return(new InExpression(expression, values));
                }
            }
            return(inExpression);
        }
Exemplo n.º 25
0
        public object VisitIn(InExpression expression, Context context)
        {
            _queryBuilder.AppendFormat("ARRAY_CONTAINS([");

            var values = expression.Values.ToArray();

            for (int i = 0; i < values.Length; i++)
            {
                string paramName = AddParameterMapping(values[i]);
                _queryBuilder.Append(paramName);

                if (i < values.Length - 1)
                {
                    _queryBuilder.Append(',');
                }
            }

            _queryBuilder.Append("], ");
            _queryBuilder.Append(context.InstanceVariableName).Append('.').Append(GetFieldName(expression, context)).Append(')');

            return(null);
        }
Exemplo n.º 26
0
        public void TestInExpressionSingleValue()
        {
            var actual = new InExpression()
            {
                Expression = new ColumnReference()
                {
                    Identifiers = new List <string>()
                    {
                        "c1"
                    }
                },
                Values = new List <ScalarExpression>()
                {
                    new StringLiteral()
                    {
                        Value = "a"
                    }
                }
            }.Print();
            var expected = "c1 IN ('a')";

            actual.Should().Be(expected);
        }
Exemplo n.º 27
0
        private ICriterion BuildCriterion(QueryMember member, IEnumerator values)
        {
            ICriterion criterion;

            WhereOperator wo;

            if (!Enum.TryParse(member.Type.ToString(), out wo))
            {
                wo = WhereOperator.Equal;
            }

            switch (wo)
            {
            case WhereOperator.Between:
                criterion = new BetweenExpression(member.PropertyName, values.NextValue(), values.NextValue());
                break;

            case WhereOperator.In:
                criterion = new InExpression(member.PropertyName, values.NextValue <object[]>());
                break;

            case WhereOperator.Null:
                criterion = new NullExpression(member.PropertyName);
                break;

            default:
                criterion = new SimpleExpression(member.PropertyName, wo, values.NextValue());
                break;
            }

            if (member.HasNot)
            {
                criterion = new NotExpression(criterion);
            }

            return(criterion);
        }
Exemplo n.º 28
0
        public override void VisitInExpression(InExpression inExpression)
        {
            if (!(inExpression.Expression is ColumnReference column))
            {
                //TODO: Fix exception
                throw new System.Exception("In expressions can only be done on columns for elasticseach filters");
            }

            List <object> values = new List <object>();

            foreach (var val in inExpression.Values)
            {
                if (!(val is Literal literal))
                {
                    throw new System.Exception("In expression can only have literals as valeus for elasticsearch filters");
                }
                values.Add(GetTerm(literal.GetValue()));
            }
            Push(new Terms()
            {
                FieldName = string.Join(".", column.Identifiers),
                Values    = values
            });
        }
        private static bool ShouldRewrite(InExpression @in)
        {
            if (@in.Values == null || @in.Values.Count == 0 || @in.Values[0].NodeType != ExpressionType.Constant)
            {
                return(false);
            }

            const int MINLENGTH = 250;

            var values = new StringBuilder();

            foreach (var value in @in.Values.Where(value => value != null).Distinct())
            {
                values.Append(value);
                values.Append(",");

                if (values.Length > MINLENGTH)
                {
                    return(true);
                }
            }

            return(false);
        }
		public ISymbolValue Visit(InExpression x)
		{
			// The return value of the InExpression is null if the element is not in the array; 
			// if it is in the array it is a pointer to the element.

			return x.RightOperand != null ? x.RightOperand.Accept(this) : null;
		}
Exemplo n.º 31
0
		IExpression CmpExpression(IBlockNode Scope = null)
		{
			// TODO: Make this into a switch.
			var left = ShiftExpression(Scope);

			OperatorBasedExpression ae;

			switch (laKind) {
			case DTokens.Equal:
			case DTokens.NotEqual:
				ae = new EqualExpression (laKind == NotEqual);
				break;

			case DTokens.LessThan:
			case DTokens.LessEqual:
			case DTokens.GreaterThan:
			case DTokens.GreaterEqual:
			case DTokens.Unordered:
			case DTokens.LessOrGreater:
			case DTokens.LessEqualOrGreater:
			case DTokens.UnorderedOrGreater:
			case DTokens.UnorderedGreaterOrEqual:
			case DTokens.UnorderedOrLess:
			case DTokens.UnorderedLessOrEqual:
			case DTokens.UnorderedOrEqual:
				ae = new RelExpression (laKind);
				break;

			case DTokens.Is:
				ae = new IdentityExpression (false);
				break;

			case DTokens.In:
				ae = new InExpression (false);
				break;

			case Not:
				switch (Peek (1).Kind) {
				case DTokens.Is:
					ae = new IdentityExpression (false);
					Step ();
					break;
				case DTokens.In:
					ae = new InExpression (true);
					Step ();
					break;
				default:
					return left;
				}
				break;

			default:
				return left;
			}

			// Skip operator
			Step();

			ae.LeftOperand = left;
			ae.RightOperand = ShiftExpression(Scope);
			return ae;
		}
Exemplo n.º 32
0
        IExpression CmpExpression(IBlockNode Scope = null)
        {
            // TODO: Make this into a switch.
            var left = ShiftExpression(Scope);

            OperatorBasedExpression ae = null;

            // Equality Expressions
            if (laKind == Equal || laKind == NotEqual)
                ae = new EqualExpression(laKind == NotEqual);

            // Relational Expressions
            else if (IsRelationalOperator(laKind))
                ae = new RelExpression(laKind);

            // Identity Expressions
            else if (laKind == Is || (laKind == Not && Peek(1).Kind == Is))
                ae = new IdentityExpression(laKind == Not);

            // In Expressions
            else if (laKind == In || (laKind == Not && Peek(1).Kind == In))
                ae = new InExpression(laKind == Not);

            else return left;

            // Skip possible !-Token
            if (laKind == Not)
                Step();

            // Skip operator
            Step();

            ae.LeftOperand = left;
            ae.RightOperand = ShiftExpression(Scope);
            return ae;
        }
Exemplo n.º 33
0
 protected override Expression VisitIn(InExpression @in)
 {
     VisitValue(@in.Expression);
     sb.Append(" IN (");
     if (@in.Select != null)
     {
         Visit(@in.Select);
         sb.Append(")");
     }
     else if (@in.Values == null)
     {
         return @in;
     }
     for (int i = 0, n = @in.Values.Count; i < n; i++)
     {
         if (i > 0)
             sb.Append(", ");
         VisitValue(@in.Values[i]);
     }
     sb.Append(")");
     return @in;
 }
Exemplo n.º 34
0
 protected virtual Expression VisitIn(InExpression @in)
 {
     Expression expr = this.Visit(@in.Expression);
     if (@in.Select != null)
     {
         SelectExpression select = (SelectExpression)this.Visit(@in.Select);
         if (expr != @in.Expression || select != @in.Select)
         {
             return new InExpression(expr, select);
         }
     }
     else
     {
         IEnumerable<Expression> values = this.VisitExpressionList(@in.Values);
         if (expr != @in.Expression || values != @in.Values)
         {
             return new InExpression(expr, values);
         }
     }
     return @in;
 }
Exemplo n.º 35
0
        protected override Expression VisitIn(InExpression inExpression)
        {
            if (inExpression.Values != null)
            {
                var inValues     = new List <SqlConstantExpression>();
                var hasNullValue = false;

                switch (inExpression.Values)
                {
                case SqlConstantExpression sqlConstant:
                {
                    var values = (IEnumerable)sqlConstant.Value;
                    foreach (var value in values)
                    {
                        if (value == null)
                        {
                            hasNullValue = true;
                            continue;
                        }

                        inValues.Add(
                            new SqlConstantExpression(
                                Expression.Constant(value),
                                sqlConstant.TypeMapping));
                    }
                }
                break;

                case SqlParameterExpression sqlParameter:
                {
                    var values = (IEnumerable)_parametersValues[sqlParameter.Name];
                    foreach (var value in values)
                    {
                        if (value == null)
                        {
                            hasNullValue = true;
                            continue;
                        }

                        inValues.Add(
                            new SqlConstantExpression(
                                Expression.Constant(value),
                                sqlParameter.TypeMapping));
                    }
                }
                break;
                }

                if (inValues.Count > 0)
                {
                    if (hasNullValue)
                    {
                        _relationalCommandBuilder.Append("(");
                    }

                    Visit(inExpression.Item);
                    _relationalCommandBuilder.Append(inExpression.Negated ? " NOT IN " : " IN ");
                    _relationalCommandBuilder.Append("(");
                    GenerateList(inValues, e => Visit(e));
                    _relationalCommandBuilder.Append(")");

                    if (hasNullValue)
                    {
                        _relationalCommandBuilder.Append(_operatorMap[ExpressionType.OrElse]);
                        Visit(new SqlUnaryExpression(
                                  ExpressionType.Equal, inExpression.Item, inExpression.Type, inExpression.TypeMapping));
                        _relationalCommandBuilder.Append(")");
                    }
                }
                else
                {
                    Visit(
                        hasNullValue
                        ? (Expression) new SqlUnaryExpression(
                            ExpressionType.Equal, inExpression.Item, inExpression.Type, inExpression.TypeMapping)
                        : new SqlBinaryExpression(
                            ExpressionType.Equal,
                            new SqlConstantExpression(Expression.Constant(true), inExpression.TypeMapping),
                            new SqlConstantExpression(Expression.Constant(false), inExpression.TypeMapping),
                            typeof(bool),
                            inExpression.TypeMapping));
                }
            }
            else
            {
                Visit(inExpression.Item);
                _relationalCommandBuilder.Append(inExpression.Negated ? " NOT IN " : " IN ");
                _relationalCommandBuilder.AppendLine("(");

                using (_relationalCommandBuilder.Indent())
                {
                    Visit(inExpression.Subquery);
                }

                _relationalCommandBuilder.AppendLine().AppendLine(")");
            }

            return(inExpression);
        }
Exemplo n.º 36
0
        internal static void PatchInExpressions(this InExpression expression, RelationalQueryContext context, List <string> usedParams = null)
        {
            if (context is null ||
                expression is null)
            {
                return;
            }

            expression.Item.PatchInExpressions(context, usedParams);

            expression.Subquery?.PatchInExpressions(context, usedParams);

            if (expression.Values is null)
            {
                return;
            }

            // The version of VisitIn in EF Core 3.1.1 has two requirements.
            // 1) The Values must be from a SqlConstantExpression
            // 2) The Value from the SqlConstantExpression must be castable to IEnumerable<object>

            var currentValue = expression.Values;

            switch (currentValue)
            {
            case SqlParameterExpression paramEx:
            {
                // Fix issue 1 & 2 by grabbing the parameter and converting to a constant IEnumerable<object>.
                var value = context.ParameterValues[paramEx.Name];
                if (usedParams != null &&
                    !usedParams.Contains(paramEx.Name))
                {
                    usedParams.Add(paramEx.Name);
                }

                var newVal = (value as IEnumerable)?.Cast <object>().ToArray() ?? new object[0];
                var newEx  = new SqlConstantExpression(Expression.Constant(newVal), paramEx.TypeMapping);
                if (!expression.SetNonPublicProperty("Values", newEx))
                {
                    throw new InvalidOperationException("Could not update Values for InExpression.");
                }

                break;
            }

            case SqlConstantExpression sqlConstEx:
            {
                // Fix issue 2, castable to IEnumerable<object>
                var constEx = sqlConstEx.GetNonPublicField <ConstantExpression>("_constantExpression");
                var newVal  = ((IEnumerable)constEx.Value).Cast <object>().ToArray();
                var newEx   = new SqlConstantExpression(Expression.Constant(newVal), sqlConstEx.TypeMapping);
                if (!expression.SetNonPublicProperty("Values", newEx))
                {
                    throw new InvalidOperationException("Could not update Values for InExpression.");
                }
                break;
            }

            default:
                throw new InvalidOperationException($"Don't know how to convert {currentValue.GetType()} to SqlConstantExpression.");
            }
        }
Exemplo n.º 37
0
 private bool IsValidInExpression(InExpression expression)
 {
     return expression != null && _inExpressions.Contains(VfpFormatter.Format(expression));
 }
Exemplo n.º 38
0
 protected virtual Expression VisitIn(InExpression @in)
 {
     var expression = this.Visit(@in.Expression);
     var select = (SelectExpression)this.Visit(@in.Select);
     if (expression != @in.Expression || select != @in.Select)
     {
         if (select != null)
             return new InExpression(expression, select);
         else
             return InExpression.FromValues(expression, @in.Values);
     }
     return @in;
 }
Exemplo n.º 39
0
        IExpression CmpExpression(IBlockNode Scope = null)
        {
            var left = ShiftExpression(Scope);

            OperatorBasedExpression ae = null;

            // Equality Expressions
            if (laKind == Equal || laKind == NotEqual)
                ae = new EqualExpression(laKind == NotEqual);

            // Relational Expressions
            else if (RelationalOperators[laKind])
                ae = new RelExpression(laKind);

            // Identity Expressions
            else if (laKind == Is || (laKind == Not && Peek(1).Kind == Is))
                ae = new IdendityExpression(laKind == Not);

            // In Expressions
            else if (laKind == In || (laKind == Not && Peek(1).Kind == In))
                ae = new InExpression(laKind == Not);

            else return left;

            LastParsedObject = ae;

            // Skip possible !-Token
            if (laKind == Not)
                Step();

            // Skip operator
            Step();

            ae.LeftOperand = left;
            ae.RightOperand = ShiftExpression(Scope);
            return ae;
        }
Exemplo n.º 40
0
 private Expression BindContains(Expression source, Expression match, bool isRoot)
 {
     ConstantExpression constSource = source as ConstantExpression;
     if (constSource != null && !IsQuery(constSource))
     {
         Debug.Assert(!isRoot);
         List<Expression> values = new List<Expression>();
         foreach (object value in (IEnumerable) constSource.Value)
         {
             values.Add(Expression.Constant(Convert.ChangeType(value, match.Type), match.Type));
         }
         match = Visit(match);
         return new InExpression(match, values);
     }
     else
     {
         ProjectionExpression projection = VisitSequence(source);
         match = Visit(match);
         Expression result = new InExpression(match, projection.Source);
         if (isRoot)
         {
             return GetSingletonSequence(result, "SingleOrDefault");
         }
         return result;
     }
 }
Exemplo n.º 41
0
 protected virtual Expression VisitIn(InExpression @in)
 {
     var expr = this.Visit(@in.Expression);
     var select = (SelectExpression)this.Visit(@in.Select);
     var values = this.VisitExpressionList(@in.Values);
     return this.UpdateIn(@in, expr, select, values);
 }
Exemplo n.º 42
0
 protected InExpression UpdateIn(InExpression @in, Expression expression, SelectExpression select, IEnumerable<Expression> values)
 {
     if (expression != @in.Expression || select != @in.Select || values != @in.Values)
     {
         if (select != null)
         {
             return new InExpression(expression, select);
         }
         else
         {
             return new InExpression(expression, values);
         }
     }
     return @in;
 }
Exemplo n.º 43
0
        public void Visit(InExpression expression)
        {
            var values = expression.ArrayValueExpression.Values;

            if (values.IsEmpty())
            {
                throw new WeenyMapperException("Can not generate IN constraint from empty collection");
            }

            var columnName = expression.PropertyExpression.PropertyName;
            var actualValue = _row.GetColumnValue(columnName).Value;

            foreach (var value in values)
            {
                if (Equals(value, actualValue))
                    return;
            }

            _isMatch = false;
        }
Exemplo n.º 44
0
 protected override Expression VisitIn(InExpression @in)
 {
     if (@in.Values != null)
         return base.VisitIn(@in);
     else
         using (Scope())
             return base.VisitIn(@in);
 }
Exemplo n.º 45
0
 protected override Expression VisitIn(InExpression @in)
 {
     if (@in.Values != null)
     {
         if (@in.Values.Count == 0)
         {
             this.Write("0 <> 0");
         }
         else
         {
             this.VisitValue(@in.Expression);
             this.Write(" IN (");
             for (int i = 0, n = @in.Values.Count; i < n; i++)
             {
                 if (i > 0) this.Write(", ");
                 this.VisitValue(@in.Values[i]);
             }
             this.Write(")");
         }
     }
     else
     {
         this.VisitValue(@in.Expression);
         this.Write(" IN (");
         this.WriteLine(Indentation.Inner);
         this.Visit(@in.Select);
         this.WriteLine(Indentation.Same);
         this.Write(")");
         this.Indent(Indentation.Outer);
     }
     return @in;
 }
		public void Visit(InExpression x)
		{
			
		}
        ISemantic E(InExpression x, ISemantic l=null)
        {
            // The return value of the InExpression is null if the element is not in the array;
            // if it is in the array it is a pointer to the element.

            return E(x.RightOperand);
        }
Exemplo n.º 48
0
 public AbstractType Visit(InExpression x)
 {
     return(x.RightOperand != null?x.RightOperand.Accept(this) : null);
 }
Exemplo n.º 49
0
 protected override Expression VisitIn(InExpression @in)
 {
     if (@in.Select != null)
     {
         this.VisitValue(@in.Expression);
         sb.Append(" IN (");
         this.AppendNewLine(Indentation.Inner);
         this.Visit(@in.Select);
         this.AppendNewLine(Indentation.Same);
         sb.Append(")");
         this.Indent(Indentation.Outer);
     }
     else if (@in.Values != null)
     {
         if (@in.Values.Any())
         {
             this.VisitValue(@in.Expression);
             sb.Append(" IN (");
             for (int i = 0, n = @in.Values.Count; i < n; i++)
             {
                 if (i > 0) sb.Append(", ");
                 this.VisitValue(@in.Values[i]);
             }
             sb.Append(")");
         }
         else
         {
             //If Values is empty, the generated string "ColumnName IN ()" is invalid sql, but
             //  that logic should always return false, so we can just replace it with a false statement
             sb.Append(" 1 = 0 ");
         }
     }
     else
     {
         throw new Exception("Either .Values or .Select must be populated.");
     }
     return @in;
 }
Exemplo n.º 50
0
 private Expression BindContains(Expression source, Expression match, bool isRoot)
 {
     ConstantExpression constSource = source as ConstantExpression;
     if (constSource != null && !IsQuery(constSource))
     {
         System.Diagnostics.Debug.Assert(!isRoot);
         List<Expression> values = new List<Expression>();
         foreach (object value in (IEnumerable)constSource.Value)
         {
             values.Add(Expression.Constant(Convert.ChangeType(value, match.Type), match.Type));
         }
         match = this.Visit(match);
         return new InExpression(match, values);
     }
     else if (isRoot && !this.language.AllowSubqueryInSelectWithoutFrom)
     {
         var p = Expression.Parameter(TypeHelper.GetElementType(source.Type), "x");
         var predicate = Expression.Lambda(p.Equal(match), p);
         var exp = Expression.Call(typeof(Queryable), "Any", new Type[] { p.Type }, source, predicate);
         this.root = exp;
         return this.Visit(exp);
     }
     else
     {
         ProjectionExpression projection = this.VisitSequence(source);
         match = this.Visit(match);
         Expression result = new InExpression(match, projection.Select);
         if (isRoot)
         {
             return this.GetSingletonSequence(result, "SingleOrDefault");
         }
         return result;
     }
 }
Exemplo n.º 51
0
 protected override Expression VisitIn(InExpression inExpression)
 {
     Visit(inExpression.Expression);
     sb.Append(" IN (");
     if (inExpression.Select == null)
     {
         bool any = false;
         foreach (var obj in inExpression.Values)
         {
             VisitConstant(Expression.Constant(obj));
             sb.Append(",");
             any = true;
         }
         if (any)
             sb.Remove(sb.Length - 1, 1);
     }
     else
     {
         Visit(inExpression.Select);
     }
     sb.Append(" )");
     return inExpression;
 }
Exemplo n.º 52
0
 protected virtual bool CompareIn(InExpression a, InExpression b)
 {
     return this.Compare(a.Expression, b.Expression)
         && this.Compare(a.Select, b.Select)
         && this.CompareExpressionList(a.Values, b.Values);
 }
Exemplo n.º 53
0
 protected override Expression VisitIn(InExpression @in)
 {
     this.VisitValue(@in.Expression);
     sb.Append(" IN (");
     if (@in.Select != null)
     {
         this.AppendNewLine(Indentation.Inner);
         this.Visit(@in.Select);
         this.AppendNewLine(Indentation.Same);
         sb.Append(")");
         this.Indent(Indentation.Outer);
     }
     else if (@in.Values != null)
     {
         for (int i = 0, n = @in.Values.Count; i < n; i++)
         {
             if (i > 0) sb.Append(", ");
             this.VisitValue(@in.Values[i]);
         }
         sb.Append(")");
     }
     return @in;
 }
Exemplo n.º 54
0
 public void Visit(InExpression x)
 {
 }
Exemplo n.º 55
0
            protected override Expression VisitIn(InExpression expression)
            {
                if (HasNoValues(expression) && HasXmlToCursorExpression(expression.Select)) {
                    _expressions.Add(expression);
                }

                return expression;
            }
 public EntityInExpression(InExpression inExpression)
 {
     Assert.NotNull(inExpression, "InExpression must not be null");
     this.inExpression = inExpression;
 }
Exemplo n.º 57
0
 private static bool HasNoValues(InExpression expression)
 {
     return expression.Values == null;
 }
Exemplo n.º 58
0
 /// <summary>
 ///     Visits the children of the in expression.
 /// </summary>
 /// <param name="inExpression"> The expression to visit. </param>
 /// <returns> The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. </returns>
 protected abstract Expression VisitIn([NotNull] InExpression inExpression);
Exemplo n.º 59
0
 // don't count aggregates in subqueries
 protected internal override Expression VisitIn(InExpression @in)
 {
     return base.VisitIn(@in);
 }