Ejemplo n.º 1
0
        public void LdapFilter_NestedExpression_Value()
        {
            string result =
                _translator.Translate <LdapUser>(x =>
                                                 (x.CommonName == "gosho" || x.DistinguishedName == "pesho") && x.GivenName == "sasho" ||
                                                 x.CommonName == "tisho");


            Assert.AreEqual("(|(&(|(cn=gosho)(dn=pesho))(gn=sasho))(cn=tisho))", result);
        }
Ejemplo n.º 2
0
 internal void OrderBy <T>(Expression <T> predicate, SORTTYPE type)
 {
     try
     {
         var result = _translateQuery.Translate(predicate, ClauseType.OrderBy);
         _sqlBuilder.OrderBy(TranslateToNativeColumn(result.CommandText), type);
     }
     catch (Exception e)
     {
         this._dbError.Code = ErrorCode.InvalidOperation;
         this._dbError.Text = e.Message;
     }
 }
Ejemplo n.º 3
0
        /// <summary>
        ///     Executes expression query.
        /// </summary>
        /// <param name="expression">Expression.</param>
        /// <returns>Result.</returns>
        public override object Execute(Expression expression)
        {
            if (expression == null)
            {
                throw new ArgumentNullException(nameof(expression));
            }

            var result = new TranslationResult();

            _queryTranslator.Translate(expression, result);

            IEnumerable <DynamicTableEntity> tableEntities = _cloudTable.ExecuteQuery(result.TableQuery);

            return(GetProcessedResult(tableEntities, result));
        }
Ejemplo n.º 4
0
        public IEnumerable <T> Get <T>(string collection, Expression <Func <T, bool> > filter = null) where T : class, new()
        {
            var qt      = new QueryTranslator <T>();
            var tfilter = qt.Translate(filter) as Expression <Func <JObject, bool> >;

            return(GetJSon(collection, tfilter).Select(doc => JsonConvert.DeserializeObject <T>(doc)).AsEnumerable());
        }
Ejemplo n.º 5
0
        public ExecutionResult Execute(Query query)
        {
            var translator = new QueryTranslator();
            var translated = translator.Translate(query);
            var result     = new ExecutionResult();

            using (var connection = _factory.OpenSubjectDbConnection())
            {
                using var command = new NpgsqlCommand(translated.Sql, connection);
                foreach (var parameter in translated.Parameters)
                {
                    command.Parameters.AddWithValue(parameter.Key, parameter.Value);
                }

                using var reader = command.ExecuteReader();
                while (reader.Read())
                {
                    result.Data.Add(new List <string>());
                    for (var field = 0; field < reader.FieldCount; ++field)
                    {
                        var value = reader[field].ToString();
                        result.Data[result.Data.Count - 1].Add(value);
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 6
0
        public void Test_Distinct_With_Count_And_Select()
        {
            using (var db = new TestingContext())
            {
                var query = db.Blogs
                            .Where(b => b.BlogId > 0)
                            .Select(b => new
                {
                    b.BlogId,
                    Cnt = b.Posts.Select(p => p.Title).Distinct().Count()
                });

                var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqliteObjectFactory());
                var sql    = script.ToString();

                const string expected = @"
select b0.BlogId, coalesce(sq0.count0, 0) as 'Cnt'
from Blogs b0
left outer join (
    select distinct sq0.Title, sq0.BlogId_jk0, count(1) as 'count0'
    from (
        select p0.BlogId as 'BlogId_jk0', p0.Title
        from Posts p0
        group by p0.BlogId, p0.Title
    ) sq0
) sq0 on b0.BlogId = sq0.BlogId_jk0
where b0.BlogId > 0";

                TestUtils.AssertStringEqual(expected, sql);
            }
        }
Ejemplo n.º 7
0
        public int Count <T>(Expression <Func <T, bool> > filter) where T : class, new()
        {
            var qt      = new QueryTranslator <T>();
            var tfilter = qt.Translate(filter) as Expression <Func <JObject, bool> >;

            return(Count(typeof(T).Name, tfilter));
        }
Ejemplo n.º 8
0
        public void Test_Basic_With_Condition()
        {
            using (var db = new TestingContext())
            {
                var query = db.Posts.
                            Where(p => p.Content != null).
                            GroupBy(p => p.BlogId).
                            Select(g => new
                {
                    BID = g.Key,
                    cnt = g.Count(p => p.Blog.Url != null || p.User.UserId > 0)
                });

                var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqliteObjectFactory());
                var sql    = script.ToString();

                const string expected = @"
select p0.BlogId as 'BID', count(case
    when (b0.Url is not null) or (u0.UserId > 0) then 1
    else null
end) as 'cnt'
from Posts p0
left outer join Blogs b0 on p0.BlogId = b0.BlogId
left outer join Users u0 on p0.UserId = u0.UserId
where p0.Content is not null
group by p0.BlogId";

                TestUtils.AssertStringEqual(expected, sql);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Convert the query expression into an execution plan
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public virtual Expression GetExecutionPlan(Expression expression)
        {
            // strip off lambda for now
            LambdaExpression lambda = expression as LambdaExpression;

            if (lambda != null)
            {
                expression = lambda.Body;
            }

            QueryTranslator translator = this.CreateTranslator();

            // translate query into client & server parts
            Expression translation = translator.Translate(expression);

            var        parameters         = lambda != null ? lambda.Parameters : null;
            Expression providerExpression = this.Find(expression, parameters, typeof(EntityProvider));

            if (providerExpression == null)
            {
                Expression rootQueryable = this.Find(expression, parameters, typeof(IQueryable));
                providerExpression = Expression.Property(rootQueryable, typeof(IQueryable).GetProperty(nameof(IQueryable.Provider)));
            }


            return(translator.Police.BuildExecutionPlan(translation, providerExpression));
        }
        public void TranslateExpressionWithInvocations()
        {
            // Arrange
            var country1 = new Country {
                Continent = "Europe"
            };
            var country2 = new Country {
                Continent = "South America", Name = "Brazil"
            };

            Expression <Func <Country, bool> > predicate = country => country.Continent == country1.Continent;

            predicate = Or(predicate, country => country.Continent == country2.Continent);
            predicate = And(predicate, country => country.Name == country2.Name);

            IQueryable <Country> query = GetQueryable <Country>().Where(predicate);

            var translator  = new QueryTranslator(_nameChanges);
            var translation = new TranslationResult();

            // Act
            translator.Translate(query.Expression, translation);

            // Assert
            Assert.NotNull(translation.TableQuery);
            Assert.NotNull(translation.TableQuery.FilterString);
            Assert.Equal("(PartitionKey eq 'Europe' or PartitionKey eq 'South America') and RowKey eq 'Brazil'", translation.TableQuery.FilterString);
        }
Ejemplo n.º 11
0
        public void TranslateWhereStartsWith()
        {
            var TestObject = new QueryTranslator <AllReferencesAndID>(Mappings, QueryProviders);
            IQueryable <AllReferencesAndID> TestQuery = new Query <AllReferencesAndID>(new DbContext <AllReferencesAndID>());

            TestQuery = TestQuery.Where(x => x.StringValue1.StartsWith("ABC"))
                        .Where(x => x.StringValue1.EndsWith("ABC"))
                        .Where(x => x.StringValue1.Contains("ABC"));
            var TempData = TestObject.Translate(TestQuery.Expression);

            Assert.Equal(2, TempData.Count);
            var Result = TempData[Mappings.Sources.First(x => x.Source.Name == "Default")];

            Assert.Equal("WHERE ((([dbo].[AllReferencesAndID_].[StringValue1_] LIKE @1) AND ([dbo].[AllReferencesAndID_].[StringValue1_] LIKE @2)) AND ([dbo].[AllReferencesAndID_].[StringValue1_] LIKE @3))", Result.WhereClause.ToString());
            var Parameters = Result.WhereClause.GetParameters();

            Assert.Equal("1", Parameters[0].ID);
            Assert.Equal("ABC%", Parameters[0].InternalValue);
            Assert.Equal(DbType.String, Parameters[0].DatabaseType);
            Assert.Equal("2", Parameters[1].ID);
            Assert.Equal("%ABC", Parameters[1].InternalValue);
            Assert.Equal(DbType.String, Parameters[1].DatabaseType);
            Assert.Equal("3", Parameters[2].ID);
            Assert.Equal("%ABC%", Parameters[2].InternalValue);
            Assert.Equal(DbType.String, Parameters[2].DatabaseType);
        }
Ejemplo n.º 12
0
        public void Test_On_Children_With_Condition()
        {
            using (var db = new TestingContext())
            {
                var query = db.Blogs.
                            Where(b => b.Url != null).
                            Select(b => new
                {
                    b.Url,
                    b.User.UserId,
                    cnt = b.Posts.Count(p => p.User.UserName != null)
                });

                var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqliteObjectFactory());
                var sql    = script.ToString();

                const string expected = @"
select b0.Url, u0.UserId, coalesce(sq0.count0, 0) as 'cnt'
from Blogs b0
left outer join Users u0 on b0.UserId = u0.UserId
left outer join (
    select p0.BlogId as 'BlogId_jk0', count(case
        when u0.UserName is not null then 1
        else null
    end) as 'count0'
    from Posts p0
    inner join Users u0 on p0.UserId = u0.UserId
    group by p0.BlogId
) sq0 on b0.BlogId = sq0.BlogId_jk0
where b0.Url is not null";

                TestUtils.AssertStringEqual(expected, sql);
            }
        }
        public void Test_Multiple_Aggregatons()
        {
            using (var db = new TestingContext())
            {
                var query = db.Blogs
                            .Select(b => new
                {
                    Cnt1 = b.Posts.Count(p => p.LikeCount > 10),
                    Cnt2 = b.Posts.Count(p => p.LikeCount < 50)
                });

                var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqliteObjectFactory());
                var sql    = script.ToString();

                const string expected = @"
select coalesce(sq0.count0, 0) as 'Cnt1', coalesce(sq0.count1, 0) as 'Cnt2'
from Blogs b0
left outer join (
    select p0.BlogId as 'BlogId_jk0', count(case
        when p0.LikeCount > 10 then 1
        else null
    end) as 'count0', count(case
        when p0.LikeCount < 50 then 1
        else null
    end) as 'count1'
    from Posts p0
    group by p0.BlogId
) sq0 on b0.BlogId = sq0.BlogId_jk0";

                TestUtils.AssertStringEqual(expected, sql);
            }
        }
Ejemplo n.º 14
0
        public void TestDistinct()
        {
            using (var db = new TestingContext())
            {
                var query = db.Blogs
                            .Where(b => b.Url != null && b.Name.StartsWith("Ethan"))
                            .Select(g => new
                {
                    User  = g.User.UserName,
                    Count = g.Posts.Distinct().Count()
                });

                var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new PostgresQlObjectFactory());
                var sql    = script.ToString();

                Console.WriteLine(sql);

                const string expected = @"
select u0.""UserName"" as ""User"", coalesce(sq0.""count0"", 0) as ""Count""
from public.""Blogs"" b0
left outer join public.""Users"" u0 on b0.""UserId"" = u0.""UserId""
left outer join (
    select distinct p0.""BlogId"" as ""BlogId_jk0"", p0.""PostId"", count(1) as ""count0""
    from public.""Posts"" p0
    group by p0.""BlogId"", p0.""PostId""
) sq0 on b0.""BlogId"" = sq0.""BlogId_jk0""
where (b0.""Url"" is not null) and (b0.""Name"" like 'Ethan%')";

                TestUtils.AssertStringEqual(expected, sql);
            }
        }
Ejemplo n.º 15
0
        public void Test_GroupBy_On_Aggregation3()
        {
            using (var db = new TestingContext())
            {
                var query = db.Blogs.
                            Where(b => b.Url != null).
                            GroupBy(b => new { Cnt = b.Posts.Count(), Avg = b.Posts.Average(p => p.LikeCount) }).
                            Select(x => new { x.Key.Cnt, x.Key.Avg, CommentCount = x.Sum(b => b.CommentCount) });

                var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqlObjectFactory());
                var sql    = script.ToString();

                const string expected = @"
select coalesce(sq0.count0, 0) as 'Cnt', coalesce(sq0.avg0, 0) as 'Avg', sum(b0.CommentCount) as 'CommentCount'
from Blogs b0
left outer join (
    select p0.BlogId as 'BlogId_jk0', count(1) as 'count0', avg(p0.LikeCount) as 'avg0'
    from Posts p0
    group by p0.BlogId
) sq0 on b0.BlogId = sq0.BlogId_jk0
where b0.Url is not null
group by coalesce(sq0.count0, 0), coalesce(sq0.avg0, 0)";

                TestUtils.AssertStringEqual(expected, sql);
            }
        }
        public void Test_Multiple_Select_Calls_After_Grouping()
        {
            using (var db = new TestingContext())
            {
                var query = db.Posts
                            .Where(p => p.Content != null)
                            .Select(p => new { p.Blog })
                            .GroupBy(g => new { g.Blog, g.Blog.Url })
                            .Select(p => new { p.Key.Blog, p.Key.Blog.User, p.Key.Url })
                            .Select(g => new { g.Blog.Name, g.User.UserName, g.Url });

                var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqliteObjectFactory());
                var sql    = script.ToString();

                const string expected = @"
select sq0.Name, u0.UserName, sq0.Url
from (
    select b0.Url, b0.BlogId, b0.UserId as 'UserId_jk0', b0.Name
    from Posts p0
    left outer join Blogs b0 on p0.BlogId = b0.BlogId
    where p0.Content is not null
) sq0
left outer join Users u0 on sq0.UserId_jk0 = u0.UserId
group by sq0.BlogId, sq0.Url, u0.UserId, sq0.Name, u0.UserName";

                TestUtils.AssertStringEqual(expected, sql);
            }
        }
Ejemplo n.º 17
0
        public void Test_GroupBy_On_Aggregation4()
        {
            using (var db = new TestingContext())
            {
                var query = db.Blogs.
                            Where(b => b.Url != null).
                            GroupBy(b => b.Posts.Count()).
                            Select(x => new { x.Key, Sum = x.Sum(b => b.Comments.Count()) });

                var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqlObjectFactory());
                var sql    = script.ToString();

                const string expected = @"
select coalesce(sq0.count0, 0) as 'Key', sum(coalesce(sq1.count1, 0)) as 'Sum'
from Blogs b0
left outer join (
    select p0.BlogId as 'BlogId_jk0', count(1) as 'count0'
    from Posts p0
    group by p0.BlogId
) sq0 on b0.BlogId = sq0.BlogId_jk0
left outer join (
    select c0.BlogId as 'BlogId_jk0', count(1) as 'count1'
    from Comments c0
    group by c0.BlogId
) sq1 on b0.BlogId = sq1.BlogId_jk0
where b0.Url is not null
group by coalesce(sq0.count0, 0)";

                TestUtils.AssertStringEqual(expected, sql);
            }
        }
        public void Test_Query_SupportValueTypes()
        {
            using (var db = new TestingContext())
            {
                var query = db.Statistics
                            .GroupBy(s => s.BlogId)
                            .Select(g => new
                {
                    BId        = g.Key,
                    FloatVal   = g.Sum(s => s.FloatVal),
                    DecimalVal = g.Sum(s => s.DecimalVal),
                    DoubleVal  = g.Sum(s => s.DoubleVal)
                });

                var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqlObjectFactory());
                var sql    = script.ToString();

                Console.WriteLine(sql);

                const string expected = @"
select s0.BlogId as 'BId', sum(s0.FloatVal) as 'FloatVal', sum(s0.DecimalVal) as 'DecimalVal', sum(s0.DoubleVal) as 'DoubleVal'
from Statistics s0
group by s0.BlogId";

                TestUtils.AssertStringEqual(expected, sql);
            }
        }
Ejemplo n.º 19
0
        public void Test_OnChildRelation()
        {
            using (var db = new TestingContext())
            {
                var query = db.Blogs
                            .Where(b => b.Url.StartsWith("ethan.com"))
                            .OrderBy(b => b.Posts.Sum(p => p.LikeCount));

                var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqlObjectFactory());
                var sql    = script.ToString();

                const string expected = @"
select b0.*
from Blogs b0
left outer join (
    select p0.BlogId as 'BlogId_jk0', sum(p0.LikeCount) as 'sum0'
    from Posts p0
    group by p0.BlogId
) sq0 on b0.BlogId = sq0.BlogId_jk0
where b0.Url like 'ethan.com%'
order by coalesce(sq0.sum0, 0)";

                TestUtils.AssertStringEqual(expected, sql);
            }
        }
        public void Test_DistinctCount_On_Child_Relation()
        {
            using (var db = new TestingContext())
            {
                var query = db.Blogs.
                            Where(b => b.Url != null).
                            Select(b => new
                {
                    b.Name,
                    cnt = b.Posts.DistinctCount(p => p.PostId)
                });

                var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqliteObjectFactory());
                var sql    = script.ToString();

                const string expected = @"
select b0.Name, coalesce(sq0.count0, 0) as 'cnt'
from Blogs b0
left outer join (
    select p0.BlogId as 'BlogId_jk0', count(distinct p0.PostId) as 'count0'
    from Posts p0
    group by p0.BlogId
) sq0 on b0.BlogId = sq0.BlogId_jk0
where b0.Url is not null";

                TestUtils.AssertStringEqual(expected, sql);
            }
        }
Ejemplo n.º 21
0
        public void Test_Basic_Expression()
        {
            using (var db = new TestingContext())
            {
                var query = db.Posts.
                            Where(p => p.Content != null).
                            GroupBy(p => p.BlogId).
                            Select(g => new
                {
                    BId = g.Key,
                    cnt = g.Count(),
                    Exp = g.Sum(p => p.User.UserId) * g.Count(p => p.Content.StartsWith("Ethan"))
                });

                var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqlObjectFactory());
                var sql    = script.ToString();

                const string expected = @"
select p0.BlogId as 'BId', count(1) as 'cnt', sum(u0.UserId) * count(case
    when p0.Content like 'Ethan%' then 1
    else null
end) as 'Exp'
from Posts p0
inner join Users u0 on p0.UserId = u0.UserId
where p0.Content is not null
group by p0.BlogId";

                TestUtils.AssertStringEqual(expected, sql);
            }
        }
Ejemplo n.º 22
0
        public virtual List <SkinnyItem> RunQuery(QueryBase query, bool showAllVersions)
        {
            var translator  = new QueryTranslator(Index);
            var luceneQuery = translator.Translate(query);

            return(RunQuery(luceneQuery, showAllVersions));
        }
Ejemplo n.º 23
0
        public void Sorting()
        {
            var translator = new QueryTranslator();
            var query      = new Query();

            query.SelectAttributes.AddRange(new List <string> {
                "Название империи", "Название планеты"
            });
            query.SortAttributes.AddRange(new List <SortAttribute>
            {
                new SortAttribute
                {
                    AttributeName = "Название империи",
                    Direction     = SortDirection.Ascending
                },
                new SortAttribute
                {
                    AttributeName = "Мощь империи",
                    Direction     = SortDirection.Descending
                }
            });

            var dbQuery = translator.Translate(query);
            var sql     = "select \"empires\".\"name\", \"planets\".\"name\"\n" +
                          "from \"empires\"\n" +
                          "join \"planets\" on \"planets\".\"empire_id\" = \"empires\".\"id\"\n" +
                          "order by \"empires\".\"name\" asc, \"empires\".\"power\" desc;";

            Assert.Equal(sql, dbQuery.Sql);
        }
        public void Test_Translate_Filter_On_Multi_Level_Relation()
        {
            using (var db = new TestingContext())
            {
                var query = db.Blogs.Where(b => b.User.Comments.Any(c => c.Post.Content != null));

                var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqliteObjectFactory());
                var sql    = script.ToString();

                const string expected = @"
select b0.*
from Blogs b0
inner join Users u0 on b0.UserId = u0.UserId
left outer join (
    select c0.UserId as 'UserId_jk0'
    from Comments c0
    inner join Posts p0 on c0.PostId = p0.PostId
    where p0.Content is not null
    group by c0.UserId
) sq0 on u0.UserId = sq0.UserId_jk0
where sq0.UserId_jk0 is not null";

                TestUtils.AssertStringEqual(expected, sql);
            }
        }
Ejemplo n.º 25
0
        public void TranslateWhere()
        {
            var TestObject = new QueryTranslator <AllReferencesAndID>(Mappings, QueryProviders);
            IQueryable <AllReferencesAndID> TestQuery = new Query <AllReferencesAndID>(new DbContext <AllReferencesAndID>());
            const int LocalVariable = 45;

            TestQuery = TestQuery.Where(x => !x.BoolValue)
                        .Where(x => x.ByteValue > 14)
                        .Where(x => x.IntValue < LocalVariable);
            var TempData = TestObject.Translate(TestQuery.Expression);

            Assert.Equal(2, TempData.Count);
            var Result = TempData[Mappings.Sources.First(x => x.Source.Name == "Default")];

            Assert.Equal("WHERE ((([dbo].[AllReferencesAndID_].[BoolValue_] <> @0) AND (([dbo].[AllReferencesAndID_].[ByteValue_]) > @2)) AND ([dbo].[AllReferencesAndID_].[IntValue_] < @3))", Result.WhereClause.ToString());
            var Parameters = Result.WhereClause.GetParameters();

            Assert.Equal("0", Parameters[0].ID);
            Assert.True((bool)Parameters[0].InternalValue);
            Assert.Equal(DbType.Boolean, Parameters[0].DatabaseType);
            Assert.Equal("2", Parameters[1].ID);
            Assert.Equal(14, Parameters[1].InternalValue);
            Assert.Equal(DbType.Int32, Parameters[1].DatabaseType);
            Assert.Equal("3", Parameters[2].ID);
            Assert.Equal(45, Parameters[2].InternalValue);
            Assert.Equal(DbType.Int32, Parameters[2].DatabaseType);
        }
        public static IEnumerable <dynamic> QueryDynamic(this DbContext db,
                                                         IQueryable query, IModelInfoProvider infoProvider, IDbObjectFactory factory, out string sql,
                                                         AbstractMethodTranslator[] addons = null)
        {
            var connection = db.Database.GetDbConnection();

            if (connection.State != ConnectionState.Open)
            {
                connection.Open();
            }

            var script = QueryTranslator.Translate(query.Expression, infoProvider, factory, addons);

            var constants = script.Parameterise();
            var dParams   = new DynamicParameters();

            foreach (var dbConstant in constants)
            {
                dParams.Add(dbConstant.ParamName, dbConstant.Val, dbConstant.ValType.DbType);
            }

            sql = script.ToString();
            var results = connection.Query(sql, dParams);

            return(results);
        }
        public void TestSingleExpression()
        {
            var translator = new QueryTranslator();
            Expression<Func<TestRecord, bool>> expression = x => x.Col1 == 1;
            string result = translator.Translate(expression);

            Assert.True(result == "(Col1 = 1)");
        }
        public void TestMultiExpression()
        {
            var translator = new QueryTranslator();
            Expression<Func<TestRecord, bool>> expression = x => x.Col1 == 1 && x.Col2 == 2.3;
            string result = translator.Translate(expression);

            Assert.True(result == "((Col1 = 1) AND (Col2 = 2.3))");
        }
        public void TestAndOrExpression()
        {
            var translator = new QueryTranslator();
            Expression<Func<TestRecord, bool>> expression = x => x.Col1 == 1 && x.Col2 == 2.3 || x.Col3 == "test";
            string result = translator.Translate(expression);

            Assert.True(result == "(((Col1 = 1) AND (Col2 = 2.3)) OR (Col3 = 'test'))");
        }
Ejemplo n.º 30
0
        public async Task <IActionResult> TotalCountPeriod()
        {
            var applicationUser = await ApplicationUserRepository.GetItemAsync();

            var result = await TotalInsertDateCountQuery.ExecuteAsync(new TotalBagsCountByInsertDateQuery());

            return(QueryTranslator.Translate(result));
        }
Ejemplo n.º 31
0
        public async Task <IActionResult> Brands(int top = 10)
        {
            var applicationUser = await ApplicationUserRepository.GetItemAsync();

            var result = await BrandsCountQuery.ExecuteAsync(new BagsCountByBrandsQuery(top));

            return(QueryTranslator.Translate(result));
        }
Ejemplo n.º 32
0
        /// <summary>
        /// This is very the query is executed and the results are mapped to objects
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public virtual object Execute(System.Linq.Expressions.Expression query)
        {
            CheckDispose();
            var       translator = new QueryTranslator();
            QueryInfo info       = translator.Translate(query);

            return(Execute(info));
        }
        public void TestContainsExpression()
        {
            var translator = new QueryTranslator();
            var items = Enumerable.Range(1, 5).Cast<int?>();
            Expression<Func<TestRecord, bool>> expression = x => items.Contains(x.Col1);
            string result = translator.Translate(expression);

            Assert.True(result == "(Col1 IN(1, 2, 3, 4, 5))");
        }
Ejemplo n.º 34
0
        public static Expression <Func <TResult> > Invoke <TResult>(string query)
        {
            var expressionLexer = new ExpressionLexer(query);

            var expression = expressionLexer.BuildLambdaExpression();

            var translator = new QueryTranslator(DefaultMemberNameProvider);

            return(translator.Translate <TResult>(expression));
        }
        public void Default_Rank()
        {
            using (var provider = new LinqCloudSearchClient())
            {
                var query = provider.Query<TestDocument>();

                var translator = new QueryTranslator(provider);

                var result = translator.Translate(query.Expression);

                Assert.AreEqual(0, result.SearchRequest.Rank.Count);
            }
        }
        public void OrderByDescending_To_Rank()
        {
            using (var provider = new LinqCloudSearchClient())
            {
                var query = provider.Query<TestDocument>()
                    .OrderByDescending(td => td.SomeString);

                var translator = new QueryTranslator(provider);

                var result = translator.Translate(query.Expression);

                Assert.AreEqual("-some_string", result.SearchRequest.Rank.ToQueryStringParameterValue());
            }
        }
        public void Default_To_Return_All_Fields()
        {
            using (var provider = new LinqCloudSearchClient())
            {
                var query = provider.Query<TestDocument>();

                var translator = new QueryTranslator(provider);

                var result = translator.Translate(query.Expression);

                var actualFields = result.SearchRequest.ReturnFields;

                CollectionAssert.AreEquivalent(new string[] { "some_integer", "some_string" }, actualFields.ToArray());
            }
        }
        public void Test_Content_Search_With_TagFilter_Translate()
        {
            var opqs = new QueryTranslator();
            var sp = new ContentSearchParameters
                         {
                             From = new DateTime(1971, 2, 20),
                             Query = "prince",
                             TagFilter = new List<string> {"music/music", "culture/culture"}
                         };
            var result = new Uri(opqs.Translate(sp));

            Assert.IsTrue(result.Query.Contains("q=prince"));
            Assert.IsTrue(result.Query.Contains("from-date=1971-02-20"));
            Assert.IsTrue(result.Query.Contains("tag=music/music,culture/culture"));
            Assert.IsTrue(result.Query.Contains("api-key=" + _key));
        }
        public void Select_OrderBy()
        {
            using (var provider = new LinqCloudSearchClient())
            {
                var query = provider.Query<TestDocument>()
                    .Select(td => td.SomeInteger)
                    .OrderByDescending(p => p);

                var translator = new QueryTranslator(provider);

                var result = translator.Translate(query.Expression);

                CollectionAssert.AreEquivalent(new string[] { "some_integer" }, result.SearchRequest.ReturnFields.ToArray());
                Assert.AreEqual("-some_integer", result.SearchRequest.Rank.ToQueryStringParameterValue());
            }
        }
        public void Test_ContentSearch_Translate()
        {
            var sp = new ContentSearchParameters
                         {
                             From = new DateTime(1971, 2, 20),
                             Query = "cristiano ronaldo"
                         };

            var opqs = new QueryTranslator();
            var result = new Uri(opqs.Translate(sp));

            Assert.AreEqual(_baseUrl.Host, result.Host);
            Assert.IsTrue(result.Query.Contains("q=cristiano%20ronaldo"));
            Assert.IsTrue(result.Query.Contains("from-date=1971-02-20"));
            Assert.IsTrue(result.Query.Contains("api-key=" + _key));
        }
Ejemplo n.º 41
0
        public void Simple_Query_Translate()
        {
            var container = new NinjectContainer();
            var map = container.Resolve<IMappingManager>();
            var mapper = new PersonMap();
            mapper.ExecuteMapping();
            map.Register(mapper.MappedType, mapper);

            var query = new Query<Person>();
            query.Where(x => x.Name).Equal("Alaor").And(x => x.Age).GreaterThan(18).And(x => x.Id).NotEqual(0);

            var translator = new QueryTranslator(map);
            var result = translator.Translate(query);

            result.SqlText.Trim().ToUpper().Should().Be("NAME = @PARAMETER_0 AND AGE > @PARAMETER_1 AND ID <> @PARAMETER_2");
            result.Parameters.Count.Should().Be(3);
        }
        public void Test_Content_Search_With_ShowTags_and_ShowFields_Translate()
        {
            var opqs = new QueryTranslator();
            var sp = new ContentSearchParameters
            {
                From = new DateTime(1971, 2, 20),
                Query = "prince",
                ShowTags = new List<string>{"all"},
                ShowFields= new List<string>{"body,star-rating"}
            };
            var result = new Uri(opqs.Translate(sp));

            Assert.IsTrue(result.Query.Contains("q=prince"));
            Assert.IsTrue(result.Query.Contains("from-date=1971-02-20"));
            Assert.IsTrue(result.Query.Contains("show-tags=all"));
            Assert.IsTrue(result.Query.Contains("show-fields=body,star-rating"));
            Assert.IsTrue(result.Query.Contains("api-key=" + _key));
        }
        public void Test_ItemSearch_Translate()
        {
            var opqs = new QueryTranslator();
            var result = new Uri(opqs.Translate("tv-and-radio/2010/apr/10/charlie-brooker-mad-men-screenburn"));

            string url = "http://" + _baseUrl.Host +
                         "/tv-and-radio/2010/apr/10/charlie-brooker-mad-men-screenburn?api-key=" + _key;

            Assert.IsTrue(result.AbsoluteUri.Contains(url));
        }
        public void Test_TagSearch_Translate()
        {
            var sp = new TagSearchParameters {Query = "fish"};

            var opqs = new QueryTranslator();
            var result = new Uri(opqs.Translate(sp));

            Assert.AreEqual(_baseUrl.Host, result.Host);
            Assert.IsTrue(result.Query.Contains("q=fish"));
            Assert.IsTrue(result.Query.Contains("api-key=" + _key));
        }