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
- Model
- Word RAM
- Evidence
- Proof sketchCode in 1 languages
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 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 over a set of attributes. It supports:
- build from a join query and its input relations, or from one relation;
- enumerate the tuples of , each once;
- count the tuples of 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 is the relation with one tuple, with the value for the attribute . An f-representation is an expression built from singletons with union and Cartesian product .
An f-tree is a rooted forest in which each node is an attribute. A representation over has this form:
- over a forest with trees : a product , with over ;
- over a tree with root and child forest : a union over distinct values , with each over .
So below each value of , the subtrees of the children are independent. A relation has a representation over 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 of the relations , an f-tree with the attributes of 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 .
Operations
FROMJOIN(T, D) ▷ D holds the relations of the natural join Q- 1
if T and Q have different attributes, or the attributes of some relation are not on one root-to-leaf path of T, then fail - 2
E ← PRODUCT(the roots of T, the empty tuple); return E, or one empty union per root if E = ∅ PRODUCT(F, t) ▷ t gives a value to each attribute above the trees of F- 3
for each tree of F, with root A, do - 4
U_A ← UNION(A, t) - 5
if U_A is empty then return ∅ - 6
return the product of the unions U_A UNION(A, t)- 7
V ← 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 - 8
for each a in V, in increasing order, do - 9
P ← PRODUCT(the children of A, t extended by A = a) - 10
if P ≠ ∅ then add the pair ⟨A:a⟩ × P to the union - 11
return the union
Line L7 uses one hash index per relation and attribute of : it maps the values of the attributes of above to the set of values of . 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 , 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 and , and the f-tree with root and children and . 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
with 9 singletons. If one value of has values of and values of , the join has tuples and the representation has singletons.
The f-tree matters. Example 1.1 of Olteanu and Závodný takes the relation of all with , which has 10 tuples and 30 values. Over the f-tree with root and children and , the representation is
with 15 singletons. Over the path it has singletons. Over the f-tree with root and children and there is no representation, because ties and for a fixed .
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 match the distinct tuples of the result restricted to the path to . 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. is the natural join of the relations of , each with at least one attribute, and is an f-tree whose node set is the set of attributes of . The relations are read as sets and hold no nulls. For a node , is the set of proper ancestors of , , and is the subtree rooted at , with attribute set . For a list of subtrees, is the union of their attribute sets. A tuple is a map from a set of attributes to values, and is its restriction to .
Semantics. A singleton stands for the relation with the one tuple . A pair in a union for stands for , a union stands for the union of its pairs, and a product stands for . The empty product stands for , the relation with the one tuple on no attributes. A union with no pairs stands for .
The target sets. Let be the list of children of a node , or the list of roots, and let , or for the roots. For a tuple on , let
For one subtree with , define in the same way.
Lemma 1 (splitting). Let and let satisfy the path condition. Every relation that meets meets exactly one , and . Hence .
Proof. The attributes of lie on one root-to-leaf path . A path that meets passes through , and it then contains no node of for , since the subtrees are disjoint and the nodes of are pairwise comparable. The nodes of above are in . So the conditions on split into one set of conditions for each , and the set of solutions is the product.
Lemma 2 (one subtree). For a node and a tuple on , let be the set of line L7. Then
Proof. Let be in with , and let contain . Then , and this tuple of agrees with on the attributes of above and has the value at . So . The relations that meet also meet , so the rest of is in .
Conversely, let and , and put . Let meet . If meets , then by the choice of . Otherwise contains and, by the path condition, all its other attributes are in . Then is the tuple that agrees with above and has at , which is in because .
Theorem 1 (correctness). Let be valid for . For each call, PRODUCT returns if , and otherwise a product with . UNION returns a union with , whose pairs have distinct values in increasing order, and none of whose pairs has an empty product. FROMJOIN returns a representation with .
Proof. By induction on the height of the subtrees. If is empty, then and PRODUCT returns at line L6. Otherwise lines L3 to L5 call UNION on each root of , and by the induction hypothesis . If one of them is empty, then is empty by Lemma 1, and line L5 returns . Otherwise line L6 returns the product, which stands for by Lemma 1.
UNION takes the values of in increasing order (lines L7 and L8), and for each it calls PRODUCT on the children (line L9). By the induction hypothesis that call returns exactly when , and line L10 keeps the pair only otherwise. By Lemma 2 the union of the kept pairs stands for .
At line L2, is the list of roots and is empty. Every attribute of is in and every relation has an attribute, so every relation meets , and . If it is empty, line L2 returns one empty union per root, which stands for . Line L1 rejects an f-tree that is not valid.
Termination. Each call of PRODUCT or UNION goes one level down in , and each union iterates over a finite set , 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 once, and COUNT, which adds over unions and multiplies over products, returns .
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 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.
Theorem 3 (size). For each attribute , the number of singletons in the output is . So the size of is .
Proof. An occurrence of in is reached from the top by choosing one pair in each union on the way, so it determines a tuple on , with . Two occurrences of give two different tuples , because the unions above them have distinct values. By Theorem 1 no union in is empty, so every occurrence lies in a nonempty product on every level, and it extends to a tuple of that agrees with . So . Conversely, each tuple of is reached through one occurrence of , the one for its values on . This is a bijection.
This is Corollary 7.6 of Olteanu and Závodný (2015). For the bound on the page: is contained in the join of the projections over the relations that meet . By the AGM bound, the join has at most tuples, where is the fractional edge cover number of the query restricted to . Taking the largest exponent over the nodes gives .
FACTORIZE. For one relation , 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, contains , because each row of is in its group at every level. If has some representation over , then on each forest 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 itself. By Theorem 2, the construction then has exactly tuples. So FACTORIZE raises an error exactly when has no representation over , and the argument of Theorem 3 gives its size .
Complexity
- Exact size. The number of singletons of is the number of distinct tuples of restricted to the path from the root to (Corollary 7.6). So the size is a sum of terms, one per attribute.
- The parameter . By the AGM bound, each term is at most , where 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 , and is the smallest over the valid f-trees. The size is , while the flat result can have tuples, and .
- Tightness. Olteanu and Závodný show that for each f-tree of there are arbitrarily large databases on which the representation over has singletons (Theorem 7.1). For a fixed query, there are databases on which every representation over every f-tree has singletons (Theorem 7.2).
- Build time. Each call of UNION at has as its a tuple of the join of the relations restricted to the path above , so there are at most calls. Each call does at most steps with hashing. The algorithm of the paper computes a representation of size in time 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 , 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 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.
# 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 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 7ZFJ86 Edit this page History Report an error Markdown