Example #1
0
        /// <inheritdoc />
        public override bool TryHandleEnter(
            Neo4JFilterVisitorContext context,
            IFilterField field,
            ObjectFieldNode node,
            [NotNullWhen(true)] out ISyntaxVisitorAction?action)
        {
            if (node.Value.IsNull())
            {
                context.ReportError(
                    ErrorHelper.CreateNonNullError(field, node.Value, context));

                action = SyntaxVisitor.Skip;
                return(true);
            }

            if (context.RuntimeTypes.Count > 0 &&
                context.RuntimeTypes.Peek().TypeArguments is { Count : > 0 } args)
            {
                IExtendedType element = args[0];
                context.RuntimeTypes.Push(element);
                context.AddScope();

                action = SyntaxVisitor.Continue;
                return(true);
            }

            action = null;
            return(false);
        }
Example #2
0
 protected override Expression HandleListOperation(
     QueryableFilterContext context,
     IFilterField field,
     ObjectFieldNode node,
     Type closureType,
     LambdaExpression lambda) =>
 FilterExpressionBuilder.All(closureType, context.GetInstance(), lambda);
Example #3
0
        /// <inheritdoc />
        public override bool TryHandleEnter(
            Neo4JFilterVisitorContext context,
            IFilterField field,
            ObjectFieldNode node,
            [NotNullWhen(true)] out ISyntaxVisitorAction?action)
        {
            if (node.Value.IsNull())
            {
                context.ReportError(ErrorHelper.CreateNonNullError(field, node.Value, context));

                action = SyntaxVisitor.Skip;
                return(true);
            }

            if (field.RuntimeType is null)
            {
                action = null;
                return(false);
            }

            context.GetNeo4JFilterScope().Path.Push(field.GetName());
            context.RuntimeTypes.Push(field.RuntimeType);
            action = SyntaxVisitor.Continue;
            return(true);
        }
Example #4
0
        public override bool TryHandleLeave(
            QueryableFilterContext context,
            IFilterField field,
            ObjectFieldNode node,
            [NotNullWhen(true)] out ISyntaxVisitorAction?action)
        {
            if (field.RuntimeType is null)
            {
                action = null;
                return(false);
            }

            // Deque last
            Expression condition = context.GetLevel().Dequeue();

            context.PopInstance();
            context.RuntimeTypes.Pop();

            if (context.InMemory)
            {
                condition = FilterExpressionBuilder.NotNullAndAlso(
                    context.GetInstance(), condition);
            }

            context.GetLevel().Enqueue(condition);
            action = SyntaxVisitor.Continue;
            return(true);
        }
        /// <inheritdoc />
        public override bool TryHandleLeave(
            QueryableFilterContext context,
            IFilterField field,
            ObjectFieldNode node,
            [NotNullWhen(true)] out ISyntaxVisitorAction?action)
        {
            IExtendedType runtimeType = context.RuntimeTypes.Pop();

            if (context.TryCreateLambda(out LambdaExpression? lambda))
            {
                context.Scopes.Pop();
                Expression instance   = context.PopInstance();
                Expression expression = HandleListOperation(
                    context,
                    field,
                    node,
                    runtimeType.Source,
                    lambda);

                if (context.InMemory)
                {
                    expression = FilterExpressionBuilder.NotNullAndAlso(
                        instance,
                        expression);
                }

                context.GetLevel().Enqueue(expression);
            }


            action = SyntaxVisitor.Continue;
            return(true);
        }
Example #6
0
        /// <inheritdoc />
        protected override MongoDbFilterDefinition HandleListOperation(
            MongoDbFilterVisitorContext context,
            IFilterField field,
            MongoDbFilterScope scope,
            string path)
        {
            var negatedChilds = new List <MongoDbFilterDefinition>();
            Queue <MongoDbFilterDefinition> level = scope.Level.Peek();

            while (level.Count > 0)
            {
                negatedChilds.Add(
                    new MongoDbFilterOperation(
                        path,
                        new MongoDbFilterOperation(
                            "$elemMatch",
                            new NotMongoDbFilterDefinition(level.Dequeue()))));
            }

            return(new AndFilterDefinition(
                       new MongoDbFilterOperation(
                           path,
                           new BsonDocument
            {
                { "$exists", true },
                { "$nin", new BsonArray {
                      new BsonArray(), BsonNull.Value
                  } }
            }),
                       new NotMongoDbFilterDefinition(
                           new OrMongoDbFilterDefinition(negatedChilds)
                           )));
        }
Example #7
0
 /// <inheritdoc />
 protected override MongoDbFilterDefinition HandleListOperation(
     MongoDbFilterVisitorContext context,
     IFilterField field,
     MongoDbFilterScope scope,
     string path) =>
 field.Type is IComparableOperationFilterInputType
         ? CreateArrayAllScalar(scope, path)
         : CreateArrayAll(scope, path);
Example #8
0
 /// <inheritdoc />
 public virtual bool TryHandleLeave(
     TContext context,
     IFilterField field,
     ObjectFieldNode node,
     [NotNullWhen(true)] out ISyntaxVisitorAction?action)
 {
     action = null;
     return(false);
 }
Example #9
0
 /// <inheritdoc />
 protected override MongoDbFilterDefinition HandleListOperation(
     MongoDbFilterVisitorContext context,
     IFilterField field,
     MongoDbFilterScope scope,
     string path)
 {
     return(new MongoDbFilterOperation(
                path,
                new MongoDbFilterOperation("$elemMatch", CombineOperationsOfScope(scope))));
 }
Example #10
0
        public static string GetName(this IFilterField field)
        {
            string fieldName = field.Name;

            if (field.Member is { } p)
            {
                fieldName = p.Name;
            }

            return(fieldName);
        }
Example #11
0
 protected bool TryGetParameter <T>(
     IFilterField parentField,
     IValueNode node,
     string fieldName,
     [NotNullWhen(true)] out T fieldNode)
 => SpatialOperationHandlerHelper.TryGetParameter(
     parentField,
     node,
     fieldName,
     InputParser,
     out fieldNode);
Example #12
0
 /// <inheritdoc/>
 public override bool TryHandleEnter(
     TContext context,
     IFilterField field,
     ObjectFieldNode node,
     [NotNullWhen(true)] out ISyntaxVisitorAction?action)
 {
     if (field is IFilterOperationField filterOperationField &&
         TryHandleOperation(context, filterOperationField, node, out T? result))
     {
         context.GetLevel().Enqueue(result);
         action = SyntaxVisitor.SkipAndLeave;
     }
Example #13
0
        /// <inheritdoc />
        public override bool TryHandleLeave(
            Neo4JFilterVisitorContext context,
            IFilterField field,
            ObjectFieldNode node,
            [NotNullWhen(true)] out ISyntaxVisitorAction?action)
        {
            context.RuntimeTypes.Pop();
            context.GetNeo4JFilterScope().Path.Pop();

            action = SyntaxVisitor.Continue;
            return(true);
        }
        public static Type GetReturnType(
            this IFilterField field)
        {
            if (field.Member is PropertyInfo propertyInfo)
            {
                return(propertyInfo.PropertyType);
            }
            else if (field.Member is MethodInfo methodInfo)
            {
                return(methodInfo.ReturnType);
            }

            throw new InvalidOperationException();
        }
Example #15
0
 protected override ISyntaxVisitorAction OnFieldLeave(
     TContext context,
     IFilterField field,
     ObjectFieldNode node)
 {
     if (field?.Handler is IFilterFieldHandler <TContext, T> handler &&
         handler.TryHandleLeave(
             context,
             field,
             node,
             out ISyntaxVisitorAction? action))
     {
         return(action);
     }
     return(SyntaxVisitor.Skip);
 }
Example #16
0
        public static IError CreateNonNullError <T>(
            IFilterField field,
            IValueNode value,
            IFilterVisitorContext <T> context)
        {
            IFilterInputType filterType = context.Types.OfType <IFilterInputType>().First();

            return(ErrorBuilder.New()
                   .SetMessage(
                       DataResources.ErrorHelper_CreateNonNullError,
                       context.Operations.Peek().Name,
                       filterType.Visualize())
                   .AddLocation(value)
                   .SetExtension("expectedType", new NonNullType(field.Type).Visualize())
                   .SetExtension("filterType", filterType.Visualize())
                   .Build());
        }
Example #17
0
        public static IError CreateNonNullError <T>(
            IFilterField field,
            IValueNode value,
            IFilterVisitorContext <T> context)
        {
            IFilterInputType filterType = context.Types.OfType <IFilterInputType>().First();

            return(ErrorBuilder.New()
                   .SetMessage(
                       "The provided value for filter `{0}` of type {1} is invalid. " +
                       "Null values are not supported.",
                       context.Operations.Peek().Name,
                       filterType.Visualize())
                   .AddLocation(value)
                   .SetExtension("expectedType", new NonNullType(field.Type).Visualize())
                   .SetExtension("filterType", filterType.Visualize())
                   .Build());
        }
Example #18
0
        private static QueryContainer GetQuery(
            IComparator c,
            IFilterField filter)
        {
            return(c switch
            {
                AnyWordComparator aw => GetQuery(aw, filter),
                BetweenComparator bw => GetQuery(bw, filter),
                EqualComparator eq => GetQuery(eq, filter),
                FullPhraseComparator full => GetQuery(full, filter),
                GreaterThanComparator gt => GetQuery(gt, filter),
                GreaterThanOrEqualComparator gte => GetQuery(gte, filter),
                LessThanComparator lt => GetQuery(lt, filter),
                LessThanOrEqualComparator lte => GetQuery(lte, filter),
                NotAnyWordComparator naw => GetQuery(naw, filter),
                NotEqualComparator neq => GetQuery(neq, filter),
                PartialPhraseComparator part => GetQuery(part, filter),

                _ => throw new TypeAccessException($"Type {c.GetType().FullName} not recognized as a valid comparator.")
            });
Example #19
0
        public override bool TryHandleEnter(
            QueryableFilterContext context,
            IFilterField field,
            ObjectFieldNode node,
            [NotNullWhen(true)] out ISyntaxVisitorAction?action)
        {
            if (node.Value.IsNull())
            {
                context.ReportError(
                    ErrorHelper.CreateNonNullError(field, node.Value, context));

                action = SyntaxVisitor.Skip;
                return(true);
            }

            if (field.RuntimeType is null)
            {
                action = null;
                return(false);
            }

            Expression nestedProperty;

            if (field.Member is PropertyInfo propertyInfo)
            {
                nestedProperty = Expression.Property(context.GetInstance(), propertyInfo);
            }
            else if (field.Member is MethodInfo methodInfo)
            {
                nestedProperty = Expression.Call(context.GetInstance(), methodInfo);
            }
            else
            {
                throw new InvalidOperationException();
            }

            context.PushInstance(nestedProperty);
            context.RuntimeTypes.Push(field.RuntimeType);
            action = SyntaxVisitor.Continue;
            return(true);
        }
Example #20
0
    public override bool TryHandleEnter(
        QueryableFilterContext context,
        IFilterField field,
        ObjectFieldNode node,
        [NotNullWhen(true)] out ISyntaxVisitorAction?action)
    {
        if (node.Value.IsNull())
        {
            context.ReportError(
                ErrorHelper.CreateNonNullError(field, node.Value, context));

            action = SyntaxVisitor.Skip;
            return(true);
        }

        if (field.RuntimeType is null)
        {
            action = null;
            return(false);
        }

        Expression nestedProperty = field.Member switch
        {
            PropertyInfo propertyInfo =>
            Expression.Property(context.GetInstance(), propertyInfo),

            MethodInfo methodInfo =>
            Expression.Call(context.GetInstance(), methodInfo),

            null =>
            throw ThrowHelper.QueryableFiltering_NoMemberDeclared(field),

                  _ =>
                  throw ThrowHelper.QueryableFiltering_MemberInvalid(field.Member, field)
        };

        context.PushInstance(nestedProperty);
        context.RuntimeTypes.Push(field.RuntimeType);
        action = SyntaxVisitor.Continue;
        return(true);
    }
Example #21
0
        public override bool TryHandleEnter(
            QueryableFilterContext context,
            IFilterField field,
            ObjectFieldNode node,
            [NotNullWhen(true)] out ISyntaxVisitorAction?action)
        {
            if (field is IFilterOperationField filterOperationField)
            {
                if (node.Value.IsNull())
                {
                    context.ReportError(
                        ErrorHelper.CreateNonNullError(
                            field, node.Value, context));
                    action = SyntaxVisitor.Skip;
                    return(true);
                }

                if (!TryHandleOperation(
                        context,
                        filterOperationField,
                        node,
                        out Expression? nestedProperty))
                {
                    context.ReportError(
                        ErrorHelper.CouldNotCreateFilterForOperation(
                            field, node.Value, context));
                    action = SyntaxVisitor.Skip;
                    return(true);
                }

                context.RuntimeTypes.Push(_runtimeType);
                context.PushInstance(nestedProperty);
                action = SyntaxVisitor.Continue;
            }
            else
            {
                action = SyntaxVisitor.Break;
            }

            return(true);
        }
Example #22
0
        public static bool TryGetParameter <T>(
            IFilterField parentField,
            IValueNode node,
            string fieldName,
            [NotNullWhen(true)] out T fieldNode)
        {
            if (parentField.Type is InputObjectType inputType &&
                node is ObjectValueNode objectValueNode)
            {
                for (var i = 0; i < objectValueNode.Fields.Count; i++)
                {
                    if (objectValueNode.Fields[i].Name.Value == fieldName)
                    {
                        ObjectFieldNode field = objectValueNode.Fields[i];
                        if (inputType.Fields[fieldName].Type.ParseLiteral(field.Value) is T val)
                        {
                            fieldNode = val;
                            return(true);
                        }

                        fieldNode = default !;
Example #23
0
 /// <inheritdoc />
 protected override MongoDbFilterDefinition HandleListOperation(
     MongoDbFilterVisitorContext context,
     IFilterField field,
     MongoDbFilterScope scope,
     string path)
 {
     return(new AndFilterDefinition(
                new MongoDbFilterOperation(
                    path,
                    new BsonDocument
     {
         { "$exists", true },
         { "$nin", new BsonArray {
               new BsonArray(), BsonNull.Value
           } }
     }),
                new MongoDbFilterOperation(
                    path,
                    new NotMongoDbFilterDefinition(
                        new MongoDbFilterOperation("$elemMatch", CombineOperationsOfScope(scope)))
                    )));
 }
Example #24
0
        /// <inheritdoc />
        public override bool TryHandleLeave(
            Neo4JFilterVisitorContext context,
            IFilterField field,
            ObjectFieldNode node,
            [NotNullWhen(true)] out ISyntaxVisitorAction?action)
        {
            context.RuntimeTypes.Pop();

            if (context.TryCreateQuery(out CompoundCondition? query) &&
                context.Scopes.Pop() is Neo4JFilterScope scope)
            {
                var path = context.GetNeo4JFilterScope().GetPath();

                Condition combinedOperations =
                    HandleListOperation(context, field, scope, path);

                context.GetLevel().Enqueue(combinedOperations);
            }

            action = SyntaxVisitor.Continue;
            return(true);
        }
Example #25
0
        /// <summary>
        ///   Converts a list of FilterLine objects to a WHERE clause usable in a SQL select query.</summary>
        /// <param name="lines">
        ///   List of FilterLine objects to convert to a WHERE clause.</param>
        /// <param name="filterFields">
        ///   Collection of FilterField objects to determine field types and check filterability of fields.
        ///   This list is usually the filter field options list that is sent to a filter panel object.
        ///   If this list is specified, for a filter to be considered valid, its fieldname must be
        ///   found in the list. If the list is given null, field name is looked up in fieldExpressions,
        ///   query or row and field type is determined by the field object in the row.</param>
        /// <param name="fieldExpressions">
        ///   An optional dictionary of field expressions. If a field's corresponding SQL expression like
        ///   "join.field_name" is not determinable by reading in the query or the row, this list must be specified.
        ///   When specified, this list takes priority over the query and row objects to determine the field
        ///   expression.</param>
        /// <param name="query">
        ///   An optional SqlSelect query to determine field expressions. If a field's expression is not found
        ///   in "fieldExpressions" dictionary, it is looked up in query object.</param>
        /// <param name="row">
        ///   An optional Row object to determine field types and expressions.</param>
        /// <param name="process">
        ///   An optional delegate to preprocess a filter line and return a filter. It should return an empty
        ///   filter if this line should be ignored. Null if this line should be processed as usual.</param>
        /// <returns>
        ///   WHERE clause.</returns>
        /// <remarks>
        ///   Invalid filter lines are simply skipped, no error occurs.</remarks>
        public static string ToWhereString(SqlQuery query, IEnumerable <FilterLine> lines, FilterFields filterFields,
                                           IDictionary <string, string> fieldExpressions = null, Row row = null, Func <FilterLine, BaseCriteria> process = null)
        {
            if (lines == null)
            {
                throw new ArgumentNullException("lines");
            }

            const string AND    = " AND ";
            const string OR     = " OR ";
            const string LPAREN = "(";
            const string RPAREN = ")";
            //const string TRUE = "1=1";

            // build a dictionary of FilterField objects if the list is specified
            // this list is usually the filter field options list that is sent to FilterPanel object.

            /*Dictionary<string, FilterField> filterFieldDict = null;
             * if (filterFields != null)
             * {
             *  filterFieldDict = new Dictionary<string, FilterField>(StringComparer.OrdinalIgnoreCase);
             *  foreach (FilterField f in filterFields)
             *  {
             *      filterFieldDict[f.GetName()] = f;
             *
             *      if (f.GetTextual() != null)
             *          filterFieldDict[f.GetTextual()] = f;
             *  }
             * }*/

            bool inParens = false;
            bool hasOr    = false;

            StringBuilder sb = new StringBuilder();

            foreach (FilterLine line in lines)
            {
                if (inParens &&
                    (line._rightParen || line._leftParen))
                {
                    sb.Append(RPAREN);
                    inParens = false;
                }

                if (sb.Length > 0)
                {
                    sb.Append(line._or ? OR : AND);
                    if (line._or)
                    {
                        hasOr = true;
                    }
                }

                if (line._leftParen)
                {
                    sb.Append(LPAREN);
                    inParens = true;
                }

                if (!line.IsValid)
                {
                    throw new ArgumentOutOfRangeException("InvalidFilterLine", line.ToJson());
                    //sb.Append(TRUE);
                    //continue;
                }

                if (process != null)
                {
                    var filter = process(line);
                    if (!Object.ReferenceEquals(filter, null))
                    {
                        if (filter.IsEmpty)
                        {
                            //sb.Append(TRUE);
                            throw new ArgumentOutOfRangeException("EmptyFilterLine", line.ToJson());
                        }
                        else
                        {
                            sb.Append(filter.ToStringIgnoreParams()); // FIX!!!!
                        }
                        continue;
                    }
                }

                string fieldName = line.Field;

                // if filter fields list is specified, the fieldname must exist in this list, otherwise
                // it may be an hacking attempt, as user tries to filter a field that he is not
                // represented with
                IFilterField filterField = null;
                if (filterFields != null)
                {
                    filterField = filterFields.ByNameOrTextual(fieldName);
                    if (filterField == null)
                    {
                        throw new ArgumentOutOfRangeException("UnknownFilterField", line.ToJson());
                    }
                    //sb.Append(TRUE);
                    //continue;
                }

                Field field = null;
                if (row != null)
                {
                    field = row.FindField(fieldName);
                }


                /*// by default, suppose fields are string typed
                 * FilterFieldType type = FilterFieldType.String;
                 * // if given, determine field type by looking up in the filter field options
                 * if (filterField != null)
                 *  type = filterField.GetType();
                 * // otherwise, determine field type by the class of field object
                 * else if (field != null)
                 *  type = FilterField.ToFilterFieldType(field);*/

                // to determine field expression, first look it up in fieldExpressions dictionary
                string fieldExpr;
                if (fieldExpressions == null ||
                    !fieldExpressions.TryGetValue(fieldName, out fieldExpr))
                {
                    fieldExpr = null;
                }

                if (fieldExpr == null)
                {
                    if (field != null)
                    {
                        fieldExpr = field.Expression;
                    }
                    else if (query != null)
                    {
                        fieldExpr = query.GetExpression(fieldName);
                    }
                }

                if (fieldExpr == null)
                {
                    // field is not found anywhere, don't allow unknown fields as it may cause a script injection
                    // attack or other types of security threats!
                    //sb.Append(TRUE);
                    throw new ArgumentOutOfRangeException("UnknownFilterField", line.ToJson());
                    //continue;
                }

                bool isNumeric =
                    (filterField != null && (filterField.Handler == "Integer" || filterField.Handler == "Decimal")) ||
                    (filterField == null && field != null &&
                     (field is Int16Field || field is Int32Field || field is Int64Field || field is DoubleField || field is DecimalField));

                // determine expression for this filter by operator type
                FilterOp op    = line.Op;
                string   sqlOp = SqlConditionOperators[(int)(op)];

                if (op == FilterOp.IN)
                {
                    StringBuilder vs = new StringBuilder();

                    var values = line.Values;
                    if (line.Values != null)
                    {
                        foreach (var s in line.Values)
                        {
                            if (isNumeric)
                            {   // parse invariant decimal value for integer and float fields
                                decimal d;
                                if (Decimal.TryParse(s, NumberStyles.Float, Invariants.NumberFormat, out d))
                                {
                                    if (vs.Length > 0)
                                    {
                                        vs.Append(",");
                                    }
                                    vs.Append(d.ToInvariant());
                                }
                            }
                            else
                            {
                                if (vs.Length > 0)
                                {
                                    vs.Append(",");
                                }
                                vs.Append(s.ToSql());
                            }
                        }
                    }

                    if (vs.Length == 0)
                    {
                        //sb.Append(TRUE);
                        throw new ArgumentOutOfRangeException("InvalidFilterLine", line.ToJson());
                    }
                    else
                    {
                        sb.AppendFormat(sqlOp, fieldExpr, vs.ToString());
                    }

                    continue;
                }

                // operator needs value if not one of "true", "false", "is null", "is not null"
                if (op.IsNeedsValue())
                {
                    // starts with and contains operators requires special care, as their sql expressions
                    // already contains single quotes, so .ToSql() cannot be used
                    if (op.IsLike())
                    {
                        if (line.Value != null)
                        {
                            sb.AppendFormat(SqlConditionOperators[(int)(op)],
                                            fieldExpr, line.Value.Replace("'", "''"));
                        }
                        continue;
                    }

                    // parse value1 and value2
                    string value1 = "";
                    string value2 = "";

                    // simple loop to parse value1 and value2 in one turn
                    for (int phase = 0; phase <= 1; phase++)
                    {
                        string valueText;

                        if (phase == 0)
                        {
                            valueText = line.Value;
                        }
                        else
                        {
                            valueText = line.Value2;
                        }

                        valueText = valueText.TrimToNull();

                        // value must be entered
                        if (valueText == null)
                        {
                            throw new ArgumentOutOfRangeException("InvalidFilterLine", line.ToJson());
                        }

                        bool isDateTime =
                            (filterField != null && (filterField.Handler == "Date")) ||
                            (filterField == null && field != null &&
                             (field is DateTimeField));

                        if (isNumeric)
                        {   // parse invariant decimal value for integer and float fields
                            decimal d;
                            if (!Decimal.TryParse(valueText, NumberStyles.Float, Invariants.NumberFormat, out d))
                            {
                                throw new ArgumentOutOfRangeException("InvalidFilterLine", line.ToJson());
                            }

                            valueText = d.ToInvariant();
                        }
                        else if (isDateTime)
                        {   // parse iso date-time string
                            DateTime d;
                            if (!DateHelper.TryParseISO8601DateTime(valueText, out d))
                            {
                                throw new ArgumentOutOfRangeException("InvalidFilterLine", line.ToJson());
                            }

                            DateTimeKind kind = DateTimeKind.Unspecified;
                            object       dateKindObj;
                            if (filterField != null && filterField.Params != null && filterField.Params.TryGetValue("DateKind", out dateKindObj))
                            {
                                var dateKind = ((DateFilterKind)Convert.ToInt32(dateKindObj));
                                kind = dateKind == DateFilterKind.DateTimeLocal ? DateTimeKind.Local : (dateKind == DateFilterKind.DateTimeUTC ? DateTimeKind.Utc : DateTimeKind.Unspecified);
                            }
                            else if (field != null && field is DateTimeField)
                            {
                                kind = ((DateTimeField)field).DateTimeKind;
                            }

                            d = DateTimeField.ToDateTimeKind(d, kind);

                            if (op == FilterOp.BW)
                            {
                                if (phase == 1)
                                {
                                    sqlOp = "{0} >= {1} AND {0} < {2}";
                                    d     = d.AddDays(1);
                                }
                            }
                            else if (phase == 0)
                            {
                                if (op == FilterOp.NE || op == FilterOp.EQ)
                                {
                                    value1 = d.ToSql();
                                    value2 = d.AddDays(1).ToSql();
                                    if (op == FilterOp.NE)
                                    {
                                        sqlOp = "NOT ({0} >= {1} AND {0} < {2})";
                                    }
                                    else
                                    {
                                        sqlOp = "{0} >= {1} AND {0} < {2}";
                                    }
                                    op = FilterOp.BW;
                                    break;
                                }
                                else
                                {
                                    if (op == FilterOp.GT)
                                    {
                                        op = FilterOp.GE;
                                        d  = d.AddDays(1);
                                    }
                                    else if (op == FilterOp.LE)
                                    {
                                        op = FilterOp.LT;
                                        d  = d.AddDays(1);
                                    }
                                }
                            }

                            valueText = d.ToSql();
                        }
                        else // convert simple string value to sql string (duplicate quotes)
                        {
                            valueText = valueText.ToSql();
                        }

                        if (phase == 0)
                        {
                            value1 = valueText;
                        }
                        else
                        {
                            value2 = valueText;
                        }

                        // use second phase to parse value2 if operator is BW
                        if (op != FilterOp.BW)
                        {
                            break;
                        }
                    }

                    // format sql operator text with values
                    if (op == FilterOp.BW)
                    {
                        sb.AppendFormat(sqlOp, fieldExpr, value1, value2);
                    }
                    else
                    {
                        sb.AppendFormat(sqlOp, fieldExpr, value1);
                    }
                }
                else
                {
                    sb.AppendFormat(sqlOp, fieldExpr);
                }
            }

            if (inParens)
            {
                sb.Append(RPAREN);
            }

            if (hasOr)
            {
                sb.Append(RPAREN);
                sb.Insert(0, LPAREN);
            }

            return(sb.ToString());
        }
Example #26
0
 /// <summary>
 /// Maps a operation field to a mongodb list filter definition.
 /// This method is called when the <see cref="FilterVisitor{TContext,T}"/> enters a
 /// field
 /// </summary>
 /// <param name="context">The context of the visitor</param>
 /// <param name="field">The currently visited filter field</param>
 /// <param name="scope">The current scope of the visitor</param>
 /// <param name="path">The path that leads to this visitor</param>
 /// <returns></returns>
 protected abstract MongoDbFilterDefinition HandleListOperation(
     MongoDbFilterVisitorContext context,
     IFilterField field,
     MongoDbFilterScope scope,
     string path);
        private BaseCriteria Convert(BasicFilter filter)
        {
            if (filter == null)
            {
                throw new ArgumentNullException("criteria");
            }

            if (!filter.IsValid)
            {
                throw new ArgumentOutOfRangeException("InvalidFilterCriteria", filter.ToJson());
            }

            if (_processCriteria != null)
            {
                var processed = _processCriteria(filter);
                if (!Object.ReferenceEquals(processed, null))
                {
                    if (processed.IsEmpty)
                    {
                        throw new ArgumentOutOfRangeException("EmptyFilterLine", filter.ToJson());
                    }

                    return(processed);
                }
            }

            string fieldName = filter.Field;

            Field field = null;

            if (_row != null)
            {
                field = _row.FindField(fieldName);
            }

            // if filter fields list is specified, the fieldname must exist in this list, otherwise
            // it may be an hacking attempt, as user tries to filter a field that he is not
            // represented with
            IFilterField filterField = null;

            if (filterFields != null)
            {
                filterField = filterFields.ByNameOrTextual(fieldName);
                if (filterField == null &&
                    (field == null || field.Flags.HasFlag(FieldFlags.DenyFiltering)))
                {
                    throw new ArgumentOutOfRangeException("UnknownFilterField", fieldName);
                }
            }

            //var type = GetFilterFieldType(field, fieldName);
            var fieldExpr = GetFieldExpression(field, fieldName);

            if (fieldExpr == null)
            {
                // field is not found anywhere, don't allow unknown fields as it may cause a script injection
                // attack or other types of security threats!
                throw new ArgumentOutOfRangeException("UnknownFilterField", filter.ToJson());
            }

            bool isInteger = (filterField != null && (filterField.Handler == "Integer")) ||
                             (filterField == null && field != null && (field is Int16Field || field is Int32Field || field is Int64Field));

            bool isDecimal = (filterField != null && (filterField.Handler == "Decimal")) ||
                             (filterField == null && field != null && (field is DoubleField || field is DecimalField));

            bool isNumeric = isInteger || isDecimal;

            bool isDateTime =
                (filterField != null && (filterField.Handler == "Date")) ||
                (filterField == null && field != null &&
                 (field is DateTimeField));

            var op = filter.Operator;

            switch (op)
            {
            case FilterOp.True:
                return(new Criteria(fieldExpr) == 1);

            case FilterOp.False:
                return(new Criteria(fieldExpr) == 0);

            case FilterOp.IsNull:
                return(new Criteria(fieldExpr).IsNull());

            case FilterOp.IsNotNull:
                return(new Criteria(fieldExpr).IsNotNull());

            case FilterOp.Like:
                return(new Criteria(fieldExpr).Like(filter.Value));

            case FilterOp.NotLike:
                return(new Criteria(fieldExpr).NotLike(filter.Value));

            case FilterOp.Contains:
                return(new Criteria(fieldExpr).Contains(filter.Value));

            case FilterOp.NotContains:
                return(new Criteria(fieldExpr).NotContains(filter.Value));

            case FilterOp.StartsWith:
                return(new Criteria(fieldExpr).StartsWith(filter.Value));

            case FilterOp.EndsWith:
                return(new Criteria(fieldExpr).EndsWith(filter.Value));

            case FilterOp.IN:
            case FilterOp.NotIN:
            {
                var values = new List <object>();
                foreach (var s in filter.Values)
                {
                    if (isDecimal)
                    {
                        values.Add(ParseDoubleValue(s));
                    }
                    else if (isInteger)
                    {
                        values.Add(ParseIntegerValue(field, s));
                    }
                    else
                    {
                        values.Add(s);
                    }
                }

                if (values.Count == 0)
                {
                    throw new ArgumentOutOfRangeException("InvalidFilterLine", filter.ToJson());
                }

                if (op == FilterOp.IN)
                {
                    return(new Criteria(fieldExpr).In(values.ToArray()));
                }
                else
                {
                    return(new Criteria(fieldExpr).NotIn(values.ToArray()));
                }
            }
            }

            // parse value1 and value2
            string value1Text = filter.Value.TrimToEmpty();
            string value2Text = filter.Value2.TrimToEmpty();

            if ((op == FilterOp.BW || op == FilterOp.NotBW))
            {
                if (value1Text.IsNullOrEmpty() || value2Text.IsNullOrEmpty())
                {
                    throw new ArgumentOutOfRangeException("InvalidFilterLine", filter.ToJson());
                }

                if (isInteger)
                {
                    return(new Criteria(fieldExpr) >= ParseIntegerValue(field, value1Text) &
                           new Criteria(fieldExpr) <= ParseIntegerValue(field, value2Text));
                }
                else if (isDecimal)
                {
                    return(new Criteria(fieldExpr) >= ParseDoubleValue(value1Text) &
                           new Criteria(fieldExpr) <= ParseDoubleValue(value2Text));
                }
                else if (isDateTime)
                {
                    var d1 = ParseDateTimeValue(value1Text);
                    var d2 = ParseDateTimeValue(value2Text);

                    if (d1.Date == d1 && d2.Date == d2)
                    {
                        if (op == FilterOp.BW)
                        {
                            return(new Criteria(fieldExpr) >= d1.Date & new Criteria(fieldExpr) < d2.Date.AddDays(1));
                        }
                        else
                        {
                            return(~(new Criteria(fieldExpr) < d1.Date | new Criteria(fieldExpr) >= d2.Date.AddDays(1)));
                        }
                    }
                    else
                    {
                        if (op == FilterOp.BW)
                        {
                            return(new Criteria(fieldExpr) >= d1 & new Criteria(fieldExpr) <= d2);
                        }
                        else
                        {
                            return(~((new Criteria(fieldExpr) < d1 | new Criteria(fieldExpr) > d2)));
                        }
                    }
                }
                else
                {
                    if (op == FilterOp.BW)
                    {
                        return(new Criteria(fieldExpr) >= value1Text & new Criteria(fieldExpr) <= value2Text);
                    }
                    else
                    {
                        return(~((new Criteria(fieldExpr) < value2Text | new Criteria(fieldExpr) > value2Text)));
                    }
                }
            }

            var result = new Criteria(fieldExpr);

            if (isInteger)
            {
                var i = ParseIntegerValue(field, value1Text);
                if (op == FilterOp.EQ)
                {
                    return(result == i);
                }
                else if (op == FilterOp.NE)
                {
                    return(result != i);
                }
                else if (op == FilterOp.GT)
                {
                    return(result > i);
                }
                else if (op == FilterOp.GE)
                {
                    return(result >= i);
                }
                else if (op == FilterOp.LT)
                {
                    return(result < i);
                }
                else if (op == FilterOp.LE)
                {
                    return(result <= i);
                }
            }
            else if (isDecimal)
            {
                var o = ParseIntegerValue(field, value1Text);
                if (op == FilterOp.EQ)
                {
                    return(result == o);
                }
                else if (op == FilterOp.NE)
                {
                    return(result != o);
                }
                else if (op == FilterOp.GT)
                {
                    return(result > o);
                }
                else if (op == FilterOp.GE)
                {
                    return(result >= o);
                }
                else if (op == FilterOp.LT)
                {
                    return(result < o);
                }
                else if (op == FilterOp.LE)
                {
                    return(result <= o);
                }
            }
            else if (isDateTime)
            {
                var d = ParseDateTimeValue(value1Text);
                if (d.Date == d)
                {
                    if (op == FilterOp.EQ)
                    {
                        return(result >= d & result < d.AddDays(1));
                    }
                    else if (op == FilterOp.NE)
                    {
                        return(~(result < d | result >= d.AddDays(1)));
                    }
                    else if (op == FilterOp.GT)
                    {
                        return(result >= d.AddDays(1));
                    }
                    else if (op == FilterOp.GE)
                    {
                        return(result >= d);
                    }
                    else if (op == FilterOp.LT)
                    {
                        return(result < d);
                    }
                    else if (op == FilterOp.LE)
                    {
                        return(result < d.AddDays(1));
                    }
                }
                else
                {
                    if (op == FilterOp.EQ)
                    {
                        return(result == d);
                    }
                    else if (op == FilterOp.NE)
                    {
                        return(result != d);
                    }
                    else if (op == FilterOp.GT)
                    {
                        return(result > d);
                    }
                    else if (op == FilterOp.GE)
                    {
                        return(result >= d);
                    }
                    else if (op == FilterOp.LT)
                    {
                        return(result < d);
                    }
                    else if (op == FilterOp.LE)
                    {
                        return(result <= d);
                    }
                }
            }
            else
            {
                if (op == FilterOp.EQ)
                {
                    return(result == value1Text);
                }
                else if (op == FilterOp.NE)
                {
                    return(result != value1Text);
                }
                else if (op == FilterOp.GT)
                {
                    return(result > value1Text);
                }
                else if (op == FilterOp.GE)
                {
                    return(result >= value1Text);
                }
                else if (op == FilterOp.LT)
                {
                    return(result < value1Text);
                }
                else if (op == FilterOp.LE)
                {
                    return(result <= value1Text);
                }
            }

            throw new InvalidOperationException();
        }
 /// <summary>
 /// Maps a operation field to a list filter definition.
 /// This method is called when the <see cref="FilterVisitor{TContext,T}"/> enters a
 /// field
 /// </summary>
 /// <param name="context">The context of the visitor</param>
 /// <param name="field">The currently visited filter field</param>
 /// <param name="closureType">The runtime type of the scope</param>
 /// <param name="lambda">The expression of the nested operations</param>
 /// <returns></returns>
 protected abstract Expression HandleListOperation(
     QueryableFilterContext context,
     IFilterField field,
     ObjectFieldNode node,
     Type closureType,
     LambdaExpression lambda);
Example #29
0
 /// <summary>
 /// Maps a operation field to a Neo4J list filter definition.
 /// This method is called when the <see cref="FilterVisitor{TContext,T}"/> enters a
 /// field
 /// </summary>
 /// <param name="context">The context of the visitor</param>
 /// <param name="field">The currently visited filter field</param>
 /// <param name="scope">The current scope of the visitor</param>
 /// <param name="path">The path that leads to this visitor</param>
 /// <returns></returns>
 protected abstract Condition HandleListOperation(
     Neo4JFilterVisitorContext context,
     IFilterField field,
     Neo4JFilterScope scope,
     string path);
Example #30
0
 public static QueryContainer GetQueryContainer(IFilterField filter)
 {
     return(comparatorQueries[filter.Comparator.Value]?.Invoke(filter.Comparator, filter));
 }