Algorithm Search⌘K

Definitioncore

Horizontal fragmentation

Also called primary horizontal fragmentation, derived horizontal fragmentation.

Split a relation into subsets of rows defined by selection predicates or by a join with another fragmented relation.

A horizontal fragmentation splits a relation into fragments that each hold some of its rows and all of its columns. In a primary fragmentation each fragment is a selection σm(R)\sigma_{m}(R) by a predicate mm on RR; in a derived fragmentation each fragment of a relation SS is a semijoin S⋉RmS \ltimes R_m with a fragment of another relation RR. The fragments can then be stored at different sites, so that each site holds the rows that its users need. A fragmentation is correct when it is complete, can be put back together, and puts each row in one fragment.

Definition

Let RR be a relation, a bag of rows. A horizontal fragmentation of RR is a list of fragments R1,…,RnR_1, \dots, R_n with Ri=σqi(R)R_i = \sigma_{q_i}(R) for some predicates qiq_i. It is correct if it meets three rules.

  • Completeness. Every row of RR is in at least one fragment.
  • Reconstruction. RR is the bag union of the fragments, R=R1∪⋯∪RnR = R_1 \cup \dots \cup R_n (UNION ALL in SQL), with the right count for every row.
  • Disjointness. No row is in two fragments.

For bags, completeness and disjointness together give reconstruction. If the fragments are complete but not disjoint, a set union still gives RR back, but a bag union counts a row twice.

Minterm fragments. Let p1,…,pkp_1, \dots, p_k be simple predicates, each a comparison of one attribute with a constant. A minterm chooses, for each pip_i, either "pip_i is true" or "pip_i is not true". The primary horizontal fragmentation by p1,…,pkp_1, \dots, p_k has one fragment σm(R)\sigma_m(R) for each minterm mm that some row satisfies. With "not true" read as "FALSE or UNKNOWN", each row satisfies exactly one minterm, so the minterm fragments are always correct, also when the data has NULLs.

Derived fragments. Let SS be a relation that refers to RR by the attributes JJ, for example by a foreign key. The derived horizontal fragmentation of SS by a fragmentation R1,…,RnR_1, \dots, R_n of RR has the fragments Si=S⋉RiS_i = S \ltimes R_i. It puts a row of SS in the same fragment as the row of RR that it refers to, so a join of SS with RR on JJ can run fragment by fragment, Si⋈RiS_i \bowtie R_i, at one site each.

  1. PRIMARY(R, p_1..p_k)
  2. 1for each minterm m over p_1..p_k ▷ each p_i taken as "is true" or "is not true"
  3. 2R_m ← σ_m(R)
  4. 3keep R_m if it is not empty
  5. DERIVED(S, R_1..R_n)
  6. 4for each fragment R_i of the owner R
  7. 5S_i ← S ⋉ R_i ▷ on the common attributes; NULL matches nothing
  8. RECONSTRUCT(fragments)
  9. 6return the bag union of the fragments

There are 2k2^k minterms, but no more fragments than distinct rows survive line L3, and many minterms are empty because they are contradictory, such as A<5A < 5 together with A>10A > 10. The proof page shows that the minterm fragments are complete and disjoint, and that the derived fragments are complete when every row of SS refers to a row of RR and disjoint when JJ is a key of RR.

Examples and non-examples

A primary fragmentation. The relation ACCOUNT(id,branch,balance)ACCOUNT(id, branch, balance) has five rows: (1,Paris,500)(1, Paris, 500), (2,Paris,2500)(2, Paris, 2500), (3,Lyon,800)(3, Lyon, 800), (4,Lyon,NULL)(4, Lyon, NULL) and (5,Nice,1200)(5, Nice, 1200). The simple predicates are p1p_1: branch=Parisbranch = Paris and p2p_2: balance<1000balance < 1000.

minterm rows
p1p_1 true, p2p_2 true 1
p1p_1 true, p2p_2 not true 2
p1p_1 not true, p2p_2 true 3
p1p_1 not true, p2p_2 not true 4, 5

Row 4 has a NULL balance, so p2p_2 is UNKNOWN on it, which is "not true". The four fragments are complete and disjoint, and their bag union is ACCOUNTACCOUNT.

A non-example: NOT in place of "not true". If the last fragment is written as σ¬p1∧¬p2(ACCOUNT)\sigma_{\lnot p_1 \land \lnot p_2}(ACCOUNT) in SQL, then on row 4 the predicate ¬p2\lnot p_2 is UNKNOWN, and the selection drops the row. Row 4 is in no fragment, so this fragmentation is not complete. The fix is to write the negative literal as p2p_2 IS NOT TRUE, or to declare the attribute NOT NULL.

A derived fragmentation. The relation TXN(tid,id,amount)TXN(tid, id, amount) refers to ACCOUNTACCOUNT by idid, with the rows 10 and 11 for account 1, row 12 for account 3, row 13 for account 4 and row 14 for account 5. The derived fragments are {10,11}\{10, 11\}, {}\{\}, {12}\{12\} and {13,14}\{13, 14\}: each transaction goes to the fragment of its account. Since idid is a key of ACCOUNTACCOUNT and every transaction refers to an existing account, the fragments are complete and disjoint.

A non-example: a derived fragmentation on a non-key. If the owner has two rows with the same value of JJ in two different fragments, a member row with that value is in both derived fragments, and disjointness fails. If a member row has a NULL in JJ, or a value that is not in the owner, it is in no fragment, and completeness fails. The tests of the implementation check these cases.

A non-example: a fragmentation that keeps only some columns. Splitting ACCOUNTACCOUNT into πid,branch\pi_{id, branch} and πid,balance\pi_{id, balance} is a vertical fragmentation, not a horizontal one: each fragment has all the rows and some of the columns.

  • Hash partitioning. Hash partitioning puts a row in the fragment that a hash function of a key chooses. It is a horizontal fragmentation whose predicates are h(K) mod n=ih(K) \bmod n = i, but they come from the hash function, not from the workload, so a query with a range predicate must read every fragment.
  • Range partitioning. Range partitioning uses predicates of the form ci−1≤K<cic_{i-1} \le K < c_i on one attribute. It is the special case of a primary fragmentation with simple predicates on one attribute only, and a range query reads only the fragments that meet its range.
  • Sharding. Sharding is the systems name for a horizontal fragmentation together with its placement: each fragment, a shard, lives on one server, and a router maps a key to its shard. The fragmentation is the logical split; sharding adds the servers, the routing and the moving of shards.
  • Hybrid fragmentation. A vertical fragmentation of a horizontal fragment, or the other way around. Reconstruction then uses both joins and unions.
  • Allocation. Where to store each fragment and its copies is the data allocation problem. Schism chooses a fragmentation and an allocation together from a trace of transactions.
  • Localization. In distributed query processing, a query on RR is rewritten on the fragments, and the fragments whose predicates contradict the query are dropped.
Proof: Minterm fragments are complete and disjoint, also with NULLs, and derived fragments follow their ownerfull

We use the line numbers of the pseudocode on the page. A relation RR is a bag: each row has a count. A simple predicate pp maps each row to TRUE, FALSE or UNKNOWN, as in SQL, where a comparison with NULL is UNKNOWN. For a list p1,…,pkp_1, \dots, p_k and a sign vector m∈{+,−}km \in \{+, -\}^k, the minterm mm holds on a row tt when, for each ii, pi(t)p_i(t) is TRUE if mi=+m_i = + and pi(t)p_i(t) is not TRUE (FALSE or UNKNOWN) if mi=−m_i = -. Line L2 sets Rm=σm(R)R_m = \sigma_m(R), with the counts of RR.

Theorem 1. The minterm fragments of lines L1 to L3 are disjoint, complete, and their bag union (line L6) is RR, with the same count for every row.

Proof. For a row tt, define m(t)m(t) by m(t)i=+m(t)_i = + exactly when pi(t)p_i(t) is TRUE. Then tt satisfies m(t)m(t). If tt satisfies a minterm mm, then for each ii, mi=+m_i = + exactly when pi(t)p_i(t) is TRUE, so m=m(t)m = m(t). So every row satisfies exactly one minterm: it is in exactly one fragment (disjointness) and in at least one (completeness). Each fragment keeps the count of each of its rows, so the bag union has the count of RR for each row. Line L3 drops only empty fragments, which add nothing to the union. □\square

The form with NOT. If the minterm uses ¬pi\lnot p_i for mi=−m_i = -, with the SQL rule that ¬\lnot UNKNOWN is UNKNOWN and that a selection keeps only TRUE rows, then a row tt with pi(t)p_i(t) UNKNOWN for some ii satisfies no minterm. The fragments are still disjoint, but their union is σno pi is UNKNOWN(R)\sigma_{\text{no } p_i \text{ is UNKNOWN}}(R), a proper sub-bag of RR whenever such a row exists. The two forms agree when no predicate can be UNKNOWN on the data, for example when the attributes they use are declared NOT NULL.

Derived fragments. Let SS be a member relation and RR its owner, with common attributes JJ, and let RmR_m be fragments of RR. Line L5 sets Sm=S⋉RmS_m = S \ltimes R_m: the rows of SS, with their counts, that agree on JJ with some row of RmR_m and have no NULL in JJ.

Theorem 2. Let the fragments RmR_m of the owner be complete and disjoint.

  1. A row of SS is in some SmS_m exactly when it joins with some row of RR. So the derived fragments are complete exactly when S⋉R=SS \ltimes R = S, which holds when every row of SS has a non-null value of JJ that appears in RR (referential integrity from SS to RR).
  2. If JJ is a key of RR, the derived fragments are disjoint.
  3. Under both conditions, the bag union of the SmS_m is SS.

Proof. (1) A row ss of SS is in SmS_m when it joins with a row of RmR_m. Every row of RR is in some RmR_m and every row of an RmR_m is in RR, so ss is in some SmS_m exactly when it joins with a row of RR. (2) If JJ is a key of RR, then a row ss joins with at most one row rr of RR, the one with r[J]=s[J]r[J] = s[J]. That row is in exactly one fragment, so ss is in exactly one SmS_m. (3) By (1) and (2) each row of SS is in exactly one SmS_m, with its count. □\square

Both conditions are needed. If a value of JJ appears in two rows of RR that lie in different fragments, a row of SS with that value is in both derived fragments, and the bag union counts it twice. If a row of SS has a NULL in JJ, or a value that is not in RR, it is in no fragment. The tests check both failures.

Reconstruction is a query. By Theorem 1, R=⋃mRmR = \bigcup_m R_m with bag union, so any query on RR can be answered from the fragments. A query with a selection σq\sigma_q needs only the fragments whose minterm is consistent with qq: if mm and qq cannot both be TRUE on any row, then σq(Rm)\sigma_q(R_m) is empty. This is the reason to fragment by the predicates of the workload.

Code

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)
horizontal_fragmentation.py 107 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/horizontal-fragmentation/. The authors are listed in prov/XH9D31.jsonl.

"""Primary and derived horizontal fragmentation, and the three correctness rules.

A relation is a schema (a tuple of attribute names) and a Counter from rows to
counts, so duplicates are kept (bag semantics). A simple predicate is a
function from a row, given as a dict, to True, False or None (UNKNOWN, as in
SQL when a NULL is compared).

A minterm over the simple predicates p_1, ..., p_k fixes, for each p_i, whether
"p_i is true" or "p_i is not true". "Not true" holds when p_i is False or
UNKNOWN. With this form, every row satisfies exactly one minterm, so the
minterm fragments are complete and disjoint even when the data has NULLs. The
naive form, which uses NOT p_i, loses the rows where p_i is UNKNOWN.

A derived fragmentation of a member relation S follows a fragmentation of an
owner relation R: S_m is S semijoin R_m on the common attributes. A NULL in a
join attribute matches nothing.
"""

from __future__ import annotations

from collections import Counter
from itertools import product
from collections.abc import Callable, Mapping, Sequence

Pred = Callable[[dict], "bool | None"]


def minterms(k: int) -> list[tuple[bool, ...]]:
    """All 2^k sign vectors; True at i means "p_i is true", False means "p_i is not true"."""
    return list(product((True, False), repeat=k))


def satisfies(row: dict, preds: Sequence[Pred], m: tuple[bool, ...]) -> bool:
    return all((p(row) is True) == want for p, want in zip(preds, m))


def primary_fragments(schema: Sequence[str], rows: Counter, preds: Sequence[Pred],
                      keep_empty: bool = False) -> dict:
    """The minterm fragments of the relation: minterm -> Counter of its rows."""
    schema = tuple(schema)
    out = {}
    for m in minterms(len(preds)):  # @line L1
        frag = Counter({t: c for t, c in rows.items() if satisfies(dict(zip(schema, t)), preds, m)})  # @line L2
        if frag or keep_empty:  # @line L3
            out[m] = frag
    return out


def naive_fragments(schema: Sequence[str], rows: Counter, preds: Sequence[Pred]) -> dict:
    """The fragments with "NOT p_i" in place of "p_i is not true". They are wrong when
    a predicate can be UNKNOWN: a row with UNKNOWN p_i is in no fragment."""
    schema = tuple(schema)

    def holds(v, want):
        return v is True if want else v is False   # NOT UNKNOWN is UNKNOWN, which is not True

    out = {}
    for m in minterms(len(preds)):
        frag = Counter({t: c for t, c in rows.items()
                        if all(holds(p(dict(zip(schema, t))), w) for p, w in zip(preds, m))})
        if frag:
            out[m] = frag
    return out


def derived_fragments(member_schema: Sequence[str], member_rows: Counter, owner_schema: Sequence[str],
                      owner_fragments: Mapping) -> dict:
    """S_m = S semijoin R_m for each fragment R_m of the owner R, on the common attributes."""
    member_schema, owner_schema = tuple(member_schema), tuple(owner_schema)
    common = [a for a in member_schema if a in owner_schema]
    mi = [member_schema.index(a) for a in common]
    oi = [owner_schema.index(a) for a in common]
    out = {}
    for m, frag in owner_fragments.items():  # @line L4
        keys = {tuple(t[i] for i in oi) for t in frag}
        keys = {k for k in keys if None not in k}
        out[m] = Counter({t: c for t, c in member_rows.items() if tuple(t[i] for i in mi) in keys})  # @line L5
    return out


def reconstruct(fragments: Mapping) -> Counter:
    """The bag union of the fragments (UNION ALL)."""
    out: Counter = Counter()
    for frag in fragments.values():  # @line L6
        out.update(frag)
    return out


def is_complete(rows: Counter, fragments: Mapping) -> bool:
    """Every row of the relation, with its full count, is in the bag union of the fragments
    at least as often as in the relation."""
    union = reconstruct(fragments)
    return all(union[t] >= c for t, c in rows.items())


def is_disjoint(fragments: Mapping) -> bool:
    """No row is in two fragments."""
    seen = set()
    for frag in fragments.values():
        for t in frag:
            if t in seen:
                return False
            seen.add(t)
    return True
test_horizontal_fragmentation.py 114 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/horizontal-fragmentation/. The authors are listed in prov/XH9D31.jsonl.

import random
from collections import Counter
from functools import reduce

import pytest

import dbrel
from horizontal_fragmentation import (derived_fragments, is_complete, is_disjoint, minterms, naive_fragments,
                                      primary_fragments, reconstruct)

ACCOUNT = ("id", "branch", "balance")
ACCOUNT_ROWS = Counter({(1, "Paris", 500): 1, (2, "Paris", 2500): 1, (3, "Lyon", 800): 1,
                        (4, "Lyon", None): 1, (5, "Nice", 1200): 1})
P1 = lambda r: dbrel.cmp3("=", r["branch"], "Paris")
P2 = lambda r: dbrel.cmp3("<", r["balance"], 1000)
TXN = ("tid", "id", "amount")
TXN_ROWS = Counter({(10, 1, 20): 1, (11, 1, 30): 1, (12, 3, 5): 1, (13, 4, 7): 1, (14, 5, 9): 1})


def rel(schema, rows):
    return dbrel.Relation(schema, rows)


def bag_union(schema, frags):
    return reduce(dbrel.union, (rel(schema, f) for f in frags), rel(schema, ()))


def test_page_example_primary():
    frags = primary_fragments(ACCOUNT, ACCOUNT_ROWS, [P1, P2])
    ids = {m: sorted(t[0] for t in f) for m, f in frags.items()}
    assert ids == {(True, True): [1], (True, False): [2], (False, True): [3], (False, False): [4, 5]}
    assert reconstruct(frags) == ACCOUNT_ROWS and is_disjoint(frags)


def test_page_example_naive_minterms_lose_the_null_row():
    frags = naive_fragments(ACCOUNT, ACCOUNT_ROWS, [P1, P2])
    lost = ACCOUNT_ROWS - reconstruct(frags)
    assert lost == Counter({(4, "Lyon", None): 1})
    assert not is_complete(ACCOUNT_ROWS, frags)


def test_page_example_derived():
    owner = primary_fragments(ACCOUNT, ACCOUNT_ROWS, [P1, P2])
    frags = derived_fragments(TXN, TXN_ROWS, ACCOUNT, owner)
    tids = {m: sorted(t[0] for t in f) for m, f in frags.items()}
    assert tids == {(True, True): [10, 11], (True, False): [], (False, True): [12], (False, False): [13, 14]}
    assert reconstruct(frags) == TXN_ROWS and is_disjoint(frags)


def random_preds(rng, schema, k):
    preds = []
    for _ in range(k):
        a = rng.choice(schema)
        op = rng.choice(["=", "<>", "<", "<=", ">", ">="])
        v = rng.randint(0, 3)
        preds.append(lambda r, a=a, op=op, v=v: dbrel.cmp3(op, r[a], v))
    return preds


@pytest.mark.parametrize("seed", range(80))
def test_minterm_fragments_are_complete_disjoint_and_reconstruct(seed):
    rng = random.Random(seed)
    schema = ("A", "B", "C")
    r = dbrel.random_relation(rng, schema, rng.randint(0, 25), domain=4, null_rate=0.2)
    preds = random_preds(rng, schema, rng.randint(0, 4))
    frags = primary_fragments(schema, r.rows, preds)
    assert len(frags) <= min(2 ** len(preds), max(1, len(r.rows)))
    assert is_disjoint(frags) and is_complete(r.rows, frags)
    assert bag_union(schema, frags.values()) == r
    for m, f in frags.items():
        want = dbrel.select(r, lambda row: all(dbrel.is_true(p(row)) == s for p, s in zip(preds, m)))
        assert rel(schema, f) == want
    # The naive fragments keep exactly the rows on which no predicate is UNKNOWN.
    naive = reconstruct(naive_fragments(schema, r.rows, preds))
    assert rel(schema, naive) == dbrel.select(r, lambda row: all(p(row) is not None for p in preds))


@pytest.mark.parametrize("seed", range(60))
def test_derived_fragments(seed):
    rng = random.Random(1000 + seed)
    keys = rng.sample(range(10), rng.randint(1, 6))
    owner = rel(("K", "G"), [(k, rng.randint(0, 3)) for k in keys])  # K is a key of the owner
    preds = random_preds(rng, ("G",), rng.randint(1, 3))
    ofr = primary_fragments(owner.schema, owner.rows, preds)
    member = dbrel.random_relation(rng, ("M", "K"), rng.randint(0, 15), domain={"M": 5, "K": keys + [None, 99]})
    frags = derived_fragments(member.schema, member.rows, owner.schema, ofr)
    for m, f in frags.items():
        assert rel(member.schema, f) == dbrel.semijoin(member, rel(owner.schema, ofr[m]))
    # K is a key of the owner, so the fragments are disjoint.
    assert is_disjoint(frags)
    # A member row is lost exactly when it has no owner row: a NULL or a dangling key.
    assert rel(member.schema, member.rows - reconstruct(frags)) == dbrel.antijoin(member, owner)
    ok = dbrel.semijoin(member, owner)
    clean = derived_fragments(member.schema, ok.rows, owner.schema, ofr)
    assert reconstruct(clean) == ok.rows and is_complete(ok.rows, clean)


def test_derived_fragments_overlap_without_a_key():
    owner = Counter({(1, 0): 1, (1, 1): 1})         # K = 1 appears twice, in two fragments
    ofr = primary_fragments(("K", "G"), owner, [lambda r: dbrel.cmp3("=", r["G"], 0)])
    frags = derived_fragments(("M", "K"), Counter({(7, 1): 1}), ("K", "G"), ofr)
    assert not is_disjoint(frags)
    assert reconstruct(frags) == Counter({(7, 1): 2})   # the union counts the row twice


def test_minterm_count_and_duplicates():
    assert len(minterms(0)) == 1 and len(minterms(3)) == 8
    rows = Counter({(1, 2): 3, (2, 2): 2})
    frags = primary_fragments(("A", "B"), rows, [lambda r: dbrel.cmp3("=", r["A"], 1)])
    assert frags == {(True,): Counter({(1, 2): 3}), (False,): Counter({(2, 2): 2})}
    assert primary_fragments(("A", "B"), Counter(), [lambda r: True]) == {}

References

  1. Stefano Ceri, Mauro Negri and Giuseppe Pelagatti, Horizontal data partitioning in database design, Proceedings of the 1982 ACM SIGMOD International Conference on Management of Data, 1982, starting at page 128, horizontal fragments defined by minterm predicates over the simple predicates that the applications use, and derived fragments that follow the fragments of another relation
  2. M. Tamer Özsu and Patrick Valduriez, Principles of Distributed Database Systems, fourth edition, Springer, 2020, Chapter 2, Distributed and Parallel Database Design, the sections on fragmentation (the rules of completeness, reconstruction and disjointness, and primary and derived horizontal fragmentation)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/XH9D31/proof-correctness.yaml
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)
WritingW4 complete
  • a review of the text: no review record reviews/XH9D31/text.yaml