Algorithm Search⌘K

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.

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
Properties
deterministicexactrecursive
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 (n3−n)/6(n^3 - n)/6 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 v0,…,vn−1v_0, \ldots, v_{n-1}, 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 P1⋈P2P_1 \bowtie P_2 depends only on the sets of relations of P1P_1 and P2P_2, for example CoutC_{out}, 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.

N(S)N(S) is the neighborhood of a set SS: the relations outside SS with an edge into SS. Bi={v0,…,vi}B_i = \{v_0, \ldots, v_i\}.

The algorithm

  1. DPCCP(query graph G)
  2. 1number the relations v_0, ..., v_(n-1) in breadth-first order
  3. 2for each relation v do best[{v}] ← the scan of v
  4. 3for each csg S1 from ENUMERATE-CSG do
  5. 4for each S2 from ENUMERATE-CMP(S1) do
  6. 5S ← S1 ∪ S2
  7. 6for (P1, P2) in (best[S1], best[S2]) and (best[S2], best[S1]) do
  8. 7if best[S] is empty or cost(P1 ⋈ P2) < cost(best[S]) then best[S] ← P1 ⋈ P2
  9. 8return best[all relations]
  1. ENUMERATE-CSG
  2. 1for i ← n-1 down to 0 do
  3. 2emit {v_i}
  4. 3ENUMERATE-CSG-REC({v_i}, B_i)
  5. ENUMERATE-CSG-REC(S, X)
  6. 4N ← N(S) - X
  7. 5for each nonempty subset S' of N, smaller subsets first do emit S ∪ S'
  8. 6for each nonempty subset S' of N, smaller subsets first do ENUMERATE-CSG-REC(S ∪ S', X ∪ N)
  9. ENUMERATE-CMP(S1)
  10. 7X ← B_min(S1) ∪ S1
  11. 8N ← N(S1) - X
  12. 9for each v_i in N, by decreasing i do
  13. 10emit {v_i}
  14. 11ENUMERATE-CSG-REC({v_i}, X ∪ (B_i ∩ N))

ENUMERATE-CSG starts a new set from each relation viv_i and only lets it grow into relations with a larger index, so viv_i is the smallest member of every set it makes in that iteration. ENUMERATE-CSG-REC grows a connected set SS by any nonempty subset of its neighborhood. The set XX 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 S1S_1 from its neighbors, in the same way, but only with relations above the smallest index of S1S_1, so each unordered pair appears once, with S1S_1 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 AA-BB-CC-DD, with 50, 1000, 200 and 10 tuples and the selectivities 1/100, 1/50 and 1/2 on the three edges. The cost is CoutC_{out}. 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.

S1S_1 S2S_2 size of the union candidate cost best plan after the pair
CC DD 1000 1000 C⋈DC \bowtie D, 1000
BB CC 4000 4000 B⋈CB \bowtie C, 4000
BB CDCD 20 000 21 000 B⋈(C⋈D)B \bowtie (C \bowtie D), 21 000
BCBC DD 20 000 24 000 unchanged, 21 000
AA BB 500 500 A⋈BA \bowtie B, 500
AA BCBC 2000 6000 A⋈(B⋈C)A \bowtie (B \bowtie C), 6000
AA BCDBCD 10 000 31 000 A⋈(B⋈(C⋈D))A \bowtie (B \bowtie (C \bowtie D)), 31 000
ABAB CC 2000 2500 (A⋈B)⋈C(A \bowtie B) \bowtie C, 2500
ABAB CDCD 10 000 11 500 (A⋈B)⋈(C⋈D)(A \bowtie B) \bowtie (C \bowtie D), 11 500
ABCABC DD 10 000 12 500 unchanged, 11 500

There are 10 pairs, which is (43−4)/6(4^3 - 4)/6. The pairs for {B,C,D}\{B, C, D\} come before BCDB C D is used as a half, and ABCABC has its final plan before the last row. The result is the bushy tree (A⋈B)⋈(C⋈D)(A \bowtie B) \bowtie (C \bowtie D) with cost 11 500; the cheapest left-deep tree, ((A⋈B)⋈C)⋈D((A \bowtie B) \bowtie C) \bowtie D, 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 viv_i is made only in the iteration for ii, and inside it the set XX decides in which branch each relation is added. Second, ENUMERATE-CMP(S1S_1) emits exactly the connected sets that are disjoint from S1S_1, 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 S1S_1 or S2S_2 have been used: the halves of S2S_2 have a larger smallest index, so they come in an earlier iteration of line L9, and the halves of S1S_1 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 GG has the relations v0,…,vn−1v_0, \ldots, v_{n-1} and is connected. N(S)N(S) is the set of relations outside SS with an edge into SS, and Bi={vj:j≤i}B_i = \{v_j : j \le i\}. A csg is a nonempty set of relations that induces a connected subgraph. A csg-cmp pair is an unordered pair {S1,S2}\{S_1, S_2\} of disjoint csgs with an edge between them. A plan without cross products is a leaf vv, or a join of two plans without cross products, for sets S1S_1 and S2S_2, with an edge between S1S_1 and S2S_2. The cost of a join is c(P1)+c(P2)+j(∣S1∣,∣S2∣,∣S1∪S2∣)c(P_1) + c(P_2) + j(|S_1|, |S_2|, |S_1 \cup S_2|), where the sizes depend only on the sets. Lines L13 and L14 go through the nonempty subsets of NN in increasing order as integers, so every subset comes before its proper supersets.

Lemma 1. Let SS be a csg and S⊆XS \subseteq X. The call ENUMERATE-CSG-REC(S,X)(S, X) emits, each exactly once, the sets TT with T⊋ST \supsetneq S, TT connected and T∩X=ST \cap X = S. If U⊊TU \subsetneq T are two of them, UU is emitted before TT.

Proof. By induction on the number of relations outside XX. Let N=N(S)−XN = N(S) - X (line L12). A set TT of the lemma has a relation in T−ST - S with an edge into SS, because TT is connected; that relation is not in XX, so S′=T∩NS' = T \cap N is not empty. If T=S∪S′T = S \cup S', then line L13 emits TT for this S′S'. Otherwise T⊋S∪S′T \supsetneq S \cup S' and T∩(X∪N)=S∪S′T \cap (X \cup N) = S \cup S'; the recursive call of line L14 for S′S' has a larger XX (since N≠∅N \neq \emptyset) and emits TT by induction. The other calls of line L14 emit only sets whose intersection with X∪NX \cup N is S∪S′′S \cup S'' for their own S′′S'', and line L13 emits only sets inside X∪NX \cup N, so TT is emitted exactly once. Conversely every emitted set is connected (each relation of S′S' has an edge into the connected SS), strictly contains SS, and meets XX only in SS, because N∩X=∅N \cap X = \emptyset. If NN is empty, no set TT exists and nothing is emitted.

For the order, let U⊊TU \subsetneq T, and let SU′=U∩N⊆ST′=T∩NS'_U = U \cap N \subseteq S'_T = T \cap N. If TT is emitted by line L13, then U⊆X∪NU \subseteq X \cup N, so U=S∪SU′U = S \cup S'_U is emitted by line L13 too, at an earlier subset. If TT is emitted inside the call for ST′S'_T and UU by line L13, then UU comes first, because line L13 runs before line L14. If both come from recursive calls, then either SU′=ST′S'_U = S'_T and the induction hypothesis applies to the one call, or SU′⊊ST′S'_U \subsetneq S'_T and the call for SU′S'_U comes first. □\square

Lemma 2 (csgs). ENUMERATE-CSG emits every csg exactly once, and it emits all csgs with smallest index ii before all csgs with a smaller smallest index. Two csgs U⊊TU \subsetneq T with the same smallest index are emitted with UU first.

Proof. The iteration for ii emits {vi}\{v_i\} and, by Lemma 1 with S={vi}S = \{v_i\} and X=BiX = B_i, every connected T⊋{vi}T \supsetneq \{v_i\} with T∩Bi={vi}T \cap B_i = \{v_i\}, that is, with smallest index ii. The iterations run for i=n−1i = n-1 down to 00. The order inside one iteration is the order of Lemma 1, and {vi}\{v_i\} comes first. □\square

Lemma 3 (complements). For a csg S1S_1 with smallest index mm, ENUMERATE-CMP(S1)(S_1) emits, each exactly once, the csgs S2S_2 that are disjoint from S1S_1, have an edge into S1S_1, and have a smallest index larger than mm.

Proof. Let X=Bm∪S1X = B_m \cup S_1 and N=N(S1)−XN = N(S_1) - X (lines L15 and L16). A set S2S_2 as in the lemma is disjoint from XX and meets N(S1)N(S_1), so it meets NN. Let viv_i be the member of S2∩NS_2 \cap N with the smallest index. Then S2∩(X∪(Bi∩N))={vi}S_2 \cap (X \cup (B_i \cap N)) = \{v_i\}, so the iteration of line L17 for viv_i emits S2S_2, at line L18 if S2={vi}S_2 = \{v_i\} and by Lemma 1 otherwise. Every set that the iteration for vjv_j emits contains vjv_j and no other member of Bj∩NB_j \cap N, so vjv_j is its member of NN with the smallest index; hence no other iteration emits S2S_2. Conversely every emitted set is connected, disjoint from XX (so from S1S_1, and with all indexes above mm), and contains vi∈N(S1)v_i \in N(S_1). □\square

By Lemmas 2 and 3, lines L3 and L4 produce every csg-cmp pair exactly once, as (S1,S2)(S_1, S_2) with the smaller smallest index in S1S_1.

Lemma 4 (final plans). When lines L5 to L7 use a pair (S1,S2)(S_1, S_2), every pair whose union is S1S_1, and every pair whose union is S2S_2, has been used already.

Proof. A pair (U1,U2)(U_1, U_2) is used in the iteration of line L3 for U1U_1, and U1U_1 has the same smallest index as U1∪U2U_1 \cup U_2. If U1∪U2=S1U_1 \cup U_2 = S_1, then U1⊊S1U_1 \subsetneq S_1 are csgs with the same smallest index, so U1U_1 comes before S1S_1 by Lemma 2. If U1∪U2=S2U_1 \cup U_2 = S_2, then the smallest index of U1U_1 is that of S2S_2, which is larger than that of S1S_1, so U1U_1 comes before S1S_1 by Lemma 2. In both cases the whole iteration for U1U_1 ends before the iteration for S1S_1 starts. □\square

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 nn relations.

Proof. Let opt(S)\mathrm{opt}(S) be the least cost of a plan without cross products for a csg SS. We show that after all pairs with union SS are used, best[S]\mathrm{best}[S] is a plan for SS without cross products with cost opt(S)\mathrm{opt}(S). 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 QQ for SS with ∣S∣≥2|S| \ge 2; its last join combines plans Q1Q_1 and Q2Q_2 for sets S1S_1 and S2S_2. By induction on the plan, the set of every plan without cross products is connected, so {S1,S2}\{S_1, S_2\} is a csg-cmp pair, and it is used once. By Lemma 4 and induction on ∣S∣|S|, at that moment best[S1]\mathrm{best}[S_1] and best[S2]\mathrm{best}[S_2] cost opt(S1)≤c(Q1)\mathrm{opt}(S_1) \le c(Q_1) and opt(S2)≤c(Q2)\mathrm{opt}(S_2) \le c(Q_2). 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 c(Q)=opt(S)c(Q) = \mathrm{opt}(S), and line L7 keeps a plan of that cost. Later pairs can only lower best[S]\mathrm{best}[S], and no plan is cheaper than opt(S)\mathrm{opt}(S). Since GG is connected, the set of all relations is a csg. ■\blacksquare

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 nn. A call costs O(n)O(n) for the neighborhood and O(1)O(1) 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 c+nc + n csgs, where cc is the number of pairs. Line L4 emits cc sets in total. So with the sizes stored per set, the work is O(n(c+n))=O(nc)O(n (c + n)) = O(n c) for a connected graph, where c≥n−1c \ge n - 1.

Complexity

Let cc be the number of csg-cmp pairs. Every call of ENUMERATE-CSG-REC belongs to a set that was just emitted, and costs O(n)O(n) to compute a neighborhood with bit operations, so the enumeration takes O(nc)O(n c) time; there are at most c+nc + n connected sets, and each pair costs O(1)O(1) at lines L5 to L7 when the sizes are stored per set. The table holds one plan per connected set, at most 2n2^n.

query graph csg-cmp pairs cc n=5n = 5 n=10n = 10 n=20n = 20
chain (n3−n)/6(n^3 - n)/6 20 165 1330
star (n−1) 2n−2(n - 1)\, 2^{n-2} 32 2304 4 980 736
clique (3n−2n+1+1)/2(3^n - 2^{n+1} + 1)/2 90 28 501 1 742 343 625

Any dynamic program that considers every csg-cmp pair must do at least cc steps, so DPccp is within a factor nn of that bound, and its work adapts to the shape of the graph. DPsub, which tries every split of every subset, does Θ(3n)\Theta(3^n) 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 NN 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 A.x=C.xA.x = C.x from A.x=B.xA.x = B.x and B.x=C.xB.x = C.x. 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.

dbrel.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example