-
Notifications
You must be signed in to change notification settings - Fork 0
/
Lesson-RecurSQL.qmd
402 lines (331 loc) · 10.9 KB
/
Lesson-RecurSQL.qmd
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
---
title: "Biostat 823 - Recursive data structures in SQL"
author: "Hilmar Lapp"
institute: "Duke University, Department of Biostatistics & Bioinformatics"
date: "Sep 17, 2024"
format:
revealjs:
slide-number: true
editor: visual
knitr:
opts_chunk:
echo: TRUE
---
## Recursive data structure
* Trees and more generally Directed Acyclic Graphs (DAGs) are commonly occurring recursive data structures
- Subject classification systems, hierarchical codes, etc
- Biological taxonomies (species classifications)
- Ancestry trees, phylogenetic trees
- Ontologies
## Example: Tree (a special case of DAG)
::: {layout-ncol=2 layout-valign="bottom"}
![Edges = Child to parent node](images/Recursion/Tree.png)
```{mermaid}
%%| fig-cap: "Relational model: Adjacency table using self-referential FK\n(Root node is identified by `Parent_ID IS NULL`.)"
erDiagram
Node |o--o{ Node : "parent node"
Node {
integer ID PK
string Label
integer Parent_ID FK
}
```
:::
## Recursion is through relationship
* Define _x_ ancestor of _y_ as $anc(x,y) := \{ parent(x, y)\ \cup\ parent(x, anc(z, y)) \}$
- Node $x$ is an ancestor of node $y$ iff $x$ is a parent of $y$, or if $x$ is a parent of $z$ and $z$ is an ancestor of $y$.
* Examples of queries requiring recursion:
- List all ancestors of node $x$.
- List all nodes for which node $x$ is an ancestor.
- List the _common_ (or _distinct_) ancestors of nodes $x$ and $y$.
- Obtain the _most recent_ common ancestor (MRCA) of nodes $x$ and $y$ (ancestor with shortest distance).
## Options for enabling recursive queries
1. Create and then query transitive closure ("path") table
2. Implement and then query nested sets enumeration (only for trees, not graphs)
3. Use recursive SQL SELECT query (if RDBMS supports it)
::: aside
If the SQL database is accessed through a programming language environment, the recursion could of course be handled there, though at the potentially prohibitive expense of potentially 100s or more of queries.
:::
## Transitive closure E-R model
```{mermaid}
%%| fig-cap: "E-R Diagram of adjacency table with path table"
erDiagram
Node |o--o{ Node : "parent node"
Node ||--o{ Node_Path : "ancestor"
Node ||--o{ Node_Path : "node"
Node {
integer ID PK
string Label
integer Parent_ID FK
}
Node_Path {
integer Node_ID FK
integer Ancestor_ID FK
integer Path_Length
}
```
## Transitive closure computation (I)
:::: {.columns}
::: {.column width="32%"}
```{mermaid}
%%| fig-cap: "E-R Diagram of adjacency table with path table"
erDiagram
Node |o--o{ Node : "parent node"
Node ||--o{ Node_Path : "ancestor"
Node ||--o{ Node_Path : "node"
Node {
integer ID PK
string Label
integer Parent_ID FK
}
Node_Path {
integer Node_ID FK
integer Ancestor_ID FK
integer Path_Length
}
```
:::
::: {.column width="65%"}
Algorithm:
1. Add $anc(x,y,1)\ \\\forall\ (x,y) \in \{ parent(x,y) \}$
2. Let _l_ = 1
a. Add $anc(x,y,l+1)\ \\\forall (x,y) \in \{anc(z,y,l) \land parent(x,z)\}$
b. $l = l + 1$
c. Repeat (a) unless no tuples added.
:::
::::
## Transitive closure computation (II)
:::: {.columns}
::: {.column width="32%"}
```{mermaid}
%%| fig-cap: "E-R Diagram of adjacency table with path table"
erDiagram
Node |o--o{ Node : "parent node"
Node ||--o{ Node_Path : "ancestor"
Node ||--o{ Node_Path : "node"
Node {
integer ID PK
string Label
integer Parent_ID FK
}
Node_Path {
integer Node_ID FK
integer Ancestor_ID FK
integer Path_Length
}
```
:::
::: {.column width="68%"}
Transitive closure computation in SQL:
```sql
INSERT INTO Node_Path
(Node_ID, Ancestor_ID, Path_Length)
SELECT ID, Parent_ID, 1 FROM Node
WHERE Parent_ID IS NOT NULL;
```
```sql
-- Repeat until no more rows inserted
INSERT INTO Node_Path
(Node_ID, Ancestor_ID, Path_Length)
SELECT p.Node_ID, n.Parent_ID, p.Path_Length+1
FROM Node_Path p
JOIN Node n ON (p.Ancestor_ID = n.ID)
WHERE n.Parent_ID IS NOT NULL
AND NOT EXISTS (
SELECT 1 FROM Node_Path pp
WHERE pp.Node_ID = p.Node_ID
AND pp.Ancestor_ID = n.Parent_ID
-- Note that for graphs we would also have to
-- test path length!
)
```
:::
::::
## Transitive closure visualized
![Node relationships added by transitive closure in <span style="color: blue">blue</span>](images/Recursion/Tree with paths.png)
## Nested Set Enumeration
We add two attributes to a Node, a _left_ and a _right_ number:
![Same tree as before, but nodes with _left_ and _right_ (integer) values added](images/Recursion/Tree with leftright.png)
## Nested Set Computation (I)
The _left_ and _right_ nested set values are computed using recursive depth-first traversal of the nodes in the tree structure:
```Python
def nestedSet(node, nestedNumber):
node.left = nestedNumber
for child in node.children():
nestedNumber = nestedSet(child, nestedNumber + 1)
node.right = nestedNumber + 1
return node.right
nestedSet(rootNode, 1)
```
## Nested Set Computation (II)
![Tree with computed Nested Set values](images/Recursion/Tree with nestedset.png)
## Recursive SQL SELECT
* Oracle introduced a non-standard `CONNECT BY` clause in the 1980s
* [Common Table Expressions](https://en.wikipedia.org/wiki/Hierarchical_and_recursive_queries_in_SQL#Common_table_expression) (CTE) enabling recursive queries introduced in the SQL:1999 standard
- In essence, CTEs can be seen as temporary named result sets
- Supported by many popular RDBMSs (including MySQL, PostgreSQL, Sqlite) in their more modern versions
## Recursive CTE example: factorial() {.smaller .scrollable}
```{r setupSQLite, include=FALSE}
library(RSQLite)
library(DBI)
db <- dbConnect(RSQLite::SQLite(), ":memory:")
knitr::opts_chunk$set(connection = "db")
```
```{sql, label="recursiveFactorial"}
WITH RECURSIVE factorials (n, factorial) AS (
SELECT 0, 1 -- Initial Subquery
UNION ALL
-- Recursive Subquery
SELECT n+1, (n+1)*factorial
FROM factorials
WHERE n < 10
)
SELECT * FROM factorials;
```
## Recursive CTE example: fibonacci() {.smaller .scrollable}
```{sql, label=recursiveFib}
WITH RECURSIVE fibonacci (n, fib_n, fib_n1) AS (
SELECT 1, 1, 0 -- Initial Subquery
UNION ALL
-- Recursive Subquery
SELECT n+1, fib_n+fib_n1, fib_n
FROM fibonacci
WHERE n < 10
)
SELECT n, fib_n as "fib(n)", fib_n1 as "fib(n-1)" FROM fibonacci;
```
## Transitive closure using CTE (I) {.smaller .scrollable}
```{r, label="changeConn", include=FALSE}
db <- dbConnect(RSQLite::SQLite(), "data/ncbi20170203.db")
knitr::opts_chunk$set(connection = "db")
```
```{sql, label="recursive2", max.print=NA}
WITH RECURSIVE Node_Path (Node_ID, Ancestor_ID, Path_Len) AS (
SELECT ID, Parent_ID, 1 -- Initial Subquery
FROM Node
WHERE Name = 'Homo sapiens'
UNION ALL
-- Recursive Subquery
SELECT Node_ID, p.Parent_ID, Path_Len + 1
FROM Node AS p JOIN Node_Path ON (p.ID = Node_Path.Ancestor_ID)
)
SELECT n.ID, n.Name, a.ID, a.Name, np.Path_Len
FROM Node_Path np JOIN Node AS n ON (np.Node_ID = n.ID)
JOIN Node AS a ON (np.Ancestor_ID = a.ID)
ORDER BY np.Path_Len;
```
## Transitive closure using CTE (II) {.smaller .scrollable}
```{sql, label="recursive3", max.print=NA}
WITH RECURSIVE Node_Path (Node_ID, Ancestor_ID, Path_Len) AS (
SELECT ID, Parent_ID, 1 -- Initial Subquery
FROM Node
WHERE Name IN ('Homo sapiens', 'Gallus gallus')
UNION ALL
-- Recursive Subquery
SELECT Node_ID, p.Parent_ID, Path_Len + 1
FROM Node AS p JOIN Node_Path ON (p.ID = Node_Path.Ancestor_ID)
)
SELECT a.ID, a.Name, np1.Path_Len, np2.Path_Len
FROM Node_Path AS np1 JOIN Node AS a ON (np1.Ancestor_ID = a.ID)
JOIN Node_Path AS np2 ON (np1.Ancestor_ID = np2.Ancestor_ID)
WHERE np1.Node_ID < np2.Node_ID;
```
## Transitive closure using CTE (III) {.smaller .scrollable}
```{sql, label="recursive4", max.print=NA}
WITH RECURSIVE Node_Path (Node_ID, Ancestor_ID, Path_Len) AS (
SELECT ID, Parent_ID, 1 -- Initial Subquery
FROM Node
WHERE Name IN ('Homo sapiens', 'Gallus gallus')
UNION ALL
-- Recursive Subquery
SELECT Node_ID, p.Parent_ID, Path_Len + 1
FROM Node AS p JOIN Node_Path ON (p.ID = Node_Path.Ancestor_ID)
WHERE p.Parent_ID IS NOT NULL
)
SELECT a.ID, a.Name, group_concat(n.Name,', ') AS Common_Ancestor_Of,
MIN(np.Path_Len) AS Min_Path_Len
FROM Node_Path AS np
JOIN Node AS a ON (np.Ancestor_ID = a.ID)
JOIN Node AS n ON (np.Node_ID = n.ID)
GROUP BY a.ID, a.Name
HAVING COUNT(n.Name) > 1
ORDER BY Min_Path_Len;
```
## Directed Acyclic Graph (DAG)
:::: {.columns}
::: {.column width="50%"}
![Edges = directed from "start" to "end"](images/Recursion/DAG.png)
:::
::: {.column width="50%"}
![Edges can have a label or type](images/Recursion/DAG with edge types.png)
:::
::::
## Directed Graph as relational model {.smaller}
:::: {.columns}
::: {.column width="45%"}
```{mermaid}
%%| fig-cap: "Relational model of a Directed Graph: Adjacency table connecting nodes to each other. (Note that acyclic property of graph cannot be enforced by a relational database.)"
erDiagram
Node ||--o{ Edge : "edge start"
Node ||--o{ Edge : "edge end"
Node {
integer ID PK
string Label
}
Edge {
integer startNode FK
string Label
integer endNode FK
}
```
:::
::: {.column width="45%"}
```{mermaid}
%%| fig-cap: "Relational model of a Directed Graph with edge type normalized as a node entity. (This could also be a separate table.)"
erDiagram
Node ||--o{ Edge : "edge start"
Node ||--o{ Edge : "edge end"
Node ||--o{ Edge : "edge type"
Node {
integer ID PK
string Label
}
Edge {
integer startNode FK
integer type FK
integer endNode FK
}
```
:::
::::
## Paths through directed graph
* Define recursively: $path(x,y,t,l) := \{ edge(x,y,t) \cup\ edge(path(x,z,t,l-1), y, t) \}$
- There is a path from $x$ to $y$ of type $t$ and length $l$ iff there is an edge from $x$ to $y$ of type $t$, or if there is path from $x$ to $z$ of type $t$ and length $l-1$ and an egde of type $t$ from $z$ to $y$.
* The set of all paths is called the transitive closure.
## Transitive closure for directed graph
```{mermaid}
erDiagram
%%| fig-cap: "Relational model of a Directed Graph with a path table for transitive closure."
Node ||--o{ Edge : "edge start"
Node ||--o{ Edge : "edge end"
Node ||--o{ Edge : "edge type"
Node ||--o{ Path : "path start"
Node ||--o{ Path : "path end"
Node ||--o{ Path : "path type"
Node {
integer ID PK
string Label
boolean isTransitive
}
Edge {
integer startNode FK
integer type FK
integer endNode FK
}
Path {
integer startNode FK
integer type FK
integer endNode FK
integer length
}
```