Algorithmadvanced
DPccp
Also called dynamic programming over connected subgraph complement pairs, csg-cmp pair enumeration.
Dynamic programming for join ordering that enumerates exactly the connected subgraph and complement pairs of the query graph.
- Solves
- Join ordering problem
- Time
- O(n c) worst
- Space
- O(2^n) extra
- Where
- c = the number of csg-cmp pairs of the query graph; n = the number of relations
- Model
- Word RAM
- Properties
- deterministicexactrecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Guido Moerkotte, Thomas Neumann, 2006
DPccp is a dynamic program that finds the cheapest bushy join tree without cross products for a connected query graph. Like the Selinger enumeration, it keeps the best plan for each set of relations and builds larger plans from smaller ones. The difference is in which pairs of sets it tries. Every join in a plan without cross products combines two disjoint connected sets of relations that a join predicate links: a csg-cmp pair (connected subgraph and connected complement). DPccp enumerates exactly these pairs, each once, in an order where the plans of both halves are already final. So its work grows with the number of such pairs, which is for a chain query, and not with the number of all subsets. Moerkotte and Neumann gave it in 2006.
In plain words
A dynamic program for join ordering keeps the cheapest plan for each group of tables and joins two groups to make a larger one. Older versions try many pairs of groups that are useless: groups whose tables are not linked by any predicate, or two groups with no predicate between them. On a long chain of tables almost every pair they try is useless.
DPccp only makes useful pairs. It grows each group from its smallest table, one ring of neighbors at a time, so every group it makes is linked. For each group, it grows the partners the same way, starting from the neighbors of the group. It never makes a pair twice, and it makes the smaller pieces of a group before the group itself, so their best plans are ready when it needs them.
The problem
The input is a connected query graph on relations , with the size of each relation and a selectivity on each edge, and a cost function. The cost of a join tree is the sum of a join cost over its inner nodes, where the join cost of depends only on the sets of relations of and , for example , the size of the result. The output is a cheapest bushy join tree in which each join has a predicate between its two inputs. This is the join ordering problem for bushy trees without cross products.
is the neighborhood of a set : the relations outside with an edge into . .
The algorithm
DPCCP(query graph G)- 1
number the relations v_0, ..., v_(n-1) in breadth-first order - 2
for each relation v do best[{v}] ← the scan of v - 3
for each csg S1 from ENUMERATE-CSG do - 4
for each S2 from ENUMERATE-CMP(S1) do - 5
S ← S1 ∪ S2 - 6
for (P1, P2) in (best[S1], best[S2]) and (best[S2], best[S1]) do - 7
if best[S] is empty or cost(P1 ⋈ P2) < cost(best[S]) then best[S] ← P1 ⋈ P2 - 8
return best[all relations]
ENUMERATE-CSG- 1
for i ← n-1 down to 0 do - 2
emit {v_i} - 3
ENUMERATE-CSG-REC({v_i}, B_i) ENUMERATE-CSG-REC(S, X)- 4
N ← N(S) - X - 5
for each nonempty subset S' of N, smaller subsets first do emit S ∪ S' - 6
for each nonempty subset S' of N, smaller subsets first do ENUMERATE-CSG-REC(S ∪ S', X ∪ N) ENUMERATE-CMP(S1)- 7
X ← B_min(S1) ∪ S1 - 8
N ← N(S1) - X - 9
for each v_i in N, by decreasing i do - 10
emit {v_i} - 11
ENUMERATE-CSG-REC({v_i}, X ∪ (B_i ∩ N))
ENUMERATE-CSG starts a new set from each relation and only lets it grow into relations with a larger index, so is the smallest member of every set it makes in that iteration. ENUMERATE-CSG-REC grows a connected set by any nonempty subset of its neighborhood. The set holds the relations that this branch must not add, either because they have a smaller index or because another branch adds them; this is what makes every set appear only once. ENUMERATE-CMP grows the partners of from its neighbors, in the same way, but only with relations above the smallest index of , so each unordered pair appears once, with as the half that holds the smaller index. Line L6 tries both orders of the inputs, which matters when the join cost is not symmetric, as for a hash join with a build side.
Example
Four relations form a chain ---, with 50, 1000, 200 and 10 tuples and the selectivities 1/100, 1/50 and 1/2 on the three edges. The cost is . The table lists the pairs in the order that DPccp uses them, with the size of the union, the cost of the new candidate, and the best plan stored for the union after the pair.
| size of the union | candidate cost | best plan after the pair | ||
|---|---|---|---|---|
| 1000 | 1000 | , 1000 | ||
| 4000 | 4000 | , 4000 | ||
| 20 000 | 21 000 | , 21 000 | ||
| 20 000 | 24 000 | unchanged, 21 000 | ||
| 500 | 500 | , 500 | ||
| 2000 | 6000 | , 6000 | ||
| 10 000 | 31 000 | , 31 000 | ||
| 2000 | 2500 | , 2500 | ||
| 10 000 | 11 500 | , 11 500 | ||
| 10 000 | 12 500 | unchanged, 11 500 |
There are 10 pairs, which is . The pairs for come before is used as a half, and has its final plan before the last row. The result is the bushy tree with cost 11 500; the cheapest left-deep tree, , costs 12 500. A dynamic program over all subsets with all their splits would look at 50 ordered splits for these four relations, most of them with a disconnected half.
Correctness
There are three facts to show. First, ENUMERATE-CSG emits each connected set exactly once: a set with smallest member is made only in the iteration for , and inside it the set decides in which branch each relation is added. Second, ENUMERATE-CMP() emits exactly the connected sets that are disjoint from , linked to it by an edge, and above its smallest index, each once; with the first fact, every csg-cmp pair is used exactly once. Third, when a pair is used, all pairs with union or have been used: the halves of have a larger smallest index, so they come in an earlier iteration of line L9, and the halves of are smaller sets with the same smallest member, which line L13 emits first because it takes smaller subsets first. Then the usual argument applies: the last join of an optimal plan combines a csg-cmp pair, and the best plans of its halves are optimal. The proof file has the details; the argument does not need the breadth-first numbering.
Proof: DPccp enumerates every csg-cmp pair once, in a valid order, and finds the cheapest bushy plan without cross productsfull
Setting. The query graph has the relations and is connected. is the set of relations outside with an edge into , and . A csg is a nonempty set of relations that induces a connected subgraph. A csg-cmp pair is an unordered pair of disjoint csgs with an edge between them. A plan without cross products is a leaf , or a join of two plans without cross products, for sets and , with an edge between and . The cost of a join is , where the sizes depend only on the sets. Lines L13 and L14 go through the nonempty subsets of in increasing order as integers, so every subset comes before its proper supersets.
Lemma 1. Let be a csg and . The call ENUMERATE-CSG-REC emits, each exactly once, the sets with , connected and . If are two of them, is emitted before .
Proof. By induction on the number of relations outside . Let (line L12). A set of the lemma has a relation in with an edge into , because is connected; that relation is not in , so is not empty. If , then line L13 emits for this . Otherwise and ; the recursive call of line L14 for has a larger (since ) and emits by induction. The other calls of line L14 emit only sets whose intersection with is for their own , and line L13 emits only sets inside , so is emitted exactly once. Conversely every emitted set is connected (each relation of has an edge into the connected ), strictly contains , and meets only in , because . If is empty, no set exists and nothing is emitted.
For the order, let , and let . If is emitted by line L13, then , so is emitted by line L13 too, at an earlier subset. If is emitted inside the call for and by line L13, then comes first, because line L13 runs before line L14. If both come from recursive calls, then either and the induction hypothesis applies to the one call, or and the call for comes first.
Lemma 2 (csgs). ENUMERATE-CSG emits every csg exactly once, and it emits all csgs with smallest index before all csgs with a smaller smallest index. Two csgs with the same smallest index are emitted with first.
Proof. The iteration for emits and, by Lemma 1 with and , every connected with , that is, with smallest index . The iterations run for down to . The order inside one iteration is the order of Lemma 1, and comes first.
Lemma 3 (complements). For a csg with smallest index , ENUMERATE-CMP emits, each exactly once, the csgs that are disjoint from , have an edge into , and have a smallest index larger than .
Proof. Let and (lines L15 and L16). A set as in the lemma is disjoint from and meets , so it meets . Let be the member of with the smallest index. Then , so the iteration of line L17 for emits , at line L18 if and by Lemma 1 otherwise. Every set that the iteration for emits contains and no other member of , so is its member of with the smallest index; hence no other iteration emits . Conversely every emitted set is connected, disjoint from (so from , and with all indexes above ), and contains .
By Lemmas 2 and 3, lines L3 and L4 produce every csg-cmp pair exactly once, as with the smaller smallest index in .
Lemma 4 (final plans). When lines L5 to L7 use a pair , every pair whose union is , and every pair whose union is , has been used already.
Proof. A pair is used in the iteration of line L3 for , and has the same smallest index as . If , then are csgs with the same smallest index, so comes before by Lemma 2. If , then the smallest index of is that of , which is larger than that of , so comes before by Lemma 2. In both cases the whole iteration for ends before the iteration for starts.
The proof does not use the breadth-first numbering of line L1; any numbering gives the same guarantees.
Theorem. Line L8 returns a cheapest plan without cross products for all relations.
Proof. Let be the least cost of a plan without cross products for a csg . We show that after all pairs with union are used, is a plan for without cross products with cost . For a single relation this holds by line L2. Every entry that line L7 stores joins two stored plans across an edge, so it is a plan without cross products for its set. Take a cheapest plan for with ; its last join combines plans and for sets and . By induction on the plan, the set of every plan without cross products is connected, so is a csg-cmp pair, and it is used once. By Lemma 4 and induction on , at that moment and cost and . Line L6 tries both orders of the two inputs, and the join term depends only on the sets, so one of the candidates costs at most , and line L7 keeps a plan of that cost. Later pairs can only lower , and no plan is cheaper than . Since is connected, the set of all relations is a csg.
Work. Each call of ENUMERATE-CSG-REC, other than the top call of an iteration, is for a set that line L13 has just emitted, so the number of calls is at most the number of emitted sets plus . A call costs for the neighborhood and per emitted set. Every csg with two or more relations is the union of at least one csg-cmp pair (split it along an edge of a spanning tree), so there are at most csgs, where is the number of pairs. Line L4 emits sets in total. So with the sizes stored per set, the work is for a connected graph, where .
Complexity
Let be the number of csg-cmp pairs. Every call of ENUMERATE-CSG-REC belongs to a set that was just emitted, and costs to compute a neighborhood with bit operations, so the enumeration takes time; there are at most connected sets, and each pair costs at lines L5 to L7 when the sizes are stored per set. The table holds one plan per connected set, at most .
| query graph | csg-cmp pairs | |||
|---|---|---|---|---|
| chain | 20 | 165 | 1330 | |
| star | 32 | 2304 | 4 980 736 | |
| clique | 90 | 28 501 | 1 742 343 625 |
Any dynamic program that considers every csg-cmp pair must do at least steps, so DPccp is within a factor of that bound, and its work adapts to the shape of the graph. DPsub, which tries every split of every subset, does steps on every graph, including a chain.
Properties
- Exact. The result is a cheapest bushy tree without cross products for any cost that adds a join term which depends only on the sets of the two inputs.
- No wasted pairs. Every pair it builds is a legal join, and no pair is built twice.
- Needs a connected graph. If the graph is not connected, there is no plan without a cross product; a system must add cross product edges first.
- Simple predicates only. Each edge links two relations. Predicates over three or more relations, and the ordering limits of outer joins, need hyperedges, which is what DPhyp adds.
Variants and improvements
- DPsize and DPsub. The older dynamic programs enumerate pairs by the sizes of the sets, or by the subsets of each set, and test each pair for connectivity and for an edge. They find the same optimum but test many pairs that fail. Moerkotte and Neumann analyze both.
- DPhyp. Moerkotte and Neumann (2008) generalize the neighborhood and the enumeration to hypergraphs. For a graph without hyperedges it enumerates the same pairs.
- Physical properties. Keeping one plan per (set, interesting order) pair, as in the Selinger enumeration, adds sort orders without changing the enumeration.
- Cross products. To allow cross products, add an edge with selectivity 1 between every pair of relations; the graph becomes a clique and DPccp then behaves like DPsub.
When to use it
Use it as the exact bushy join enumerator of an optimizer for queries with up to 10 to 20 relations, when cross products are not wanted. It is most useful for sparse graphs (chains, stars, snowflakes with few joins), where it avoids most of the work of DPsub. For a star with 20 relations or a large clique it is still exponential; then use a heuristic such as greedy operator ordering or, for tree queries and left-deep plans, the IKKBZ algorithm.
Pitfalls
- Subset order in ENUMERATE-CSG-REC. The proof needs smaller subsets of before their supersets at lines L13 and L14. Enumerating them in another order, for example from the largest down, can use a set as a half before its best plan is final.
- Asymmetric costs. Each unordered pair appears once, so the code must try both orders of the inputs at line L6 when the join cost is not symmetric.
- Equivalent predicates. The graph should contain the edges implied by equalities, such as from and . Without them, the graph has fewer edges and the search misses plans.
- Estimates. The plan is optimal for the estimated sizes; see cardinality estimation.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the databases pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Naive relations, operators by definition, SQL three-valued logic and a page-counting disk.
This is the reference that the tests of the databases pages compare against.
Every operator here follows its definition directly, with nested loops and no
index, hash table or sort of the input. Do not use it as a fast engine.
Relations
Relation(schema, rows, mode) holds a tuple of distinct attribute names and
a collections.Counter from tuples to positive counts. mode is "bag" (the
default, SQL semantics) or "set" (relational theory); in set mode every
count is 1. rows may be an iterable of tuples (duplicates add up) or a
mapping from tuples to counts. Two relations are equal when they have the
same attributes (in any column order) and the same count for each tuple.
The mode is not compared.
Operators (each returns a new Relation in the mode of its input)
select(rel, pred) keeps a row only when pred(row) is True
where(rel, pred) the same as select (the SQL WHERE filter)
project(rel, attrs) bag: counts add up; set: duplicates removed
rename(rel, mapping) mapping is {old: new}
union(r, s) bag: UNION ALL (counts add); set: union
difference(r, s) bag: monus max(0, m - n); set: r - s
intersection(r, s) bag: min(m, n); set: intersection
product(r, s) attributes must be disjoint; counts multiply
natural_join(r, s) nested loops on the common attributes
theta_join(r, s, pred) select(product(r, s), pred)
semijoin(r, s), antijoin(r, s)
distinct(rel) every count becomes 1
aggregate(rel, group_attrs, aggs)
aggs is a list of (func, attr, out) with func in
count_star, count, count_distinct, sum, avg, min, max
A predicate receives the row as a dict from attribute name to value. It may
return True, False or None (UNKNOWN). Only True keeps the row.
Nulls
NULL is None. Joins follow SQL: a common attribute that is None in either
row never matches. aggregate follows SQL: GROUP BY puts all nulls of a
column in one group, every aggregate except count_star skips nulls, and
sum, avg, min and max of no non-null value give None while count gives 0.
With no grouping attributes, aggregate returns one row even for an empty
input, as SQL does.
Expressions
evaluate(expr, db, mode) evaluates a tree of nested tuples:
("scan", name)
("select", pred, e) ("project", attrs, e)
("rename", mapping, e) ("distinct", e)
("union", e1, e2) ("difference", e1, e2)
("intersection", e1, e2) ("product", e1, e2)
("join", e1, e2) ("theta_join", pred, e1, e2)
("semijoin", e1, e2) ("antijoin", e1, e2)
("aggregate", group_attrs, aggs, e)
db maps a name to a Relation. Each scanned relation is first put in mode.
Three-valued logic
tv_and, tv_or and tv_not are the strong Kleene connectives on True, False
and None. cmp3(op, x, y) compares with op in =, <>, !=, <, <=, >, >= and
returns None when x or y is None.
Disk
Disk counts page reads and writes. load(rows, per_page) puts an existing
input on the disk without counting it. paginate(rows, per_page) splits a
list of rows into pages.
Random data
random_relation(rng, schema, n, domain, mode, null_rate) draws n rows.
"""
from collections import Counter
from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence
from fractions import Fraction
from numbers import Number
import random
BAG = "bag"
SET = "set"
MODES = (BAG, SET)
# ---------------------------------------------------------------- ordering
def value_key(v: object) -> tuple:
"""A total order on the values of one column: None first, then numbers, then strings."""
if v is None:
return (0, 0)
if isinstance(v, Number):
return (1, v)
if isinstance(v, str):
return (2, v)
if isinstance(v, tuple):
return (3, tuple(value_key(x) for x in v))
return (4, repr(v))
def row_key(t: Sequence) -> tuple:
"""A total order on tuples that tolerates None. Use it to sort rows in tests."""
return tuple(value_key(v) for v in t)
# ---------------------------------------------------------------- relations
class Relation:
"""A relation: a schema (tuple of names), a Counter of tuples and a mode."""
__slots__ = ("schema", "rows", "mode")
def __init__(self, schema: Sequence[str], rows: Iterable | Mapping = (), mode: str = BAG) -> None:
if mode not in MODES:
raise ValueError("mode must be 'bag' or 'set'")
schema = tuple(schema)
if len(set(schema)) != len(schema):
raise ValueError("duplicate attribute in schema %r" % (schema,))
counts: Counter = Counter()
items = rows.items() if isinstance(rows, Mapping) else ((t, 1) for t in rows)
for t, c in items:
t = tuple(t)
if len(t) != len(schema):
raise ValueError("tuple %r does not fit schema %r" % (t, schema))
if c < 0:
raise ValueError("negative count for %r" % (t,))
if c:
counts[t] += c
if mode == SET:
counts = Counter({t: 1 for t in counts})
self.schema = schema
self.rows = counts
self.mode = mode
def index(self, attr: str) -> int:
return self.schema.index(attr)
def reorder(self, schema: Sequence[str]) -> "Relation":
"""The same relation with its columns in the order of schema."""
schema = tuple(schema)
if sorted(schema) != sorted(self.schema):
raise ValueError("schemas %r and %r differ" % (self.schema, schema))
pos = [self.schema.index(a) for a in schema]
return Relation(schema, {tuple(t[i] for i in pos): c for t, c in self.rows.items()}, self.mode)
def with_mode(self, mode: str) -> "Relation":
return Relation(self.schema, self.rows, mode)
def as_dict(self, t: Sequence) -> dict:
return dict(zip(self.schema, t))
def sorted_rows(self) -> list:
"""Every tuple, repeated by its count, in row_key order."""
out = []
for t in sorted(self.rows, key=row_key):
out.extend([t] * self.rows[t])
return out
def __iter__(self):
return iter(self.sorted_rows())
def __len__(self) -> int:
return sum(self.rows.values())
def __eq__(self, other: object) -> bool:
if not isinstance(other, Relation):
return NotImplemented
if sorted(self.schema) != sorted(other.schema):
return False
return self.rows == other.reorder(self.schema).rows
def __repr__(self) -> str:
body = ", ".join("%r: %d" % (t, self.rows[t]) for t in sorted(self.rows, key=row_key))
return "Relation(%r, {%s}, %r)" % (self.schema, body, self.mode)
def _mode2(r: Relation, s: Relation) -> str:
if r.mode != s.mode:
raise ValueError("operands have modes %r and %r" % (r.mode, s.mode))
return r.mode
def _same_schema(r: Relation, s: Relation) -> Relation:
"""s with its columns in the order of r; the attribute sets must be equal."""
if sorted(r.schema) != sorted(s.schema):
raise ValueError("union-incompatible schemas %r and %r" % (r.schema, s.schema))
return s.reorder(r.schema)
# ---------------------------------------------------------------- three-valued logic
def tv_and(a: bool | None, b: bool | None) -> bool | None:
if a is False or b is False:
return False
if a is None or b is None:
return None
return True
def tv_or(a: bool | None, b: bool | None) -> bool | None:
if a is True or b is True:
return True
if a is None or b is None:
return None
return False
def tv_not(a: bool | None) -> bool | None:
return None if a is None else not a
_CMP = {
"=": lambda x, y: x == y,
"<>": lambda x, y: x != y,
"!=": lambda x, y: x != y,
"<": lambda x, y: x < y,
"<=": lambda x, y: x <= y,
">": lambda x, y: x > y,
">=": lambda x, y: x >= y,
}
def cmp3(op: str, x: object, y: object) -> bool | None:
"""SQL comparison: None (UNKNOWN) if either side is NULL."""
if op not in _CMP:
raise ValueError("unknown comparison %r" % (op,))
if x is None or y is None:
return None
return bool(_CMP[op](x, y))
def is_true(v: bool | None) -> bool:
"""The WHERE test: only True passes; False and None (UNKNOWN) do not."""
return v is True
# ---------------------------------------------------------------- operators
def select(rel: Relation, pred: Callable[[dict], bool | None]) -> Relation:
out = {t: c for t, c in rel.rows.items() if pred(rel.as_dict(t)) is True}
return Relation(rel.schema, out, rel.mode)
where = select
def project(rel: Relation, attrs: Sequence[str]) -> Relation:
attrs = tuple(attrs)
pos = [rel.index(a) for a in attrs]
out: Counter = Counter()
for t, c in rel.rows.items():
out[tuple(t[i] for i in pos)] += c
return Relation(attrs, out, rel.mode)
def rename(rel: Relation, mapping: Mapping[str, str]) -> Relation:
for a in mapping:
if a not in rel.schema:
raise ValueError("no attribute %r to rename" % (a,))
return Relation(tuple(mapping.get(a, a) for a in rel.schema), rel.rows, rel.mode)
def union(r: Relation, s: Relation) -> Relation:
mode = _mode2(r, s)
s = _same_schema(r, s)
out = Counter(r.rows)
out.update(s.rows)
return Relation(r.schema, out, mode)
def difference(r: Relation, s: Relation) -> Relation:
mode = _mode2(r, s)
s = _same_schema(r, s)
out = {t: max(0, c - s.rows.get(t, 0)) for t, c in r.rows.items()}
return Relation(r.schema, out, mode)
def intersection(r: Relation, s: Relation) -> Relation:
mode = _mode2(r, s)
s = _same_schema(r, s)
out = {t: min(c, s.rows.get(t, 0)) for t, c in r.rows.items()}
return Relation(r.schema, out, mode)
def product(r: Relation, s: Relation) -> Relation:
mode = _mode2(r, s)
common = [a for a in r.schema if a in s.schema]
if common:
raise ValueError("product needs disjoint schemas; common: %r" % (common,))
out: Counter = Counter()
for t, c in r.rows.items():
for u, d in s.rows.items():
out[t + u] += c * d
return Relation(r.schema + s.schema, out, mode)
def _matches(r: Relation, s: Relation, t: tuple, u: tuple, common: Sequence[str]) -> bool:
for a in common:
x, y = t[r.index(a)], u[s.index(a)]
if x is None or y is None or x != y:
return False
return True
def natural_join(r: Relation, s: Relation) -> Relation:
"""Nested loops over both inputs. With no common attribute it is the product."""
mode = _mode2(r, s)
common = [a for a in r.schema if a in s.schema]
rest = [a for a in s.schema if a not in common]
rest_pos = [s.index(a) for a in rest]
out: Counter = Counter()
for t, c in r.rows.items():
for u, d in s.rows.items():
if _matches(r, s, t, u, common):
out[t + tuple(u[i] for i in rest_pos)] += c * d
return Relation(r.schema + tuple(rest), out, mode)
def theta_join(r: Relation, s: Relation, pred: Callable[[dict], bool | None]) -> Relation:
return select(product(r, s), pred)
def semijoin(r: Relation, s: Relation) -> Relation:
"""Rows of r (with their counts) that join with at least one row of s."""
_mode2(r, s)
common = [a for a in r.schema if a in s.schema]
out = {t: c for t, c in r.rows.items() if any(_matches(r, s, t, u, common) for u in s.rows)}
return Relation(r.schema, out, r.mode)
def antijoin(r: Relation, s: Relation) -> Relation:
"""Rows of r (with their counts) that join with no row of s."""
_mode2(r, s)
common = [a for a in r.schema if a in s.schema]
out = {t: c for t, c in r.rows.items() if not any(_matches(r, s, t, u, common) for u in s.rows)}
return Relation(r.schema, out, r.mode)
def distinct(rel: Relation) -> Relation:
return Relation(rel.schema, {t: 1 for t in rel.rows}, rel.mode)
AGG_FUNCS = ("count_star", "count", "count_distinct", "sum", "avg", "min", "max")
def _avg(vals: list) -> object:
total = sum(vals)
if all(isinstance(v, (int, Fraction)) for v in vals):
return Fraction(total, 1) / len(vals)
return total / len(vals)
def agg_value(func: str, vals: list) -> object:
"""One SQL aggregate over a list of column values (with repeats). count_star counts all."""
if func == "count_star":
return len(vals)
nn = [v for v in vals if v is not None]
if func == "count":
return len(nn)
if func == "count_distinct":
seen: list = []
for v in nn:
if v not in seen:
seen.append(v)
return len(seen)
if not nn:
return None
if func == "sum":
return sum(nn)
if func == "avg":
return _avg(nn)
if func == "min":
return min(nn)
if func == "max":
return max(nn)
raise ValueError("unknown aggregate %r" % (func,))
def aggregate(rel: Relation, group_attrs: Sequence[str], aggs: Sequence[tuple]) -> Relation:
"""gamma_{G; f(A) -> B}(rel) by definition.
aggs is a list of (func, attr, out); attr is ignored for count_star and may
be None. For each distinct group key, in row_key order, the whole input is
scanned. Each result row has count 1 in either mode.
"""
group_attrs = tuple(group_attrs)
gpos = [rel.index(a) for a in group_attrs]
for func, attr, _ in aggs:
if func not in AGG_FUNCS:
raise ValueError("unknown aggregate %r" % (func,))
if func != "count_star":
rel.index(attr)
keys: list = []
for t in rel.rows:
k = tuple(t[i] for i in gpos)
if k not in keys:
keys.append(k)
if not group_attrs and not keys:
keys = [()]
out: Counter = Counter()
for k in sorted(keys, key=row_key):
row = list(k)
for func, attr, _ in aggs:
vals: list = []
for t, c in rel.rows.items():
if tuple(t[i] for i in gpos) == k:
vals.extend([None if func == "count_star" else t[rel.index(attr)]] * c)
row.append(agg_value(func, vals))
out[tuple(row)] = 1
schema = group_attrs + tuple(o for _, _, o in aggs)
return Relation(schema, out, rel.mode)
# ---------------------------------------------------------------- evaluation
def evaluate(expr: tuple, db: Mapping[str, Relation], mode: str = BAG) -> Relation:
"""Evaluate an expression tree of nested tuples over db, in mode."""
if mode not in MODES:
raise ValueError("mode must be 'bag' or 'set'")
op = expr[0]
ev = lambda e: evaluate(e, db, mode)
if op == "scan":
return db[expr[1]].with_mode(mode)
if op == "select":
return select(ev(expr[2]), expr[1])
if op == "project":
return project(ev(expr[2]), expr[1])
if op == "rename":
return rename(ev(expr[2]), expr[1])
if op == "distinct":
return distinct(ev(expr[1]))
if op == "aggregate":
return aggregate(ev(expr[3]), expr[1], expr[2])
if op == "theta_join":
return theta_join(ev(expr[2]), ev(expr[3]), expr[1])
binary = {
"union": union, "difference": difference, "intersection": intersection,
"product": product, "join": natural_join, "semijoin": semijoin, "antijoin": antijoin,
}
if op in binary:
return binary[op](ev(expr[1]), ev(expr[2]))
raise ValueError("unknown operator %r" % (op,))
# ---------------------------------------------------------------- disk
def paginate(rows: Sequence, per_page: int) -> list:
"""Split rows into pages of per_page rows; the last page may be shorter."""
if per_page < 1:
raise ValueError("per_page must be at least 1")
rows = list(rows)
return [rows[i:i + per_page] for i in range(0, len(rows), per_page)]
class Disk:
"""Pages on a simulated disk. Each read_page and write_page call costs one I/O."""
def __init__(self) -> None:
self.pages: dict = {}
self.reads = 0
self.writes = 0
self._next = 0
def alloc(self) -> int:
pid = self._next
self._next += 1
self.pages[pid] = ()
return pid
def write_page(self, pid: int, rows: Iterable) -> None:
if pid not in self.pages:
raise KeyError("page %r was not allocated" % (pid,))
self.pages[pid] = tuple(rows)
self.writes += 1
def read_page(self, pid: int) -> list:
self.reads += 1
return list(self.pages[pid])
def free(self, pid: int) -> None:
del self.pages[pid]
def load(self, rows: Sequence, per_page: int) -> list:
"""Store an input file without counting I/O; return its page ids in order."""
ids = []
for page in paginate(rows, per_page):
pid = self.alloc()
self.pages[pid] = tuple(page)
ids.append(pid)
return ids
def io(self) -> int:
return self.reads + self.writes
def reset_counters(self) -> None:
self.reads = 0
self.writes = 0
# ---------------------------------------------------------------- random data
def random_relation(rng: random.Random, schema: Sequence[str], n: int,
domain: int | Sequence | Mapping = 4, mode: str = BAG,
null_rate: float = 0.0) -> Relation:
"""n rows drawn with rng. domain is a size k (values 0 to k - 1), a list of
values, or a dict from attribute to either. Each value is None with
probability null_rate. In set mode duplicates collapse, so there may be
fewer than n rows."""
schema = tuple(schema)
def values(a: str) -> list:
d = domain[a] if isinstance(domain, Mapping) else domain
return list(range(d)) if isinstance(d, int) else list(d)
doms = [values(a) for a in schema]
rows = []
for _ in range(n):
t = []
for d in doms:
if null_rate and rng.random() < null_rate:
t.append(None)
else:
t.append(rng.choice(d))
rows.append(tuple(t))
return Relation(schema, rows, mode)
dpccp.py 184 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dpccp/. The authors are listed in prov/0ECWZS.jsonl.
"""DPccp: dynamic programming over csg-cmp pairs (Moerkotte and Neumann, 2006).
It finds the cheapest bushy join tree without cross products for a connected
query graph. A csg is a connected set of relations; a csg-cmp pair is two
disjoint csgs S1 and S2 with an edge between them. Every join in a tree without
cross products combines such a pair, and DPccp enumerates each unordered pair
exactly once, in an order where the best plans of S1 and S2 are final when the
pair is used.
Sets of relations are bitmasks over the relations 0 .. n - 1. A plan is a
relation number (a leaf) or a pair (left, right) of plans. The cost of a plan
is the sum, over its joins, of join_cost(|left|, |right|, |result|), with sizes
under the independence assumption. All arithmetic is exact.
"""
from collections import deque
from fractions import Fraction
from typing import Callable, Dict, Iterator, List, Optional, Sequence, Tuple, Union
Plan = Union[int, tuple]
JoinCost = Callable[[Fraction, Fraction, Fraction], Fraction]
def c_out(left: Fraction, right: Fraction, out: Fraction) -> Fraction:
"""C_out: the size of each intermediate result."""
return out
def hash_cost(left: Fraction, right: Fraction, out: Fraction) -> Fraction:
"""An asymmetric cost: the right input is the build side and costs more per tuple."""
return out + left + 3 * right
class Query:
"""Relation sizes and a query graph with a selectivity per edge (i, j), i < j."""
def __init__(self, card: Sequence, sel: Dict[Tuple[int, int], Fraction]) -> None:
self.n = len(card)
self.card = [Fraction(c) for c in card]
self.sel = {(min(i, j), max(i, j)): Fraction(f) for (i, j), f in sel.items()}
self.adj = [0] * self.n
for (i, j) in self.sel:
self.adj[i] |= 1 << j
self.adj[j] |= 1 << i
def size(self, S: int) -> Fraction:
p = Fraction(1)
for i in members(S):
p *= self.card[i]
for (i, j), f in self.sel.items():
if S >> i & 1 and S >> j & 1:
p *= f
return p
def neighborhood(self, S: int) -> int:
"""N(S): the relations outside S with an edge into S."""
out = 0
for i in members(S):
out |= self.adj[i]
return out & ~S
def connected(self, S: int) -> bool:
if S == 0:
return False
reach = S & -S
while True:
nxt = reach | (self.neighborhood(reach) & S)
if nxt == reach:
return reach == S
reach = nxt
def relabel(self, perm: Sequence[int]) -> "Query":
"""The same query with relation perm[k] renamed k."""
pos = {v: k for k, v in enumerate(perm)}
return Query([self.card[v] for v in perm], {(pos[i], pos[j]): f for (i, j), f in self.sel.items()})
def members(S: int) -> List[int]:
out, i = [], 0
while S:
if S & 1:
out.append(i)
S >>= 1
i += 1
return out
def subsets(N: int) -> Iterator[int]:
"""The nonempty subsets of N, in increasing order as integers (so every subset comes before its supersets)."""
s = (0 - N) & N
while s:
yield s
s = (s - N) & N
def bfs_order(q: Query) -> List[int]:
"""The relations in breadth-first order from relation 0, neighbors by number."""
seen, order, queue = {0}, [], deque([0])
while queue:
v = queue.popleft()
order.append(v)
for w in members(q.adj[v]):
if w not in seen:
seen.add(w)
queue.append(w)
return order
def enumerate_csg_rec(q: Query, S: int, X: int) -> Iterator[int]:
N = q.neighborhood(S) & ~X # @line L12
for s in subsets(N): # @line L13
yield S | s
for s in subsets(N): # @line L14
yield from enumerate_csg_rec(q, S | s, X | N)
def enumerate_csg(q: Query) -> Iterator[int]:
"""Every connected set exactly once, sets with a larger smallest member first."""
for i in range(q.n - 1, -1, -1): # @line L9
yield 1 << i # @line L10
yield from enumerate_csg_rec(q, 1 << i, (1 << (i + 1)) - 1) # @line L11
def enumerate_cmp(q: Query, S1: int) -> Iterator[int]:
"""Every csg S2 that is disjoint from S1, joined to it by an edge, and has a larger smallest member."""
low = (S1 & -S1).bit_length() - 1
X = ((1 << (low + 1)) - 1) | S1 # @line L15
N = q.neighborhood(S1) & ~X # @line L16
for i in reversed(members(N)): # @line L17
yield 1 << i # @line L18
yield from enumerate_csg_rec(q, 1 << i, X | (N & ((1 << (i + 1)) - 1))) # @line L19
def csg_cmp_pairs(q: Query) -> Iterator[Tuple[int, int]]:
"""The csg-cmp pairs (S1, S2) in the order DPccp uses them."""
for S1 in enumerate_csg(q): # @line L3
for S2 in enumerate_cmp(q, S1): # @line L4
yield S1, S2
def plan_cost(q: Query, plan: Plan, join_cost: JoinCost = c_out) -> Fraction:
def rec(p: Plan) -> Tuple[Fraction, int]:
if isinstance(p, int):
return Fraction(0), 1 << p
cl, sl = rec(p[0])
cr, sr = rec(p[1])
return cl + cr + join_cost(q.size(sl), q.size(sr), q.size(sl | sr)), sl | sr
return rec(plan)[0]
def map_plan(plan: Plan, perm: Sequence[int]) -> Plan:
if isinstance(plan, int):
return perm[plan]
return (map_plan(plan[0], perm), map_plan(plan[1], perm))
def dpccp(q: Query, join_cost: JoinCost = c_out, bfs: bool = True,
on_pair: Optional[Callable[[int, int], None]] = None) -> Tuple[Fraction, Plan]:
"""The cheapest bushy plan without cross products and its cost.
The query graph must be connected. bfs=False keeps the given numbering.
on_pair(S1, S2), if given, is called for each pair as it is used, with the
sets as bitmasks over the original relation numbers."""
if q.n == 0:
raise ValueError("no relations")
perm = bfs_order(q) if bfs else list(range(q.n)) # @line L1
if len(perm) != q.n or not q.connected((1 << q.n) - 1):
raise ValueError("DPccp needs a connected query graph")
g = q.relabel(perm)
back = lambda S: sum(1 << perm[i] for i in members(S))
best: Dict[int, Tuple[Fraction, Plan]] = {1 << v: (Fraction(0), v) for v in range(g.n)} # @line L2
for S1, S2 in csg_cmp_pairs(g):
if on_pair is not None:
on_pair(back(S1), back(S2))
S = S1 | S2 # @line L5
size = (g.size(S1), g.size(S2), g.size(S))
for (A, B, sa, sb) in ((S1, S2, size[0], size[1]), (S2, S1, size[1], size[0])): # @line L6
cost = best[A][0] + best[B][0] + join_cost(sa, sb, size[2])
if S not in best or cost < best[S][0]: # @line L7
best[S] = (cost, (best[A][1], best[B][1]))
cost, plan = best[(1 << g.n) - 1] # @line L8
return cost, map_plan(plan, perm)
test_dpccp.py 204 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dpccp/. The authors are listed in prov/0ECWZS.jsonl.
import math
import random
import unittest
from collections import Counter
from fractions import Fraction
import dbrel
from dpccp import Query, c_out, csg_cmp_pairs, dpccp, enumerate_csg, hash_cost, members, plan_cost
def random_graph(rng, n, extra=0.3):
sel = {}
for i in range(1, n):
j = rng.randrange(i)
sel[(j, i)] = Fraction(1, rng.choice([1, 2, 5, 10, 100]))
for i in range(n):
for j in range(i + 1, n):
if (i, j) not in sel and rng.random() < extra:
sel[(i, j)] = Fraction(1, rng.choice([1, 2, 5, 10, 100]))
perm = list(range(n))
rng.shuffle(perm)
sel = {(min(perm[i], perm[j]), max(perm[i], perm[j])): f for (i, j), f in sel.items()}
card = [rng.choice([1, 5, 10, 50, 100, 1000]) for _ in range(n)]
return Query(card, sel)
def chain(n):
return Query([10] * n, {(i, i + 1): Fraction(1, 2) for i in range(n - 1)})
def star(n):
return Query([10] * n, {(0, i): Fraction(1, 2) for i in range(1, n)})
def clique(n):
return Query([10] * n, {(i, j): Fraction(1, 2) for i in range(n) for j in range(i + 1, n)})
def brute_pairs(q):
"""Unordered csg-cmp pairs, by definition."""
out = set()
full = (1 << q.n) - 1
for A in range(1, full + 1):
if not q.connected(A):
continue
rest = full & ~A
B = rest
while B:
if q.connected(B) and q.neighborhood(A) & B:
out.add(frozenset((A, B)))
B = (B - 1) & rest
return out
def all_trees(q, S, memo):
"""Every ordered bushy tree without cross products for the set S."""
if S in memo:
return memo[S]
if S & (S - 1) == 0:
memo[S] = [S.bit_length() - 1]
return memo[S]
out = []
A = (S - 1) & S
while A:
B = S & ~A
if q.connected(A) and q.connected(B) and q.neighborhood(A) & B:
for ta in all_trees(q, A, memo):
for tb in all_trees(q, B, memo):
out.append((ta, tb))
A = (A - 1) & S
memo[S] = out
return out
def tree_cost(q, t, join_cost, sizes):
def rec(p):
if isinstance(p, int):
return Fraction(0), 1 << p
cl, sl = rec(p[0])
cr, sr = rec(p[1])
S = sl | sr
for X in (sl, sr, S):
if X not in sizes:
sizes[X] = q.size(X)
return cl + cr + join_cost(sizes[sl], sizes[sr], sizes[S]), S
return rec(t)[0]
def leaves(t):
return [t] if isinstance(t, int) else leaves(t[0]) + leaves(t[1])
class TestDPccp(unittest.TestCase):
def test_csgs_are_all_connected_sets_once(self):
rng = random.Random(1)
for _ in range(60):
q = random_graph(rng, rng.randint(1, 8))
got = list(enumerate_csg(q))
want = [S for S in range(1, 1 << q.n) if q.connected(S)]
self.assertEqual(sorted(got), want)
def test_pairs_are_all_csg_cmp_pairs_once(self):
rng = random.Random(2)
for _ in range(60):
q = random_graph(rng, rng.randint(1, 8))
got = list(csg_cmp_pairs(q))
for S1, S2 in got:
self.assertLess((S1 & -S1), (S2 & -S2))
self.assertEqual(len(got), len(set(frozenset(p) for p in got)))
self.assertEqual(set(frozenset(p) for p in got), brute_pairs(q))
def test_pair_counts_for_chain_star_clique(self):
for n in range(2, 10):
self.assertEqual(sum(1 for _ in csg_cmp_pairs(chain(n))), (n ** 3 - n) // 6)
self.assertEqual(sum(1 for _ in csg_cmp_pairs(star(n))), (n - 1) * 2 ** (n - 2))
self.assertEqual(sum(1 for _ in csg_cmp_pairs(clique(n))), (3 ** n - 2 ** (n + 1) + 1) // 2)
if n <= 7:
for q in (chain(n), star(n), clique(n)):
self.assertEqual(sum(1 for _ in csg_cmp_pairs(q)), len(brute_pairs(q)))
def test_best_plans_are_final_when_used(self):
rng = random.Random(3)
for _ in range(60):
q = random_graph(rng, rng.randint(2, 8))
for bfs in (True, False):
total = Counter(A | B for A, B in brute_pairs(q))
done = Counter()
def check(S1, S2):
self.assertEqual(done[S1], total[S1])
self.assertEqual(done[S2], total[S2])
done[S1 | S2] += 1
dpccp(q, on_pair=check, bfs=bfs)
self.assertEqual(done, total)
def test_optimal_against_all_trees(self):
rng = random.Random(4)
for trial in range(50):
n = rng.randint(1, 6) if trial % 10 == 0 else rng.randint(1, 5)
q = random_graph(rng, n, extra=rng.choice([0.0, 0.3, 0.7]))
trees = all_trees(q, (1 << n) - 1, {})
sizes = {}
for join_cost in (c_out, hash_cost):
for bfs in (True, False):
cost, plan = dpccp(q, join_cost, bfs=bfs)
self.assertIn(plan, trees)
self.assertEqual(plan_cost(q, plan, join_cost), cost)
self.assertEqual(min(tree_cost(q, t, join_cost, sizes) for t in trees), cost)
def test_shape_counts_without_cross_products(self):
f = math.factorial
for n in range(1, 6):
catalan = math.comb(2 * n - 2, n - 1) // n
self.assertEqual(len(all_trees(chain(n), (1 << n) - 1, {})), catalan * 2 ** (n - 1))
self.assertEqual(len(all_trees(star(n), (1 << n) - 1, {})), f(n - 1) * 2 ** (n - 1))
self.assertEqual(len(all_trees(clique(n), (1 << n) - 1, {})), f(2 * n - 2) // f(n - 1))
def test_plan_runs_and_gives_the_join(self):
rng = random.Random(5)
for _ in range(30):
n = rng.randint(1, 5)
q = random_graph(rng, n)
_, plan = dpccp(q, hash_cost)
self.assertEqual(sorted(leaves(plan)), list(range(n)))
schema = {v: ["id%d" % v] for v in range(n)}
for (i, j) in q.sel:
schema[i].append("k%d_%d" % (i, j))
schema[j].append("k%d_%d" % (i, j))
db = {v: dbrel.random_relation(rng, schema[v], rng.randint(0, 5), domain=3, null_rate=0.1)
for v in range(n)}
def run(p):
if isinstance(p, int):
return db[p]
left, right = run(p[0]), run(p[1])
self.assertTrue(set(left.schema) & set(right.schema))
return dbrel.natural_join(left, right)
naive = db[0]
for v in range(1, n):
naive = dbrel.natural_join(naive, db[v])
self.assertEqual(run(plan), naive)
def test_worked_example(self):
q = Query([100, 1000, 100, 10], {(0, 1): Fraction(1, 100), (1, 2): Fraction(1, 2), (2, 3): Fraction(1, 2)})
cost, plan = dpccp(q)
self.assertEqual(cost, 251500)
self.assertEqual(sorted(leaves(plan[0])), [0, 1])
def test_rejects_disconnected_graphs(self):
with self.assertRaises(ValueError):
dpccp(Query([1, 2, 3], {(0, 1): Fraction(1, 2)}))
self.assertEqual(dpccp(Query([5], {})), (0, 0))
def test_members(self):
self.assertEqual(members(0b10110), [1, 2, 4])
if __name__ == "__main__":
unittest.main()
History
The Selinger optimizer of System R (1979) introduced dynamic programming for join ordering, over left-deep trees. Later optimizers extended it to bushy trees with DPsize, which enumerates by the size of the sets, and DPsub, which enumerates the subsets of each set. In 2006 Moerkotte and Neumann analyzed these two, showed how far each is from the number of csg-cmp pairs, and gave DPccp, which enumerates the pairs directly. In 2008 they extended it to hypergraphs as DPhyp, which is used for queries with complex predicates and outer joins.
References
- Analysis of two existing and one new dynamic programming algorithm for the generation of optimal bushy join trees without cross products, the algorithms DPsize, DPsub and DPccp, the procedures EnumerateCsg, EnumerateCsgRec and EnumerateCmp, and the number of csg-cmp pairs for chain, cycle, star and clique queries
- P. Griffiths Selinger, M. M. Astrahan, D. D. Chamberlin, R. A. Lorie and T. G. Price, Access path selection in a relational database management system, Proceedings of ACM SIGMOD 1979, 23 to 34, Section 5, the dynamic program over subsets of relations that DPsize generalizes
- Dynamic programming strikes back, the extension of DPccp to hypergraphs (DPhyp), which builds on the same csg and cmp enumeration
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 0ECWZS Edit this page History Report an error Markdown