Exemplo n.º 1
0
        public override SQ.Entity OnBuildQueryNode(QueryBuilderContext context, bool allowReuse)
        {
            if (context.Settings.ContextEntity == null)
            {
                return(null);
            }

            var contextEntity = context.Settings.ContextEntity;

            SQ.Entity result;

            if (allowReuse)
            {
                result = contextEntity;
            }
            else
            {
                var proxy = new SQ.JoinToSelfEntity( );
                proxy.EntityTypeId = contextEntity.EntityTypeId;   // just in case
                result             = proxy;
            }

            AddChildNodes(context, result, allowReuse);
            return(result);
        }
Exemplo n.º 2
0
        public override SQ.Entity OnBuildQueryNode(QueryBuilderContext context, bool allowReuse)
        {
            // Find a node
            if (ChildContainer.ChildEntityNodes.Count > 1)
            {
                throw new Exception("Cross-join in report calculations are unsupported.");
            }

            SQ.Entity reportNode;
            if (ChildContainer.ChildEntityNodes.Count == 0)
            {
                reportNode = new SingleRowNode( );
            }
            else
            {
                reportNode = ChildContainer.ChildEntityNodes.Single( ).BuildQueryNode(context, false);
            }

            // Attach conditions
            ScalarExpression condition = Right.BuildQuery(context);

            if (reportNode.Conditions == null)
            {
                reportNode.Conditions = new List <ScalarExpression>();
            }
            reportNode.Conditions.Add(condition);

            return(reportNode);
        }
        public void Build <T>(QueryBuilderContext <T> ctx) where T : class, new()
        {
            var softDeletesQuery = ctx.GetSourceAs <ISoftDeletesQuery>();

            if (softDeletesQuery == null || softDeletesQuery.IncludeSoftDeletes)
            {
                return;
            }

            var idsQuery = ctx.GetSourceAs <IIdentityQuery>();
            var opt      = ctx.GetOptionsAs <IElasticQueryOptions>();

            if (opt == null || !opt.SupportsSoftDeletes || (idsQuery != null && idsQuery.Ids.Count > 0))
            {
                return;
            }

            var missingFilter = new MissingFilter {
                Field = Deleted
            };
            var termFilter = new TermFilter {
                Field = Deleted, Value = softDeletesQuery.IncludeSoftDeletes
            };

            ctx.Filter &= (new FilterContainer(missingFilter) || new FilterContainer(termFilter));
        }
Exemplo n.º 4
0
        public Task BuildAsync <T>(QueryBuilderContext <T> ctx) where T : class, new()
        {
            var stackIds         = ctx.Source.GetStacks();
            var excludedStackIds = ctx.Source.GetExcludedStacks();

            if (stackIds.Count == 1)
            {
                ctx.Filter &= Query <T> .Term(_stackIdFieldName, stackIds.Single());
            }
            else if (stackIds.Count > 1)
            {
                ctx.Filter &= Query <T> .Terms(d => d.Field(_stackIdFieldName).Terms(stackIds));
            }

            if (excludedStackIds.Count == 1)
            {
                ctx.Filter &= Query <T> .Bool(b => b.MustNot(Query <T> .Term(_stackIdFieldName, excludedStackIds.Single())));
            }
            else if (excludedStackIds.Count > 1)
            {
                ctx.Filter &= Query <T> .Bool(b => b.MustNot(Query <T> .Terms(d => d.Field(_stackIdFieldName).Terms(excludedStackIds))));
            }

            return(Task.CompletedTask);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Returns a tree node that is representative of an entity or.
        /// </summary>
        /// <param name="context">Context information about this query building session, including the target structured query object.</param>
        /// <param name="allowReuse">A dedicated node should be returned because the caller intends on disturbing it.</param>
        /// <returns>A query node that can be used within the query.</returns>
        public override SQ.Entity OnBuildQueryNode(QueryBuilderContext context, bool allowReuse)
        {
            SQ.Entity result = context.ResolveParameterNode(ParameterName);

            AddChildNodes(context, result, allowReuse);

            return(result);
        }
Exemplo n.º 6
0
 protected void AddChildNodes(QueryBuilderContext context, SQ.Entity parent, bool allowReuse)
 {
     context.ParentNodeStack.Push(parent);
     foreach (var node in ChildContainer.ChildEntityNodes)
     {
         node.BuildQueryNode(context, allowReuse);
     }
     context.ParentNodeStack.Pop();
 }
Exemplo n.º 7
0
        protected override ScalarExpression OnBuildQuery(QueryBuilderContext context)
        {
            var result = new SQ.ResourceExpression
            {
                NodeId  = context.GetNode(this).NodeId,
                FieldId = new EntityRef("core:name")
            };

            return(result);
        }
Exemplo n.º 8
0
        protected override ScalarExpression OnBuildQuery(QueryBuilderContext context)
        {
            var queryNode = context.GetNode(Argument);
            var result    = new EDC.ReadiNow.Metadata.Query.Structured.IdExpression
            {
                NodeId = queryNode.NodeId
            };

            return(result);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Convert the expression tree into a structured query expression.
        /// </summary>
        /// <param name="context">Context information about this query building session, including the target structured query object.</param>
        /// <param name="allowReuse">if set to <c>true</c> [allow reuse].</param>
        /// <returns>
        /// A query node that can be used within the query.
        /// </returns>
        public EDC.ReadiNow.Metadata.Query.Structured.Entity BuildQueryNode(QueryBuilderContext context, bool allowReuse)
        {
            EDC.ReadiNow.Metadata.Query.Structured.Entity result;

            if (!context.NodeCache.TryGetValue(this, out result))
            {
                result = OnBuildQueryNode(context, allowReuse);
                context.NodeCache[this] = result;
            }
            return(result);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Convert the expression tree into a structured query expression.
        /// </summary>
        /// <param name="context">Context information about this query building session, including the target structured query object.</param>
        /// <returns>A scalar expression that can be used within the query.</returns>
        public ScalarExpression BuildQuery(QueryBuilderContext context)
        {
            ScalarExpression result = OnBuildQuery(context);

            //if (!context.ExpressionCache.TryGetValue(this, out result))
            //{
            //    result = OnBuildQuery(context);
            //    context.ExpressionCache[this] = result;
            //}
            return(result);
        }
Exemplo n.º 11
0
        protected override ScalarExpression OnBuildQuery(QueryBuilderContext context)
        {
            if (ResultType.Type != DataType.String)
            {
                throw new InvalidOperationException(ResultType.Type.ToString());
            }

            ScalarExpression argument = Argument.BuildQuery(context);
            var result = CastToString(argument);

            return(result);
        }
Exemplo n.º 12
0
 protected override void DisposeCore()
 {
     lock (_lockObject)
     {
         _connectionDbRepository  = null;
         _projectsRepository      = null;
         _projectsShareRepository = null;
         _queriesRepository       = null;
         _usersRepository         = null;
     }
     QueryBuilderContext.Dispose();
 }
        public Task BuildAsync <T>(QueryBuilderContext <T> ctx) where T : class, new()
        {
            var emailAddress = ctx.Source.GetEmailAddress();

            if (String.IsNullOrEmpty(emailAddress))
            {
                return(Task.CompletedTask);
            }

            ctx.Filter &= Query <Employee> .Term(f => f.EmailAddress, emailAddress);

            return(Task.CompletedTask);
        }
Exemplo n.º 14
0
        protected override ScalarExpression OnBuildQuery(QueryBuilderContext context)
        {
            var result = new ComparisonExpression
            {
                Operator    = InvertResult ? ComparisonOperator.IsNotNull : ComparisonOperator.IsNull,
                Expressions = new List <ScalarExpression>
                {
                    Left.BuildQuery(context)
                }
            };

            return(result);
        }
Exemplo n.º 15
0
        public void Build <T>(QueryBuilderContext <T> ctx) where T : class, new()
        {
            var organizationIdQuery = ctx.GetSourceAs <IOrganizationIdQuery>();

            if (organizationIdQuery?.OrganizationIds == null || organizationIdQuery.OrganizationIds.Count <= 0)
            {
                return;
            }

            ctx.Filter &= new TermsFilter {
                Terms = organizationIdQuery.OrganizationIds, Field = "organization"
            };
        }
Exemplo n.º 16
0
        public void Build <T>(QueryBuilderContext <T> ctx) where T : class, new()
        {
            var sfq = ctx.GetSourceAs <IExceptionlessSystemFilterQuery>();

            if (sfq == null)
            {
                return;
            }

            var allowedOrganizations = sfq.Organizations.Where(o => o.HasPremiumFeatures || (!o.HasPremiumFeatures && !sfq.UsesPremiumFeatures)).ToList();

            if (allowedOrganizations.Count == 0)
            {
                ctx.Filter &= Filter <T> .Term("organization", "none");

                return;
            }

            string field = GetDateField(ctx.GetOptionsAs <IElasticQueryOptions>());

            if (sfq.Stack != null)
            {
                var organization = sfq.Organizations.Single(o => o.Id == sfq.Stack.OrganizationId);
                ctx.Filter &= (Filter <T> .Term("stack", sfq.Stack.Id) && GetRetentionFilter <T>(field, organization.RetentionDays));
                return;
            }

            FilterContainer container = null;

            if (sfq.Projects?.Count > 0)
            {
                foreach (var project in sfq.Projects)
                {
                    var organization = sfq.Organizations.Single(o => o.Id == project.OrganizationId);
                    container |= (Filter <T> .Term("project", project.Id) && GetRetentionFilter <T>(field, organization.RetentionDays));
                }

                ctx.Filter &= container;
                return;
            }

            if (sfq.Organizations?.Count > 0)
            {
                foreach (var organization in sfq.Organizations)
                {
                    container |= (Filter <T> .Term("organization", organization.Id) && GetRetentionFilter <T>(field, organization.RetentionDays));
                }

                ctx.Filter &= container;
            }
        }
Exemplo n.º 17
0
 protected override ScalarExpression OnBuildQuery(QueryBuilderContext context)
 {
     // In SQL, return 'false' for null literals.
     if (ResultType.Type == DataType.Bool)
     {
         TypedValue falseValue = new TypedValue();
         falseValue.Type  = DatabaseType.BoolType;
         falseValue.Value = false;
         return(new LiteralExpression {
             Value = falseValue
         });
     }
     return(base.OnBuildQuery(context));
 }
Exemplo n.º 18
0
        protected override ScalarExpression OnBuildQuery(QueryBuilderContext context)
        {
            var result = new CalculationExpression
            {
                Operator     = CalculationOperator.DateName,
                DateTimePart = DateTimePart,
                Expressions  = new List <ScalarExpression>
                {
                    Argument.BuildQuery(context)
                }
            };

            return(result);
        }
Exemplo n.º 19
0
        protected override ScalarExpression OnBuildQuery(QueryBuilderContext context)
        {
            if (ResultType.IsList)
            {
                throw new InvalidOperationException();
            }

            var result = new LiteralExpression
            {
                Value = TypedValueHelper.FromDataType(ResultType.Type, Value)
            };

            return(result);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Convert the expression tree into a structured query expression.
        /// </summary>
        /// <param name="context">Context information about this query building session, including the target structured query object.</param>
        /// <returns>A scalar expression that can be used within the query.</returns>
        protected virtual ScalarExpression OnBuildQuery(QueryBuilderContext context)
        {
            // Reflect for attributes
            Type type = GetType();
            var  queryEngAttribute = GetQueryEngineOperator(type);

            if (queryEngAttribute == null)
            {
                throw new NotImplementedException(type.Name);
            }

            // Build arguments
            var arguments = new List <ScalarExpression>();

            foreach (ExpressionNode argument in Arguments)
            {
                ScalarExpression queryExpr = argument.BuildQuery(context);
                arguments.Add(queryExpr);
            }

            // Generic Calculation Expression
            if (queryEngAttribute.CalculationOperator != null)
            {
                var result = new CalculationExpression();
                result.Operator    = queryEngAttribute.CalculationOperator.Value;
                result.Expressions = arguments;
                return(result);
            }

            // Generic Comparison Expression
            if (queryEngAttribute.ComparisonOperator != null)
            {
                var result = new ComparisonExpression();
                result.Operator    = queryEngAttribute.ComparisonOperator.Value;
                result.Expressions = arguments;
                return(result);
            }

            // Generic Comparison Expression
            if (queryEngAttribute.LogicalOperator != null)
            {
                var result = new LogicalExpression();
                result.Operator    = queryEngAttribute.LogicalOperator.Value;
                result.Expressions = arguments;
                return(result);
            }

            throw new InvalidOperationException(type.Name);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Returns a tree node that is representative of an entity or.
        /// </summary>
        /// <param name="context">Context information about this query building session, including the target structured query object.</param>
        /// <param name="allowReuse">A dedicated node should be returned because the caller intends on disturbing it.</param>
        /// <returns>A query node that can be used within the query.</returns>
        public override SQ.Entity OnBuildQueryNode(QueryBuilderContext context, bool allowReuse)
        {
            IEntity instance = Instance.Entity;
            long    typeId   = instance.TypeIds.First( );

            if (context.ParentNode == null)
            {
                throw new Exception("No context.");
            }

            // Look for an existing relationship node in the tree that we can reuse
            SQ.CustomJoinNode result = !allowReuse ? null :
                                       context.ParentNode
                                       .RelatedEntities
                                       .OfType <SQ.CustomJoinNode>( )
                                       .FirstOrDefault(cj => IsMatch(cj, Instance.Id) && cj.EntityTypeId.Id == typeId);

            // New node
            if (result == null)
            {
                result = new SQ.CustomJoinNode
                {
                    EntityTypeId        = typeId,
                    JoinPredicateScript = "true"
                };
                SQ.ScalarExpression predicate = new SQ.ComparisonExpression
                {
                    Operator    = SQ.ComparisonOperator.Equal,
                    Expressions =
                    {
                        new SQ.IdExpression
                        {
                            NodeId = result.NodeId
                        },
                        new SQ.LiteralExpression
                        {
                            Value = TypedValueHelper.FromDataType(ResultType.Type, Instance.Id)
                        }
                    }
                };
                result.Conditions = new List <SQ.ScalarExpression> {
                    predicate
                };
            }
            context.ParentNode.RelatedEntities.Add(result);
            AddChildNodes(context, result, allowReuse);

            return(result);
        }
Exemplo n.º 22
0
        protected override ScalarExpression OnBuildQuery(QueryBuilderContext context)
        {
            var aggregateNode = context.GetNode(this);
            var result        = new EDC.ReadiNow.Metadata.Query.Structured.AggregateExpression
            {
                NodeId          = aggregateNode.NodeId,
                AggregateMethod = Method
            };

            if (Method != AggregateMethod.Count)
            {
                result.Expression = Argument.BuildQuery(context);
            }
            return(result);
        }
Exemplo n.º 23
0
        protected override ScalarExpression OnBuildQuery(QueryBuilderContext context)
        {
            ScalarExpression condition = Arguments[0].BuildQuery(context);
            ScalarExpression ifTrue    = Arguments[1].BuildQuery(context);
            ScalarExpression ifFalse   = Arguments[2].BuildQuery(context);

            var result = new IfElseExpression
            {
                BooleanExpression   = condition,
                IfBlockExpression   = ifTrue,
                ElseBlockExpression = ifFalse
            };

            return(result);
        }
Exemplo n.º 24
0
        private IQueryable <Product> ApplyOrdering(QueryBuilderContext ctx, IQueryable <Product> query)
        {
            var ordered = false;

            foreach (var sort in ctx.SearchQuery.Sorting)
            {
                if (sort.FieldName.IsEmpty())
                {
                    // Sort by relevance.
                    if (ctx.CategoryId > 0)
                    {
                        query = OrderBy(ref ordered, query, x => x.ProductCategories.Where(pc => pc.CategoryId == ctx.CategoryId.Value).FirstOrDefault().DisplayOrder);
                    }
                    else if (ctx.ManufacturerId > 0)
                    {
                        query = OrderBy(ref ordered, query, x => x.ProductManufacturers.Where(pm => pm.ManufacturerId == ctx.ManufacturerId.Value).FirstOrDefault().DisplayOrder);
                    }
                }
                else if (sort.FieldName == "createdon")
                {
                    query = OrderBy(ref ordered, query, x => x.CreatedOnUtc, sort.Descending);
                }
                else if (sort.FieldName == "name")
                {
                    query = OrderBy(ref ordered, query, x => x.Name, sort.Descending);
                }
                else if (sort.FieldName == "price")
                {
                    query = OrderBy(ref ordered, query, x => x.Price, sort.Descending);
                }
            }

            if (!ordered)
            {
                if (FindFilter(ctx.SearchQuery.Filters, "parentid") != null)
                {
                    query = query.OrderBy(x => x.DisplayOrder);
                }
                else
                {
                    query = query.OrderBy(x => x.Id);
                }
            }

            return(query);
        }
Exemplo n.º 25
0
        protected override ScalarExpression OnBuildQuery(QueryBuilderContext context)
        {
            var result = new CalculationExpression
            {
                Operator     = CalculationOperator.DateAdd,
                DateTimePart = DateTimePart,
                InputType    = InputType.Type,
                Expressions  = new List <ScalarExpression>
                {
                    // Caution.. CalculationOperator.DateAdd was implemented backwards
                    Right.BuildQuery(context),
                    Left.BuildQuery(context)
                }
            };

            return(result);
        }
Exemplo n.º 26
0
        protected virtual IQueryable <Product> ApplySearchTerm(QueryBuilderContext ctx, IQueryable <Product> query)
        {
            var term       = ctx.SearchQuery.Term;
            var fields     = ctx.SearchQuery.Fields;
            var languageId = ctx.SearchQuery.LanguageId ?? 0;

            if (term.HasValue() && fields != null && fields.Length != 0 && fields.Any(x => x.HasValue()))
            {
                ctx.IsGroupingRequired = true;

                var lpQuery = _db.LocalizedProperties.AsNoTracking();

                // SearchMode.ExactMatch doesn't make sense here
                if (ctx.SearchQuery.Mode == SearchMode.StartsWith)
                {
                    query =
                        from p in query
                        join lp in lpQuery on p.Id equals lp.EntityId into plp
                        from lp in plp.DefaultIfEmpty()
                        where
                        (fields.Contains("name") && p.Name.StartsWith(term)) ||
                        (fields.Contains("sku") && p.Sku.StartsWith(term)) ||
                        (fields.Contains("shortdescription") && p.ShortDescription.StartsWith(term)) ||
                        (languageId != 0 && lp.LanguageId == languageId && lp.LocaleKeyGroup == "Product" && lp.LocaleKey == "Name" && lp.LocaleValue.StartsWith(term)) ||
                        (languageId != 0 && lp.LanguageId == languageId && lp.LocaleKeyGroup == "Product" && lp.LocaleKey == "ShortDescription" && lp.LocaleValue.StartsWith(term))
                        select p;
                }
                else
                {
                    query =
                        from p in query
                        join lp in lpQuery on p.Id equals lp.EntityId into plp
                        from lp in plp.DefaultIfEmpty()
                        where
                        (fields.Contains("name") && p.Name.Contains(term)) ||
                        (fields.Contains("sku") && p.Sku.Contains(term)) ||
                        (fields.Contains("shortdescription") && p.ShortDescription.Contains(term)) ||
                        (languageId != 0 && lp.LanguageId == languageId && lp.LocaleKeyGroup == "Product" && lp.LocaleKey == "Name" && lp.LocaleValue.Contains(term)) ||
                        (languageId != 0 && lp.LanguageId == languageId && lp.LocaleKeyGroup == "Product" && lp.LocaleKey == "ShortDescription" && lp.LocaleValue.Contains(term))
                        select p;
                }
            }

            return(query);
        }
Exemplo n.º 27
0
        public void Build <T>(QueryBuilderContext <T> ctx) where T : class, new()
        {
            var organizationIdQuery = ctx.GetSourceAs <IOrganizationIdQuery>();

            if (organizationIdQuery?.OrganizationIds == null || organizationIdQuery.OrganizationIds.Count <= 0)
            {
                return;
            }

            if (organizationIdQuery.OrganizationIds.Count == 1)
            {
                ctx.Filter &= Filter <T> .Term("organization", organizationIdQuery.OrganizationIds.First());
            }
            else
            {
                ctx.Filter &= Filter <T> .Terms("organization", organizationIdQuery.OrganizationIds.ToArray());
            }
        }
Exemplo n.º 28
0
        public void Build <T>(QueryBuilderContext <T> ctx) where T : class, new()
        {
            var projectIdQuery = ctx.GetSourceAs <IProjectIdQuery>();

            if (projectIdQuery?.ProjectIds == null || projectIdQuery.ProjectIds.Count <= 0)
            {
                return;
            }

            if (projectIdQuery.ProjectIds.Count == 1)
            {
                ctx.Filter &= Filter <T> .Term("project", projectIdQuery.ProjectIds.First());
            }
            else
            {
                ctx.Filter &= Filter <T> .Terms("project", projectIdQuery.ProjectIds.ToArray());
            }
        }
Exemplo n.º 29
0
        public void Build <T>(QueryBuilderContext <T> ctx) where T : class, new()
        {
            var stackIdQuery = ctx.GetSourceAs <IStackIdQuery>();

            if (stackIdQuery?.StackIds == null || stackIdQuery.StackIds.Count <= 0)
            {
                return;
            }

            if (stackIdQuery.StackIds.Count == 1)
            {
                ctx.Filter &= Filter <T> .Term("stack", stackIdQuery.StackIds.First());
            }
            else
            {
                ctx.Filter &= Filter <T> .Terms("stack", stackIdQuery.StackIds.ToArray());
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// Returns a tree node that is representative of an entity or.
        /// </summary>
        /// <param name="context">Context information about this query building session, including the target structured query object.</param>
        /// <param name="allowReuse">A dedicated node should be returned because the caller intends on disturbing it.</param>
        /// <returns>A query node that can be used within the query.</returns>
        public override SQ.Entity OnBuildQueryNode(QueryBuilderContext context, bool allowReuse)
        {
            if (context.ParentNode == null)
            {
                throw new Exception("No context.");
            }

            // New node
            SQ.CustomJoinNode result = new SQ.CustomJoinNode
            {
                EntityTypeId        = EntityTypeId,
                JoinPredicateScript = "true"
            };

            context.ParentNode.RelatedEntities.Add(result);
            AddChildNodes(context, result, allowReuse);

            return(result);
        }