public void HandleResultOperator_CreatesAndPreparesSubStatementWithNewProjection()
        {
            var resultOperator = new SkipResultOperator(Expression.Constant(0));

            _sqlStatementBuilder.Orderings.Add(_ordering);

            var expectedNewProjection = Expression.New(
                _tupleCtor,
                new Expression[] { _selectProjection, new SqlRowNumberExpression(new[] { _ordering }) },
                new MemberInfo[] { GetTupleMethod("get_Key"), GetTupleMethod("get_Value") });

            var fakePreparedProjection = GetFakePreparedProjection();

            _stageMock
            .Expect(mock => mock.PrepareSelectExpression(Arg <Expression> .Is.Anything, Arg.Is(_context)))
            .WhenCalled(mi => SqlExpressionTreeComparer.CheckAreEqualTrees(expectedNewProjection, (Expression)mi.Arguments[0]))
            .Return(fakePreparedProjection);
            _stageMock.Replay();

            _handler.HandleResultOperator(resultOperator, _sqlStatementBuilder, UniqueIdentifierGenerator, _stageMock, _context);

            _stageMock.VerifyAllExpectations();

            Assert.That(_sqlStatementBuilder.SqlTables.Count, Is.EqualTo(1));
            var sqlTable = _sqlStatementBuilder.SqlTables[0];

            Assert.That(sqlTable.TableInfo, Is.TypeOf(typeof(ResolvedSubStatementTableInfo)));
            Assert.That(sqlTable.JoinSemantics, Is.EqualTo(JoinSemantics.Inner));

            var subStatementTableInfo = ((ResolvedSubStatementTableInfo)sqlTable.TableInfo);

            Assert.That(subStatementTableInfo.SqlStatement.SelectProjection, Is.SameAs(fakePreparedProjection));
            Assert.That(subStatementTableInfo.TableAlias, Is.EqualTo("q0"));
        }
    public void HandleResultOperator_CreatesAndPreparesSubStatementWithNewProjection ()
    {
      var resultOperator = new SkipResultOperator (Expression.Constant (0));

      _sqlStatementBuilder.Orderings.Add (_ordering);

      var expectedNewProjection = Expression.New (
          _tupleCtor, 
          new Expression[] { _selectProjection, new SqlRowNumberExpression (new[] { _ordering }) }, 
          new MemberInfo[] { _tupleCtor.DeclaringType.GetMethod ("get_Key"), _tupleCtor.DeclaringType.GetMethod ("get_Value") });

      var fakePreparedProjection = GetFakePreparedProjection();

      _stageMock
          .Expect (mock => mock.PrepareSelectExpression (Arg<Expression>.Is.Anything, Arg.Is (_context)))
          .WhenCalled (mi => SqlExpressionTreeComparer.CheckAreEqualTrees (expectedNewProjection, (Expression) mi.Arguments[0]))
          .Return (fakePreparedProjection);
      _stageMock.Replay();

      _handler.HandleResultOperator (resultOperator, _sqlStatementBuilder, _generator, _stageMock, _context);

      _stageMock.VerifyAllExpectations();

      Assert.That (_sqlStatementBuilder.SqlTables.Count, Is.EqualTo (1));
      var sqlTable = ((SqlTable) _sqlStatementBuilder.SqlTables[0]);
      Assert.That (sqlTable.TableInfo, Is.TypeOf (typeof (ResolvedSubStatementTableInfo)));
      Assert.That (sqlTable.JoinSemantics, Is.EqualTo (JoinSemantics.Inner));

      var subStatementTableInfo = ((ResolvedSubStatementTableInfo) sqlTable.TableInfo);
      Assert.That (subStatementTableInfo.SqlStatement.SelectProjection, Is.SameAs (fakePreparedProjection));
      Assert.That (subStatementTableInfo.TableAlias, Is.EqualTo ("q0"));
    }
        private static Expression HandleSkip(
            EntityQueryModelVisitor entityQueryModelVisitor,
            SkipResultOperator skipResultOperator)
        {
            var countExpression
                = new DefaultQueryExpressionVisitor(entityQueryModelVisitor)
                  .Visit(skipResultOperator.Count);

            if (entityQueryModelVisitor.Expression is MethodCallExpression methodCallExpression &&
                methodCallExpression.Method
                .MethodIsClosedFormOf(entityQueryModelVisitor.LinqOperatorProvider.Select))
            {
                // Push Skip down below Select

                return
                    (methodCallExpression.Update(
                         methodCallExpression.Object,
                         new[]
                {
                    Expression.Call(
                        entityQueryModelVisitor.LinqOperatorProvider.Skip
                        .MakeGenericMethod(methodCallExpression.Arguments[0].Type.GetSequenceType()),
                        methodCallExpression.Arguments[0],
                        countExpression),
                    methodCallExpression.Arguments[1]
                }));
            }

            return(Expression.Call(
                       entityQueryModelVisitor.LinqOperatorProvider.Skip
                       .MakeGenericMethod(entityQueryModelVisitor.Expression.Type.GetSequenceType()),
                       entityQueryModelVisitor.Expression,
                       countExpression));
        }
 private static Expression HandleSkip(
     EntityQueryModelVisitor entityQueryModelVisitor, SkipResultOperator skipResultOperator)
 {
     return(Expression.Call(
                _skip.MakeGenericMethod(entityQueryModelVisitor.StreamedSequenceInfo.ResultItemType),
                entityQueryModelVisitor.Expression, skipResultOperator.Count));
 }
 private static Expression HandleSkip(
     EntityQueryModelVisitor entityQueryModelVisitor, SkipResultOperator skipResultOperator)
 => Expression.Call(
     entityQueryModelVisitor.LinqOperatorProvider.Skip
     .MakeGenericMethod(entityQueryModelVisitor.Expression.Type.GetSequenceType()),
     entityQueryModelVisitor.Expression,
     new DefaultQueryExpressionVisitor(entityQueryModelVisitor)
     .Visit(skipResultOperator.Count));
        private void VisitSkipResultOperator(SkipResultOperator skipResultOperation, Remotion.Linq.QueryModel queryModel, int index)
        {
            if (!(skipResultOperation.Count is System.Linq.Expressions.ConstantExpression))
            {
                throw new InvalidOperationException("Only constant expressions are supported for the Skip operators.");
            }

            _query.Offset = Convert.ToInt32(((System.Linq.Expressions.ConstantExpression)skipResultOperation.Count).Value);
        }
        public void HandleResultOperator_SetsCurrentRowNumberOffset()
        {
            var resultOperator = new SkipResultOperator(Expression.Constant(10));

            StubStageMock_PrepareSelectExpression();

            _handler.HandleResultOperator(resultOperator, _sqlStatementBuilder, UniqueIdentifierGenerator, _stageMock, _context);

            Assert.That(_sqlStatementBuilder.CurrentRowNumberOffset, Is.SameAs(resultOperator.Count));
        }
Example #8
0
 public void Visit(SkipResultOperator resultOperator)
 {
     if (resultOperator.Count.NodeType == ExpressionType.Constant)
     {
         _queryBuilder.Skip = (int)((ConstantExpression)resultOperator.Count).Value;
     }
     else
     {
         throw new NotSupportedException("The Skip clause only supports constant values. Methods and variables are currently not supported.");
     }
 }
        public void HandleResultOperator_SkipAfterSetOperations_MovesStatementToSubStatement()
        {
            _sqlStatementBuilder.SetOperationCombinedStatements.Add(SqlStatementModelObjectMother.CreateSetOperationCombinedStatement());

            var resultOperator = new SkipResultOperator(Expression.Constant(0));

            var stage = CreateDefaultSqlPreparationStage();

            _handler.HandleResultOperator(resultOperator, _sqlStatementBuilder, UniqueIdentifierGenerator, stage, _context);

            AssertStatementWasMovedToSubStatement(GetSubStatement(_sqlStatementBuilder.SqlTables[0]));
        }
        public void HandleResultOperator_AddsMappingForItemExpression()
        {
            var originalItemExpression = ((StreamedSequenceInfo)_sqlStatementBuilder.DataInfo).ItemExpression;

            var resultOperator = new SkipResultOperator(Expression.Constant(10));

            StubStageMock_PrepareSelectExpression();

            _handler.HandleResultOperator(resultOperator, _sqlStatementBuilder, UniqueIdentifierGenerator, _stageMock, _context);

            Assert.That(_context.GetExpressionMapping(originalItemExpression), Is.EqualTo(_sqlStatementBuilder.SelectProjection));
        }
        public void HandleResultOperator_SetsOuterDataInfo()
        {
            var originalDataInfo = _sqlStatementBuilder.DataInfo;

            var resultOperator = new SkipResultOperator(Expression.Constant(10));

            StubStageMock_PrepareSelectExpression();

            _handler.HandleResultOperator(resultOperator, _sqlStatementBuilder, UniqueIdentifierGenerator, _stageMock, _context);

            Assert.That(_sqlStatementBuilder.DataInfo, Is.SameAs(originalDataInfo));
        }
        public void HandleResultOperator_SetsOuterSelect_ToOriginalProjectionSelector()
        {
            var resultOperator = new SkipResultOperator(Expression.Constant(0));

            StubStageMock_PrepareSelectExpression();

            _handler.HandleResultOperator(resultOperator, _sqlStatementBuilder, UniqueIdentifierGenerator, _stageMock, _context);

            var expectedSelectProjection = Expression.MakeMemberAccess(
                new SqlTableReferenceExpression(_sqlStatementBuilder.SqlTables[0]), GetTupleProperty("Key"));

            SqlExpressionTreeComparer.CheckAreEqualTrees(expectedSelectProjection, _sqlStatementBuilder.SelectProjection);
        }
        public void HandleResultOperator_CalculatesDataInfo()
        {
            var resultOperator = new SkipResultOperator(Expression.Constant(0));

            StubStageMock_PrepareSelectExpression();

            _handler.HandleResultOperator(resultOperator, _sqlStatementBuilder, UniqueIdentifierGenerator, _stageMock, _context);

            var subStatement = GetSubStatement(_sqlStatementBuilder.SqlTables[0]);

            Assert.That(subStatement.DataInfo, Is.InstanceOf(typeof(StreamedSequenceInfo)));
            Assert.That(subStatement.DataInfo.DataType, Is.EqualTo(typeof(IQueryable <KeyValuePair <Cook, int> >)));
        }
        public void TestBasicTakeSkip()
        {
            var t = new TypeHandlerCache();

            MEFUtilities.Compose(t);
            GeneratedCode gc = new GeneratedCode();

            gc.Add(new LINQToTTreeLib.Statements.StatementInlineBlock());
            gc.Add(new LINQToTTreeLib.Tests.TestUtils.SimpleLoop());
            var skipper = new SkipResultOperator(Expression.Constant(10));

            ProcessResultOperator(new ROTakeSkipOperators(), skipper, null, gc);
        }
        public void HandleResultOperator_SetsRowNumberSelector()
        {
            var resultOperator = new SkipResultOperator(Expression.Constant(10));

            StubStageMock_PrepareSelectExpression();

            _handler.HandleResultOperator(resultOperator, _sqlStatementBuilder, _generator, _stageMock, _context);

            var expectedRowNumberSelector = Expression.MakeMemberAccess(
                new SqlTableReferenceExpression(_sqlStatementBuilder.SqlTables[0]),
                _tupleCtor.DeclaringType.GetProperty("Value"));

            SqlExpressionTreeComparer.CheckAreEqualTrees(expectedRowNumberSelector, _sqlStatementBuilder.RowNumberSelector);
        }
Example #16
0
        public void TransformExpressions()
        {
            var oldExpression  = Expression.Constant(0);
            var newExpression  = Expression.Constant(1);
            var resultOperator = new SkipResultOperator(oldExpression);

            resultOperator.TransformExpressions(ex =>
            {
                Assert.That(ex, Is.SameAs(oldExpression));
                return(newExpression);
            });

            Assert.That(resultOperator.Count, Is.SameAs(newExpression));
        }
        public void HandleResultOperator_RemovesOrderingsFromSubStatement_IfNoTopExpression()
        {
            var resultOperator = new SkipResultOperator(Expression.Constant(0));

            _sqlStatementBuilder.Orderings.Add(_ordering);
            Assert.That(_sqlStatementBuilder.TopExpression, Is.Null);
            StubStageMock_PrepareSelectExpression();

            _handler.HandleResultOperator(resultOperator, _sqlStatementBuilder, UniqueIdentifierGenerator, _stageMock, _context);

            var subStatement = GetSubStatement(_sqlStatementBuilder.SqlTables[0]);

            Assert.That(subStatement.Orderings, Is.Empty);
        }
        public void HandleResultOperator_SetsOuterWhereCondition()
        {
            var resultOperator = new SkipResultOperator(Expression.Constant(10));

            StubStageMock_PrepareSelectExpression();

            _handler.HandleResultOperator(resultOperator, _sqlStatementBuilder, UniqueIdentifierGenerator, _stageMock, _context);

            var expectedRowNumberSelector = Expression.MakeMemberAccess(
                new SqlTableReferenceExpression(_sqlStatementBuilder.SqlTables[0]),
                GetTupleProperty("Value"));
            var expectedWhereCondition = Expression.GreaterThan(expectedRowNumberSelector, resultOperator.Count);

            SqlExpressionTreeComparer.CheckAreEqualTrees(expectedWhereCondition, _sqlStatementBuilder.WhereCondition);
        }
        public void HandleResultOperator_LeavesOrderingsInSubStatement_IfTopExpression()
        {
            var resultOperator = new SkipResultOperator(Expression.Constant(0));

            _sqlStatementBuilder.Orderings.Add(_ordering);
            _sqlStatementBuilder.TopExpression = Expression.Constant(20);
            StubStageMock_PrepareSelectExpression();

            _handler.HandleResultOperator(resultOperator, _sqlStatementBuilder, _generator, _stageMock, _context);

            var subStatement = GetSubStatement(_sqlStatementBuilder.SqlTables[0]);

            Assert.That(subStatement.Orderings, Is.Not.Empty);
            Assert.That(subStatement.Orderings, Is.EqualTo(new[] { _ordering }));
        }
        public void HandleResultOperator_SetsOuterOrdering()
        {
            var resultOperator = new SkipResultOperator(Expression.Constant(10));

            StubStageMock_PrepareSelectExpression();

            _handler.HandleResultOperator(resultOperator, _sqlStatementBuilder, UniqueIdentifierGenerator, _stageMock, _context);

            var expectedRowNumberSelector = Expression.MakeMemberAccess(
                new SqlTableReferenceExpression(_sqlStatementBuilder.SqlTables[0]),
                GetTupleProperty("Value"));

            Assert.That(_sqlStatementBuilder.Orderings.Count, Is.EqualTo(1));
            Assert.That(_sqlStatementBuilder.Orderings[0].OrderingDirection, Is.EqualTo(OrderingDirection.Asc));

            SqlExpressionTreeComparer.CheckAreEqualTrees(expectedRowNumberSelector, _sqlStatementBuilder.Orderings[0].Expression);
        }
Example #21
0
        public virtual void OnBeforeFromClauseVisited(Expression expression)
        {
            // This is a workaround for a bug in OpenLink Virtuoso where it throws an exception
            // when it receives a SPARQL query with a OFFSET but not LIMIT clause.
            if (QueryModel.HasResultOperator <SkipResultOperator>() && !QueryModel.HasResultOperator <TakeResultOperator>())
            {
                SkipResultOperator op = QueryModel.ResultOperators.OfType <SkipResultOperator>().First();

                int skipCount = int.Parse(op.Count.ToString());

                if (skipCount > 0)
                {
                    // OpenLink Virtuoso does not support returning more than 10000 results in an ordered query.
                    int limit = QueryModel.HasOrdering() ? 10000 - skipCount : int.MaxValue;

                    QueryModel.ResultOperators.Insert(0, new TakeResultOperator(Expression.Constant(limit)));
                }
            }
        }
Example #22
0
        public override void VisitResultOperator(ResultOperatorBase resultOperator, QueryModel queryModel, int index)
        {
            base.VisitResultOperator(resultOperator, queryModel, index);

            if (clause.HasFlag(VisitorClause.SkipTake))
            {
                if (resultOperator.ToString().Contains("Skip"))
                {
                    SkipResultOperator skip = resultOperator as SkipResultOperator;
                    builderMongoQuery.AddModifier(Constants.STR_QUERY_MODIFIER_SKIP + skip.Count);
                }
                else if (resultOperator.ToString().Contains("Take"))
                {
                    TakeResultOperator take = resultOperator as TakeResultOperator;
                    builderMongoQuery.AddModifier(Constants.STR_QUERY_MODIFIER_LIMIT + take.Count);
                }
                else
                {
                    throw new KinveyException(EnumErrorCategory.ERROR_GENERAL, EnumErrorCode.ERROR_METHOD_NOT_IMPLEMENTED, "LINQ result operator not supported.");
                }
            }
        }
        public void HandleResultOperator_CreatesAndPreparesSubStatementWithNewProjection_WithoutOrderings()
        {
            var resultOperator = new SkipResultOperator(Expression.Constant(0));

            Assert.That(_sqlStatementBuilder.Orderings, Is.Empty);

            var fakePreparedProjection = GetFakePreparedProjection();

            _stageMock
            .Expect(mock => mock.PrepareSelectExpression(Arg <Expression> .Is.Anything, Arg.Is(_context)))
            .WhenCalled(mi =>
            {
                var selectProjection    = (NewExpression)mi.Arguments[0];
                var rowNumberExpression = (SqlRowNumberExpression)selectProjection.Arguments[1];
                var ordering            = rowNumberExpression.Orderings[0];
                SqlExpressionTreeComparer.CheckAreEqualTrees(ordering.Expression, Expression.Constant(1));
            })
            .Return(fakePreparedProjection);
            _stageMock.Replay();

            _handler.HandleResultOperator(resultOperator, _sqlStatementBuilder, UniqueIdentifierGenerator, _stageMock, _context);

            _stageMock.VerifyAllExpectations();
        }
 public void TestBasicTakeSkip()
 {
     var t = new TypeHandlerCache();
     MEFUtilities.Compose(t);
     GeneratedCode gc = new GeneratedCode();
     gc.Add(new LINQToTTreeLib.Statements.StatementInlineBlock());
     gc.Add(new LINQToTTreeLib.Tests.TestUtils.SimpleLoop());
     var skipper = new SkipResultOperator(Expression.Constant(10));
     ProcessResultOperator(new ROTakeSkipOperators(), skipper, null, gc);
 }
    public void HandleResultOperator_AddsMappingForItemExpression ()
    {
      var originalItemExpression = ((StreamedSequenceInfo) _sqlStatementBuilder.DataInfo).ItemExpression;

      var resultOperator = new SkipResultOperator (Expression.Constant (10));
      StubStageMock_PrepareSelectExpression ();

      _handler.HandleResultOperator (resultOperator, _sqlStatementBuilder, _generator, _stageMock, _context);

      Assert.That (_context.GetExpressionMapping (originalItemExpression), Is.EqualTo (_sqlStatementBuilder.SelectProjection));
    }
    public void HandleResultOperator_SetsCurrentRowNumberOffset ()
    {
      var resultOperator = new SkipResultOperator (Expression.Constant (10));
      StubStageMock_PrepareSelectExpression ();

      _handler.HandleResultOperator (resultOperator, _sqlStatementBuilder, _generator, _stageMock, _context);

      Assert.That (_sqlStatementBuilder.CurrentRowNumberOffset, Is.SameAs (resultOperator.Count));
    }
    public void HandleResultOperator_SetsRowNumberSelector ()
    {
      var resultOperator = new SkipResultOperator (Expression.Constant (10));
      StubStageMock_PrepareSelectExpression ();

      _handler.HandleResultOperator (resultOperator, _sqlStatementBuilder, _generator, _stageMock, _context);

      var expectedRowNumberSelector = Expression.MakeMemberAccess (
          new SqlTableReferenceExpression (_sqlStatementBuilder.SqlTables[0]),
          _tupleCtor.DeclaringType.GetProperty ("Value"));
      SqlExpressionTreeComparer.CheckAreEqualTrees (expectedRowNumberSelector, _sqlStatementBuilder.RowNumberSelector);
    }
    public void HandleResultOperator_SetsOuterDataInfo ()
    {
      var originalDataInfo = _sqlStatementBuilder.DataInfo;

      var resultOperator = new SkipResultOperator (Expression.Constant (10));
      StubStageMock_PrepareSelectExpression ();

      _handler.HandleResultOperator (resultOperator, _sqlStatementBuilder, _generator, _stageMock, _context);

      Assert.That (_sqlStatementBuilder.DataInfo, Is.SameAs (originalDataInfo));
    }
    public void TransformExpressions ()
    {
      var oldExpression = Expression.Constant (0);
      var newExpression = Expression.Constant (1);
      var resultOperator = new SkipResultOperator (oldExpression);

      resultOperator.TransformExpressions (ex =>
      {
        Assert.That (ex, Is.SameAs (oldExpression));
        return newExpression;
      });

      Assert.That (resultOperator.Count, Is.SameAs (newExpression));
    }
 /// <summary>
 /// Visits the result operator.
 /// </summary>
 /// <param name="resultOperator">Result operator.</param>
 /// <param name="queryModel">Query model.</param>
 /// <param name="index">Index.</param>
 public override void VisitResultOperator(ResultOperatorBase resultOperator, QueryModel queryModel, int index)
 {
     if (resultOperator is SkipResultOperator)
     {
         SkipResultOperator @operator = resultOperator as SkipResultOperator;
         this.commandBuilder.LimitParts.From = @operator.GetConstantCount();
     }
     else if (resultOperator is TakeResultOperator)
     {
         TakeResultOperator @operator = resultOperator as TakeResultOperator;
         this.commandBuilder.LimitParts.Count = @operator.GetConstantCount();
     }
     else if (resultOperator is CountResultOperator || resultOperator is LongCountResultOperator)
     {
         this.commandBuilder.IsCount = true;
     }
     else if (resultOperator is FirstResultOperator || resultOperator is SingleResultOperator)
     {
     }
     else if (resultOperator is DistinctResultOperator)
     {
         this.commandBuilder.IsDistinct = true;
     }
     else
     {
         if (resultOperator is AverageResultOperator)
         {
             throw new NotSupportedException();
         }
         if (resultOperator is MaxResultOperator)
         {
             throw new NotSupportedException();
         }
         if (resultOperator is MinResultOperator)
         {
             throw new NotSupportedException();
         }
         if (resultOperator is SumResultOperator)
         {
             throw new NotSupportedException();
         }
         if (resultOperator is ContainsResultOperator)
         {
             throw new NotSupportedException();
         }
         if (resultOperator is DefaultIfEmptyResultOperator)
         {
             throw new NotSupportedException();
         }
         if (resultOperator is ExceptResultOperator)
         {
             throw new NotSupportedException();
         }
         if (resultOperator is GroupResultOperator)
         {
             throw new NotSupportedException();
         }
         if (resultOperator is IntersectResultOperator)
         {
             throw new NotSupportedException();
         }
         if (resultOperator is OfTypeResultOperator)
         {
             throw new NotSupportedException();
         }
         if (resultOperator is UnionResultOperator)
         {
             throw new NotSupportedException();
         }
     }
 }
        public override void SetObjectOperator(ResultOperatorBase resultOperator)
        {
            base.SetObjectOperator(resultOperator);

            if (ObjectVariable != null)
            {
                if (resultOperator is AnyResultOperator)
                {
                    // When using x.Any(), we add a LIMIT 1 the query results in the SparqlQueryGenerator.

                    // When using .Any(x => ..), the variable x is locally scoped and cannot be
                    // used in outer queries. Therefore do not need to actually select it.

                    // This avoids issues with Stardog:
                    // https://community.stardog.com/t/sparql-union-only-working-with-inferencing-enabled/1040/9
                }
                else if (resultOperator is AverageResultOperator)
                {
                    var aggregate = new AverageAggregate(new VariableTerm(ObjectVariable.Name));
                    SetObjectVariable(aggregate.AsSparqlVariable(), true);
                }
                else if (resultOperator is CountResultOperator)
                {
                    var aggregate = new CountDistinctAggregate(new VariableTerm(ObjectVariable.Name));
                    SetObjectVariable(aggregate.AsSparqlVariable(), true);
                }
                else if (resultOperator is FirstResultOperator)
                {
                    // "Using LIMIT and OFFSET to select different subsets of the query solutions
                    // will not be useful unless the order is made predictable by using ORDER BY."
                    // Source: https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#modOffset

                    // Therefore, if no ordering exists we add an ordering on the current subject
                    // to make the query result predictable.
                    if (!QueryModel.BodyClauses.OfType <OrderByClause>().Any())
                    {
                        OrderBy(SubjectVariable);
                    }
                    else
                    {
                        // In case the order was make explicit, we have to do nothing.
                    }

                    Limit(1);
                }
                else if (resultOperator is LastResultOperator)
                {
                    // "Using LIMIT and OFFSET to select different subsets of the query solutions
                    // will not be useful unless the order is made predictable by using ORDER BY."
                    // Source: https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#modOffset

                    // Therefore, if no ordering exists we add an ordering on the current subject
                    // to make the query result predictable.
                    if (!QueryModel.BodyClauses.OfType <OrderByClause>().Any())
                    {
                        OrderByDescending(SubjectVariable);
                    }
                    else
                    {
                        // Inverting the direction of the first ordering is handled in SparqlQueryModelVisitor.VisitOrdering().
                        // This is because the orderings are not necessarily processed *before* the result operators..
                    }

                    Limit(1);
                }
                else if (resultOperator is MaxResultOperator)
                {
                    var aggregate = new MaxAggregate(new VariableTerm(ObjectVariable.Name));
                    SetObjectVariable(aggregate.AsSparqlVariable(), true);
                }
                else if (resultOperator is MinResultOperator)
                {
                    var aggregate = new MinAggregate(new VariableTerm(ObjectVariable.Name));
                    SetObjectVariable(aggregate.AsSparqlVariable(), true);
                }
                else if (resultOperator is SumResultOperator)
                {
                    var aggregate = new SumAggregate(new VariableTerm(ObjectVariable.Name));
                    SetObjectVariable(aggregate.AsSparqlVariable(), true);
                }
                else if (resultOperator is OfTypeResultOperator)
                {
                    OfTypeResultOperator ofType = resultOperator as OfTypeResultOperator;
                    RdfClassAttribute    type   = ofType.SearchedItemType.TryGetCustomAttribute <RdfClassAttribute>();

                    if (type == null)
                    {
                        throw new ArgumentException("No RdfClass attrribute declared on type: " + ofType.SearchedItemType);
                    }

                    SparqlVariable s = ObjectVariable;
                    SparqlVariable p = VariableGenerator.CreatePredicateVariable();
                    SparqlVariable o = VariableGenerator.CreateObjectVariable();

                    WhereResource(s, p, o);
                    WhereResourceOfType(o, ofType.SearchedItemType);
                }
                else if (resultOperator is SkipResultOperator)
                {
                    SkipResultOperator op = resultOperator as SkipResultOperator;
                    Offset(int.Parse(op.Count.ToString()));
                }
                else if (resultOperator is TakeResultOperator)
                {
                    TakeResultOperator op = resultOperator as TakeResultOperator;
                    Limit(int.Parse(op.Count.ToString()));
                }
                else
                {
                    throw new NotImplementedException(resultOperator.ToString());
                }
            }
        }
 public void SetUp ()
 {
   _resultOperator = new SkipResultOperator (Expression.Constant (2));
 }
Example #33
0
        public void GetConstantCount_NoConstantExpression()
        {
            var resultOperator = new SkipResultOperator(new QuerySourceReferenceExpression(ExpressionHelper.CreateMainFromClause_Int()));

            resultOperator.GetConstantCount();
        }
Example #34
0
 public void SetUp()
 {
     _resultOperator = new SkipResultOperator(Expression.Constant(2));
 }
 private static Expression HandleSkip(
     EntityQueryModelVisitor entityQueryModelVisitor, SkipResultOperator skipResultOperator)
     => Expression.Call(
         entityQueryModelVisitor.LinqOperatorProvider.Skip
             .MakeGenericMethod(entityQueryModelVisitor.Expression.Type.GetSequenceType()),
         entityQueryModelVisitor.Expression,
         new DefaultQueryExpressionVisitor(entityQueryModelVisitor)
             .Visit(skipResultOperator.Count));
 private static Expression HandleSkip(
     EntityQueryModelVisitor entityQueryModelVisitor, SkipResultOperator skipResultOperator)
     => Expression.Call(
         entityQueryModelVisitor.LinqOperatorProvider.Skip
             .MakeGenericMethod(entityQueryModelVisitor.StreamedSequenceInfo.ResultItemType),
         entityQueryModelVisitor.Expression, skipResultOperator.Count);
    public void HandleResultOperator_CreatesAndPreparesSubStatementWithNewProjection_WithoutOrderings ()
    {
      var resultOperator = new SkipResultOperator (Expression.Constant (0));

      Assert.That (_sqlStatementBuilder.Orderings, Is.Empty);

      var fakePreparedProjection = GetFakePreparedProjection();

      _stageMock
          .Expect (mock => mock.PrepareSelectExpression (Arg<Expression>.Is.Anything, Arg.Is (_context)))
          .WhenCalled (mi =>
          {
            var selectProjection = (NewExpression) mi.Arguments[0];
            var rowNumberExpression = (SqlRowNumberExpression) selectProjection.Arguments[1];
            var ordering = rowNumberExpression.Orderings[0];
            SqlExpressionTreeComparer.CheckAreEqualTrees (ordering.Expression, Expression.Constant (1));
          })
          .Return (fakePreparedProjection);
      _stageMock.Replay ();

      _handler.HandleResultOperator (resultOperator, _sqlStatementBuilder, _generator, _stageMock, _context);

      _stageMock.VerifyAllExpectations ();
    }
 public void GetConstantCount_NoConstantExpression ()
 {
   var resultOperator = new SkipResultOperator (new QuerySourceReferenceExpression (ExpressionHelper.CreateMainFromClause_Int ()));
   resultOperator.GetConstantCount ();
 }
        public override void VisitResultOperator(ResultOperatorBase resultOperator, QueryModel queryModel, int index)
        {
            resultOptionType = resultOptionType ?? queryModel.SelectClause.Selector.Type;
            if (resultOperator is CastResultOperator)
            {
                CastResultOperator castResultOperator = (CastResultOperator)resultOperator;
                Type       castType = castResultOperator.CastItemType;
                MethodInfo cast     = GetMethod("Cast", expression.Type).MakeGenericMethod(castType);
                resultOptionType = castType;
                expression       = Expression.Call(cast, expression);
                return;
            }
            if (resultOperator is AllResultOperator)
            {
                AllResultOperator   allResultOperator   = (AllResultOperator)resultOperator;
                ParameterExpression parameterExpression = Expression.Parameter(selectorType, "p");
                Expression          predicateUpdate     = UpdateExpressionVisitor.Update(allResultOperator.Predicate, new[] { parameterExpression }, dbContext, queryContext);
                Expression          allLamda            = Expression.Lambda(predicateUpdate, parameterExpression);
                MethodInfo          all = GetMethod("All", expression.Type, 1).MakeGenericMethod(selectorType);
                expression = Expression.Call(all, new[] { expression, allLamda });
                return;
            }
            if (resultOperator is FirstResultOperator)
            {
                FirstResultOperator firstResultOperator = (FirstResultOperator)resultOperator;
                if (firstResultOperator.ReturnDefaultWhenEmpty)
                {
                    MethodInfo firstOrDefault = GetMethod("FirstOrDefault", expression.Type, 0).MakeGenericMethod(selectorType);
                    expression = Expression.Call(firstOrDefault, new[] { expression });
                }
                else
                {
                    MethodInfo first = GetMethod("First", expression.Type, 0).MakeGenericMethod(selectorType);
                    expression = Expression.Call(first, new[] { expression });
                }
                return;
            }
            if (resultOperator is SingleResultOperator)
            {
                SingleResultOperator singleResultOperator = (SingleResultOperator)resultOperator;
                if (singleResultOperator.ReturnDefaultWhenEmpty)
                {
                    MethodInfo firstOrDefault = GetMethod("SingleOrDefault", expression.Type, 0).MakeGenericMethod(selectorType);
                    expression = Expression.Call(firstOrDefault, new[] { expression });
                }
                else
                {
                    MethodInfo first = GetMethod("Single", expression.Type, 0).MakeGenericMethod(selectorType);
                    expression = Expression.Call(first, new[] { expression });
                }
                return;
            }
            if (resultOperator is AnyResultOperator)
            {
                MethodInfo any = GetMethod("Any", expression.Type).MakeGenericMethod(selectorType);
                expression = Expression.Call(any, new[] { expression });
                return;
            }
            if (resultOperator is TrackingResultOperator)
            {
                MethodInfo asNoTracking = typeof(EntityFrameworkQueryableExtensions).GetMethod("AsNoTracking").MakeGenericMethod(selectorType);
                expression = Expression.Call(asNoTracking, new[] { expression });
                return;
            }
            if (resultOperator is CountResultOperator)
            {
                MethodInfo count = GetMethod("Count", expression.Type).MakeGenericMethod(selectorType);
                expression = Expression.Call(count, new[] { expression });
                return;
            }
            if (resultOperator is AverageResultOperator)
            {
                MethodInfo average = GetAgregateMethod("Average", expression.Type, selectorType);
                expression = Expression.Call(average, new[] { expression });
                return;
            }
            if (resultOperator is ContainsResultOperator)
            {
                ContainsResultOperator containsResultOperator = (ContainsResultOperator)resultOperator;
                Expression             valExp;
                object value;
                ParameterExpression paramExp = containsResultOperator.Item as ParameterExpression;
                if (paramExp != null &&
                    queryContext.ParameterValues.TryGetValue(paramExp.Name, out value))
                {
                    valExp = Expression.Constant(value);
                }
                else
                {
                    valExp = containsResultOperator.Item;
                }
                if (containsResultOperator.Item is SubQueryExpression)
                {
                    SubQueryExpression subQueryExpression = (SubQueryExpression)containsResultOperator.Item;
                    QueryModelVisitor  queryModelVisitor  = new QueryModelVisitor(dbContext, queryContext);
                    queryModelVisitor.VisitQueryModel(subQueryExpression.QueryModel);
                    valExp = queryModelVisitor.expression;
                }

                MethodInfo contains = GetMethod("Contains", expression.Type, 1).MakeGenericMethod(selectorType);
                expression = Expression.Call(contains, new[] { expression, valExp });
                return;
            }
            if (resultOperator is DefaultIfEmptyResultOperator)
            {
                DefaultIfEmptyResultOperator defaultIfEmptyResultOperator = (DefaultIfEmptyResultOperator)resultOperator;
                MethodInfo defaultIfEmpty;
                if (defaultIfEmptyResultOperator.OptionalDefaultValue != null)
                {
                    defaultIfEmpty = GetMethod("DefaultIfEmpty", expression.Type, 1).MakeGenericMethod(selectorType);
                    expression     = Expression.Call(defaultIfEmpty, new[] { expression, defaultIfEmptyResultOperator.OptionalDefaultValue });
                }
                defaultIfEmpty = GetMethod("DefaultIfEmpty", expression.Type).MakeGenericMethod(selectorType);
                expression     = Expression.Call(defaultIfEmpty, expression);
                return;
            }
            if (resultOperator is DistinctResultOperator)
            {
                MethodInfo distinct = GetMethod("Distinct", expression.Type).MakeGenericMethod(selectorType);
                expression = Expression.Call(distinct, expression);
                return;
            }
            if (resultOperator is GroupResultOperator)
            {
                GroupResultOperator groupResultOperator = (GroupResultOperator)resultOperator;
                Type keySelectorType = GetTypeParameter(groupResultOperator.KeySelector);
                ParameterExpression keyExpressionParam  = Expression.Parameter(keySelectorType, "p");
                Expression          keyExpression       = UpdateExpressionVisitor.Update(groupResultOperator.KeySelector, new[] { keyExpressionParam }, dbContext, queryContext);
                LambdaExpression    keyLambdaExpression = Expression.Lambda(keyExpression, keyExpressionParam);
                Type elementSelectorType = GetTypeParameter(groupResultOperator.ElementSelector);
                ParameterExpression ElementExpressionParam  = Expression.Parameter(elementSelectorType, "p");
                Expression          ElementExpression       = UpdateExpressionVisitor.Update(groupResultOperator.ElementSelector, new[] { ElementExpressionParam }, dbContext, queryContext);
                LambdaExpression    ElementLambdaExpression = Expression.Lambda(ElementExpression, ElementExpressionParam);
                Type       tSource  = queryModel.MainFromClause.ItemType;
                Type       tKey     = keyExpression.Type;
                Type       tElement = ElementExpression.Type;
                Type       tResult  = queryModel.ResultTypeOverride;
                MethodInfo groupBy  = GetMethods("GroupBy", expression.Type, 2).Where(p => p.GetParameters()[2].Name == "elementSelector").Single().
                                      MakeGenericMethod(tSource, tKey, tElement);
                expression = Expression.Call(groupBy, new[] { expression, keyLambdaExpression, ElementLambdaExpression });
                return;
            }
            if (resultOperator is LastResultOperator)
            {
                LastResultOperator lastResultOperator = (LastResultOperator)resultOperator;
                if (lastResultOperator.ReturnDefaultWhenEmpty)
                {
                    MethodInfo lastOrDefault = GetMethod("LastOrDefault", expression.Type, 0).MakeGenericMethod(selectorType);
                    expression = Expression.Call(lastOrDefault, new[] { expression });
                }
                else
                {
                    MethodInfo last = GetMethod("Last", expression.Type, 0).MakeGenericMethod(selectorType);
                    expression = Expression.Call(last, new[] { expression });
                }
                return;
            }
            if (resultOperator is LongCountResultOperator)
            {
                MethodInfo longCount = GetMethod("LongCount", expression.Type).MakeGenericMethod(selectorType);
                expression = Expression.Call(longCount, new[] { expression });
                return;
            }
            if (resultOperator is MaxResultOperator)
            {
                MethodInfo max = GetMethod("Max", expression.Type).MakeGenericMethod(selectorType);
                expression = Expression.Call(max, expression);
                return;
            }
            if (resultOperator is MinResultOperator)
            {
                MethodInfo min = GetMethod("Min", expression.Type).MakeGenericMethod(selectorType);
                expression = Expression.Call(min, expression);
                return;
            }
            if (resultOperator is SumResultOperator)
            {
                MethodInfo sum = GetAgregateMethod("Sum", expression.Type, selectorType);
                expression = Expression.Call(sum, expression);
                return;
            }
            if (resultOperator is SkipResultOperator)
            {
                SkipResultOperator  skipResultOperator = (SkipResultOperator)resultOperator;
                Expression          expVal;
                object              value;
                ParameterExpression paramExp = skipResultOperator.Count as ParameterExpression;
                if (paramExp != null &&
                    queryContext.ParameterValues.TryGetValue(paramExp.Name, out value))
                {
                    expVal = Expression.Constant(value);
                }
                else
                {
                    expVal = skipResultOperator.Count;
                }
                MethodInfo skip = GetMethod("Skip", expression.Type, 1).MakeGenericMethod(selectorType);
                expression = Expression.Call(skip, new[] { expression, expVal });
                return;
            }
            if (resultOperator is TakeResultOperator)
            {
                TakeResultOperator  takeResultOperator = (TakeResultOperator)resultOperator;
                Expression          expVal;
                object              value;
                ParameterExpression paramExp = takeResultOperator.Count as ParameterExpression;
                if (paramExp != null &&
                    queryContext.ParameterValues.TryGetValue(paramExp.Name, out value))
                {
                    expVal = Expression.Constant(value);
                }
                else
                {
                    expVal = takeResultOperator.Count;
                }
                MethodInfo take = GetMethod("Take", expression.Type, 1).MakeGenericMethod(selectorType);
                expression = Expression.Call(take, new[] { expression, expVal });
                return;
            }
            if (resultOperator is IncludeResultOperator)
            {
                IncludeResultOperator includeResultOperator = (IncludeResultOperator)resultOperator;
                Expression            includeExpression     = includeResultOperator.NavigationPropertyPath;
                Type paramExpressionType = null;
                ParameterExpression parameterExpression = null;
                if (includeExpression is MemberExpression)
                {
                    MemberExpression memberExpression = (MemberExpression)includeExpression;
                    paramExpressionType = memberExpression.Expression.Type;
                    parameterExpression = Expression.Parameter(paramExpressionType, "p");
                    includeExpression   = Expression.Property(parameterExpression, memberExpression.Member.Name);
                }
                else
                {
                    paramExpressionType = GetTypeParameter(includeExpression);
                    parameterExpression = Expression.Parameter(paramExpressionType, "p");
                }
                Expression       updateOuterExpression   = UpdateExpressionVisitor.Update(includeExpression, new[] { parameterExpression }, dbContext, queryContext);
                LambdaExpression lambdaIncludeExpression = Expression.Lambda(updateOuterExpression, parameterExpression);
                MethodInfo       include = typeof(EntityFrameworkQueryableExtensions).GetMethods().First(m => m.Name == "Include").MakeGenericMethod(selectorType, updateOuterExpression.Type);
                expression = Expression.Call(include, new[] { expression, lambdaIncludeExpression });

                if (includeResultOperator.ChainedNavigationProperties != null)
                {
                    foreach (PropertyInfo propertyInfo in includeResultOperator.ChainedNavigationProperties)
                    {
                        Type       propertyType = propertyInfo.PropertyType;
                        Type       argument     = expression.Type.GetGenericArguments().Last();
                        MethodInfo thenInclude;
                        Type       realType;
                        if (typeof(IEnumerable).IsAssignableFrom(argument))
                        {
                            realType    = argument.GetGenericArguments().First();
                            thenInclude = ThenIncludeCollection.MakeGenericMethod(includeResultOperator.QuerySource.ItemType, realType, propertyType);
                        }
                        else
                        {
                            realType    = argument;
                            thenInclude = ThenIncludeProperty.MakeGenericMethod(includeResultOperator.QuerySource.ItemType, realType, propertyType);
                        }
                        ParameterExpression parameterThenIncludeExpression = Expression.Parameter(realType, "p");
                        MemberExpression    property = Expression.Property(parameterThenIncludeExpression, propertyInfo);
                        LambdaExpression    lambdaThenIncludeExpression = Expression.Lambda(property, parameterThenIncludeExpression);
                        expression = Expression.Call(thenInclude, new[] { expression, lambdaThenIncludeExpression });
                    }
                }
                return;
            }
            if (resultOperator is OfTypeResultOperator)
            {
                OfTypeResultOperator ofTypeResultOperator = (OfTypeResultOperator)resultOperator;
                selectorType = ofTypeResultOperator.SearchedItemType;
                var miOfType = GetMethod("OfType", expression.Type).MakeGenericMethod(ofTypeResultOperator.SearchedItemType);
                expression = Expression.Call(miOfType, new[] { expression });
                return;
            }
            throw new NotSupportedException();
        }
    public void HandleResultOperator_RemovesOrderingsFromSubStatement_IfNoTopExpression ()
    {
      var resultOperator = new SkipResultOperator (Expression.Constant (0));

      _sqlStatementBuilder.Orderings.Add (_ordering);
      Assert.That (_sqlStatementBuilder.TopExpression, Is.Null);
      StubStageMock_PrepareSelectExpression();

      _handler.HandleResultOperator (resultOperator, _sqlStatementBuilder, _generator, _stageMock, _context);

      var subStatement = GetSubStatement(_sqlStatementBuilder.SqlTables[0]);
      Assert.That (subStatement.Orderings, Is.Empty);
    }
Example #41
0
		private void ProcessSkipOperator(SkipResultOperator resultOperator)
		{
			_additionalCriteria.Add(q => q.SetFirstResult(resultOperator.GetConstantCount()));
		}
    public void HandleResultOperator_LeavesOrderingsInSubStatement_IfTopExpression ()
    {
      var resultOperator = new SkipResultOperator (Expression.Constant (0));

      _sqlStatementBuilder.Orderings.Add (_ordering);
      _sqlStatementBuilder.TopExpression = Expression.Constant (20);
      StubStageMock_PrepareSelectExpression ();

      _handler.HandleResultOperator (resultOperator, _sqlStatementBuilder, _generator, _stageMock, _context);

      var subStatement = GetSubStatement (_sqlStatementBuilder.SqlTables[0]);
      Assert.That (subStatement.Orderings, Is.Not.Empty);
      Assert.That (subStatement.Orderings, Is.EqualTo (new[] { _ordering }));
    }
        private void VisitSkipResultOperator(SkipResultOperator skipResultOperation, Remotion.Linq.QueryModel queryModel, int index)
        {
            if (!(skipResultOperation.Count is System.Linq.Expressions.ConstantExpression))
            {
                throw new InvalidOperationException("Only constant expressions are supported for the Skip operators.");
            }

            _query.Offset = Convert.ToInt32(((System.Linq.Expressions.ConstantExpression)skipResultOperation.Count).Value);
        }
    public void HandleResultOperator_CalculatesDataInfo ()
    {
      var resultOperator = new SkipResultOperator (Expression.Constant (0));
      StubStageMock_PrepareSelectExpression ();

      _handler.HandleResultOperator (resultOperator, _sqlStatementBuilder, _generator, _stageMock, _context);

      var subStatement = GetSubStatement (_sqlStatementBuilder.SqlTables[0]);
      Assert.That (subStatement.DataInfo, Is.InstanceOf (typeof (StreamedSequenceInfo)));
      Assert.That (subStatement.DataInfo.DataType, Is.EqualTo(typeof (IQueryable<KeyValuePair<Cook, int>>)));
    }