mono /mcs/class/System.Data.Linq/src/DbLinq/Test/Providers/DynamicLinqTest.cs

Language C# Lines 338
MD5 Hash c347e235201bb5dbb82af15546574e82 Estimated Cost $5,721 (why?)
Repository https://bitbucket.org/danipen/mono.git View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
#region MIT license
// 
// MIT license
//
// Copyright (c) 2007-2008 Jiri Moudry, Pascal Craponne
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// 
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.Linq.Dynamic;
using Test_NUnit;
using System.Linq.Expressions;
using System.Reflection;

using nwind;

// test ns 
#if MYSQL
    namespace Test_NUnit_MySql
#elif ORACLE && ODP
    namespace Test_NUnit_OracleODP
#elif ORACLE
    namespace Test_NUnit_Oracle
#elif POSTGRES
    namespace Test_NUnit_PostgreSql
#elif SQLITE
    namespace Test_NUnit_Sqlite
#elif INGRES
    namespace Test_NUnit_Ingres
#elif MSSQL && L2SQL
    namespace Test_NUnit_MsSql_Strict
#elif MSSQL
    namespace Test_NUnit_MsSql
#elif FIREBIRD
    namespace Test_NUnit_Firebird
#endif
{
    [TestFixture]
    public class DynamicLinqTest : TestBase
    {
        [Test]
        public void DL1_Products()
        {
            Northwind db = CreateDB();

            var q = db.Products.Where("SupplierID=1 And UnitsInStock>2")
                .OrderBy("ProductID");
            var list = q.ToList();
            Assert.IsTrue(list.Count > 0, "Expected results from dynamic query");
        }

        [Test]
        public void DL2_ProductCount()
        {
            Northwind db = CreateDB();

            int numProducts = db.Products.Where("SupplierID=1").Count();
            Assert.IsTrue(numProducts > 0, "Expected results from dynamic query");
        }

        //note:
        //user Sqlite reports problems with DynamicLinq Count() -
        //but neither DL2 nor DL3 tests seem to hit the problem.

        [Test]
        public void DL3_ProductCount()
        {
            Northwind db = CreateDB();

            int numProducts = db.Products.Count();
            Assert.IsTrue(numProducts > 0, "Expected results from dynamic query");
        }

        [Test]
        public void DL4_DynamicAssociationProperty()
        {

            Northwind db = CreateDB();
            var orders = db.GetTable<Order>();
            var res = orders.Select(@"new (OrderID,Customer.ContactName)");

            List<object> list = new List<object>();
            foreach (var u in res)
                list.Add(u);
            Assert.IsTrue(list.Count > 0);
        }

        #region NestedPropertiesDynamicSelect

        const string obsoleteError=@"Since beta2 in Linq2Sql to project a new entity (ie: select new Order(3)) is forbidden for coherence reasons, so this tests doesn't mimic the Linq2Sql behavior and it is obsolete and should be modified. If you apply such test cases to Linq2Sql you'll get Test_NUnit_MsSql_Strict.DynamicLinqTest.DL5_NestedObjectSelect:
        System.NotSupportedException : Explicit construction of entity type 'MsNorthwind.XX' in query is not allowed.\n\nMore Info in: http://linqinaction.net/blogs/roller/archive/2007/11/27/explicit-construction-of-entity-type-in-query-is-not-allowed.aspx";
        [Test(Description = "dynamic version of F16_NestedObjectSelect")]
        public void DL5_NestedObjectSelect()
        {
            Assert.Ignore(obsoleteError);
            Northwind db = CreateDB();
            var orders = db.GetTable<Order>();
            var res = orders.SelectNested(new string[] { "OrderID", "Customer.ContactName" });

            List<Order> list = res.ToList();
            Assert.IsTrue(list.Count > 0);
        }

        [Test]
        public void DL6_StaticVersionOfDynamicAssociatonWithExtensionMethodTest(bool bug_in_dynamic_linq)
        {
            Assert.Ignore(obsoleteError);

            //is this maybe a bug in DynamicLinq?
            //from DynamicLinq, we receive this query which has ContactName but misses ContactTitle:
            //MTable.CreateQuery: value(Table`1[Order]).Select(o => new Order() {OrderID = o.OrderID, Customer = new Customer() {ContactName = o.Customer.ContactName}})

            //Also - the non-dynamic version F17_NestedObjectSelect_Ver2 succeeds.

            Northwind db = CreateDB();
            var orders = db.GetTable<Order>().ToArray().AsQueryable();

            var query = from order in orders
                        //where order.Customer != null
                        select new Order
                        {
                            OrderID = order.OrderID,
                            Customer = new Customer
                            {
                                ContactName = order.Customer.ContactName,
                                ContactTitle = order.Customer.ContactTitle
                            }
                        };
            var list = query.ToList();
            Assert.IsTrue(list.Count > 0);
        }

        [Test]
        public void DL7_DynamicAssociatonUsingDoubleProjection(bool bug_in_dynamic_linq)
        {
            Assert.Ignore(obsoleteError);

            //this fails - but not in our code:
            //A first chance exception of type 'System.NullReferenceException' occurred in Unknown Module.
            //System.Transactions Critical: 0 : <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Critical"><TraceIdentifier>http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/Unhandled</TraceIdentifier><Description>Unhandled exception</Description><AppDomain>Test_NUnit_Mysql.vshost.exe</AppDomain><Exception><ExceptionType>System.NullReferenceException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType><Message>Object reference not set to an instance of an object.</Message><StackTrace>   at lambda_method(ExecutionScope , Order )
            //   at System.Linq.Enumerable.&amp;lt;SelectIterator&amp;gt;d__d`2.MoveNext()
            //   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
            //   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
            //   at Test_NUnit_MySql.DynamicLinqTest.DL7_DynamicAssociatonUsingDoubleProjection() in E:\ggprj\dbLinq\dblinq2007\Tests\Test_NUnit\DynamicLinqTest.cs:line 150

            Northwind db = CreateDB();

            // Double projection works in Linq-SQL:
            var orders = db.GetTable<Order>().ToArray().AsQueryable();
            var query = orders.SelectNested(new string[] { "OrderID", "Customer.ContactName" });
            var list = query.ToList();
            Assert.IsTrue(list.Count > 0);
        }

        #endregion

        #region Predicates

        /// <summary>
        /// Reported by pwy.mail in issue http://code.google.com/p/dblinq2007/issues/detail?id=68
        /// </summary>
        [Test]
        public void DL8_CountTest2()
        {
            Northwind db = CreateDB();
            Expression<Func<Customer, bool>> predicate = c => c.City == "Paris";
            int count = db.Customers.Count(predicate);
            Assert.Greater(count, 0); // Some databases have more than 1 customer in Paris
        }

        /// <summary>
        /// Reported by pwy.mail in issue http://code.google.com/p/dblinq2007/issues/detail?id=69
        /// </summary>
        [Test]
        public void DL9_PredicateBuilderCount()
        {
            //2008.May.17: breaks because we are not handling an 'InvocationExpression' in ExpressionTreeParser.
            //possibily a tree rewrite is needed.
            Northwind db = CreateDB();
            var predicate = PredicateBuilder.True<Customer>();
            predicate = predicate.And(m => m.City == "Paris");
            int predicateCount  = db.Customers.Count(predicate);
            int normalCount     = db.Customers.Where(c => c.City == "Paris").Count();
            Assert.AreEqual(normalCount, predicateCount);
        }


        /// <summary>
        /// Reported by pwy.mail in issue http://code.google.com/p/dblinq2007/issues/detail?id=69
        /// </summary>
        [Test]
        public void DL10_PredicateBuilderWhere()
        {
            Northwind db = CreateDB();
            var predicate = PredicateBuilder.True<Customer>();

            predicate = predicate.And(m => m.City == "Paris");
            predicate = predicate.And(n => n.CompanyName == "Around the Horn");
            IList<Customer> list = db.Customers.AsQueryable().Where(predicate).ToList();
        }

        /// <summary>
        /// Reported by pwy.mail in issue http://code.google.com/p/dblinq2007/issues/detail?id=73
        /// </summary>
        [Test]
        public void DL11_ThenByDescending()
        {
            Northwind db = CreateDB();
            var q = db.Products.Where("SupplierID=1 And UnitsInStock>2")
                .OrderBy(" ProductName asc,ProductID desc");
            var list = q.ToList();
            Assert.IsTrue(list.Count > 0, "Expected results from dynamic query");
        }

        /// <summary>
        /// Build predicate expressions dynamically.
        /// </summary>
        static class PredicateBuilder
        {
            public static Expression<Func<T, bool>> True<T>() { return f => true; }
            public static Expression<Func<T, bool>> False<T>() { return f => false; }
        }

        // Test patch from:
        // http://groups.google.com/group/dblinq/browse_frm/thread/9fa41554044afeaa/4ef1605e020be9fc?lnk=raot#4ef1605e020be9fc
        [Test]
        public void DL12_Count_Via_Expression()
        {
            var db = CreateDB();
            IQueryable employees = db.Employees;
            var employeeCount = (int) employees.Provider.Execute(
                Expression.Call(typeof(Queryable), "Count",
                    new Type[]{employees.ElementType},
                    employees.Expression));
            Assert.AreEqual(9, employeeCount);
        }

    }
        #endregion

    #region ExtensionMethods

    /// <summary>
    /// Extension written by Marc Gravell.
    /// Traverses nested properties
    /// </summary>
    static class SelectUsingSingleProjection
    {
        internal static IQueryable<T> SelectNested<T>(this IQueryable<T> source, params string[] propertyNames)
            where T : new()
        {
            Type type = typeof(T);
            var sourceItem = Expression.Parameter(type, "t");
            Expression exp = CreateAndInit(type, sourceItem, propertyNames);
            return source.Select(Expression.Lambda<Func<T, T>>(exp, sourceItem));
        }

        static Expression CreateAndInit(Type type, Expression source, string[] propertyNames)
        {
            if (type == null) throw new ArgumentNullException("type");
            if (source == null) throw new ArgumentNullException("source");
            if (propertyNames == null) throw new ArgumentNullException("propertyNames");

            var newExpr = Expression.New(type.GetConstructor(Type.EmptyTypes));
            // take "Foo.A", "Bar", "Foo.B" to "Foo" ["A","B"], "Bar" []
            var groupedNames = from name in propertyNames
                               let dotIndex = name.IndexOf('.')
                               let primary = dotIndex < 0 ? name : name.Substring(0, dotIndex)
                               let aux = dotIndex < 0 ? null : name.Substring(dotIndex + 1)
                               group aux by primary into grouped
                               select new
                               {
                                   Primary = grouped.Key,
                                   Aux = grouped.Where(x => x != null).ToArray()
                               };
            List<MemberBinding> bindings = new List<MemberBinding>();
            foreach (var grp in groupedNames)
            {
                PropertyInfo dest = type.GetProperty(grp.Primary);
                Expression value, readFrom = Expression.Property(source, grp.Primary);
                if (grp.Aux.Length == 0)
                {
                    value = readFrom;
                }
                else
                {
                    value = CreateAndInit(dest.PropertyType, readFrom, grp.Aux);
                }
                bindings.Add(Expression.Bind(dest, value));
            }
            return Expression.MemberInit(newExpr, bindings);
        }


        /// <summary>
        /// Extension method provided by pwy.mail in issue http://code.google.com/p/dblinq2007/issues/detail?id=69
        /// </summary>
        internal static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
                                                        Expression<Func<T, bool>> expr2)
        {
            var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, bool>>
                  (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
        }

        internal static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
            Expression<Func<T, bool>> expr2)
        {
            var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, bool>>
                  (Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
        }
    }
    #endregion

}
Back to Top