Algorithm Search⌘K

Data structureresearch

Factorized representation

Also called factorized database, f-representation, d-representation.

A join result stored as nested unions and products over a tree of attributes. It can be much smaller than the list of its tuples, and the tuples can still be listed one by one.

Time
O(k r (k + n) n^s) worst
Space
O(k n^s) extra
Where
k = the number of attributes; n = the number of tuples in the input relations; r = the number of relations; s = the parameter s(T) of the f-tree

A factorized representation stores a relation, usually the result of a join, as an expression built from single values with unions and Cartesian products. The nesting of the expression follows a tree of attributes, the f-tree. A join result with many tuples that repeat the same combinations can have a representation that is polynomially smaller, with an exponent ss that depends only on the query and the f-tree. The tuples can still be listed one at a time with constant delay for a fixed query, so the representation can replace the flat result. Olteanu and Závodný (2015) gave the size bounds and showed that they are tight. The construction on this page reads the input relations directly, in the style of generic join, and never builds the flat result.

In plain words

A shop sells shirts in many colors and sizes, but only some combinations exist for each brand. A list of every brand, color and size combination can be very long.

You can write it in a shorter way: "brand X: (red or blue) and (small, medium or large)". For each brand you list the colors once and the sizes once, and you say that each color goes with each size. This works when, for a fixed brand, the choice of color does not depend on the choice of size.

A factorized representation does this for a whole table, level by level, following a tree of columns. Under each value of a column, the subtrees below it are independent of each other, so the table is a product of short lists. You can still read every row from it, one at a time.

The abstract type

A factorized representation stands for a relation RR over a set of attributes. It supports:

  • build from a join query and its input relations, or from one relation;
  • enumerate the tuples of RR, each once;
  • count the tuples of RR without listing them;
  • size, the number of singletons, which is the measure of space.

The representation does not support updates in place. Other work, cited by Olteanu and Závodný, applies selections, projections and joins to representations; this is outside this page.

Representation

A singleton ⟨A:a⟩\langle A{:}a \rangle is the relation with one tuple, with the value aa for the attribute AA. An f-representation is an expression built from singletons with union ∪\cup and Cartesian product ×\times.

An f-tree TT is a rooted forest in which each node is an attribute. A representation over TT has this form:

  • over a forest with trees T1,…,TkT_1, \dots, T_k: a product E1×⋯×EkE_1 \times \dots \times E_k, with EiE_i over TiT_i;
  • over a tree with root AA and child forest FF: a union ⋃a⟨A:a⟩×Ea\bigcup_{a} \langle A{:}a \rangle \times E_a over distinct values aa, with each EaE_a over FF.

So below each value of AA, the subtrees of the children are independent. A relation has a representation over TT if and only if it has this independence, and then the representation is unique up to the order of the terms. In the code, a union is a list of pairs (value, factors) sorted by value, and the factors are a tuple with one union per child.

For a natural join QQ of the relations R1,…,RmR_1, \dots, R_m, an f-tree with the attributes of QQ is valid if it satisfies the path condition: the attributes of each relation lie on one root-to-leaf path. Two attributes in different subtrees below a node then never occur in one relation, so the join result is independent across these subtrees once the values above them are fixed, and it has a representation over TT.

Operations

  1. FROMJOIN(T, D) ▷ D holds the relations of the natural join Q
  2. 1if T and Q have different attributes, or the attributes of some relation are not on one root-to-leaf path of T, then fail
  3. 2E ← PRODUCT(the roots of T, the empty tuple); return E, or one empty union per root if E = ∅
  4. PRODUCT(F, t) ▷ t gives a value to each attribute above the trees of F
  5. 3for each tree of F, with root A, do
  6. 4U_A ← UNION(A, t)
  7. 5if U_A is empty then return ∅
  8. 6return the product of the unions U_A
  9. UNION(A, t)
  10. 7V ← the values a such that each relation R that contains A has a tuple that agrees with t above A and has a at A
  11. 8for each a in V, in increasing order, do
  12. 9P ← PRODUCT(the children of A, t extended by A = a)
  13. 10if P ≠ ∅ then add the pair ⟨A:a⟩ × P to the union
  14. 11return the union

Line L7 uses one hash index per relation RR and attribute AA of RR: it maps the values of the attributes of RR above AA to the set of values of AA. The code intersects these sets, starting from the smallest, as generic join does. Line L10 prunes a value whose subtrees have no tuple, so the result has no dead branches.

  • Factorize one relation. Group the rows by the value of the root, recurse on each group for the children, and over a forest build each tree on the same rows. The result always contains the relation; it is equal to it, and so a representation of it, exactly when the counts agree. Otherwise the relation has no representation over TT, and the code raises an error.
  • Count. Add the counts over the pairs of a union, and multiply the counts over the factors of a product. This takes time linear in the size.
  • Enumerate. Walk the expression depth first, choosing one pair in each union. Each choice gives one tuple, and no choice is a dead end, so the delay between two tuples depends only on the number of attributes.
  • Size. Count the singletons.

Example

Take R(A,B)={(1,1),(1,2),(1,3),(2,4)}R(A, B) = \{(1,1), (1,2), (1,3), (2,4)\} and S(A,C)={(1,5),(1,6),(2,7)}S(A, C) = \{(1,5), (1,6), (2,7)\}, and the f-tree with root AA and children BB and CC. Both relations lie on a root-to-leaf path, so the f-tree is valid. The join has 7 tuples, 21 values in all. FROMJOIN gives

⟨A:1⟩×(⟨B:1⟩∪⟨B:2⟩∪⟨B:3⟩)×(⟨C:5⟩∪⟨C:6⟩)  ∪  ⟨A:2⟩×⟨B:4⟩×⟨C:7⟩,\langle A{:}1 \rangle \times (\langle B{:}1 \rangle \cup \langle B{:}2 \rangle \cup \langle B{:}3 \rangle) \times (\langle C{:}5 \rangle \cup \langle C{:}6 \rangle) \;\cup\; \langle A{:}2 \rangle \times \langle B{:}4 \rangle \times \langle C{:}7 \rangle,

with 9 singletons. If one value of AA has nn values of BB and nn values of CC, the join has n2n^2 tuples and the representation has 2n+12n + 1 singletons.

The f-tree matters. Example 1.1 of Olteanu and Závodný takes the relation of all (a,b,c)(a, b, c) with 1≤a<b<c≤51 \le a < b < c \le 5, which has 10 tuples and 30 values. Over the f-tree with root bb and children aa and cc, the representation is

⟨b:2⟩×⟨a:1⟩×(⟨c:3⟩∪⟨c:4⟩∪⟨c:5⟩)  ∪  ⟨b:3⟩×(⟨a:1⟩∪⟨a:2⟩)×(⟨c:4⟩∪⟨c:5⟩)  ∪  ⟨b:4⟩×(⟨a:1⟩∪⟨a:2⟩∪⟨a:3⟩)×⟨c:5⟩,\langle b{:}2 \rangle \times \langle a{:}1 \rangle \times (\langle c{:}3 \rangle \cup \langle c{:}4 \rangle \cup \langle c{:}5 \rangle) \;\cup\; \langle b{:}3 \rangle \times (\langle a{:}1 \rangle \cup \langle a{:}2 \rangle) \times (\langle c{:}4 \rangle \cup \langle c{:}5 \rangle) \;\cup\; \langle b{:}4 \rangle \times (\langle a{:}1 \rangle \cup \langle a{:}2 \rangle \cup \langle a{:}3 \rangle) \times \langle c{:}5 \rangle,

with 15 singletons. Over the path a,b,ca, b, c it has 3+6+10=193 + 6 + 10 = 19 singletons. Over the f-tree with root aa and children bb and cc there is no representation, because b<cb < c ties bb and cc for a fixed aa.

Correctness

The proof defines, for each call, the set of partial tuples below the call that agree with every relation they touch. The path condition makes this set split into a product over the subtrees of a forest, and into a union over the values of the root of a tree. Each pruned pair has no partial tuple below it. So FROMJOIN returns a representation of exactly the join result. Since the values in a union are distinct, each tuple is enumerated once, and the occurrences of the singletons of AA match the distinct tuples of the result restricted to the path to AA. The full proof is in the proof page.

Proof: FROMJOIN builds a representation of the join result, each tuple is listed once, and the number of singletons is the sum of the path projectionsfull

We use the line numbers of the pseudocode. QQ is the natural join of the relations R1,…,RmR_1, \dots, R_m of DD, each with at least one attribute, and TT is an f-tree whose node set is the set of attributes of QQ. The relations are read as sets and hold no nulls. For a node AA, anc(A)\mathit{anc}(A) is the set of proper ancestors of AA, path(A)=anc(A)∪{A}\mathit{path}(A) = \mathit{anc}(A) \cup \{A\}, and TAT_A is the subtree rooted at AA, with attribute set at(TA)\mathit{at}(T_A). For a list FF of subtrees, at(F)\mathit{at}(F) is the union of their attribute sets. A tuple is a map from a set of attributes to values, and t∣St|_S is its restriction to SS.

Semantics. A singleton ⟨A:a⟩\langle A{:}a \rangle stands for the relation with the one tuple {A↦a}\{A \mapsto a\}. A pair (a,P)(a, P) in a union for AA stands for ⟨A:a⟩×[ ⁣[P] ⁣]\langle A{:}a \rangle \times [\![P]\!], a union stands for the union of its pairs, and a product (U1,…,Uk)(U_1, \dots, U_k) stands for [ ⁣[U1] ⁣]×⋯×[ ⁣[Uk] ⁣][\![U_1]\!] \times \dots \times [\![U_k]\!]. The empty product ()() stands for {()}\{()\}, the relation with the one tuple on no attributes. A union with no pairs stands for ∅\emptyset.

The target sets. Let FF be the list of children of a node BB, or the list of roots, and let C=path(B)C = \mathit{path}(B), or C=∅C = \emptyset for the roots. For a tuple tt on CC, let

J(F,t)={ u on at(F):(t∪u)∣R∈R for every relation R with R∩at(F)≠∅ }.J(F, t) = \{\, u \text{ on } \mathit{at}(F) : (t \cup u)|_{R} \in R \text{ for every relation } R \text{ with } R \cap \mathit{at}(F) \ne \emptyset \,\}.

For one subtree TAT_A with anc(A)=C\mathit{anc}(A) = C, define J(TA,t)J(T_A, t) in the same way.

Lemma 1 (splitting). Let F=(TA1,…,TAk)F = (T_{A_1}, \dots, T_{A_k}) and let TT satisfy the path condition. Every relation RR that meets at(F)\mathit{at}(F) meets exactly one at(TAi)\mathit{at}(T_{A_i}), and R⊆C∪at(TAi)R \subseteq C \cup \mathit{at}(T_{A_i}). Hence J(F,t)=J(TA1,t)×⋯×J(TAk,t)J(F, t) = J(T_{A_1}, t) \times \dots \times J(T_{A_k}, t).

Proof. The attributes of RR lie on one root-to-leaf path π\pi. A path that meets at(TAi)\mathit{at}(T_{A_i}) passes through AiA_i, and it then contains no node of TAjT_{A_j} for j≠ij \ne i, since the subtrees are disjoint and the nodes of π\pi are pairwise comparable. The nodes of π\pi above AiA_i are in anc(Ai)=C\mathit{anc}(A_i) = C. So the conditions on uu split into one set of conditions for each u∣at(TAi)u|_{\mathit{at}(T_{A_i})}, and the set of solutions is the product. □\square

Lemma 2 (one subtree). For a node AA and a tuple tt on anc(A)\mathit{anc}(A), let VV be the set of line L7. Then

J(TA,t)=⋃a∈V⟨A:a⟩×J(kids(A),t∪{A↦a}).J(T_A, t) = \bigcup_{a \in V} \langle A{:}a \rangle \times J(\mathit{kids}(A), t \cup \{A \mapsto a\}).

Proof. Let uu be in J(TA,t)J(T_A, t) with u(A)=au(A) = a, and let RR contain AA. Then (t∪u)∣R∈R(t \cup u)|_R \in R, and this tuple of RR agrees with tt on the attributes of RR above AA and has the value aa at AA. So a∈Va \in V. The relations that meet at(kids(A))\mathit{at}(\mathit{kids}(A)) also meet at(TA)\mathit{at}(T_A), so the rest of uu is in J(kids(A),t∪{A↦a})J(\mathit{kids}(A), t \cup \{A \mapsto a\}).

Conversely, let a∈Va \in V and w∈J(kids(A),t∪{A↦a})w \in J(\mathit{kids}(A), t \cup \{A \mapsto a\}), and put u={A↦a}∪wu = \{A \mapsto a\} \cup w. Let RR meet at(TA)\mathit{at}(T_A). If RR meets at(kids(A))\mathit{at}(\mathit{kids}(A)), then (t∪u)∣R∈R(t \cup u)|_R \in R by the choice of ww. Otherwise RR contains AA and, by the path condition, all its other attributes are in anc(A)\mathit{anc}(A). Then (t∪u)∣R(t \cup u)|_R is the tuple that agrees with tt above AA and has aa at AA, which is in RR because a∈Va \in V. □\square

Theorem 1 (correctness). Let TT be valid for QQ. For each call, PRODUCT(F,t)(F, t) returns ∅\emptyset if J(F,t)=∅J(F, t) = \emptyset, and otherwise a product EE with [ ⁣[E] ⁣]=J(F,t)[\![E]\!] = J(F, t). UNION(A,t)(A, t) returns a union UU with [ ⁣[U] ⁣]=J(TA,t)[\![U]\!] = J(T_A, t), whose pairs have distinct values in increasing order, and none of whose pairs has an empty product. FROMJOIN returns a representation EE with [ ⁣[E] ⁣]=Q(D)[\![E]\!] = Q(D).

Proof. By induction on the height of the subtrees. If FF is empty, then J(F,t)={()}J(F, t) = \{()\} and PRODUCT returns ()() at line L6. Otherwise lines L3 to L5 call UNION on each root AiA_i of FF, and by the induction hypothesis [ ⁣[UAi] ⁣]=J(TAi,t)[\![U_{A_i}]\!] = J(T_{A_i}, t). If one of them is empty, then J(F,t)J(F, t) is empty by Lemma 1, and line L5 returns ∅\emptyset. Otherwise line L6 returns the product, which stands for J(F,t)J(F, t) by Lemma 1.

UNION(A,t)(A, t) takes the values of VV in increasing order (lines L7 and L8), and for each aa it calls PRODUCT on the children (line L9). By the induction hypothesis that call returns ∅\emptyset exactly when J(kids(A),t∪{A↦a})=∅J(\mathit{kids}(A), t \cup \{A \mapsto a\}) = \emptyset, and line L10 keeps the pair only otherwise. By Lemma 2 the union of the kept pairs stands for J(TA,t)J(T_A, t).

At line L2, FF is the list of roots and tt is empty. Every attribute of QQ is in TT and every relation has an attribute, so every relation meets at(F)\mathit{at}(F), and J(F,())=Q(D)J(F, ()) = Q(D). If it is empty, line L2 returns one empty union per root, which stands for ∅\emptyset. Line L1 rejects an f-tree that is not valid. ■\blacksquare

Termination. Each call of PRODUCT or UNION goes one level down in TT, and each union iterates over a finite set VV, which is a subset of a finite index set. So the recursion is finite.

Theorem 2 (enumeration and counting). In the output, distinct paths of pairs give distinct tuples. So the enumeration lists each tuple of Q(D)Q(D) once, and COUNT, which adds over unions and multiplies over products, returns ∣Q(D)∣|Q(D)|.

Proof. The pairs of one union have distinct values of one attribute, so they stand for disjoint sets. The factors of a product are on disjoint attribute sets, so a tuple of the product determines its part in each factor. By induction, each tuple of [ ⁣[E] ⁣][\![E]\!] comes from exactly one choice of a pair in each union that the enumeration visits, and the size of a union is the sum of the sizes of its pairs while the size of a product is the product of the sizes of its factors. □\square

Theorem 3 (size). For each attribute AA, the number of singletons ⟨A:⋅⟩\langle A{:}\cdot \rangle in the output EE is ∣πpath(A)Q(D)∣|\pi_{\mathit{path}(A)} Q(D)|. So the size of EE is ∑A∣πpath(A)Q(D)∣\sum_A |\pi_{\mathit{path}(A)} Q(D)|.

Proof. An occurrence of ⟨A:a⟩\langle A{:}a \rangle in EE is reached from the top by choosing one pair in each union on the way, so it determines a tuple ss on path(A)\mathit{path}(A), with s(A)=as(A) = a. Two occurrences of AA give two different tuples ss, because the unions above them have distinct values. By Theorem 1 no union in EE is empty, so every occurrence lies in a nonempty product on every level, and it extends to a tuple of [ ⁣[E] ⁣]=Q(D)[\![E]\!] = Q(D) that agrees with ss. So s∈πpath(A)Q(D)s \in \pi_{\mathit{path}(A)} Q(D). Conversely, each tuple of Q(D)Q(D) is reached through one occurrence of AA, the one for its values on path(A)\mathit{path}(A). This is a bijection. □\square

This is Corollary 7.6 of Olteanu and Závodný (2015). For the bound on the page: πpath(A)Q(D)\pi_{\mathit{path}(A)} Q(D) is contained in the join of the projections πR∩path(A)R\pi_{R \cap \mathit{path}(A)} R over the relations that meet path(A)\mathit{path}(A). By the AGM bound, the join has at most ∣D∣ρ∗|D|^{\rho^*} tuples, where ρ∗\rho^* is the fractional edge cover number of the query restricted to path(A)\mathit{path}(A). Taking the largest exponent over the nodes gives ∣E∣≤∣T∣⋅∣D∣s(T)|E| \le |T| \cdot |D|^{s(T)}.

FACTORIZE. For one relation RR, FACTORIZE groups the rows by the value of the root and recurses on each group, and over a forest it builds each tree on the same rows. By induction, [ ⁣[FACTORIZE(T,R)] ⁣][\![\mathrm{FACTORIZE}(T, R)]\!] contains RR, because each row of RR is in its group at every level. If RR has some representation over TT, then on each forest RR is the product of its projections on the trees, and on each tree it is the union over the root values of the groups, so by induction the construction stands for RR itself. By Theorem 2, the construction then has exactly ∣R∣|R| tuples. So FACTORIZE raises an error exactly when RR has no representation over TT, and the argument of Theorem 3 gives its size ∑A∣πpath(A)R∣\sum_A |\pi_{\mathit{path}(A)} R|.

Complexity

  • Exact size. The number of singletons of AA is the number of distinct tuples of Q(D)Q(D) restricted to the path from the root to AA (Corollary 7.6). So the size is a sum of kk terms, one per attribute.
  • The parameter ss. By the AGM bound, each term is at most nρ∗n^{\rho^*}, where ρ∗\rho^* is the fractional edge cover number of the query restricted to the attributes on the path. The largest of these exponents over the nodes is s(T)s(T), and s(Q)s(Q) is the smallest s(T)s(T) over the valid f-trees. The size is O(k⋅ns(T))O(k \cdot n^{s(T)}), while the flat result can have nρ∗(Q)n^{\rho^*(Q)} tuples, and s(Q)≤ρ∗(Q)s(Q) \le \rho^*(Q).
  • Tightness. Olteanu and Závodný show that for each f-tree TT of QQ there are arbitrarily large databases on which the representation over TT has Ω((n/∣Q∣)s(Q))\Omega((n / |Q|)^{s(Q)}) singletons (Theorem 7.1). For a fixed query, there are databases on which every representation over every f-tree has Ω(ns(Q))\Omega(n^{s(Q)}) singletons (Theorem 7.2).
  • Build time. Each call of UNION at AA has as its tt a tuple of the join of the relations restricted to the path above AA, so there are at most k⋅nsk \cdot n^{s} calls. Each call does at most r(k+n)r (k + n) steps with hashing. The algorithm of the paper computes a representation of size O(ns(Q))O(n^{s(Q)}) in time O(ns(Q)log⁡n)O(n^{s(Q)} \log n) for a fixed query.
  • Queries on it. Count takes time linear in the size. Enumeration has constant delay for a fixed query.

Variants

  • Sharing. If equal subexpressions are stored once and referenced, as a directed acyclic graph, the size can drop further. Olteanu and Závodný give a parameter for this case that is at most s(Q)s(Q), and they relate it to the fractional hypertree width.
  • Query evaluation on representations. Selections, projections, joins and aggregates can be computed on the representation itself, which changes the f-tree.
  • Other systems with the same idea. Nested relations, hierarchical clustered schemas and compiled circuits for counting, such as d-DNNF, also store a set as nested unions and products.

When to use it

Use a factorized representation for a join result that is much larger than its inputs, such as a many-to-many join that later feeds an aggregate or a learning task. If the query is acyclic and only the output is needed once, Yannakakis's algorithm lists the tuples directly. If the result is small, the flat list is simpler.

Pitfalls

  • The choice of the f-tree. The size depends on the f-tree. A path through all attributes is always valid, but it shares only common prefixes. Finding the f-tree with the smallest s(T)s(T) means trying many trees, which is cheap only for small queries.
  • Dead branches. Without the pruning of line L10, a value of an attribute can stay in a union while no tuple goes through it. Then count and enumeration still work, but the size formula and the constant delay fail.
  • Nulls. The code joins equal values. A null in SQL never joins, so nulls must be removed first.
  • Not every relation factorizes. A single relation has a representation over an f-tree only if it has the independence that the f-tree states. The code checks this by counting.

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)
factorized_representation.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/factorized-representation/. The authors are listed in prov/7ZFJ86.jsonl.

"""Factorized representations of relations and of natural join results over f-trees.

A representation over a forest of attributes is a tuple with one union per
root. A union for the attribute A is a list of pairs (a, factors), sorted by
the value a, where factors is a tuple with one union per child of A. The pair
stands for the singleton <A:a> times the product of the factors, and a union
stands for the union of its pairs. A union with no pairs is the empty relation.
"""

from collections import defaultdict
from math import prod


class FTree:
    """A rooted forest with one attribute per node.

    nodes is a list of (attribute, parent), with parent None for a root. A
    parent must come before its children. The children keep the input order.
    """

    def __init__(self, nodes: list) -> None:
        self.parent = {}
        self.kids = {}
        self.roots = []
        for a, p in nodes:
            if a in self.parent:
                raise ValueError("the attribute %r occurs twice" % (a,))
            if p is not None and p not in self.parent:
                raise ValueError("the parent %r must come before %r" % (p, a))
            self.parent[a] = p
            self.kids[a] = []
            (self.roots if p is None else self.kids[p]).append(a)
        self.attrs = tuple(a for a, _ in nodes)

    def path(self, a: str) -> list:
        """The attributes from the root down to a, a included."""
        out = []
        while a is not None:
            out.append(a)
            a = self.parent[a]
        return out[::-1]


def path_condition(ftree: FTree, schemas: list) -> bool:
    """True when the attributes of each schema lie on one root-to-leaf path."""
    for schema in schemas:
        for a in schema:
            for b in schema:
                if a not in ftree.path(b) and b not in ftree.path(a):
                    return False
    return True


def valid(ftree: FTree, schemas: list) -> bool:
    """True when the f-tree has exactly the attributes of the query and the path condition holds."""
    attrs = {a for schema in schemas for a in schema}
    return len(ftree.attrs) > 0 and set(ftree.attrs) == attrs and path_condition(ftree, schemas)


def from_join(ftree: FTree, rels: list) -> tuple:
    """The representation over ftree of the natural join of rels, a list of dbrel.Relation, read as sets."""
    if not valid(ftree, [r.schema for r in rels]):                              # @line L1
        raise ValueError("the f-tree is not valid for this join")              # @line L1
    users = defaultdict(list)
    for r in rels:
        for a in r.schema:
            above = [b for b in ftree.path(a)[:-1] if b in r.schema]
            pos, ia = [r.index(b) for b in above], r.index(a)
            idx = defaultdict(set)
            for t in r.rows:
                idx[tuple(t[j] for j in pos)].add(t[ia])
            users[a].append((above, idx))

    def product(trees: list, t: dict):
        factors = []
        for a in trees:                                                         # @line L3
            u = union(a, t)                                                     # @line L4
            if not u:                                                           # @line L5
                return None                                                     # @line L5
            factors.append(u)                                                   # @line L4
        return tuple(factors)                                                   # @line L6

    def union(a: str, t: dict) -> list:
        sets = [idx.get(tuple(t[b] for b in above), ()) for above, idx in users[a]]  # @line L7
        small = min(sets, key=len)                                              # @line L7
        values = sorted(v for v in small if all(v in s for s in sets))          # @line L7
        out = []
        for v in values:                                                        # @line L8
            t[a] = v                                                            # @line L9
            p = product(ftree.kids[a], t)                                       # @line L9
            del t[a]                                                            # @line L9
            if p is not None:                                                   # @line L10
                out.append((v, p))                                              # @line L10
        return out                                                              # @line L11

    top = product(ftree.roots, {})                                              # @line L2
    return top if top is not None else tuple([] for _ in ftree.roots)          # @line L2


def factorize(ftree: FTree, rel) -> tuple:
    """The representation over ftree of one relation, read as a set.

    It raises ValueError when the relation has no representation over ftree.
    """
    if set(rel.schema) != set(ftree.attrs):
        raise ValueError("the f-tree and the relation have different attributes")
    pos = {a: rel.index(a) for a in rel.schema}

    def product(trees: list, rows: set) -> tuple:
        return tuple(union(a, rows) for a in trees)

    def union(a: str, rows: set) -> list:
        groups = defaultdict(set)
        for t in rows:
            groups[t[pos[a]]].add(t)
        return [(v, product(ftree.kids[a], groups[v])) for v in sorted(groups)]

    rows = set(rel.rows)
    e = product(ftree.roots, rows)
    if count(e) != len(rows):
        raise ValueError("the relation does not factorize over this f-tree")
    return e


def count(e: tuple) -> int:
    """The number of tuples that the representation stands for."""
    return prod(sum(count(factors) for _, factors in u) for u in e)


def size(e: tuple) -> int:
    """The number of singletons in the representation."""
    return sum(len(u) + sum(size(factors) for _, factors in u) for u in e)


def tuples(ftree: FTree, e: tuple):
    """Yield every tuple once, with the attributes in the order ftree.attrs."""

    def walk(pending: list, t: dict):
        if not pending:
            yield tuple(t[a] for a in ftree.attrs)
            return
        (a, u), rest = pending[0], pending[1:]
        for v, factors in u:
            t[a] = v
            yield from walk(list(zip(ftree.kids[a], factors)) + rest, t)
        t.pop(a, None)

    yield from walk(list(zip(ftree.roots, e)), {})
test_factorized_representation.py 139 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/factorized-representation/. The authors are listed in prov/7ZFJ86.jsonl.

import random

import dbrel
from factorized_representation import FTree, count, factorize, from_join, path_condition, size, tuples, valid

# Example 1.1 of Olteanu and Zavodny (2015): all (a, b, c) with 1 <= a < b < c <= 5.
R11 = dbrel.Relation(("a", "b", "c"),
                     [(a, b, c) for a in range(1, 6) for b in range(1, 6) for c in range(1, 6) if a < b < c], "set")


def join(rels: list, attrs: tuple) -> dbrel.Relation:
    db = {"R%d" % i: r for i, r in enumerate(rels)}
    expr = ("scan", "R0")
    for i in range(1, len(rels)):
        expr = ("join", expr, ("scan", "R%d" % i))
    return dbrel.evaluate(expr, db, "set").reorder(attrs)


def path_sizes(ftree: FTree, rel: dbrel.Relation) -> int:
    """The sum over the attributes A of the number of distinct values of the path to A."""
    return sum(len(dbrel.project(rel, ftree.path(a))) for a in ftree.attrs)


def test_example_1_1() -> None:
    star = FTree([("b", None), ("a", "b"), ("c", "b")])
    e = factorize(star, R11)
    assert count(e) == len(R11) == 10 and 3 * len(R11) == 30
    assert size(e) == 15 == path_sizes(star, R11)
    assert e[0][1] == (3, ([(1, ()), (2, ())], [(4, ()), (5, ())]))
    chain = FTree([("a", None), ("b", "a"), ("c", "b")])
    assert size(factorize(chain, R11)) == 3 + 6 + 10
    try:
        factorize(FTree([("a", None), ("b", "a"), ("c", "a")]), R11)
    except ValueError:
        pass
    else:
        raise AssertionError("b < c ties b and c, so they cannot be siblings below a")


def test_join_example() -> None:
    r = dbrel.Relation(("A", "B"), [(1, 1), (1, 2), (1, 3), (2, 4)], "set")
    s = dbrel.Relation(("A", "C"), [(1, 5), (1, 6), (2, 7)], "set")
    tree = FTree([("A", None), ("B", "A"), ("C", "A")])
    e = from_join(tree, [r, s])
    assert e == ([(1, ([(1, ()), (2, ()), (3, ())], [(5, ()), (6, ())])), (2, ([(4, ())], [(7, ())]))],)
    assert count(e) == 7 and size(e) == 9 == 2 + 4 + 3
    assert sorted(tuples(tree, e)) == join([r, s], tree.attrs).sorted_rows()


def test_gap_grows_with_n() -> None:
    n = 60
    r = dbrel.Relation(("A", "B"), [(0, i) for i in range(n)], "set")
    s = dbrel.Relation(("A", "C"), [(0, i) for i in range(n)], "set")
    e = from_join(FTree([("A", None), ("B", "A"), ("C", "A")]), [r, s])
    assert count(e) == n * n and size(e) == 2 * n + 1


def random_tree(rng: random.Random, attrs: list) -> FTree:
    order = attrs[:]
    rng.shuffle(order)
    nodes = []
    for i, a in enumerate(order):
        nodes.append((a, None if i == 0 or rng.random() < 0.2 else order[rng.randrange(i)]))
    return FTree(nodes)


def test_random_joins_against_dbrel() -> None:
    rng = random.Random(5)
    checked = 0
    for trial in range(600):
        rels = []
        for _ in range(rng.randrange(1, 5)):
            schema = tuple(rng.sample("ABCDE", rng.randrange(1, 4)))
            rels.append(dbrel.random_relation(rng, schema, rng.randrange(0, 9), range(3), "set"))
        attrs = sorted({a for r in rels for a in r.schema})
        tree = random_tree(rng, attrs)
        if not valid(tree, [r.schema for r in rels]):
            try:
                from_join(tree, rels)
            except ValueError:
                continue
            raise AssertionError("an invalid f-tree was accepted")
        checked += 1
        e = from_join(tree, rels)
        q = join(rels, tree.attrs)
        out = list(tuples(tree, e))
        assert len(out) == len(set(out)) == count(e)
        assert set(out) == set(q.rows)
        assert size(e) == path_sizes(tree, q)
        assert e == factorize(tree, q)
    assert checked > 150


def test_factorize_random_relations() -> None:
    rng = random.Random(6)
    accepted = 0
    for trial in range(400):
        rel = dbrel.random_relation(rng, ("A", "B", "C", "D"), rng.randrange(0, 12), range(2), "set")
        tree = random_tree(rng, ["A", "B", "C", "D"])
        # The relation factorizes over the tree when it is the join of its projections on the root-to-leaf paths.
        leaves = [a for a in tree.attrs if not tree.kids[a]]
        splits = join([dbrel.project(rel, tree.path(a)) for a in leaves], tree.attrs) == rel.reorder(tree.attrs)
        try:
            e = factorize(tree, rel)
        except ValueError:
            assert not splits
            continue
        assert splits
        accepted += 1
        assert set(tuples(tree, e)) == set(rel.reorder(tree.attrs).rows) and count(e) == len(rel)
        assert size(e) == path_sizes(tree, rel)
    assert accepted > 50


def test_path_condition_and_edges() -> None:
    tree = FTree([("A", None), ("B", "A"), ("C", "A")])
    assert path_condition(tree, [("A", "B"), ("A", "C")])
    assert not path_condition(tree, [("B", "C")])
    assert not valid(tree, [("A", "B")])
    assert not valid(FTree([]), [])
    empty = dbrel.Relation(("A", "B"), [], "set")
    full = dbrel.Relation(("A", "C"), [(1, 2)], "set")
    e = from_join(tree, [empty, full])
    assert e == ([],) and count(e) == 0 and size(e) == 0 and list(tuples(tree, e)) == []
    # A value of A that has a B but no C is pruned.
    r = dbrel.Relation(("A", "B"), [(1, 1), (2, 2)], "set")
    assert from_join(tree, [r, full]) == ([(1, ([(1, ())], [(2, ())]))],)
    forest = FTree([("A", None), ("C", None)])
    e = from_join(forest, [dbrel.Relation(("A",), [(1,), (2,)], "set"), dbrel.Relation(("C",), [(3,)], "set")])
    assert count(e) == 2 and size(e) == 3
    for bad in ([("A", None), ("A", None)], [("B", "A"), ("A", None)]):
        try:
            FTree(bad)
        except ValueError:
            continue
        raise AssertionError("a malformed f-tree was accepted")

History

Olteanu and Závodný introduced factorized representations of query results in 2012 and gave the full theory in the 2015 article in ACM Transactions on Database Systems: the f-trees, the exact number of singletons, the parameter s(Q)s(Q) with matching upper and lower bounds, and algorithms that build the representation directly from the input. Their article relates these ideas to earlier work on nested relations and on decompositions of relations, and later systems use them for query processing and machine learning on join results.

References

  1. Dan Olteanu and Jakub Závodný, Size bounds for factorised representations of query results, ACM Transactions on Database Systems 40(1), Article 2 (2015), Example 1.1; Definitions 5.1 and 5.2 (f-trees and f-representations); Proposition 5.10 (existence and uniqueness); Proposition 6.1 (the path condition); Corollary 7.6 (the number of singletons); Definition 7.14 and Theorem 7.16 (the parameter s and the upper bound); Theorems 7.1 and 7.2 (the upper bound and the matching lower bounds); Section 8 (computing the representation)
  2. Albert Atserias, Martin Grohe and Dániel Marx, Size bounds and query plans for relational joins, SIAM Journal on Computing 42(4), 1737 to 1767 (2013); first in FOCS 2008, 739 to 748, the bound on the size of a join by a fractional edge cover, which gives the bound on each path of the f-tree

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
  • at least three sources