-
Notifications
You must be signed in to change notification settings - Fork 0
/
Aurelius.Sql.JoinIterator.pas
101 lines (85 loc) · 2.05 KB
/
Aurelius.Sql.JoinIterator.pas
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
unit Aurelius.Sql.JoinIterator;
interface
uses
SysUtils,
Aurelius.Sql.BaseTypes;
type
TJoinNode = record
Join: TSQLJoin;
RightTable: TSQLTable;
LeftTable: TSQLTable;
constructor Init(AJoin: TSQLJoin);
end;
TNodeHandler = reference to procedure (ANode: TJoinNode);
TJoinIterator = class
private
FRoot: TSQLJoin;
public
constructor Create(ARoot: TSQLJoin);
procedure ForEachDo(AHandler: TNodeHandler);
end;
implementation
uses
Generics.Collections;
type
TNodeStack = TStack<TJoinNode>;
{ TJoinIterator }
constructor TJoinIterator.Create(ARoot: TSQLJoin);
begin
inherited Create;
if ARoot=nil then
raise Exception.Create('Join is required');
FRoot := ARoot;
end;
procedure TJoinIterator.ForEachDo(AHandler: TNodeHandler);
function FindJoinedTable(AJoin: TSQLJoin; AStack: TNodeStack): TSQLTable;
var
Node: TJoinNode;
C, I: Integer;
begin
C := AStack.Count;
Node.Init(AJoin);
repeat
AStack.Push(Node);
if Node.Join.LeftRelation is TSQLTable then
begin
Result := TSQLTable(Node.Join.LeftRelation);
Break;
end else
Node.Join := TSQLJoin(Node.Join.LeftRelation);
until False;
for I := Pred(AStack.Count) downto C do
AStack.List[I].LeftTable := Result;
end;
var
Node: TJoinNode;
Stack: TNodeStack;
begin
if not Assigned(AHandler) then
Exit;
Stack := TNodeStack.Create;
try
Node.Init(nil);
Node.LeftTable := FindJoinedTable(FRoot, Stack); // the first/main table
AHandler(Node);
while Stack.Count>0 do
begin
Node := Stack.Pop;
if Node.Join.RightRelation is TSQLTable then
Node.RightTable := TSQLTable(Node.Join.RightRelation)
else
Node.RightTable := FindJoinedTable(TSQLJoin(Node.Join.RightRelation), Stack);
AHandler(Node);
end;
finally
Stack.Free;
end;
end;
{ TJoinNode }
constructor TJoinNode.Init(AJoin: TSQLJoin);
begin
Join := AJoin;
LeftTable := nil;
RightTable := nil;
end;
end.