File: SqlOuterApplyReducer.cs

package info (click to toggle)
mono 6.12.0.199%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 1,296,836 kB
  • sloc: cs: 11,181,803; xml: 2,850,076; ansic: 699,709; cpp: 123,344; perl: 59,361; javascript: 30,841; asm: 21,853; makefile: 20,405; sh: 15,009; python: 4,839; pascal: 925; sql: 859; sed: 16; php: 1
file content (506 lines) | stat: -rw-r--r-- 23,253 bytes parent folder | download | duplicates (7)
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Data.Linq;
using System.Diagnostics.CodeAnalysis;

namespace System.Data.Linq.SqlClient {

	/// <summary>
	/// </summary>
	internal class SqlOuterApplyReducer { 
		internal static SqlNode Reduce(SqlNode node, SqlFactory factory, SqlNodeAnnotations annotations) {
			Visitor r = new Visitor(factory, annotations);
			return r.Visit(node);			
		}

		class Visitor : SqlVisitor {
            SqlFactory factory;
			SqlNodeAnnotations annotations;

            internal Visitor(SqlFactory factory, SqlNodeAnnotations annotations) {
                this.factory = factory;
                this.annotations = annotations;
            }

            internal override SqlSource VisitSource(SqlSource source) {
                source = base.VisitSource(source);

                SqlJoin join = source as SqlJoin;
                if (join != null) {
                    if (join.JoinType == SqlJoinType.OuterApply) {
                        // Reduce outer-apply into left-outer-join
                        HashSet<SqlAlias> leftProducedAliases = SqlGatherProducedAliases.Gather(join.Left);
                        HashSet<SqlExpression> liftedExpressions = new HashSet<SqlExpression>();

                        if (SqlPredicateLifter.CanLift(join.Right, leftProducedAliases, liftedExpressions) &&
                            SqlSelectionLifter.CanLift(join.Right, leftProducedAliases, liftedExpressions) &&
                            !SqlAliasDependencyChecker.IsDependent(join.Right, leftProducedAliases, liftedExpressions) ) {

                            SqlExpression liftedPredicate = SqlPredicateLifter.Lift(join.Right, leftProducedAliases);
                            List<List<SqlColumn>> liftedSelections = SqlSelectionLifter.Lift(join.Right, leftProducedAliases, liftedExpressions);

                            join.JoinType = SqlJoinType.LeftOuter;
                            join.Condition = liftedPredicate;

                            if (liftedSelections != null) {
                                foreach(List<SqlColumn> selection in liftedSelections) {
                                    source = this.PushSourceDown(source, selection);
                                }
                            }
                        }
                        else {
                            this.AnnotateSqlIncompatibility(join, SqlProvider.ProviderMode.Sql2000);
                        }
                    }
                    else if (join.JoinType == SqlJoinType.CrossApply) {
                        // reduce cross apply with special nested left-outer-join's into a single left-outer-join
                        //
                        // SELECT x.*, y.*
                        // FROM X
                        // CROSS APPLY (
                        //      SELECT y.*
                        //       FROM (
                        //          SELECT ?
                        //       ) 
                        //       LEFT OUTER JOIN (
                        //          SELECT y.* FROM Y
                        //       ) AS y
                        //
                        // ==>
                        // 
                        // SELECT x.*, y.*
                        // FROM X
                        // LEFT OUTER JOIN (
                        //     SELECT y.* FROM Y
                        // )

                        SqlJoin leftOuter = this.GetLeftOuterWithUnreferencedSingletonOnLeft(join.Right);
                        if (leftOuter != null) {
                            HashSet<SqlAlias> leftProducedAliases = SqlGatherProducedAliases.Gather(join.Left);
                            HashSet<SqlExpression> liftedExpressions = new HashSet<SqlExpression>();

                            if (SqlPredicateLifter.CanLift(leftOuter.Right, leftProducedAliases, liftedExpressions) &&
                                SqlSelectionLifter.CanLift(leftOuter.Right, leftProducedAliases, liftedExpressions) &&
                                !SqlAliasDependencyChecker.IsDependent(leftOuter.Right, leftProducedAliases, liftedExpressions)
                                ) {

                                SqlExpression liftedPredicate = SqlPredicateLifter.Lift(leftOuter.Right, leftProducedAliases);
                                List<List<SqlColumn>> liftedSelections = SqlSelectionLifter.Lift(leftOuter.Right, leftProducedAliases, liftedExpressions);

                                // add intermediate selections 
                                this.GetSelectionsBeforeJoin(join.Right, liftedSelections);

                                // push down all selections
                                foreach(List<SqlColumn> selection in liftedSelections.Where(s => s.Count > 0)) {
                                    source = this.PushSourceDown(source, selection);
                                }

                                join.JoinType = SqlJoinType.LeftOuter;
                                join.Condition = this.factory.AndAccumulate(leftOuter.Condition, liftedPredicate);
                                join.Right = leftOuter.Right;
                            }
                            else {
                                this.AnnotateSqlIncompatibility(join, SqlProvider.ProviderMode.Sql2000);
                            }
                        }
                    }

                    // re-balance join tree of left-outer-joins to expose LOJ w/ leftside unreferenced
                    while (join.JoinType == SqlJoinType.LeftOuter) {
                        // look for buried left-outer-joined-with-unreferenced singleton
                        SqlJoin leftLeftOuter = this.GetLeftOuterWithUnreferencedSingletonOnLeft(join.Left);
                        if (leftLeftOuter == null)
                            break;

                        List<List<SqlColumn>> liftedSelections = new List<List<SqlColumn>>();

                        // add intermediate selections 
                        this.GetSelectionsBeforeJoin(join.Left, liftedSelections);

                        // push down all selections
                        foreach(List<SqlColumn> selection in liftedSelections) {
                            source = this.PushSourceDown(source, selection);
                        }

                        // bubble this one up on-top of this 'join'.
                        SqlSource jRight = join.Right;
                        SqlExpression jCondition = join.Condition;

                        join.Left = leftLeftOuter.Left;
                        join.Right = leftLeftOuter;
                        join.Condition = leftLeftOuter.Condition;

                        leftLeftOuter.Left = leftLeftOuter.Right;
                        leftLeftOuter.Right = jRight;
                        leftLeftOuter.Condition = jCondition;
                    }
                }

                return source;
            }

            private void AnnotateSqlIncompatibility(SqlNode node, params SqlProvider.ProviderMode[] providers) {
                this.annotations.Add(node, new SqlServerCompatibilityAnnotation(Strings.SourceExpressionAnnotation(node.SourceExpression), providers));
            }

            [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification="Unknown reason.")]
            private SqlSource PushSourceDown(SqlSource sqlSource, List<SqlColumn> cols) {
                SqlSelect ns = new SqlSelect(new SqlNop(cols[0].ClrType, cols[0].SqlType, sqlSource.SourceExpression), sqlSource, sqlSource.SourceExpression);
                ns.Row.Columns.AddRange(cols);
                return new SqlAlias(ns);
            }

            private SqlJoin GetLeftOuterWithUnreferencedSingletonOnLeft(SqlSource source) {
                SqlAlias alias = source as SqlAlias;
                if (alias != null) {
                    SqlSelect select = alias.Node as SqlSelect;
                    if (select != null &&
                        select.Where == null &&
                        select.Top == null &&
                        select.GroupBy.Count == 0 &&
                        select.OrderBy.Count == 0) {
                        return this.GetLeftOuterWithUnreferencedSingletonOnLeft(select.From);
                    }
                }
                SqlJoin join = source as SqlJoin;
                if (join == null || join.JoinType != SqlJoinType.LeftOuter)
                    return null;
                if (!this.IsSingletonSelect(join.Left))
                    return null;
                HashSet<SqlAlias> p = SqlGatherProducedAliases.Gather(join.Left);
				HashSet<SqlAlias> c = SqlGatherConsumedAliases.Gather(join.Right);
                if (p.Overlaps(c)) {
                    return null;
                }
                return join;
            }

            private void GetSelectionsBeforeJoin(SqlSource source, List<List<SqlColumn>> selections) {
                SqlJoin join = source as SqlJoin;
                if (join != null)
                    return;
                SqlAlias alias = source as SqlAlias;
                if (alias != null) {
                    SqlSelect select = alias.Node as SqlSelect;
                    if (select != null) {
                        this.GetSelectionsBeforeJoin(select.From, selections);
                        selections.Add(select.Row.Columns);
                    }
                }
            }

            [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification="Unknown reason.")]
            private bool IsSingletonSelect(SqlSource source) {
                SqlAlias alias = source as SqlAlias;
                if (alias == null)
                    return false;
                SqlSelect select = alias.Node as SqlSelect;
                if (select == null)
                    return false;
                if (select.From != null)
                    return false;
                return true;
            }
		}

        class SqlGatherReferencedColumns {
            private SqlGatherReferencedColumns() { }
            internal static HashSet<SqlColumn> Gather(SqlNode node, HashSet<SqlColumn> columns) {
                Visitor v = new Visitor(columns);
                v.Visit(node);
                return columns;
            }
            class Visitor : SqlVisitor {
                HashSet<SqlColumn> columns;
                internal Visitor(HashSet<SqlColumn> columns) {
                    this.columns = columns;
                }
                internal override SqlExpression VisitColumnRef(SqlColumnRef cref) {
                    if (!this.columns.Contains(cref.Column)) {
                        this.columns.Add(cref.Column);
                        if (cref.Column.Expression != null) {
                            this.Visit(cref.Column.Expression);
                        }
                    }
                    return cref;
                }
            }
        }

        class SqlAliasesReferenced {
            HashSet<SqlAlias> aliases;
            bool referencesAny;
            Visitor visitor;

            internal SqlAliasesReferenced(HashSet<SqlAlias> aliases) {
                this.aliases = aliases;
                this.visitor = new Visitor(this);
            }

            internal bool ReferencesAny(SqlExpression expression) {
                this.referencesAny = false;
                this.visitor.Visit(expression);
                return this.referencesAny;
            }

            class Visitor: SqlVisitor {
                SqlAliasesReferenced parent;

                internal Visitor(SqlAliasesReferenced parent) {
                    this.parent = parent;
                }
                internal override SqlExpression VisitColumnRef(SqlColumnRef cref) {
                    if (this.parent.aliases.Contains(cref.Column.Alias)) {
                        this.parent.referencesAny = true;
                    }
                    else if (cref.Column.Expression != null) {
                        this.Visit(cref.Column.Expression);
                    }
                    return cref;
                }

                internal override SqlExpression VisitColumn(SqlColumn col) {
                    if (col.Expression != null) {
                        this.Visit(col.Expression);
                    }
                    return col;
                }
            }
        }

        static class SqlAliasDependencyChecker {
            internal static bool IsDependent(SqlNode node, HashSet<SqlAlias> aliasesToCheck, HashSet<SqlExpression> ignoreExpressions) {
                Visitor v = new Visitor(aliasesToCheck, ignoreExpressions);
                v.Visit(node);
                return v.hasDependency;
            }
            class Visitor : SqlVisitor {
                HashSet<SqlAlias> aliasesToCheck;
                HashSet<SqlExpression> ignoreExpressions;
                internal bool hasDependency;

                internal Visitor(HashSet<SqlAlias> aliasesToCheck, HashSet<SqlExpression> ignoreExpressions) {
                    this.aliasesToCheck = aliasesToCheck;
                    this.ignoreExpressions = ignoreExpressions;
                }
                internal override SqlNode Visit(SqlNode node) {
                    SqlExpression e = node as SqlExpression;
                    if (this.hasDependency)
                        return node;
                    if (e != null && this.ignoreExpressions.Contains(e)) {
                        return node;
                    }
                    return base.Visit(node);
                }
                internal override SqlExpression VisitColumnRef(SqlColumnRef cref) {
                    if (this.aliasesToCheck.Contains(cref.Column.Alias)) {
                        this.hasDependency = true;
                    }
                    else if (cref.Column.Expression != null) {
                        this.Visit(cref.Column.Expression);
                    }
                    return cref;
                }
                internal override SqlExpression VisitColumn(SqlColumn col) {
                    if (col.Expression != null) {
                        this.Visit(col.Expression);
                    }
                    return col;
                }
            }
        }

        static class SqlPredicateLifter {
            internal static bool CanLift(SqlSource source, HashSet<SqlAlias> aliasesForLifting, HashSet<SqlExpression> liftedExpressions) {
                System.Diagnostics.Debug.Assert(source != null);
                System.Diagnostics.Debug.Assert(aliasesForLifting != null);
                Visitor v = new Visitor(false, aliasesForLifting, liftedExpressions);
                v.VisitSource(source);
                return v.canLiftAll;
            }

            internal static SqlExpression Lift(SqlSource source, HashSet<SqlAlias> aliasesForLifting) {
                System.Diagnostics.Debug.Assert(source != null);
                System.Diagnostics.Debug.Assert(aliasesForLifting != null);
                Visitor v = new Visitor(true, aliasesForLifting, null);
                v.VisitSource(source);
                return v.lifted;
            }

            class Visitor : SqlVisitor {
                SqlAliasesReferenced aliases;
                HashSet<SqlExpression> liftedExpressions;
                bool doLifting;
                internal bool canLiftAll;
                internal SqlExpression lifted;
                SqlAggregateChecker aggregateChecker;


                internal Visitor(bool doLifting, HashSet<SqlAlias> aliasesForLifting, HashSet<SqlExpression> liftedExpressions) {
                    this.doLifting = doLifting;
                    this.aliases = new SqlAliasesReferenced(aliasesForLifting);
                    this.liftedExpressions = liftedExpressions;
                    this.canLiftAll = true;
                    this.aggregateChecker = new SqlAggregateChecker();
                }

                internal override SqlSelect VisitSelect(SqlSelect select) {
                    // check subqueries first
                    this.VisitSource(select.From);

                    // don't allow lifting through these operations
                    if (select.Top != null ||
                        select.GroupBy.Count > 0 ||
                        this.aggregateChecker.HasAggregates(select) ||
                        select.IsDistinct) {
                        this.canLiftAll = false;
                    }

                    // only lift predicates that actually reference the aliases
                    if (this.canLiftAll && select.Where != null) {
                        bool referencesAliases = this.aliases.ReferencesAny(select.Where);
                        if (referencesAliases) {
                            if (this.liftedExpressions != null) {
                                this.liftedExpressions.Add(select.Where);
                            }
                            if (this.doLifting) {
                                if (this.lifted != null)
                                    this.lifted = new SqlBinary(SqlNodeType.And, this.lifted.ClrType, this.lifted.SqlType, this.lifted, select.Where);
                                else
                                    this.lifted = select.Where;
                                select.Where = null;
                            }
                        }
                    }

                    return select;
                }
            }
        }

        static class SqlSelectionLifter {
            internal static bool CanLift(SqlSource source, HashSet<SqlAlias> aliasesForLifting, HashSet<SqlExpression> liftedExpressions) {
                Visitor v = new Visitor(false, aliasesForLifting, liftedExpressions);
                v.VisitSource(source);
                return v.canLiftAll;
            }

            internal static List<List<SqlColumn>> Lift(SqlSource source, HashSet<SqlAlias> aliasesForLifting, HashSet<SqlExpression> liftedExpressions) {
                Visitor v = new Visitor(true, aliasesForLifting, liftedExpressions);
                v.VisitSource(source);
                return v.lifted;
            }

            class Visitor : SqlVisitor {
                SqlAliasesReferenced aliases;
                HashSet<SqlColumn> referencedColumns;
                HashSet<SqlExpression> liftedExpressions;
                internal List<List<SqlColumn>> lifted;
                internal bool canLiftAll;
                bool hasLifted;
                bool doLifting;
                SqlAggregateChecker aggregateChecker;

                internal Visitor(bool doLifting, HashSet<SqlAlias> aliasesForLifting, HashSet<SqlExpression> liftedExpressions) {
                    this.doLifting = doLifting;
                    this.aliases = new SqlAliasesReferenced(aliasesForLifting);
                    this.referencedColumns = new HashSet<SqlColumn>();
                    this.liftedExpressions = liftedExpressions;
                    this.canLiftAll = true;
                    if (doLifting)
                        this.lifted = new List<List<SqlColumn>>();
                    this.aggregateChecker = new SqlAggregateChecker();
                }

                internal override SqlSource VisitJoin(SqlJoin join) {
                    this.ReferenceColumns(join.Condition);
                    return base.VisitJoin(join);
                }

                internal override SqlSelect VisitSelect(SqlSelect select) {
                    // reference all columns
                    this.ReferenceColumns(select.Where);
                    foreach(SqlOrderExpression oe in select.OrderBy) {
                        // 
                        this.ReferenceColumns(oe.Expression);
                    }
                    foreach(SqlExpression e in select.GroupBy) {
                        // 
                        this.ReferenceColumns(e);
                    }
                    this.ReferenceColumns(select.Having);

                    // determine what if anything should be lifted from this select
                    List<SqlColumn> lift = null;
                    List<SqlColumn> keep = null;
                    foreach (SqlColumn sc in select.Row.Columns) {
                        bool referencesAliasesForLifting = this.aliases.ReferencesAny(sc.Expression);
                        bool isLockedExpression = this.referencedColumns.Contains(sc);
                        if (referencesAliasesForLifting) {
                            // 
                            if (isLockedExpression) {
                                this.canLiftAll = false;
                                this.ReferenceColumns(sc);
                            }
                            else {
                                this.hasLifted = true;
                                if (this.doLifting) {
                                    if (lift == null)
                                        lift = new List<SqlColumn>();
                                    lift.Add(sc);
                                }
                            }
                        }
                        else {
                            if (this.doLifting) {
                                if (keep == null)
                                    keep = new List<SqlColumn>();
                                keep.Add(sc);
                            }
                            this.ReferenceColumns(sc);
                        }
                    }

                    // check subqueries too
                    if (this.canLiftAll) {
                        this.VisitSource(select.From);
                    }

                    // don't allow lifting through these operations
                    if (select.Top != null ||
                        select.GroupBy.Count > 0 ||
                        this.aggregateChecker.HasAggregates(select) ||
                        select.IsDistinct) {
                        if (this.hasLifted) {
                            // 
                            this.canLiftAll = false;
                        }
                    }

                    // do the actual lifting for this select
                    if (this.doLifting && this.canLiftAll) {
                        select.Row.Columns.Clear();
                        if (keep != null)
                            select.Row.Columns.AddRange(keep);
                        if (lift != null) {
                            // 
                            this.lifted.Add(lift);
                        }
                    }

                    return select;
                }

                private void ReferenceColumns(SqlExpression expression) {
                    if (expression != null) {
                        if (this.liftedExpressions == null || !this.liftedExpressions.Contains(expression)) {
                            SqlGatherReferencedColumns.Gather(expression, this.referencedColumns);
                        }
                    }
                }
            }
        }
	}
}