File: QueryBuilder.cs

package info (click to toggle)
mono 4.6.2.7+dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (481 lines) | stat: -rw-r--r-- 22,535 bytes parent folder | download | duplicates (2)
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
#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.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Text.RegularExpressions;

using DbLinq.Data.Linq.Sugar.ExpressionMutator;
using DbLinq.Data.Linq.Sugar.Expressions;
using DbLinq.Factory;
using DbLinq.Util;

namespace DbLinq.Data.Linq.Sugar.Implementation
{
    /// <summary>
    /// Full query builder, with cache management
    /// 1. Parses Linq Expression
    /// 2. Generates SQL
    /// </summary>
    internal partial class QueryBuilder : IQueryBuilder
    {
        public IExpressionLanguageParser ExpressionLanguageParser { get; set; }
        public IExpressionDispatcher ExpressionDispatcher { get; set; }
        public IPrequelAnalyzer PrequelAnalyzer { get; set; }
        public IExpressionOptimizer ExpressionOptimizer { get; set; }
        public ISpecialExpressionTranslator SpecialExpressionTranslator { get; set; }
        public ISqlBuilder SqlBuilder { get; set; }

        public QueryBuilder()
        {
            ExpressionLanguageParser = ObjectFactory.Get<IExpressionLanguageParser>();
            ExpressionDispatcher = ObjectFactory.Get<IExpressionDispatcher>();
            PrequelAnalyzer = ObjectFactory.Get<IPrequelAnalyzer>();
            ExpressionOptimizer = ObjectFactory.Get<IExpressionOptimizer>();
            SpecialExpressionTranslator = ObjectFactory.Get<ISpecialExpressionTranslator>();
            SqlBuilder = ObjectFactory.Get<ISqlBuilder>();
        }

        /// <summary>
        /// Builds the ExpressionQuery:
        /// - parses Expressions and builds row creator
        /// - checks names unicity
        /// </summary>
        /// <param name="expressions"></param>
        /// <param name="queryContext"></param>
        /// <returns></returns>
        protected virtual ExpressionQuery BuildExpressionQuery(ExpressionChain expressions, QueryContext queryContext)
        {
            var builderContext = new BuilderContext(queryContext);
            BuildExpressionQuery(expressions, builderContext);
            CheckTablesAlias(builderContext);
            CheckParametersAlias(builderContext);
            return builderContext.ExpressionQuery;
        }

        /// <summary>
        /// Finds all registered tables or columns with the given name.
        /// We exclude parameter because they won't be prefixed/suffixed the same way (well, that's a guess, I hope it's a good one)
        /// </summary>
        /// <param name="name"></param>
        /// <param name="builderContext"></param>
        /// <returns></returns>
        protected virtual IList<Expression> FindExpressionsByName(string name, BuilderContext builderContext)
        {
            var expressions = new List<Expression>();
            expressions.AddRange((from t in builderContext.EnumerateAllTables() where t.Alias == name select (Expression)t).Distinct());
            expressions.AddRange(from c in builderContext.EnumerateScopeColumns() where c.Alias == name select (Expression)c);
            return expressions;
        }

        protected virtual string MakeName(string aliasBase, int index, string anonymousBase, BuilderContext builderContext)
        {
            if (string.IsNullOrEmpty(aliasBase))
                aliasBase = anonymousBase;
            return string.Format("{0}{1}", aliasBase, index);
        }

        protected virtual string MakeTableName(string aliasBase, int index, BuilderContext builderContext)
        {
            return MakeName(aliasBase, index, "t", builderContext);
        }

        protected virtual string MakeParameterName(string aliasBase, int index, BuilderContext builderContext)
        {
            return MakeName(aliasBase, index, "p", builderContext);
        }

        /// <summary>
        /// Give all non-aliased tables a name
        /// </summary>
        /// <param name="builderContext"></param>
        protected virtual void CheckTablesAlias(BuilderContext builderContext)
        {
            var tables = builderContext.EnumerateAllTables().Distinct().ToList();
            // just to be nice: if we have only one table involved, there's no need to alias it
            if (tables.Count == 1)
            {
                tables[0].Alias = null;
            }
            else
            {
                foreach (var tableExpression in tables)
                {
                    // if no alias, or duplicate alias
                    if (string.IsNullOrEmpty(tableExpression.Alias) ||
                        FindExpressionsByName(tableExpression.Alias, builderContext).Count > 1)
                    {
                        int anonymousIndex = 0;
                        var aliasBase = tableExpression.Alias;
                        // we try to assign one until we have a unique alias
                        do
                        {
                            tableExpression.Alias = MakeTableName(aliasBase, ++anonymousIndex, builderContext);
                        } while (FindExpressionsByName(tableExpression.Alias, builderContext).Count != 1);
                    }
                }
            }
        }

        protected virtual IList<InputParameterExpression> FindParametersByName(string name, BuilderContext builderContext)
        {
            return (from p in builderContext.ExpressionQuery.Parameters where p.Alias == name select p).ToList();
        }

        /// <summary>
        /// Gives anonymous parameters a name and checks for names unicity
        /// The fact of giving a nice name just helps for readability
        /// </summary>
        /// <param name="builderContext"></param>
        protected virtual void CheckParametersAlias(BuilderContext builderContext)
        {
            foreach (var externalParameterExpression in builderContext.ExpressionQuery.Parameters)
            {
                if (string.IsNullOrEmpty(externalParameterExpression.Alias)
                    || FindParametersByName(externalParameterExpression.Alias, builderContext).Count > 1)
                {
                    int anonymousIndex = 0;
                    var aliasBase = externalParameterExpression.Alias;
                    // we try to assign one until we have a unique alias
                    do
                    {
                        externalParameterExpression.Alias = MakeTableName(aliasBase, ++anonymousIndex, builderContext);
                    } while (FindParametersByName(externalParameterExpression.Alias, builderContext).Count > 1);
                }
            }
        }

        /// <summary>
        /// Builds and chains the provided Expressions
        /// </summary>
        /// <param name="expressions"></param>
        /// <param name="builderContext"></param>
        protected virtual void BuildExpressionQuery(ExpressionChain expressions, BuilderContext builderContext)
        {
            var previousExpression = ExpressionDispatcher.CreateTableExpression(expressions.Expressions[0], builderContext);
            previousExpression = BuildExpressionQuery(expressions, previousExpression, builderContext);
            BuildOffsetsAndLimits(builderContext);
            // then prepare Parts for SQL translation
            PrepareSqlOperands(builderContext);
            // now, we optimize anything we can
            OptimizeQuery(builderContext);
            // finally, compile our object creation method
            CompileRowCreator(builderContext);
            // in the very end, we keep the SELECT clause
            builderContext.ExpressionQuery.Select = builderContext.CurrentSelect;
        }

        /// <summary>
        /// Builds the ExpressionQuery main Expression, given a Table (or projection) expression
        /// </summary>
        /// <param name="expressions"></param>
        /// <param name="tableExpression"></param>
        /// <param name="builderContext"></param>
        /// <returns></returns>
        protected Expression BuildExpressionQuery(ExpressionChain expressions, Expression tableExpression, BuilderContext builderContext)
        {
            tableExpression = ExpressionDispatcher.Analyze(expressions, tableExpression, builderContext);
            ExpressionDispatcher.BuildSelect(tableExpression, builderContext);
            return tableExpression;
        }

        public virtual SelectExpression BuildSelectExpression(ExpressionChain expressions, Expression tableExpression, BuilderContext builderContext)
        {
            BuildExpressionQuery(expressions, tableExpression, builderContext);
            return builderContext.CurrentSelect;
        }

        /// <summary>
        /// This is a hint for SQL generations
        /// </summary>
        /// <param name="builderContext"></param>
        protected virtual void BuildOffsetsAndLimits(BuilderContext builderContext)
        {
            foreach (var selectExpression in builderContext.SelectExpressions)
            {
                if (selectExpression.Offset != null && selectExpression.Limit != null)
                {
                    selectExpression.OffsetAndLimit = Expression.Add(selectExpression.Offset, selectExpression.Limit);
                }
            }
        }

        /// <summary>
        /// Builds the delegate to create a row
        /// </summary>
        /// <param name="builderContext"></param>
        protected virtual void CompileRowCreator(BuilderContext builderContext)
        {
            var reader = builderContext.CurrentSelect.Reader;
            reader = (LambdaExpression)SpecialExpressionTranslator.Translate(reader);
            reader = (LambdaExpression)ExpressionOptimizer.Optimize(reader, builderContext);
            builderContext.ExpressionQuery.RowObjectCreator = reader.Compile();
        }

        /// <summary>
        /// Prepares SELECT operands to help SQL transaltion
        /// </summary>
        /// <param name="builderContext"></param>
        protected virtual void PrepareSqlOperands(BuilderContext builderContext)
        {
            ProcessExpressions(PrequelAnalyzer.Analyze, true, builderContext);
        }

        /// <summary>
        /// Processes all expressions in query, with the option to process only SQL targetting expressions
        /// This method is generic, it receives a delegate which does the real processing
        /// </summary>
        /// <param name="processor"></param>
        /// <param name="processOnlySqlParts"></param>
        /// <param name="builderContext"></param>
        protected virtual void ProcessExpressions(Func<Expression, BuilderContext, Expression> processor,
                                                  bool processOnlySqlParts, BuilderContext builderContext)
        {
            for (int scopeExpressionIndex = 0; scopeExpressionIndex < builderContext.SelectExpressions.Count; scopeExpressionIndex++)
            {
                // no need to process the select itself here, all ScopeExpressions that are operands are processed as operands
                // and the main ScopeExpression (the SELECT) is processed below
                var scopeExpression = builderContext.SelectExpressions[scopeExpressionIndex];

                // where clauses
                List<int> whereToRemove = new List<int>(); // List of where clausole evaluating TRUE (could be ignored and so removed)
                bool falseWhere = false; // true when the full where evaluate to FALSE
                for (int whereIndex = 0; whereIndex < scopeExpression.Where.Count; whereIndex++)
                {
                    Expression whereClausole = processor(scopeExpression.Where[whereIndex], builderContext);
                    ConstantExpression constantWhereClausole = whereClausole as ConstantExpression;
                    if (constantWhereClausole != null)
                    {
                        if (constantWhereClausole.Value.Equals(false))
                        {
                            falseWhere = true;
                            break;
                        }
                        else if (constantWhereClausole.Value.Equals(true))
                        {
                            whereToRemove.Add(whereIndex);
                            continue;
                        }
                    }
                    scopeExpression.Where[whereIndex] = whereClausole;
                }
                if (scopeExpression.Where.Count > 0)
                {
                    if (falseWhere)
                    {
                        scopeExpression.Where.Clear();
                        scopeExpression.Where.Add(Expression.Equal(Expression.Constant(true), Expression.Constant(false)));
                    }
                    else
                        foreach (int whereIndex in whereToRemove)
                            scopeExpression.Where.RemoveAt(whereIndex);
                }

                // limit clauses
                if (scopeExpression.Offset != null)
                    scopeExpression.Offset = processor(scopeExpression.Offset, builderContext);
                if (scopeExpression.Limit != null)
                    scopeExpression.Limit = processor(scopeExpression.Limit, builderContext);
                if (scopeExpression.OffsetAndLimit != null)
                    scopeExpression.OffsetAndLimit = processor(scopeExpression.OffsetAndLimit, builderContext);

                builderContext.SelectExpressions[scopeExpressionIndex] = scopeExpression;
            }
            // now process the main SELECT
            if (processOnlySqlParts)
            {
                // if we process only the SQL Parts, these are the operands
                var newOperands = new List<Expression>();
                foreach (var operand in builderContext.CurrentSelect.Operands)
                    newOperands.Add(processor(operand, builderContext));
                builderContext.CurrentSelect = builderContext.CurrentSelect.ChangeOperands(newOperands);
            }
            else
            {
                // the output parameters and result builder
                builderContext.CurrentSelect = (SelectExpression)processor(builderContext.CurrentSelect, builderContext);
            }
        }

        /// <summary>
        /// Optimizes the query by optimizing subexpressions, and preparsing constant expressions
        /// </summary>
        /// <param name="builderContext"></param>
        protected virtual void OptimizeQuery(BuilderContext builderContext)
        {
            ProcessExpressions(ExpressionOptimizer.Optimize, false, builderContext);
        }

        protected virtual SelectQuery BuildSqlQuery(ExpressionQuery expressionQuery, QueryContext queryContext)
        {
            var sql = SqlBuilder.BuildSelect(expressionQuery, queryContext);
            var sqlQuery = new SelectQuery(queryContext.DataContext, sql, expressionQuery.Parameters, expressionQuery.RowObjectCreator, expressionQuery.Select.ExecuteMethodName);
            return sqlQuery;
        }

        private static IQueryCache queryCache;
        protected IQueryCache QueryCache
        {
            get
            {
                if (queryCache == null)
                    queryCache = ObjectFactory.Get<IQueryCache>();
                return queryCache;
            }
        }

        protected virtual SelectQuery GetFromSelectCache(ExpressionChain expressions)
        {
            var cache = QueryCache;
            return cache.GetFromSelectCache(expressions);
        }

        protected virtual void SetInSelectCache(ExpressionChain expressions, SelectQuery sqlSelectQuery)
        {
            var cache = QueryCache;
            cache.SetInSelectCache(expressions, sqlSelectQuery);
        }

        protected virtual Delegate GetFromTableReaderCache(Type tableType, IList<string> columns)
        {
            var cache = QueryCache;
            return cache.GetFromTableReaderCache(tableType, columns);
        }

        protected virtual void SetInTableReaderCache(Type tableType, IList<string> columns, Delegate tableReader)
        {
            var cache = queryCache;
            cache.SetInTableReaderCache(tableType, columns, tableReader);
        }

        /// <summary>
        /// Main entry point for the class. Builds or retrive from cache a SQL query corresponding to given Expressions
        /// </summary>
        /// <param name="expressions"></param>
        /// <param name="queryContext"></param>
        /// <returns></returns>
        public SelectQuery GetSelectQuery(ExpressionChain expressions, QueryContext queryContext)
        {
            SelectQuery query = null;
            if (queryContext.DataContext.QueryCacheEnabled)
            {
                query = GetFromSelectCache(expressions);
            }
            if (query == null)
            {
                Profiler.At("START: GetSelectQuery(), building Expression query");
                var expressionsQuery = BuildExpressionQuery(expressions, queryContext);
                Profiler.At("END: GetSelectQuery(), building Expression query");

                Profiler.At("START: GetSelectQuery(), building Sql query");
                query = BuildSqlQuery(expressionsQuery, queryContext);
                Profiler.At("END: GetSelectQuery(), building Sql query");

                if (queryContext.DataContext.QueryCacheEnabled)
                {
                    SetInSelectCache(expressions, query);
                }
            }
            else if (query.InputParameters.Count > 0)
            {
                Profiler.At("START: GetSelectQuery(), building Expression parameters of cached query");
                var parameters = BuildExpressionParameters(expressions, queryContext);
                query = new SelectQuery(queryContext.DataContext, query.Sql, parameters, query.RowObjectCreator, query.ExecuteMethodName);
                Profiler.At("END: GetSelectQuery(), building Expression parameters of cached query");
            }
            return query;
        }

        IList<InputParameterExpression> BuildExpressionParameters(ExpressionChain expressions, QueryContext queryContext)
        {
            var builderContext = new BuilderContext(queryContext);
            var previousExpression = ExpressionDispatcher.CreateTableExpression(expressions.Expressions[0], builderContext);
            previousExpression = BuildExpressionQuery(expressions, previousExpression, builderContext);
            BuildOffsetsAndLimits(builderContext);
            // then prepare Parts for SQL translation
            PrepareSqlOperands(builderContext);
            return builderContext.ExpressionQuery.Parameters;
        }

        /// <summary>
        /// Returns a Delegate to create a row for a given IDataRecord
        /// The Delegate is Func&lt;IDataRecord,MappingContext,"tableType">
        /// </summary>
        /// <param name="tableType">The table type (must be managed by DataContext)</param>
        /// <param name="parameters"></param>
        /// <param name="queryContext"></param>
        /// <returns></returns>
        public virtual Delegate GetTableReader(Type tableType, IList<string> parameters, QueryContext queryContext)
        {
            Delegate reader = null;
            if (queryContext.DataContext.QueryCacheEnabled)
            {
                reader = GetFromTableReaderCache(tableType, parameters);
            }
            if (reader == null)
            {
                var lambda = ExpressionDispatcher.BuildTableReader(tableType, parameters,
                                                                   new BuilderContext(queryContext));
                reader = lambda.Compile();
                if (queryContext.DataContext.QueryCacheEnabled)
                {
                    SetInTableReaderCache(tableType, parameters, reader);
                }
            }
            return reader;
        }

        private static readonly Regex parameterIdentifierEx = new Regex(@"\{(?<var>[\d.]+)\}", RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.Compiled);

        /// <summary>
        /// Converts a direct SQL query to a safe query with named parameters
        /// </summary>
        /// <param name="sql">Raw SQL query</param>
        /// <param name="queryContext"></param>
        /// <returns></returns>
        public virtual DirectQuery GetDirectQuery(string sql, QueryContext queryContext)
        {
            // TODO cache
            var safeSql = queryContext.DataContext.Vendor.SqlProvider.GetSafeQuery(sql);
            var parameters = new List<string>();
            var parameterizedSql = parameterIdentifierEx.Replace(safeSql, delegate(Match e)
            {
                var field = e.Groups[1].Value;
                var parameterIndex = int.Parse(field);
                while (parameters.Count <= parameterIndex)
                    parameters.Add(string.Empty);
                var literalParameterName =
                    queryContext.DataContext.Vendor.SqlProvider.GetParameterName(string.Format("p{0}", parameterIndex));
                parameters[parameterIndex] = literalParameterName;
                return literalParameterName;
            });
            return new DirectQuery(queryContext.DataContext, parameterizedSql, parameters);
        }
    }
}