Exemple #1
0
        public void LinqVisitor_Test()
        {
            var mapper = new BsonMapper();
            mapper.ResolveFieldName = (x) => x.ToLower();

            var qv = new QueryVisitor<User>(mapper);

            //var q1 = qv.Visit(x => x.Id == 1); // Query.EQ("_id", 1)

            //var q2 = qv.Visit(x => x.Active); // Query.EQ("Active", true);

            // not
            //var q3 = qv.Visit(x => !x.Active); // Query.Not("Active", true)
            //var q4 = qv.Visit(x => !(x.Id == 1)); // Query.Not(Query.EQ("_id", 1))
            //var q5 = qv.Visit(x => !x.Name.StartsWith("john")); // Query.Not(Query.StartsWith("John"))

            // enum
            //var q4 = qv.Visit(x => x.OS == PlatformID.Unix);

            //var q6 = qv.Visit(x => new int[] { 1, 2 }.Contains(x.Id));

            //var q7 = qv.Visit(x => x.Names.Contains("John"));

            //**var q8 = qv.Visit(x => x.Domains.Any(d => d.DomainName == "ABC"));

            //****var q8 = qv.Visit(x => x.Names.Any(z => z.StartsWith("John")));
            // => Query.StartsWith("Names", "John")
        }
        public void Setup()
        {
            TestUtils.ResetLINQLibrary();
            MEFUtilities.AddPart(new QVResultOperators());
            MEFUtilities.AddPart(new TypeHandlerCache());
            MEFUtilities.AddPart(new DealWithInt32());

            MEFUtilities.AddPart(new ArrayArrayInfoFactory());
            MEFUtilities.AddPart(new SubQueryArrayTypeFactory());
            MEFUtilities.AddPart(new SubQueryExpressionArrayInfoFactory());
            MEFUtilities.AddPart(new TranslatedArrayInfoFactory());
            MEFUtilities.AddPart(new EnumerableRangeArrayTypeFactory());
            MEFUtilities.AddPart(new GroupByFactory());
            MEFUtilities.AddPart(new GroupByArrayFactory());
            MEFUtilities.AddPart(new MemberAccessArrayTypeFactory());

            MEFUtilities.AddPart(new ROTakeSkipOperators());
            MEFUtilities.AddPart(new ROFirstLast());
            MEFUtilities.AddPart(new ROCount());

            GeneratedCode gc = new GeneratedCode();
            CodeContext cc = new CodeContext();
            var qv = new QueryVisitor(gc, cc, MEFUtilities.MEFContainer);
            MEFUtilities.Compose(qv);
        }
Exemple #3
0
            protected override SqlStatement ProcessQuery(SqlStatement statement)
            {
                if (statement.IsInsert() && statement.RequireInsertClause().Into !.Name == "Parent")
                {
                    var expr =
                        new QueryVisitor().Find(statement.RequireInsertClause(), e =>
                    {
                        if (e.ElementType == QueryElementType.SetExpression)
                        {
                            var se = (SqlSetExpression)e;
                            return(((SqlField)se.Column).Name == "ParentID");
                        }

                        return(false);
                    }) as SqlSetExpression;

                    if (expr != null)
                    {
                        var value = ConvertTo <int> .From(((IValueContainer)expr.Expression !).Value);

                        if (value == 555)
                        {
                            var tableName = "Parent1";
                            var dic       = new Dictionary <IQueryElement, IQueryElement>();

                            statement = new QueryVisitor().Convert(statement, e =>
                            {
                                if (e.ElementType == QueryElementType.SqlTable)
                                {
                                    var oldTable = (SqlTable)e;

                                    if (oldTable.Name == "Parent")
                                    {
                                        var newTable = new SqlTable(oldTable)
                                        {
                                            Name = tableName, PhysicalName = tableName
                                        };

                                        foreach (var field in oldTable.Fields.Values)
                                        {
                                            dic.Add(field, newTable.Fields[field.Name]);
                                        }

                                        return(newTable);
                                    }
                                }

                                IQueryElement ex;
                                return(dic.TryGetValue(e, out ex) ? ex : e);
                            });
                        }
                    }

                    return(statement);
                }

                return(statement);
            }
Exemple #4
0
            protected override SqlStatement ProcessQuery(SqlStatement statement, EvaluationContext context)
            {
                if (statement.IsInsert() && statement.RequireInsertClause().Into !.Name == "Parent")
                {
                    var expr =
                        new QueryVisitor().Find(statement.RequireInsertClause(), e =>
                    {
                        if (e.ElementType == QueryElementType.SetExpression)
                        {
                            var se = (SqlSetExpression)e;
                            return(((SqlField)se.Column).Name == "ParentID");
                        }

                        return(false);
                    }) as SqlSetExpression;

                    if (expr != null && expr.Expression !.TryEvaluateExpression(context, out var expressionValue))
                    {
                        var value = ConvertTo <int> .From(expressionValue);

                        if (value == 555)
                        {
                            var tableName = "Parent1";
                            var dic       = new Dictionary <IQueryElement, IQueryElement>();

                            statement = ConvertVisitor.Convert(statement, (v, e) =>
                            {
                                if (e.ElementType == QueryElementType.SqlTable)
                                {
                                    var oldTable = (SqlTable)e;

                                    if (oldTable.Name == "Parent")
                                    {
                                        var newTable = new SqlTable(oldTable)
                                        {
                                            Name = tableName, PhysicalName = tableName
                                        };

                                        foreach (var field in oldTable.Fields)
                                        {
                                            dic.Add(field, newTable[field.Name] ?? throw new InvalidOperationException());
                                        }

                                        return(newTable);
                                    }
                                }

                                IQueryElement?ex;
                                return(dic.TryGetValue(e, out ex) ? ex : e);
                            });
                        }
                    }

                    return(statement);
                }

                return(statement);
            }
 internal LiteCollection(string name, DbEngine engine, BsonMapper mapper, Logger log)
 {
     Name     = name;
     _engine  = engine;
     _mapper  = mapper;
     _log     = log;
     _visitor = new QueryVisitor <T>(mapper);
     //_includes = new List<string>();
 }
Exemple #6
0
        public int DeleteMany(IQueryable <TEntity> source)
        {
            var query = QueryVisitor <TEntity> .CreateModel(source.Expression,
                                                            x => ((Table <TEntity>)x).Name);

            return(Command.Create(DeleteWriter <TEntity> .CreateStatement(
                                      new Delete(_table, query.Select, true), _map), _profiler).
                   ExecuteNonQuery(_connectionManager));
        }
Exemple #7
0
        private static object GetResult(MockQueryable <Entity> query)
        {
            var statement = SelectWriter <Entity> .CreateStatement(QueryVisitor <Entity> .CreateModel(query.Expression, x => ((MockQueryable <Entity>)x).Name).Select, Map);

            var command = Command.Create(statement, Profiler);
            var loader  = new Loader <Entity>(command, Map);

            return(loader.Execute(new ConnectionManager(Database.Connection, TimeSpan.FromMinutes(5))));
        }
Exemple #8
0
        private static SqlStatement NormalizeParameters(SqlStatement statement, List <ParameterAccessor> accessors)
        {
            // remember accessor indexes
            new QueryVisitor().VisitAll(statement, e =>
            {
                if (e.ElementType == QueryElementType.SqlParameter)
                {
                    var parameter = (SqlParameter)e;
                    if (parameter.IsQueryParameter)
                    {
                        var idx = accessors.FindIndex(a => object.ReferenceEquals(a.SqlParameter, parameter));
                        parameter.AccessorId = idx >= 0 ? (int?)idx : null;
                    }
                }
            });

            // correct expressions, we have to put expressions in correct order and duplicate them if they are reused
            statement = NormalizeExpressions(statement);

            var found                     = new HashSet <ISqlExpression>();
            var columnExpressions         = new HashSet <ISqlExpression>();
            var parameterDuplicateVisitor = new QueryVisitor();

            statement = parameterDuplicateVisitor.Convert(statement, e =>
            {
                if (e.ElementType == QueryElementType.SqlParameter)
                {
                    var parameter = (SqlParameter)e;
                    if (parameter.IsQueryParameter)
                    {
                        var parentElement = parameterDuplicateVisitor.ParentElement;
                        if (parentElement is SqlColumn)
                        {
                            columnExpressions.Add(parameter);
                        }
                        else if (parentElement !.ElementType == QueryElementType.SetExpression)
                        {
                            // consider that expression is already processed by SelectQuery and we do not need duplication.
                            // It is specific how InsertStatement is built
                            if (columnExpressions.Contains(parameter))
                            {
                                return(parameter);
                            }
                        }

                        if (!found.Add(parameter))
                        {
                            var newParameter =
                                (SqlParameter)parameter.Clone(new Dictionary <ICloneableElement, ICloneableElement>(),
                                                              c => true);
                            return(newParameter);
                        }

                        // notify visitor to process this parameter always
                        parameterDuplicateVisitor.VisitedElements.Add(parameter, null);
                    }
        public void Tablename_Test()
        {
            var query = MockQueryable <Entity> .Create(TableName1);

            var select = QueryVisitor <Entity> .CreateModel(query.Expression, x => ((MockQueryable <Entity>)x).Name).Select;

            select.ShouldNotBeNull();

            select.From.Table.Name.ShouldEqual(TableName1);
        }
Exemple #10
0
        public object GetQueryable <TResult>(System.Linq.Expressions.Expression expression)
        {
            var v = new QueryVisitor();

            v.Visit(expression);

            var reader = new AdgangsAdresseReader <TResult>(v.Evaluate());

            return(reader.AsQueryable());
        }
Exemple #11
0
        private static IEnumerable <QueryResult> VisitProgram(ZMI zmi, QueryParser.ProgramContext context)
        {
            var toReturn = new QueryVisitor(zmi).Visit(context).ToList();

            if (toReturn.Any(maybe => maybe.Match(v => v.Name == null, () => false)))
            {
                throw new ArgumentException("All items in top-level SELECT must be aliased");
            }
            return(toReturn.Sequence().Match(list => list, () => new List <QueryResult>()));
        }
        public void No_Where_Test()
        {
            var query = MockQueryable <Entity> .Create(TableName1);

            query.Take(10);
            var select = QueryVisitor <Entity> .CreateModel(query.Expression, x => ((MockQueryable <Entity>)x).Name).Select;

            select.ShouldNotBeNull();
            select.HasWhere.ShouldEqual(false);
        }
        public void First_Or_Default_Test()
        {
            var query = MockQueryable <Entity> .Create(TableName1);

            query.FirstOrDefault();
            var select = QueryVisitor <Entity> .CreateModel(query.Expression, x => ((MockQueryable <Entity>)x).Name).Select;

            select.ShouldNotBeNull();
            select.FirstOrDefault.ShouldEqual(true);
        }
        public void Randomize_Test()
        {
            var query = MockQueryable <Entity> .Create(TableName1);

            query.Randomize();
            var select = QueryVisitor <Entity> .CreateModel(query.Expression, x => ((MockQueryable <Entity>)x).Name).Select;

            select.ShouldNotBeNull();
            select.Randomize.ShouldEqual(true);
        }
        public void should_set_single_flag()
        {
            var query = MockQueryable <Entity> .Create(TableName1);

            query.Single();
            var select = QueryVisitor <Entity> .CreateModel(query.Expression, x => ((MockQueryable <Entity>)x).Name).Select;

            select.ShouldNotBeNull();
            select.Single.ShouldEqual(true);
        }
Exemple #16
0
        public IQuery <TResult> Join <TResult>(Expression <Func <T, TResult, bool> > expression, SqlJoinType type = SqlJoinType.LEFT, string aliasName = "")
        {
            var join = new SqlLam <TResult>(this.Type, false);

            join.Builder      = this.Builder;
            join.FieldVisitor = this.FieldVisitor;
            join.QueryVisitor = this.QueryVisitor;
            QueryVisitor.ResolveJoin(expression, aliasName, type);
            return(join);
        }
Exemple #17
0
        private static T NormalizeExpressions <T>(T expression)
            where T : class, IQueryElement
        {
            var queryVisitor = new QueryVisitor();
            var result       = queryVisitor.Convert(expression, e =>
            {
                if (e.ElementType == QueryElementType.SqlExpression)
                {
                    var expr = (SqlExpression)e;

                    // we interested in modifying only expressions which have parameters
                    if (HasQueryParameters(expr))
                    {
                        if (expr.Expr.IsNullOrEmpty() || expr.Parameters.Length == 0)
                        {
                            return(expr);
                        }

                        var newExpressions = new List <ISqlExpression>();

                        var newExpr = QueryHelper.TransformExpressionIndexes(expr.Expr,
                                                                             idx =>
                        {
                            if (idx >= 0 && idx < expr.Parameters.Length)
                            {
                                var paramExpr  = expr.Parameters[idx];
                                var normalized = paramExpr;
                                var newIndex   = newExpressions.Count;

                                if (newExpressions.Contains(normalized) && HasQueryParameters(normalized))
                                {
                                    normalized = (ISqlExpression)normalized.Clone(
                                        new Dictionary <ICloneableElement, ICloneableElement>(),
                                        c => true);
                                }

                                newExpressions.Add(normalized);
                                return(newIndex);
                            }
                            return(idx);
                        });

                        // always create copy
                        var newExpression = new SqlExpression(expr.SystemType, newExpr, expr.Precedence, expr.IsAggregate, newExpressions.ToArray());
                        // force re-entrance
                        queryVisitor.VisitedElements.Remove(expr);
                        queryVisitor.VisitedElements.Add(expr, null);
                        return(newExpression);
                    }
                }
                return(e);
            });

            return(result);
        }
Exemple #18
0
        protected override IBuildContext BuildMethodCall(ExpressionBuilder builder, MethodCallExpression methodCall,
                                                         BuildInfo buildInfo)
        {
            var sequenceExpr    = methodCall.Arguments[0];
            var sequence        = builder.BuildSequence(new BuildInfo(buildInfo, sequenceExpr));
            var groupingType    = methodCall.Type.GetGenericArgumentsEx()[0];
            var keySelector     = (LambdaExpression)methodCall.Arguments[1].Unwrap();
            var elementSelector = (LambdaExpression)methodCall.Arguments[2].Unwrap();

            if (methodCall.Arguments[0].NodeType == ExpressionType.Call)
            {
                var call = (MethodCallExpression)methodCall.Arguments[0];

                if (call.Method.Name == "Select")
                {
                    var type = ((LambdaExpression)call.Arguments[1].Unwrap()).Body.Type;

                    if (type.IsGenericTypeEx() &&
                        type.GetGenericTypeDefinition() == typeof(ExpressionBuilder.GroupSubQuery <,>))
                    {
                        sequence = new SubQueryContext(sequence);
                    }
                }
            }

            var key      = new KeyContext(buildInfo.Parent, keySelector, sequence);
            var groupSql = builder.ConvertExpressions(key, keySelector.Body.Unwrap(), ConvertFlags.Key);

            if (sequence.Select.Select.IsDistinct ||
                sequence.Select.GroupBy.Items.Count > 0 ||
                groupSql.Any(_ => !(_.Sql is ISqlField || _.Sql is IColumn)))
            {
                sequence = new SubQueryContext(sequence);
                key      = new KeyContext(buildInfo.Parent, keySelector, sequence);
                groupSql = builder.ConvertExpressions(key, keySelector.Body.Unwrap(), ConvertFlags.Key);
            }

            foreach (var sql in groupSql)
            {
                sequence.Select.GroupBy.Expr(sql.Sql);
            }

            foreach (
                var join in
                QueryVisitor.FindOnce <IJoinedTable>(sequence.Select.From).Where(f => f.JoinType == EJoinType.Inner))
            {
                join.IsWeak = false;
            }

            var element = new SelectContext(buildInfo.Parent, elementSelector, sequence /*, key*/);
            var groupBy = new GroupByContext(buildInfo.Parent, sequenceExpr, groupingType, sequence, key, element);

            return(groupBy);
        }
        public void TestSngExpressions(string expr, string expectedQuery)
        {
            Setup(expr);

            CalcParser.ExpressionContext context = this._calcParser.expression();

            QueryVisitor visitor = new QueryVisitor();
            string       query   = visitor.Visit(context);

            Assert.AreEqual(expectedQuery, query);
        }
        public void Skip_Test()
        {
            var query = MockQueryable <Entity> .Create(TableName1);

            query.Skip(15);
            var select = QueryVisitor <Entity> .CreateModel(query.Expression, x => ((MockQueryable <Entity>)x).Name).Select;

            select.ShouldNotBeNull();
            select.HasStart.ShouldEqual(true);
            select.Start.ShouldEqual(16);
        }
 public void Setup()
 {
     TestUtils.ResetLINQLibrary();
     MEFUtilities.AddPart(new QVResultOperators());
     MEFUtilities.AddPart(new TypeHandlerCache());
     MEFUtilities.AddPart(new DealWithMyTypes());
     GeneratedCode gc = new GeneratedCode();
     CodeContext cc = new CodeContext();
     var qv = new QueryVisitor(gc, cc, MEFUtilities.MEFContainer);
     MEFUtilities.Compose(qv);
 }
Exemple #22
0
        private Maybe<ResultSingle> VisitStmt(QueryParser.StatementContext context)
        {
            var results = new QueryVisitor(_zmi).Visit(context).Sequence();
            if (results.HasNothing)
                return Maybe<ResultSingle>.Nothing;

            if (results.Val.Count != 1)
                throw new ArgumentException("Nested queries must SELECT exactly one item.");

            return new ResultSingle(results.Val.First().Value).Just();
        }
        public void Where_Test()
        {
            var query = MockQueryable <Entity> .Create(TableName1);

            query.Where(x => x.Age == 33 && (bool)x.Values["opt_out"] || x.Name.StartsWith("yada"));
            var select = QueryVisitor <Entity> .CreateModel(query.Expression, x => ((MockQueryable <Entity>)x).Name).Select;

            select.ShouldNotBeNull();
            select.Where.ShouldNotBeNull();
            select.HasWhere.ShouldEqual(true);
        }
Exemple #24
0
        public void Setup()
        {
            TestUtils.ResetLINQLibrary();
            MEFUtilities.AddPart(new QVResultOperators());
            MEFUtilities.AddPart(new TypeHandlerCache());
            MEFUtilities.AddPart(new DealWithMyTypes());
            GeneratedCode gc = new GeneratedCode();
            CodeContext   cc = new CodeContext();
            var           qv = new QueryVisitor(gc, cc, MEFUtilities.MEFContainer);

            MEFUtilities.Compose(qv);
        }
        public void TestQueryVariablesOracle(string expr, string expectedQuery)
        {
            Setup(expr);

            CalcParser.ExpressionContext context = this._calcParser.expression();
            DbTranslator translator = new OracleTranslator();

            QueryVisitor visitor = new QueryVisitor(new TestMetadataResolver(), translator);
            string       query   = visitor.Visit(context);

            Assert.AreEqual(expectedQuery, query);
        }
Exemple #26
0
        public static CodeThrowExceptionStatement @throw(Expression <Action> exp)
        {
            VisitorContext ctx = new VisitorContext();

            ctx.VisitParams(exp.Parameters);
            NewExpression newExp = new QueryVisitor((e) => e is NewExpression).Visit(exp) as NewExpression;

            return(new CodeThrowExceptionStatement(new CodeObjectCreateExpression(
                                                       new CodeTypeReference(newExp.Type),
                                                       new CodeExpressionVisitor(ctx).VisitExpressionList(newExp.Arguments).ToArray()
                                                       )));
        }
        public ElasticQueryParserConfiguration UseAliases(AliasResolver defaultAliasResolver, int priority = 50)
        {
            DefaultAliasResolver = defaultAliasResolver;

            var visitor = new AliasedQueryVisitor();

            QueryVisitor.AddVisitor(visitor, priority);
            SortVisitor.AddVisitor(visitor, priority);

            AggregationVisitor.AddVisitor(new AliasedQueryVisitor(false), priority);
            return(this);
        }
Exemple #28
0
        public void should_render_sql_with_nolock_hint()
        {
            var query = MockQueryable <Entity> .Create(TableName1);

            var select = QueryVisitor <Entity> .CreateModel(query.Expression, x => ((MockQueryable <Entity>)x).Name).Select;

            var statement = SelectWriter <Entity> .CreateStatement(select, Map, noLock : true);

            statement.Result.ShouldEqual(Statement.ResultType.Multiple);
            statement.Parameters.Count.ShouldEqual(0);
            statement.Text.ShouldEqual(string.Format("SELECT * FROM [{0}] {1} WITH (NOLOCK)", TableName1, select.From.Alias));
        }
        public void Take_Percent_Test()
        {
            var query = MockQueryable <Entity> .Create(TableName1);

            query.TakePercent(5);
            var select = QueryVisitor <Entity> .CreateModel(query.Expression, x => ((MockQueryable <Entity>)x).Name).Select;

            select.ShouldNotBeNull();
            select.HasTop.ShouldEqual(true);
            select.TopType.ShouldEqual(Select.TopValueType.Percent);
            select.Top.ShouldEqual(5);
        }
Exemple #30
0
        public void Select_Test()
        {
            var query = MockQueryable <Entity> .Create(TableName1);

            var select = QueryVisitor <Entity> .CreateModel(query.Expression, x => ((MockQueryable <Entity>)x).Name).Select;

            var statement = SelectWriter <Entity> .CreateStatement(select, Map);

            statement.Result.ShouldEqual(Statement.ResultType.Multiple);
            statement.Parameters.Count.ShouldEqual(0);
            statement.Text.ShouldEqual(string.Format("SELECT * FROM [{0}] {1}", TableName1, select.From.Alias));
        }
Exemple #31
0
        public void Columns_Test()
        {
            var query = MockQueryable <Entity> .Create(TableName1);

            query.Union(MockQueryable <Entity> .Create(TableName2).Take(5).Union(MockQueryable <Entity> .Create(TableName3).Skip(4).OrderBy(x => x.Active)));
            var statement = SchemaWriter.CreateUnionColumnsStatement(QueryVisitor <Entity> .CreateModel(query.Expression, x => ((MockQueryable <Entity>)x).Name).Select);

            statement.Parameters.Count().ShouldEqual(0);
            statement.Text.ShouldEqual("SELECT [name], CASE [system_type_id] WHEN 167 THEN 231 WHEN 175 THEN 239 WHEN 35 THEN 99 ELSE [system_type_id] END AS [system_type_id], CASE [user_type_id] WHEN 167 THEN 231 WHEN 175 THEN 239 WHEN 35 THEN 99 ELSE [user_type_id] END AS [user_type_id] FROM [sys].[columns] WHERE [object_id] = OBJECT_ID(N'XLIST_1') INTERSECT " +
                                       "SELECT [name], CASE [system_type_id] WHEN 167 THEN 231 WHEN 175 THEN 239 WHEN 35 THEN 99 ELSE [system_type_id] END AS [system_type_id], CASE [user_type_id] WHEN 167 THEN 231 WHEN 175 THEN 239 WHEN 35 THEN 99 ELSE [user_type_id] END AS [user_type_id] FROM [sys].[columns] WHERE [object_id] = OBJECT_ID(N'XLIST_2') INTERSECT " +
                                       "SELECT [name], CASE [system_type_id] WHEN 167 THEN 231 WHEN 175 THEN 239 WHEN 35 THEN 99 ELSE [system_type_id] END AS [system_type_id], CASE [user_type_id] WHEN 167 THEN 231 WHEN 175 THEN 239 WHEN 35 THEN 99 ELSE [user_type_id] END AS [user_type_id] FROM [sys].[columns] WHERE [object_id] = OBJECT_ID(N'XLIST_3')");
        }
        public void QueryTree_Visit()
        {
            var type = typeof(int);

            var query =
                new FirstOperator(
                    type,
                    new FirstPredicateOperator(
                        type,
                        new SelectOperator(
                            type,
                            type,
                            new WhereOperator(
                                type,
                                new TakeOperator(
                                    type,
                                    new MonadAbstraction(
                                        type,
                                        new LambdaAbstraction(
                                            Expression.Lambda(Expression.Empty()),
                                            EmptyReadOnlyCollection <QueryTree> .Instance
                                            )
                                        ),
                                    new LambdaAbstraction(
                                        Expression.Lambda(Expression.Empty()),
                                        EmptyReadOnlyCollection <QueryTree> .Instance
                                        )
                                    ),
                                new LambdaAbstraction(
                                    Expression.Lambda(Expression.Empty()),
                                    EmptyReadOnlyCollection <QueryTree> .Instance
                                    )
                                ),
                            new LambdaAbstraction(
                                Expression.Lambda(Expression.Empty()),
                                EmptyReadOnlyCollection <QueryTree> .Instance
                                )
                            ),
                        new LambdaAbstraction(
                            Expression.Lambda(Expression.Empty()),
                            EmptyReadOnlyCollection <QueryTree> .Instance
                            )
                        )
                    );

            var visited = new QueryVisitor().Visit(query);

            var visited2 = new QueryVisitorWithReflection().Visit(query);

            Assert.AreSame(query, visited);
            Assert.AreSame(query, visited2);
        }
Exemple #33
0
        /// <summary>
        /// Parses a user query (without validating it). You practically only get the syntax tree.
        /// </summary>
        /// <param name="text"></param>
        /// <param name="errorListener"></param>
        /// <returns></returns>
        public static Query ParseForSyntaxOnly(string text, IErrorListener errorListener = null)
        {
            var inputStream       = new AntlrInputStream(text);
            var speakLexer        = new CQLLexer(inputStream);
            var commonTokenStream = new CommonTokenStream(speakLexer);
            var parser            = new CQLParser(commonTokenStream);

            AddErrorListener(parser, errorListener);
            var parseContext = parser.query();
            var visitor      = new QueryVisitor();

            return(visitor.Visit(parseContext));
        }
Exemple #34
0
            protected override SqlQuery ProcessQuery(SqlQuery sqlQuery)
            {
                if (sqlQuery.IsInsert && sqlQuery.Insert.Into.Name == "Parent")
                {
                    var expr =
                        new QueryVisitor().Find(sqlQuery.Insert, e =>
                        {
                            if (e.ElementType == QueryElementType.SetExpression)
                            {
                                var se = (SqlQuery.SetExpression)e;
                                return ((SqlField)se.Column).Name == "ParentID";
                            }

                            return false;
                        }) as SqlQuery.SetExpression;

                    if (expr != null)
                    {
                        var value = ConvertTo<int>.From(((IValueContainer)expr.Expression).Value);

                        if (value == 555)
                        {
                            var tableName = "Parent1";
                            var dic       = new Dictionary<IQueryElement,IQueryElement>();

                            sqlQuery = new QueryVisitor().Convert(sqlQuery, e =>
                            {
                                if (e.ElementType == QueryElementType.SqlTable)
                                {
                                    var oldTable = (SqlTable)e;

                                    if (oldTable.Name == "Parent")
                                    {
                                        var newTable = new SqlTable(oldTable) { Name = tableName, PhysicalName = tableName };

                                        foreach (var field in oldTable.Fields.Values)
                                            dic.Add(field, newTable.Fields[field.Name]);

                                        return newTable;
                                    }
                                }

                                IQueryElement ex;
                                return dic.TryGetValue(e, out ex) ? ex : null;
                            });
                        }
                    }
                }

                return sqlQuery;
            }
Exemple #35
0
        /// <summary>
        /// Parst den übergeben String und gibt das Ergebnis als HttpQuery Objekt mit den Ergebnissen wieder zurück.
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public static HttpQuery Query(string query)
        {
            AntlrInputStream input = new AntlrInputStream(query);
            var lexer = new HttpQueryLexer(input);
            CommonTokenStream tokens = new CommonTokenStream(lexer);
            var parser = new HttpQueryParser(tokens);
            var context = parser.init();

            if (context.exception == null && parser.NumberOfSyntaxErrors == 0)
            {
                var visitor = new QueryVisitor<object>();

                visitor.Visit(context);
                return visitor.GetQuery();
            }
            else
            {
                return new HttpQuery() { Exception = new Exception("Syntax Error") };
            }
        }
            /// <summary>
            /// Run a sub-query for the user. The sub-query is a full-blown expression that
            /// must usually run in its own loop (or similar).
            /// </summary>
            /// <remarks>
            /// The query visitor must be re-invoked - this ends up being a full-blown
            /// parsing.
            /// </remarks>
            /// <param name="expression"></param>
            /// <returns></returns>
            protected override Expression VisitSubQuery(SubQueryExpression expression)
            {
                if (MEFContainer == null)
                    throw new InvalidOperationException("MEFContainer can't be null if we need to analyze a sub query!");

                QueryVisitor qv = new QueryVisitor(GeneratedCode, CodeContext, MEFContainer);
                MEFContainer.SatisfyImportsOnce(qv);

                ///
                /// Run it - since this result is out of this loop, we pop-back-out when done.
                /// 

                var scope = GeneratedCode.CurrentScope;
                GeneratedCode.SetCurrentScopeAsResultScope();
                qv.VisitQueryModel(expression.QueryModel);

                //
                // And the main index that was looked at we need to cache ourselves.
                //

                if (qv.MainIndexScope != null)
                    CodeContext.CacheVariableToEliminate(qv.MainIndexScope);

                ///
                /// Two possible results from the sub-expression query, and how we proceed depends
                /// on what happened in the sub query
                /// 
                /// 1. <returns a value> - an operator like Count() comes back from the sequence.
                ///    it will get used in some later sequence (like # of jets in each event). So,
                ///    we need to make sure it is declared and kept before it is used. The # that comes
                ///    back needs to be used outside the scope we are sitting in - the one that we were at
                ///    when we started this. Since this is a sub-query expression, the result isn't the final
                ///    result, so we need to reset it so no one notices it.
                /// 2. <return a sequence> - this is weird - What we are actually doing here is putting the
                ///    sequence into code. So the loop variable has been updated with the new sequence iterator
                ///    value. But there isn't really a result! So the result will be null...
                /// 

                var r = GeneratedCode.ResultValue;
                if (r != null)
                {
                    GeneratedCode.CurrentScope = scope;
                    if (r is IDeclaredParameter)
                    {
                        GeneratedCode.Add(r as IDeclaredParameter, false);
                    }
                    GeneratedCode.ResetResult();
                    return r;
                }

                //
                // The fact that we returned null means we are dealing with a
                // sequence. There really is no translated version of this expression
                // in that case - so we will return null. If someone above is depending
                // on doing something with it they are going to run into some
                // trouble!

                return null;
            }
        static bool CheckColumn(SelectQuery.Column column, ISqlExpression expr, SelectQuery query, bool optimizeValues, bool optimizeColumns)
        {
            if (expr is SqlField || expr is SelectQuery.Column)
                return false;

            if (expr is SqlValue)
                return !optimizeValues && 1.Equals(((SqlValue)expr).Value);

            if (expr is SqlBinaryExpression)
            {
                var e = (SqlBinaryExpression)expr;

                if (e.Operation == "*" && e.Expr1 is SqlValue)
                {
                    var value = (SqlValue)e.Expr1;

                    if (value.Value is int && (int)value.Value == -1)
                        return CheckColumn(column, e.Expr2, query, optimizeValues, optimizeColumns);
                }
            }

            var visitor = new QueryVisitor();

            if (optimizeColumns &&
                visitor.Find(expr, e => e is SelectQuery || IsAggregationFunction(e)) == null)
            {
                var n = 0;
                var q = query.ParentSelect ?? query;

                visitor.VisitAll(q, e => { if (e == column) n++; });

                return n > 2;
            }

            return true;
        }
        internal void ResolveWeakJoins(List<ISqlTableSource> tables)
        {
            Func<SelectQuery.TableSource,bool> findTable = null; findTable = table =>
            {
                if (tables.Contains(table.Source))
                    return true;

                foreach (var join in table.Joins)
                {
                    if (findTable(join.Table))
                    {
                        join.IsWeak = false;
                        return true;
                    }
                }

                if (table.Source is SelectQuery)
                    foreach (var t in ((SelectQuery)table.Source).From.Tables)
                        if (findTable(t))
                            return true;

                return false;
            };

            var areTablesCollected = false;

            _selectQuery.ForEachTable(table =>
            {
                for (var i = 0; i < table.Joins.Count; i++)
                {
                    var join = table.Joins[i];

                    if (join.IsWeak)
                    {
                        if (!areTablesCollected)
                        {
                            areTablesCollected = true;

                            Action<IQueryElement> tableCollector = expr =>
                            {
                                var field = expr as SqlField;

                                if (field != null && !tables.Contains(field.Table))
                                    tables.Add(field.Table);
                            };

                            var visitor = new QueryVisitor();

                            visitor.VisitAll(_selectQuery.Select,  tableCollector);
                            visitor.VisitAll(_selectQuery.Where,   tableCollector);
                            visitor.VisitAll(_selectQuery.GroupBy, tableCollector);
                            visitor.VisitAll(_selectQuery.Having,  tableCollector);
                            visitor.VisitAll(_selectQuery.OrderBy, tableCollector);

                            if (_selectQuery.IsInsert)
                                visitor.VisitAll(_selectQuery.Insert, tableCollector);

                            if (_selectQuery.IsUpdate)
                                visitor.VisitAll(_selectQuery.Update, tableCollector);

                            if (_selectQuery.IsDelete)
                                visitor.VisitAll(_selectQuery.Delete, tableCollector);

                            visitor.VisitAll(_selectQuery.From, expr =>
                            {
                                var tbl = expr as SqlTable;

                                if (tbl != null && tbl.TableArguments != null)
                                {
                                    var v = new QueryVisitor();

                                    foreach (var arg in tbl.TableArguments)
                                        v.VisitAll(arg, tableCollector);
                                }
                            });
                        }

                        if (findTable(join.Table))
                        {
                            join.IsWeak = false;
                        }
                        else
                        {
                            table.Joins.RemoveAt(i);
                            i--;
                        }
                    }
                }
            }, new HashSet<SelectQuery>());
        }