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
| ///////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2015 by Charta Software B.V. //
// All rights reserved //
// //
// Version: 1.7.0.83525 //
// Web site: https://pascal.chartasoftware.com/ //
// //
// This code and information are provided "as is" without warranty of //
// any kind. Dissemination of this information or reproduction of //
// this material is strictly forbidden unless prior written permission //
// is obtained from Charta Software B.V.. //
// //
///////////////////////////////////////////////////////////////////////////
unit Sql.Database.Logical.Optimizing;
interface
uses
Boolean,
Collection.List,
Condition,
Sql.Comparison,
Sql.Database.Logical,
Sql.Expression,
Sql.Operator_.Binary,
Sql.Result,
Sql.Rewriter.Rule,
Sql.Statement,
Sql.Statement.ResultSet,
Sql.Statement.ResultSet.Select,
Text;
type
TIsSimpleColumn = class(TCondition<TSqlResultSetColumn>)
public
function Matches(const Column: TSqlResultSetColumn): TBoolean; override;
end;
TOptimizingSqlRewriteRule = class(TSqlRewriteRule)
protected
function CanMoveLimitToInnerSelect(OuterSelect: TSqlSelect; InnerSelect: TSqlSelect): TBoolean;
procedure MoveLimitToInnerSelect(OuterSelect: TSqlSelect; InnerSelect: TSqlSelect);
procedure CopyOrderByToInnerSelect(OuterSelect: TSqlSelect; InnerSelect: TSqlSelect);
function CanMoveCountToInnerSelect(OuterSelect: TSqlSelect; InnerSelect: TSqlSelect): TBoolean;
procedure MoveCountToInnerSelect(OuterSelect, InnerSelect: TSqlSelect);
function CanMoveRestrictionsToInnerSelect(OuterSelect: TSqlSelect; InnerSelect: TSqlSelect): TBoolean;
procedure MoveRestrictionsToInnerSelect(OuterSelect: TSqlSelect; InnerSelect: TSqlSelect; const InnerIdentifier: TText);
function CanMergeOuterIntoInnerSelect(OuterSelect: TSqlSelect; InnerSelect: TSqlSelect): TBoolean;
procedure MergeOuterIntoInnerSelect(OuterSelect, InnerSelect: TSqlSelect);
function IsLiteralBooleanExpression(Restriction: TSqlExpression; Value: TBoolean): TBoolean;
function ContainsLiteralBooleanExpression(Restrictions: TList<TSqlExpression>; Value: TBoolean): TBoolean;
procedure RemoveLiteralBooleanExpressions(Restrictions: TList<TSqlExpression>; Value: TBoolean);
function SimplifyAndAll(AndAll: TSqlAndAll): TSqlExpression;
function SimplifyOrAll(OrAll: TSqlOrAll): TSqlExpression;
function SimplifyOr(LogicalOr: TSqlLogicalOr): TSqlExpression;
function SimplifyAnd(LogicalAnd: TSqlLogicalAnd): TSqlExpression;
procedure SimplifyRestrictions(Restrictions: TList<TSqlExpression>);
procedure RewriteSelect(Select: TSqlSelect);
public
procedure Rewrite(Context: TSqlRewriteContext; Expression: TSqlExpression); override;
end;
TOptimizingSqlDatabase = class(TLogicalSqlDatabase)
private
function HandleDecoratedStatement(Statement: TSqlStatement; ResultMethod: TSqlQueryResultMethod): TSqlResult;
public
function Query(Statement: TSqlStatement; ResultMethod: TSqlQueryResultMethod = sqrmStoreResult): TSqlResult; override;
end;
implementation
uses
Exception,
Integer._32,
Sql.Functions.Aggregate,
Sql.Literal,
Sql.Rewriter,
Sql.Statement.DataManipulation,
Sql.Table.Column.Reference,
Sql.Table.Expression.ResultSetStatement;
{ TOptimizingSqlDatabase }
function TOptimizingSqlDatabase.Query(Statement: TSqlStatement; ResultMethod: TSqlQueryResultMethod): TSqlResult;
begin
if (Statement is TSqlSelect) or (Statement is TSqlDelete) or (Statement is TSqlUpdate) then
Result := HandleDecoratedStatement(Statement, ResultMethod)
else
Result := Database.Query(Statement, ResultMethod);
end;
function TOptimizingSqlDatabase.HandleDecoratedStatement(Statement: TSqlStatement; ResultMethod: TSqlQueryResultMethod): TSqlResult;
var
WorkingCopy: TSqlStatement;
Rewriter: TSqlRewriter;
RewriteRule: TSqlRewriteRule;
begin
Statement.AddReference();
WorkingCopy := Statement.CopyStatement();
WorkingCopy.AddReference();
RewriteRule := TOptimizingSqlRewriteRule.Create();
Rewriter := TSqlRewriter.Create(RewriteRule);
Rewriter.DecorateStatement(WorkingCopy);
Result := Database.Query(WorkingCopy, ResultMethod);
Rewriter.Free();
RewriteRule.Free();
Statement.ReleaseReference();
WorkingCopy.ReleaseReference();
end;
{ TOptimizingSqlRewriteRule }
function TOptimizingSqlRewriteRule.CanMergeOuterIntoInnerSelect(OuterSelect: TSqlSelect; InnerSelect: TSqlSelect): TBoolean;
begin
Result :=
not OuterSelect.Limit.HasEffect()
and (OuterSelect.Restrictions.Count = 0)
and (OuterSelect.GroupBy.Count = 0)
and (OuterSelect.OrderBy.Count = 0)
and (InnerSelect.GroupBy.Count = 0)
and (InnerSelect.OrderBy.Count = 0)
and OuterSelect.Columns.MatchesAll(TIsSimpleColumn.Create());
end;
function TOptimizingSqlRewriteRule.CanMoveCountToInnerSelect(OuterSelect: TSqlSelect; InnerSelect: TSqlSelect): TBoolean;
begin
Result :=
not InnerSelect.GroupsRows()
and (OuterSelect.Columns.Count = 1)
and (OuterSelect.Columns[0].Expression is TSqlCountAll)
and (OuterSelect.Restrictions.Count = 0)
and (OuterSelect.GroupBy.Count = 0); // TODO: GROUP BY does not need to be checked when the SELECT produces no duplicate rows, i.e. has a proper primary key
end;
function TOptimizingSqlRewriteRule.CanMoveLimitToInnerSelect(OuterSelect: TSqlSelect; InnerSelect: TSqlSelect): TBoolean;
begin
Result :=
OuterSelect.Limit.HasEffect()
and (OuterSelect.Restrictions.Count = 0)
and not OuterSelect.GroupsRows()
and not InnerSelect.Limit.HasEffect()
and (InnerSelect.OrderBy.Count = 0)
and OuterSelect.OrderBy.MatchesAll(TSqlOrderByExpression.TIsColumnReference.Create());
end;
function TOptimizingSqlRewriteRule.CanMoveRestrictionsToInnerSelect(OuterSelect: TSqlSelect; InnerSelect: TSqlSelect): TBoolean;
begin
Result :=
not InnerSelect.Limit.HasEffect()
and not InnerSelect.GroupsRows(); // TODO: The inner SELECT actually is allowed to group rows as long as the restrictions do not use the aggregated columns
end;
function TOptimizingSqlRewriteRule.ContainsLiteralBooleanExpression(Restrictions: TList<TSqlExpression>; Value: TBoolean): TBoolean;
var
Index: TInteger32;
begin
Result := False;
Index := 0;
while not Result and (Index < Restrictions.Count) do
begin
Result := IsLiteralBooleanExpression(Restrictions[Index], Value);
Inc(Index);
end;
end;
function TOptimizingSqlRewriteRule.IsLiteralBooleanExpression(Restriction: TSqlExpression; Value: TBoolean): TBoolean;
begin
Result := (Restriction is TSqlLiteralBoolean) and ((Restriction as TSqlLiteralBoolean).Value = Value);
end;
procedure TOptimizingSqlRewriteRule.MergeOuterIntoInnerSelect(OuterSelect: TSqlSelect; InnerSelect: TSqlSelect);
begin
end;
procedure TOptimizingSqlRewriteRule.MoveCountToInnerSelect(OuterSelect: TSqlSelect; InnerSelect: TSqlSelect);
begin
InnerSelect.Columns.Clear();
InnerSelect.Columns.Add(TSqlResultSetColumn.Create(TSqlCountAll.Create()));
InnerSelect.OrderBy.Clear();
OuterSelect.Columns.Clear();
OuterSelect.Columns.Add(TSqlResultSetColumn.Create(TSqlAllColumns.Create()));
end;
procedure TOptimizingSqlRewriteRule.MoveLimitToInnerSelect(OuterSelect: TSqlSelect; InnerSelect: TSqlSelect);
begin
InnerSelect.Limit.AssignFrom(OuterSelect.Limit);
OuterSelect.Limit.Clear();
end;
procedure TOptimizingSqlRewriteRule.CopyOrderByToInnerSelect(OuterSelect: TSqlSelect; InnerSelect: TSqlSelect);
var
Index: TInteger32;
OuterOrderByExpression: TSqlOrderByExpression;
OuterOrderByColumn: TSqlTableColumnReference;
InnerOrderByColumn: TSqlResultSetColumn;
begin
for Index := 0 to OuterSelect.OrderBy.Count - 1 do
begin
OuterOrderByExpression := OuterSelect.OrderBy[Index];
if OuterOrderByExpression.Expression is TSqlTableColumnReference then
begin
OuterOrderByColumn := OuterOrderByExpression.Expression as TSqlTableColumnReference;
InnerOrderByColumn := InnerSelect.Columns.FindWithIdentifier(OuterOrderByColumn.Column.Identifier);
InnerSelect.OrderBy.Add(TSqlOrderByExpression.Create(InnerOrderByColumn.Expression, OuterOrderByExpression.SortOrder));
end
else
raise EException.Create('Cannot optimize ORDER BY');
end;
end;
procedure TOptimizingSqlRewriteRule.MoveRestrictionsToInnerSelect(OuterSelect: TSqlSelect; InnerSelect: TSqlSelect; const InnerIdentifier: TText);
var
Index: TInteger32;
OuterRestrictions: TList<TSqlExpression>;
InnerRestrictions: TList<TSqlExpression>;
Restriction: TSqlExpression;
BinaryOperator: TSqlBinaryOperator;
MovedRestriction: TBoolean;
AliasedExpression: TSqlExpression;
begin
OuterRestrictions := OuterSelect.Restrictions;
InnerRestrictions := InnerSelect.Restrictions;
Index := 0;
while Index < OuterRestrictions.Count do
begin
Restriction := OuterRestrictions[Index];
MovedRestriction := False;
// TODO: Not only binary operators can be moved
if Restriction is TSqlBinaryOperator then
begin
BinaryOperator := Restriction as TSqlBinaryOperator;
if
(BinaryOperator.Left is TSqlTableColumnReference)
and ((BinaryOperator.Left as TSqlTableColumnReference).Column.Scope.Identifier = InnerIdentifier) // TODO: Matching identifiers is probably not the best way, but it is the only thing we currently can do
and (BinaryOperator.Right is TSqlLiteralValue) // TODO: This is a very limiting restriction
then
begin
AliasedExpression := InnerSelect.Columns.FindWithIdentifier((BinaryOperator.Left as TSqlTableColumnReference).Column.Identifier).Expression;
BinaryOperator.Left := AliasedExpression;
InnerRestrictions.Add(Restriction);
OuterSelect.Restrictions.RemoveAt(Index);
MovedRestriction := True;
end;
end;
if not MovedRestriction then
Inc(Index);
end;
end;
procedure TOptimizingSqlRewriteRule.RemoveLiteralBooleanExpressions(Restrictions: TList<TSqlExpression>; Value: TBoolean);
var
Index: TInteger32;
begin
Index := Restrictions.Count - 1;
while Index >= 0 do
begin
if IsLiteralBooleanExpression(Restrictions[Index], Value) then
Restrictions.RemoveAt(Index);
Dec(Index);
end;
end;
procedure TOptimizingSqlRewriteRule.Rewrite(Context: TSqlRewriteContext; Expression: TSqlExpression);
begin
if Expression is TSqlSelect then
RewriteSelect(Expression as TSqlSelect);
end;
procedure TOptimizingSqlRewriteRule.RewriteSelect(Select: TSqlSelect);
var
InnerResultSetStatement: TSqlResultSetStatement;
InnerSelect: TSqlSelect;
TableExpression: TSqlResultSetStatementTableExpression;
begin
SimplifyRestrictions(Select.Restrictions);
if (Select.From.Count = 1) and (Select.From[0] is TSqlResultSetStatementTableExpression) then
begin
TableExpression := Select.From[0] as TSqlResultSetStatementTableExpression;
InnerResultSetStatement := TableExpression.Statement;
if InnerResultSetStatement is TSqlSelect then
begin
InnerSelect := InnerResultSetStatement as TSqlSelect;
if CanMoveRestrictionsToInnerSelect(Select, InnerSelect) then
MoveRestrictionsToInnerSelect(Select, InnerSelect, TableExpression.Alias);
if CanMoveLimitToInnerSelect(Select, InnerSelect) then
begin
CopyOrderByToInnerSelect(Select, InnerSelect);
MoveLimitToInnerSelect(Select, InnerSelect);
end;
if CanMoveCountToInnerSelect(Select, InnerSelect) then
MoveCountToInnerSelect(Select, InnerSelect);
if CanMergeOuterIntoInnerSelect(Select, InnerSelect) then
MergeOuterIntoInnerSelect(Select, InnerSelect);
end;
end;
end;
function TOptimizingSqlRewriteRule.SimplifyAnd(LogicalAnd: TSqlLogicalAnd): TSqlExpression;
begin
if IsLiteralBooleanExpression(LogicalAnd.Left, False) or IsLiteralBooleanExpression(LogicalAnd.Right, False) then
Result := TSqlLiteralBoolean.Create(False)
else if IsLiteralBooleanExpression(Logicaland.Left, True) then
Result := LogicalAnd.Right
else if IsLiteralBooleanExpression(LogicalAnd.Right, True) then
Result := LogicalAnd.Left
else
Result := LogicalAnd;
end;
function TOptimizingSqlRewriteRule.SimplifyAndAll(AndAll: TSqlAndAll): TSqlExpression;
begin
SimplifyRestrictions(AndAll.Expressions);
RemoveLiteralBooleanExpressions(AndAll.Expressions, True);
case AndAll.Expressions.Count of
0: Result := TSqlLiteralBoolean.Create(True);
1: Result := AndAll.Expressions[0];
else
begin
if ContainsLiteralBooleanExpression(AndAll.Expressions, False) then
Result := TSqlLiteralBoolean.Create(False)
else
Result := AndAll;
end;
end;
end;
function TOptimizingSqlRewriteRule.SimplifyOr(LogicalOr: TSqlLogicalOr): TSqlExpression;
begin
if IsLiteralBooleanExpression(LogicalOr.Left, True) or IsLiteralBooleanExpression(LogicalOr.Right, True) then
Result := TSqlLiteralBoolean.Create(True)
else if IsLiteralBooleanExpression(LogicalOr.Left, False) then
Result := LogicalOr.Right
else if IsLiteralBooleanExpression(LogicalOr.Right, False) then
Result := LogicalOr.Left
else
Result := LogicalOr;
end;
function TOptimizingSqlRewriteRule.SimplifyOrAll(OrAll: TSqlOrAll): TSqlExpression;
begin
RemoveLiteralBooleanExpressions(OrAll.Expressions, False);
case OrAll.Expressions.Count of
0: Result := TSqlLiteralBoolean.Create(False);
1: Result := OrAll.Expressions[0];
else
begin
if ContainsLiteralBooleanExpression(OrAll.Expressions, True) then
Result := TSqlLiteralBoolean.Create(True)
else
Result := OrAll;
end;
end;
end;
procedure TOptimizingSqlRewriteRule.SimplifyRestrictions(Restrictions: TList<TSqlExpression>);
var
Index: TInteger32;
Restriction: TSqlExpression;
begin
for Index := 0 to Restrictions.Count - 1 do
begin
Restriction := Restrictions[Index];
if Restriction is TSqlOrAll then
Restrictions[Index] := SimplifyOrAll(Restriction as TSqlOrAll)
else if Restriction is TSqlAndAll then
Restrictions[Index] := SimplifyAndAll(Restriction as TSqlAndAll)
else if Restriction is TSqlLogicalOr then
Restrictions[Index] := SimplifyOr(Restriction as TSqlLogicalOr)
else if Restriction is TSqlLogicalAnd then
Restrictions[Index] := SimplifyAnd(Restriction as TSqlLogicalAnd);
end;
end;
{ TIsSimpleColumn }
function TIsSimpleColumn.Matches(const Column: TSqlResultSetColumn): TBoolean;
begin
Result := Column.Expression is TSqlTableColumnReference;
end;
end.
|