Exemplo n.º 1
0
 private void ValidateFilterClause(FilterClause filter, ODataUrlValidationContext validationContext)
 {
     if (filter != null)
     {
         ValidateItem(filter, validationContext);
         validationContext.ExpressionValidator.ValidateNode(filter.Expression);
     }
 }
Exemplo n.º 2
0
        public void DistanceFunctionDefinedForGeometry()
        {
            FilterClause filter = ParseFilter("geo.distance(GeometryPoint, geometry'POINT(10 30)') eq 2", HardCodedTestModel.TestModel, HardCodedTestModel.GetPersonType(), HardCodedTestModel.GetPeopleSet());

            filter.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal);
            filter.Expression.As <BinaryOperatorNode>().Left.ShouldBeSingleValueFunctionCallQueryNode("geo.distance");
            filter.Expression.As <BinaryOperatorNode>().Right.ShouldBeConstantQueryNode(2d);
        }
Exemplo n.º 3
0
        public OeQueryContext CreateQueryContext(ODataUri odataUri, int pageSize, bool navigationNextLink, OeMetadataLevel metadataLevel)
        {
            List <OeParseNavigationSegment> navigationSegments = null;

            if (odataUri.Path.LastSegment is KeySegment ||
                odataUri.Path.LastSegment is NavigationPropertySegment)
            {
                navigationSegments = new List <OeParseNavigationSegment>();
                ODataPathSegment previousSegment = null;
                foreach (ODataPathSegment segment in odataUri.Path)
                {
                    if (segment is NavigationPropertySegment navigationSegment)
                    {
                        navigationSegments.Add(new OeParseNavigationSegment(navigationSegment, null));
                    }
                    else if (segment is KeySegment)
                    {
                        IEdmEntitySet previousEntitySet;
                        var           keySegment = segment as KeySegment;
                        navigationSegment = null;
                        if (previousSegment is EntitySetSegment)
                        {
                            var previousEntitySetSegment = previousSegment as EntitySetSegment;
                            previousEntitySet = previousEntitySetSegment.EntitySet;
                        }
                        else if (previousSegment is NavigationPropertySegment)
                        {
                            navigationSegment = previousSegment as NavigationPropertySegment;
                            previousEntitySet = (IEdmEntitySet)navigationSegment.NavigationSource;
                        }
                        else
                        {
                            throw new InvalidOperationException("invalid segment");
                        }

                        FilterClause keyFilter = CreateFilterClause(previousEntitySet, keySegment.Keys);
                        navigationSegments.Add(new OeParseNavigationSegment(navigationSegment, keyFilter));
                    }
                    previousSegment = segment;
                }
            }

            if (pageSize > 0)
            {
                odataUri.Top = pageSize;
                IEdmEntityType edmEntityType = GetEntityType(odataUri.Path, navigationSegments);
                odataUri.OrderBy = OeSkipTokenParser.GetUniqueOrderBy(_edmModel, edmEntityType, odataUri.OrderBy, odataUri.Apply);
            }

            var           entitySetSegment = (EntitySetSegment)odataUri.Path.FirstSegment;
            IEdmEntitySet entitySet        = entitySetSegment.EntitySet;

            Db.OeEntitySetAdapter entitySetAdapter = _dataAdapter.EntitySetAdapters.FindByEntitySetName(entitySet.Name);
            bool isCountSegment = odataUri.Path.LastSegment is CountSegment;

            return(new OeQueryContext(_edmModel, odataUri, entitySet, navigationSegments,
                                      isCountSegment, pageSize, navigationNextLink, _dataAdapter.IsDatabaseNullHighestValue, metadataLevel, entitySetAdapter));
        }
        /// <summary>
        /// Binds a <see cref="SyntacticTree"/>.
        /// </summary>
        /// <param name="syntax">The query descriptor token to bind.</param>
        /// <returns>The bound query descriptor.</returns>
        public ODataUri BindTree(SyntacticTree syntax)
        {
            ExceptionUtils.CheckArgumentNotNull(syntax, "syntax");
            ExceptionUtils.CheckArgumentNotNull(syntax.Path, "syntax.Path");

            // Make a copy of query options since we may consume some of them as we bind the query
            bindingState.QueryOptions = new List <CustomQueryOptionToken>(syntax.QueryOptions);

            ParameterAliasValueAccessor parameterAliasValueAccessor = new ParameterAliasValueAccessor(syntax.ParameterAliases);
            ODataPath          path         = null;
            FilterClause       filter       = null;
            OrderByClause      orderBy      = null;
            long?              skip         = null;
            long?              top          = null;
            SelectExpandClause selectExpand = null;
            bool?              count        = null;

            // set parameterAliasValueAccessor for uri path, $filter, $orderby
            this.bindingState.Configuration.ParameterAliasValueAccessor = parameterAliasValueAccessor;

            // First bind the path
            path = ODataPathFactory.BindPath(syntax.Path, this.bindingState.Configuration);

            // If the path leads to a collection, then create a range variable that represents iterating over the collection
            var rangeVariable = NodeFactory.CreateImplicitRangeVariable(path);

            if (rangeVariable != null)
            {
                this.bindingState.RangeVariables.Push(rangeVariable);
            }

            if (syntax.Filter != null || syntax.OrderByTokens.Any())
            {
                this.bindingState.ImplicitRangeVariable = this.bindingState.RangeVariables.Peek();
            }

            // Apply filter first, then order-by, skip, top, select and expand
            filter = BindFilter(syntax, rangeVariable);

            orderBy = BindOrderBy(syntax, rangeVariable, path);

            skip = BindSkip(syntax, rangeVariable, path);

            top = BindTop(syntax, rangeVariable, path);

            selectExpand = BindSelectExpand(syntax, path, this.bindingState.Configuration);

            count = BindQueryCount(syntax, path);

            // Add the remaining query options to the query descriptor.
            List <QueryNode> boundQueryOptions = MetadataBinder.ProcessQueryOptions(this.bindingState, this.bindMethod);

            Debug.Assert(bindingState.QueryOptions == null, "this.queryOptions == null");
            bindingState.RangeVariables.Pop();
            bindingState.ImplicitRangeVariable = null;

            return(new ODataUri(parameterAliasValueAccessor, path, boundQueryOptions, selectExpand, filter, orderBy, skip, top, count));
        }
Exemplo n.º 5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Join"/> class.
 /// </summary>
 /// <param name="joinType">Type of the join to create.</param>
 /// <param name="table">The table to join.</param>
 /// <param name="on">The join condition.</param>
 public Join(JoinType joinType, IDataSource table, ConditionBase on)
 {
     JoinType = joinType;
     Table    = table;
     if (!(on is null))
     {
         On = new FilterClause(on);
     }
 }
Exemplo n.º 6
0
        internal static SyncConfiguration DeserializeFromDmSet(DmSet set)
        {
            if (set == null)
            {
                return(null);
            }

            if (!set.Tables.Contains("DotmimSync__ServiceConfiguration"))
            {
                return(null);
            }

            SyncConfiguration configuration = new SyncConfiguration();
            var dmRowConfiguration          = set.Tables["DotmimSync__ServiceConfiguration"].Rows[0];

            configuration.BatchDirectory           = dmRowConfiguration["BatchDirectory"] as String;;
            configuration.Archive                  = dmRowConfiguration["Archive"] as String;;
            configuration.ConflictResolutionPolicy = (ConflictResolutionPolicy)dmRowConfiguration["ConflictResolutionPolicy"];
            configuration.DownloadBatchSizeInKB    = (int)dmRowConfiguration["DownloadBatchSizeInKB"];
            configuration.UseBulkOperations        = (bool)dmRowConfiguration["UseBulkOperations"];
            configuration.UseVerboseErrors         = (bool)dmRowConfiguration["UseVerboseErrors"];
            configuration.SerializationFormat      = (SerializationFormat)dmRowConfiguration["SerializationConverter"];

            if (set.Tables.Contains("DotmimSync__Filters"))
            {
                var dmTableFilterParameters = set.Tables["DotmimSync__Filters"];

                foreach (var dmRowFilter in dmTableFilterParameters.Rows)
                {
                    FilterClause filterClause = new FilterClause();

                    var tableName  = dmRowFilter["TableName"] as String;
                    var columnName = dmRowFilter["ColumnName"] as String;
                    configuration.Filters.Add(tableName, columnName);
                }
            }

            var configTables = set.Tables.Where(tbl => !tbl.TableName.StartsWith("DotmimSync__"));

            if (configTables != null)
            {
                foreach (var configTable in configTables)
                {
                    configuration.ScopeSet.Tables.Add(configTable.Clone());
                }
            }

            if (set.Relations != null && set.Relations.Count > 0)
            {
                foreach (var r in set.Relations)
                {
                    var relation = r.Clone(configuration.ScopeSet);
                    configuration.ScopeSet.Relations.Add(relation);
                }
            }
            return(configuration);
        }
Exemplo n.º 7
0
        public void IntersectsWorksInFilter()
        {
            FilterClause filter = ParseFilter("geo.intersects(GeometryPoint, GeometryPolygon)", HardCodedTestModel.TestModel, HardCodedTestModel.GetPersonType());

            filter.Expression.ShouldBeSingleValueFunctionCallQueryNode("geo.intersects");
            filter.Expression.As <SingleValueFunctionCallNode>().Parameters.Count().Should().Be(2);
            filter.Expression.As <SingleValueFunctionCallNode>().Parameters.ElementAt(0).ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPersonGeometryPointProp());
            filter.Expression.As <SingleValueFunctionCallNode>().Parameters.ElementAt(1).ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPersonGeometryPolygonProp());
        }
 public Query()
 {
     _selectClause  = new SelectClause(this);
     _fromClause    = new FromClause(this);
     _whereClause   = new FilterClause(this, AbstractQueryClause <FilterItem> .PREFIX_WHERE);
     _groupByClause = new GroupByClause(this);
     _havingClause  = new FilterClause(this, AbstractQueryClause <FilterItem> .PREFIX_HAVING);
     _orderByClause = new OrderByClause(this);
 } // constructor
Exemplo n.º 9
0
        /// <summary>Translates a <see cref="FilterClause"/> into a string.</summary>
        /// <param name="filterClause">The filter clause to translate.</param>
        /// <returns>The translated String.</returns>
        internal String TranslateFilterClause(FilterClause filterClause)
        {
            Debug.Assert(filterClause != null, "filterClause != null");
            rangeVariables.Push(filterClause.RangeVariable);
            string query = this.TranslateNode(filterClause.Expression);

            rangeVariables.Pop();
            return(query);
        }
Exemplo n.º 10
0
        public void HandlesNotStartsWith()
        {
            // Act
            var result = new FilterClause("startsWith(input, 'abcd') eq false");

            // Assert
            Assert.AreEqual(result.FieldName, "input");
            Assert.IsTrue(result.Predicate("234567"));
            Assert.IsFalse(result.Predicate("abcd"));
        }
Exemplo n.º 11
0
        public void HandlesStartsWith()
        {
            // Act
            var result = new FilterClause("startsWith(input, 'abcd')");

            // Assert
            Assert.AreEqual(result.FieldName, "input");
            Assert.IsTrue(result.Predicate("abcdef"));
            Assert.IsFalse(result.Predicate("fedcba"));
        }
Exemplo n.º 12
0
        public void HandlesNotContains()
        {
            // Act
            var result = new FilterClause("contains(input,'abcd') eq false");

            // Assert
            Assert.AreEqual(result.FieldName, "input");
            Assert.IsTrue(result.Predicate("12345"));
            Assert.IsFalse(result.Predicate("123abcd45"));
        }
Exemplo n.º 13
0
        public void HandlesNe()
        {
            // Act
            var result = new FilterClause("input ne 'abcd'");

            // Assert
            Assert.AreEqual(result.FieldName, "input");
            Assert.IsTrue(result.Predicate("dcba"));
            Assert.IsFalse(result.Predicate("abcd"));
        }
Exemplo n.º 14
0
 public void LengthFunctionWorksInFilter()
 {
     FilterClause filter = ParseFilter("geo.length(GeometryLineString) eq 2.0", HardCodedTestModel.TestModel, HardCodedTestModel.GetPersonType());
     filter.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal);
     var bon = Assert.IsType<BinaryOperatorNode>(filter.Expression);
     var functionCallNode = bon.Left.ShouldBeSingleValueFunctionCallQueryNode("geo.length");
     var parameter = Assert.Single(functionCallNode.Parameters);
     parameter.ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPersonGeometryLineStringProp());
     bon.Right.ShouldBeConstantQueryNode(2.0d);
 }
Exemplo n.º 15
0
        public void FilterSegmentConstructWithNullParameterAliasShouldThrowException()
        {
            const string filterExpression = "@a1";

            FilterClause filterClause = CreateFilterClause(filterExpression);

            Action create = () => new FilterSegment(null, filterClause.RangeVariable, HardCodedTestModel.GetPet1Set());

            Assert.Throws <ArgumentNullException>("expression", create);
        }
Exemplo n.º 16
0
        public void FilterSegmentConstructWithNullParameterAliasShouldThrowException()
        {
            const string filterExpression = "@a1";

            FilterClause filterClause = CreateFilterClause(filterExpression);

            Action create = () => new FilterSegment(null, filterClause.RangeVariable, HardCodedTestModel.GetPet1Set());

            create.ShouldThrow <ArgumentNullException>().WithMessage("Value cannot be null.\r\nParameter name: expression");
        }
Exemplo n.º 17
0
        public static string BindFilterQueryOption(FilterClause filterClause, IEdmModel model)
        {
            if (filterClause == null || model == null)
            {
                return(string.Empty);
            }
            SQLFilterBinder binder = new SQLFilterBinder(model);

            return(binder.BindFilterClause(filterClause) + Environment.NewLine);
        }
Exemplo n.º 18
0
        public void LengthFunctionWorksInFilter()
        {
            FilterClause filter = ParseFilter("geo.length(GeometryLineString) eq 2.0", HardCodedTestModel.TestModel, HardCodedTestModel.GetPersonType());

            filter.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal);
            filter.Expression.As <BinaryOperatorNode>().Left.ShouldBeSingleValueFunctionCallQueryNode("geo.length");
            filter.Expression.As <BinaryOperatorNode>().Left.As <SingleValueFunctionCallNode>().Parameters.Count().Should().Be(1);
            filter.Expression.As <BinaryOperatorNode>().Left.As <SingleValueFunctionCallNode>().Parameters.ElementAt(0).ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPersonGeometryLineStringProp());
            filter.Expression.As <BinaryOperatorNode>().Right.ShouldBeConstantQueryNode(2.0d);
        }
Exemplo n.º 19
0
        public void FilterSegmentShouldNotBeSingleResult()
        {
            const string filterExpression = "@a1";

            FilterClause       filterClause  = CreateFilterClause(filterExpression);
            ParameterAliasNode expression    = filterClause.Expression as ParameterAliasNode;
            FilterSegment      filterSegment = new FilterSegment(expression, filterClause.RangeVariable, HardCodedTestModel.GetPet1Set());

            filterSegment.SingleResult.Should().BeFalse();
        }
Exemplo n.º 20
0
        public void FilterSegmentShouldHaveSameTypeAsRangeVariableTypeDefinition()
        {
            const string filterExpression = "@a1";

            FilterClause       filterClause  = CreateFilterClause(filterExpression);
            ParameterAliasNode expression    = filterClause.Expression as ParameterAliasNode;
            FilterSegment      filterSegment = new FilterSegment(expression, filterClause.RangeVariable, HardCodedTestModel.GetPet1Set());

            filterSegment.EdmType.Equals(filterClause.RangeVariable.TypeReference.Definition).Should().BeFalse();
        }
Exemplo n.º 21
0
        public void FilterOptionSetCorrectly()
        {
            BinaryOperatorNode           filterExpression = new BinaryOperatorNode(BinaryOperatorKind.Equal, new ConstantNode(1), new ConstantNode(1));
            FilterClause                 filterClause     = new FilterClause(filterExpression, new EntityRangeVariable(ExpressionConstants.It, HardCodedTestModel.GetPersonTypeReference(), HardCodedTestModel.GetPeopleSet()));
            ExpandedNavigationSelectItem expansion        = new ExpandedNavigationSelectItem(new ODataExpandPath(new NavigationPropertySegment(ModelBuildingHelpers.BuildValidNavigationProperty(), null)), HardCodedTestModel.GetPeopleSet(), filterClause, null, null, null, null, null, null, null);

            expansion.FilterOption.Expression.ShouldBeBinaryOperatorNode(BinaryOperatorKind.Equal);
            expansion.FilterOption.Expression.As <BinaryOperatorNode>().Left.ShouldBeConstantQueryNode(1);
            expansion.FilterOption.Expression.As <BinaryOperatorNode>().Right.ShouldBeConstantQueryNode(1);
        }
        /// <summary>
        ///     Creates the price range query.
        /// </summary>
        /// <param name="priceLists">The price lists.</param>
        /// <param name="index">The index.</param>
        /// <param name="field">The field.</param>
        /// <param name="currency">The currency.</param>
        /// <param name="lowerbound">The lowerbound.</param>
        /// <param name="upperbound">The upperbound.</param>
        /// <param name="lowerboundincluded">
        ///     if set to <c>true</c> [lowerboundincluded].
        /// </param>
        /// <param name="upperboundincluded">
        ///     if set to <c>true</c> [upperboundincluded].
        /// </param>
        /// <returns></returns>
        private static BooleanFilter CreatePriceRangeQuery(
            string[] priceLists,
            int index,
            string field,
            string currency,
            string lowerbound,
            string upperbound,
            bool lowerboundincluded,
            bool upperboundincluded)
        {
            var query = new BooleanFilter();

            // create left part
            var filter =
                new TermRangeFilter(
                    String.Format("{0}_{1}_{2}", field, currency, priceLists[index - 1].ToLower()),
                    "*",
                    "*",
                    true,
                    false);
            var leftClause = new FilterClause(filter, Occur.MUST_NOT);

            query.Add(leftClause);

            // create right part
            if (index == priceLists.Count()) // last element
            {
                //var rangefilter = NumericRangeFilter.;
                var filter2 =
                    new TermRangeFilter(
                        String.Format("{0}_{1}_{2}", field, currency, priceLists[index - 1].ToLower()),
                        lowerbound,
                        upperbound,
                        lowerboundincluded,
                        upperboundincluded);
                var rightClause = new FilterClause(filter2, Occur.MUST);
                query.Add(rightClause);
            }
            else
            {
                query.Add(new FilterClause(
                              CreatePriceRangeQuery(
                                  priceLists,
                                  index + 1,
                                  field,
                                  currency,
                                  lowerbound,
                                  upperbound,
                                  lowerboundincluded,
                                  upperboundincluded),
                              Occur.SHOULD));
            }

            return(query);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Checks if the specified game must be retained accordingly to the specified filter
        /// </summary>
        /// <param name="rawGame">          PGN Raw game</param>
        /// <param name="iAvgELO">          Game average ELO</param>
        /// <param name="filterClause">     Filter clause</param>
        /// <returns>
        /// true if must be retained
        /// </returns>
        private bool IsRetained(PgnGame rawGame, int iAvgELO, FilterClause filterClause)
        {
            bool   bRetVal = true;
            string strGameResult;
            string strGameDate;

            if (iAvgELO == -1)
            {
                bRetVal = filterClause.m_bIncludesUnrated;
            }
            else if (filterClause.m_bAllRanges)
            {
                bRetVal = true;
            }
            else
            {
                iAvgELO = iAvgELO / 100 * 100;
                bRetVal = filterClause.m_hashRanges.ContainsKey(iAvgELO);
            }
            if (bRetVal)
            {
                if (!filterClause.m_bAllPlayers || !filterClause.m_bAllEnding)
                {
                    GetPGNGameInfo(rawGame, out strGameResult, out strGameDate);
                    if (!filterClause.m_bAllPlayers)
                    {
                        if (!filterClause.m_hashPlayerList.ContainsKey(rawGame.BlackPlayer) &&
                            !filterClause.m_hashPlayerList.ContainsKey(rawGame.WhitePlayer))
                        {
                            bRetVal = false;
                        }
                    }
                    if (bRetVal && !filterClause.m_bAllEnding)
                    {
                        if (strGameResult == "1-0")
                        {
                            bRetVal = filterClause.m_bEndingWhiteWinning;
                        }
                        else if (strGameResult == "0-1")
                        {
                            bRetVal = filterClause.m_bEndingBlackWinning;
                        }
                        else if (strGameResult == "1/2-1/2")
                        {
                            bRetVal = filterClause.m_bEndingDraws;
                        }
                        else
                        {
                            bRetVal = false;
                        }
                    }
                }
            }
            return(bRetVal);
        }
Exemplo n.º 24
0
        internal static ICriteria FilterContentQuery(this ICriteria criteria, FilterClause filterClause, IODataServiceMetadata metadata)
        {
            var criterionVisitor = new NHibernateCriterionVisitor(criteria, filterClause, metadata);
            var criterion        = criterionVisitor.Visit(filterClause.Expression);

            if (null != criterion)
            {
                criteria.Add(criterion);
            }
            return(criteria);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Build a SQL filter statement (e.g.: ColumA = param0).
        /// </summary>
        /// <param name="sqlFilterOperator"></param>
        /// <param name="filter"></param>
        /// <param name="index"></param>
        /// <param name="paramters"></param>
        /// <returns></returns>
        private string BuildParam(string sqlFilterOperator, FilterClause filter, int index, DynamicParameters paramters)
        {
            string parameterName = string.Empty;
            string filterClause  = string.Empty;

            parameterName = "@param" + index.ToString();
            filterClause  = sqlFilterOperator + " " + filter.BuildFilterClause + " " + parameterName;
            paramters.Add(parameterName, filter.ColumnValue);

            return(filterClause);
        }
Exemplo n.º 26
0
        public void HandlesNotIn()
        {
            // Act
            var result = new FilterClause("input in ( 1 , 2  )  eq   false");

            // Assert
            Assert.AreEqual(result.FieldName, "input");
            Assert.IsTrue(result.Predicate(3.ToString()));
            Assert.IsFalse(result.Predicate(1.ToString()));
            Assert.IsFalse(result.Predicate(2.ToString()));
        }
Exemplo n.º 27
0
        public void FilterSegmentWithExpressionShouldConstructSuccessfully()
        {
            const string filterExpression = "ID eq 1";

            FilterClause       filterClause  = CreateFilterClause(filterExpression);
            BinaryOperatorNode expression    = filterClause.Expression as BinaryOperatorNode;
            FilterSegment      filterSegment = new FilterSegment(expression, filterClause.RangeVariable, HardCodedTestModel.GetPet1Set());

            filterSegment.Expression.Equals(expression).Should().BeTrue();
            filterSegment.RangeVariable.Equals(filterClause.RangeVariable).Should().BeTrue();
        }
Exemplo n.º 28
0
        public void FilterSegmentWithAllParametersShouldConstructSuccessfully()
        {
            const string filterExpression = "@a1";

            FilterClause       filterClause  = CreateFilterClause(filterExpression);
            ParameterAliasNode expression    = filterClause.Expression as ParameterAliasNode;
            FilterSegment      filterSegment = new FilterSegment(expression, filterClause.RangeVariable, HardCodedTestModel.GetPet1Set());

            filterSegment.Expression.Equals(expression).Should().BeTrue();
            filterSegment.RangeVariable.Equals(filterClause.RangeVariable).Should().BeTrue();
        }
Exemplo n.º 29
0
        public void FilterSegmentConstructWithNullNavigationSourceShouldThrowException()
        {
            const string filterExpression = "@a1";

            FilterClause       filterClause = CreateFilterClause(filterExpression);
            ParameterAliasNode expression   = filterClause.Expression as ParameterAliasNode;

            Action create = () => new FilterSegment(expression, filterClause.RangeVariable, null);

            create.ShouldThrow <ArgumentNullException>().WithMessage("Value cannot be null.\r\nParameter name: navigationSource");
        }
Exemplo n.º 30
0
        public bool IsFilterable(FilterClause filterClause, OeModelBoundSettings settings)
        {
            if (settings != null)
            {
                var filterableVisitor = new FilterableVisitor(this, settings);
                filterClause.Expression.Accept(filterableVisitor);
                return(filterableVisitor.IsFilterable);
            }

            return(true);
        }
        /// <summary>
        ///     Builds the query.
        /// </summary>
        /// <param name="criteria">The criteria.</param>
        /// <returns></returns>
        public virtual object BuildQuery(ISearchCriteria criteria)
        {
            var queryBuilder = new QueryBuilder();
            var queryFilter = new BooleanFilter();
            var query = new BooleanQuery();
            queryBuilder.Query = query;
            queryBuilder.Filter = queryFilter;

            if (criteria.CurrentFilters != null)
            {
                foreach (var filter in criteria.CurrentFilters)
                {
                    // Skip currencies that are not part of the filter
                    if (filter.GetType() == typeof(PriceRangeFilter)) // special filtering 
                    {
                        var currency = (filter as PriceRangeFilter).Currency;
                        if (!currency.Equals(criteria.Currency, StringComparison.OrdinalIgnoreCase))
                        {
                            continue;
                        }
                    }

                    var filterQuery = LuceneQueryHelper.CreateQuery(criteria, filter, Occur.SHOULD);

                    // now add other values that should also be counted?

                    if (filterQuery != null)
                    {
                        var clause = new FilterClause(filterQuery, Occur.MUST);
                        queryFilter.Add(clause);
                    }
                }
            }

            return queryBuilder;
        }
 protected string BindFilterClause(FilterClause filterClause)
 {
     return Bind(filterClause.Expression);
 }
Exemplo n.º 33
0
        /// <summary>
        ///     Creates the price range query.
        /// </summary>
        /// <param name="priceLists">The price lists.</param>
        /// <param name="index">The index.</param>
        /// <param name="field">The field.</param>
        /// <param name="currency">The currency.</param>
        /// <param name="lowerbound">The lowerbound.</param>
        /// <param name="upperbound">The upperbound.</param>
        /// <param name="lowerboundincluded">
        ///     if set to <c>true</c> [lowerboundincluded].
        /// </param>
        /// <param name="upperboundincluded">
        ///     if set to <c>true</c> [upperboundincluded].
        /// </param>
        /// <returns></returns>
        private static BooleanFilter CreatePriceRangeQuery(
            string[] priceLists,
            int index,
            string field,
            string currency,
            string lowerbound,
            string upperbound,
            bool lowerboundincluded,
            bool upperboundincluded)
        {
            var query = new BooleanFilter();

            // create left part
            var filter =
                new TermRangeFilter(
                    String.Format("{0}_{1}_{2}", field, currency, priceLists[index - 1].ToLower()),
                    "*",
                    "*",
                    true,
                    false);
            var leftClause = new FilterClause(filter, Occur.MUST_NOT);
            query.Add(leftClause);

            // create right part
            if (index == priceLists.Count()) // last element
            {
                //var rangefilter = NumericRangeFilter.;
                var filter2 =
                    new TermRangeFilter(
                        String.Format("{0}_{1}_{2}", field, currency, priceLists[index - 1].ToLower()),
                        lowerbound,
                        upperbound,
                        lowerboundincluded,
                        upperboundincluded);
                var rightClause = new FilterClause(filter2, Occur.MUST);
                query.Add(rightClause);
            }
            else
            {
                query.Add(new FilterClause(
                    CreatePriceRangeQuery(
                        priceLists,
                        index + 1,
                        field,
                        currency,
                        lowerbound,
                        upperbound,
                        lowerboundincluded,
                        upperboundincluded),
                    Occur.SHOULD));
            }

            return query;
        }
		public virtual void VisitFilterClause (FilterClause filterClause)
		{
			VisitChildren (filterClause);
		}
		public void VisitFilterClause(FilterClause filterClause)
		{
			StartNode(filterClause);
			Space(policy.SpaceBeforeCatchParentheses);
			WriteKeyword(FilterClause.FilterKeywordRole);

			Space(policy.SpaceBeforeCatchParentheses);
			LPar();
			Space(policy.SpacesWithinCatchParentheses);
			filterClause.Expression.AcceptVisitor(this);
			Space(policy.SpacesWithinCatchParentheses);
			RPar();

			EndNode(filterClause);
		}