Definitioncore
Vertical fragmentation
Also called vertical partitioning.
Split a relation into projections that each keep the key, grouping attributes that queries use together.
A vertical fragmentation splits a relation into fragments that each hold some of its columns and all of its rows. Each fragment is a projection that keeps a key of , so that a join of the fragments on gives back. The groups of other attributes are chosen so that each query of the workload reads few fragments: attributes that the same queries use go into the same fragment. In a distributed database the fragments can then live at the sites that use them, and in one database they can be stored apart, so that a scan reads only the columns it needs.
Definition
Let be a relation over the attributes with a candidate key . A vertical fragmentation of is a list of fragments , where are sets of attributes outside . It is correct if it meets three rules.
- Completeness. Every attribute of is in some fragment: .
- Reconstruction. , the natural join on .
- Disjointness. The groups are pairwise disjoint. Only the key is repeated in every fragment.
When is a key, completeness gives reconstruction: a row of is the join of its own pieces, and two pieces with the same key value come from the same row. This is the special case of a lossless-join decomposition in which the shared attributes are a key of every fragment. Disjointness is not needed for reconstruction; it keeps each value in one place, so that an update of a non-key attribute changes one fragment.
FRAGMENT(R, K, G_1..G_n)- 1
for i ← 1 to n - 2
R_i ← π_{K ∪ G_i}(R) RECONSTRUCT(R_1..R_n, K)- 3
T ← R_1; for i ← 2 to n - 4
T ← T ⋈ R_i on K ▷ a NULL in K matches nothing - 5
return T, with the columns in the order of R
Choosing the groups. Navathe, Ceri, Wiederhold and Dou (1984) start from the queries of the workload. The attribute usage matrix says which attributes each query uses. The attribute affinity of two attributes and is the total frequency of the queries that use both. The bond energy algorithm permutes the affinity matrix so that attributes with high affinity are next to each other, and a split step then cuts the ordered attributes into groups that separate the queries well. The proof page shows that the fragments of lines L1 and L2 join back to when is a key.
Examples and non-examples
A vertical fragmentation. The relation has the key and four rows: , , and . A directory application reads and , and a payroll application reads . The fragments are
- , at the site of the directory,
- , at the site of the payroll.
The join of and on gives the four rows of back. The NULLs in and do no harm, because the join compares only .
A non-example: fragments without the key. Take and for the two employees of RD, Ann with 5000 and Cy with NULL. The fragments share only , which is not a key. The join on has four rows: each RD name gets each RD salary, so two of the rows were never in .
A non-example: a bag without a key. The bag split into and joins back to four rows, since is not a key. The usual fix is a tuple identifier: give each row, and each copy of a duplicate row, its own id, and keep the id in every fragment.
A non-example: a NULL in the key. A row with a NULL in is lost by the join, because a NULL matches nothing. A key used for fragmentation must be NOT NULL.
A non-example: a projection that drops an attribute. and alone are not complete, because is in no fragment, and no join can bring it back.
Related definitions
- Horizontal fragmentation. A horizontal fragmentation splits the rows and keeps all the columns; it is put back by a union, not a join. A hybrid fragmentation applies one kind of split to the fragments of the other.
- Column stores. The decomposition storage model is the extreme case: each fragment holds the key, or a row position, and one attribute. The n-ary storage model is the other extreme, one fragment with all attributes, and PAX keeps the rows of a page together but stores each column of the page apart.
- Lossless joins and dependencies. The test that a decomposition joins back without loss uses the functional dependencies of the schema; the condition that the common attributes are a key is the simplest case of the test on lossless-join decomposition.
- Allocation. Where to store each fragment and its copies is the data allocation problem.
Proof: Vertical fragments that keep a key are joined back to the relation without lossfull
We use the line numbers of the pseudocode on the page. is a bag of rows over the attributes , and . The groups cover . Line L2 sets , a bag projection that keeps the counts, and lines L3 to L5 compute on the common attributes, where a NULL matches nothing, and put the columns back in the order of .
is a key of the instance if no row has a NULL in and no two rows, and no two copies of one row, agree on . So is a set, and the map is one to one on it.
Theorem 1. If the fragmentation is complete () and is a key of the instance , the join of the fragments is , with every count equal to 1.
Proof. Each has one row for each row of , with count 1, because two rows of that agree on are equal. Two fragments and have the common attributes , which hold .
Every row of is in the join. For a row of , the rows agree with each other on all their common attributes, since they come from one row, and their values have no NULL. So they join, and their join is , because the groups cover .
No other row is in the join. A row of the join comes from rows that agree on and have no NULL there. Each is for a row of , and the agree on , so they are one row . Then agrees with on every and on , so .
Counts. Each fragment row has count 1, and by the two parts above, each row of arises from exactly one combination of fragment rows. So has count 1 in the join, as in .
The proof uses completeness only to get every attribute back. Disjointness of the groups is not needed for reconstruction; it only saves storage and makes an update touch fewer fragments. When the groups overlap, the shared attribute values agree because they come from one row.
Without a key the join can add rows. Let , with fragments and . Here is not a key. The join on has four rows, for , so it is a proper superset of . In general every row of is in the join with at least its count, since the projections keep the counts and the row joins with itself; the join can only add rows or copies. This is the case of a lossy decomposition on the page lossless-join decomposition.
A NULL in loses the row. If a row has a NULL in , its pieces never match, so it is missing from the join. A key must therefore be NOT NULL.
Tuple identifiers. If has no key, for example because it is a bag with duplicate rows, give each copy of each row a distinct identifier . The relation over has the key , so by Theorem 1 the fragments of join back to , and with bag projection is again. The tests check Theorem 1, the lossy case, the NULL case and the identifiers on random relations.
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.
# 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)
vertical_fragmentation.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vertical-fragmentation/. The authors are listed in prov/XEF5EY.jsonl.
"""Vertical fragmentation by projections that keep the key, and reconstruction by a join.
A relation is a schema (a tuple of attribute names) and a Counter from rows to
counts. A vertical fragmentation with key K and groups G_1, ..., G_n of the
other attributes has the fragments pi_{K u G_i}(R). It is complete when every
attribute is in some fragment, and disjoint when no attribute other than K is
in two fragments. It reconstructs R by a join of the fragments on K.
The join is lossless when K is a key of R: no NULL in K and no two rows with
the same K. A bag with duplicate rows has no key; with_tuple_id adds a
surrogate key, a tuple id, that makes the rows distinct first.
"""
from __future__ import annotations
from collections import Counter
from collections.abc import Sequence
def is_key(schema: Sequence[str], rows: Counter, key: Sequence[str]) -> bool:
"""K is a key of this instance: no NULL in K and no two rows (or copies) share K."""
ki = [tuple(schema).index(a) for a in key]
seen = set()
for t, c in rows.items():
k = tuple(t[i] for i in ki)
if None in k or c > 1 or k in seen:
return False
seen.add(k)
return True
def fragment(schema: Sequence[str], rows: Counter, key: Sequence[str], groups: Sequence[Sequence[str]]) -> list:
"""The fragments (schema_i, rows_i), with schema_i = K followed by G_i."""
schema, key = tuple(schema), tuple(key)
out = []
for g in groups: # @line L1
fs = key + tuple(a for a in g if a not in key)
pos = [schema.index(a) for a in fs]
proj: Counter = Counter()
for t, c in rows.items():
proj[tuple(t[i] for i in pos)] += c # @line L2
out.append((fs, proj))
return out
def reconstruct(fragments: Sequence[tuple], key: Sequence[str], schema: Sequence[str]) -> Counter:
"""The join of the fragments on K, with the columns put back in the order of schema.
The join is a hash join on K; a NULL in K matches nothing."""
key, schema = tuple(key), tuple(schema)
cur_schema, cur = fragments[0]
for fs, rows in fragments[1:]: # @line L3
common = [a for a in cur_schema if a in fs]
rest = [a for a in fs if a not in common]
table: dict = {}
for t, c in rows.items():
k = tuple(t[fs.index(a)] for a in common)
if None not in k:
table.setdefault(k, []).append((t, c))
out: Counter = Counter()
for t, c in cur.items(): # @line L4
k = tuple(t[cur_schema.index(a)] for a in common)
for u, d in table.get(k, ()):
out[t + tuple(u[fs.index(a)] for a in rest)] += c * d
cur_schema, cur = cur_schema + tuple(rest), out
pos = [cur_schema.index(a) for a in schema]
return Counter({tuple(t[i] for i in pos): c for t, c in cur.items()}) # @line L5
def is_complete(schema: Sequence[str], fragments: Sequence[tuple]) -> bool:
return set(schema) <= {a for fs, _ in fragments for a in fs}
def is_disjoint(key: Sequence[str], fragments: Sequence[tuple]) -> bool:
seen = set()
for fs, _ in fragments:
for a in fs:
if a in key:
continue
if a in seen:
return False
seen.add(a)
return True
def with_tuple_id(schema: Sequence[str], rows: Counter, name: str = "tid") -> tuple:
"""Give each copy of each row its own id: the result has the key (name,)."""
out: Counter = Counter()
n = 0
for t in sorted(rows, key=repr):
for _ in range(rows[t]):
out[(n,) + t] = 1
n += 1
return (name,) + tuple(schema), out
test_vertical_fragmentation.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vertical-fragmentation/. The authors are listed in prov/XEF5EY.jsonl.
import random
from collections import Counter
from functools import reduce
import pytest
import dbrel
from vertical_fragmentation import fragment, is_complete, is_disjoint, is_key, reconstruct, with_tuple_id
EMP = ("eno", "name", "salary", "dept")
EMP_ROWS = Counter({(1, "Ann", 5000, "R&D"): 1, (2, "Bo", 4000, "Sales"): 1,
(3, "Cy", None, "R&D"): 1, (4, "Di", 4000, None): 1})
def rel(schema, rows):
return dbrel.Relation(schema, rows)
def ref_reconstruct(frags, schema):
"""The join of the fragments by the reference operator."""
return reduce(dbrel.natural_join, (rel(fs, rows) for fs, rows in frags)).reorder(schema)
def test_page_example():
frags = fragment(EMP, EMP_ROWS, ("eno",), [("name", "dept"), ("salary",)])
assert [fs for fs, _ in frags] == [("eno", "name", "dept"), ("eno", "salary")]
assert is_complete(EMP, frags) and is_disjoint(("eno",), frags)
assert reconstruct(frags, ("eno",), EMP) == EMP_ROWS
assert ref_reconstruct(frags, EMP) == rel(EMP, EMP_ROWS)
def test_page_example_without_the_key():
# Fragments that share only dept, which is not a key: the join adds rows that were never in EMP.
frags = [(("name", "dept"), Counter({("Ann", "R&D"): 1, ("Cy", "R&D"): 1})),
(("dept", "salary"), Counter({("R&D", 5000): 1, ("R&D", None): 1}))]
joined = ref_reconstruct(frags, ("name", "dept", "salary"))
assert len(joined) == 4 # two of them are spurious
def random_keyed(rng, attrs, n):
keys = rng.sample(range(100), n)
rows = Counter()
for k in keys:
rows[(k,) + tuple(rng.choice([None, 0, 1, 2]) for _ in attrs)] += 1
return ("K",) + tuple(attrs), rows
def random_groups(rng, attrs):
attrs = list(attrs)
rng.shuffle(attrs)
cuts = sorted(rng.sample(range(1, len(attrs)), rng.randint(0, len(attrs) - 1))) if len(attrs) > 1 else []
bounds = [0] + cuts + [len(attrs)]
return [tuple(attrs[bounds[i]:bounds[i + 1]]) for i in range(len(bounds) - 1)]
@pytest.mark.parametrize("seed", range(80))
def test_lossless_with_a_key(seed):
rng = random.Random(seed)
attrs = [f"A{i}" for i in range(rng.randint(1, 5))]
schema, rows = random_keyed(rng, attrs, rng.randint(0, 12))
groups = random_groups(rng, attrs)
assert is_key(schema, rows, ("K",))
frags = fragment(schema, rows, ("K",), groups)
assert is_complete(schema, frags) and is_disjoint(("K",), frags)
for fs, f in frags:
assert rel(fs, f) == dbrel.project(rel(schema, rows), fs)
assert reconstruct(frags, ("K",), schema) == rows
assert ref_reconstruct(frags, schema) == rel(schema, rows)
@pytest.mark.parametrize("seed", range(60))
def test_bag_without_a_key_needs_a_tuple_id(seed):
rng = random.Random(1000 + seed)
r = dbrel.random_relation(rng, ("A", "B", "C"), rng.randint(1, 12), domain=2)
frags = fragment(r.schema, r.rows, ("A",), [("B",), ("C",)])
joined = reconstruct(frags, ("A",), r.schema)
assert rel(r.schema, joined) == ref_reconstruct(frags, r.schema)
# Without a key the join holds every row of R, but it can hold more rows or more copies.
assert all(joined[t] >= c for t, c in r.rows.items())
tschema, trows = with_tuple_id(r.schema, r.rows)
assert is_key(tschema, trows, ("tid",))
tfrags = fragment(tschema, trows, ("tid",), [("A", "B"), ("C",)])
back = reconstruct(tfrags, ("tid",), tschema)
assert back == trows
assert dbrel.project(rel(tschema, back), r.schema) == r
def test_lossy_case_occurs():
r = Counter({(0, 0, 0): 1, (0, 1, 1): 1})
frags = fragment(("A", "B", "C"), r, ("A",), [("B",), ("C",)])
assert reconstruct(frags, ("A",), ("A", "B", "C")) == Counter({(0, 0, 0): 1, (0, 0, 1): 1,
(0, 1, 0): 1, (0, 1, 1): 1})
def test_null_in_the_key_loses_the_row():
r = Counter({(None, 1, 2): 1, (5, 1, 2): 1})
assert not is_key(("K", "A", "B"), r, ("K",))
frags = fragment(("K", "A", "B"), r, ("K",), [("A",), ("B",)])
assert reconstruct(frags, ("K",), ("K", "A", "B")) == Counter({(5, 1, 2): 1})
def test_rules():
frags = fragment(EMP, EMP_ROWS, ("eno",), [("name",), ("name", "salary")])
assert not is_disjoint(("eno",), frags) and not is_complete(EMP, frags)
assert reconstruct(frags, ("eno",), ("eno", "name", "salary")) == dbrel.project(rel(EMP, EMP_ROWS),
("eno", "name", "salary")).rows
References
- Shamkant Navathe, Stefano Ceri, Gio Wiederhold and Jinglie Dou, Vertical partitioning algorithms for database design, ACM Transactions on Database Systems 9(4), 1984, pages 680 to 710, the attribute usage and attribute affinity matrices, the clustering of the affinity matrix by the bond energy algorithm, and the split of the clustered attributes into fragments
- M. Tamer Özsu and Patrick Valduriez, Principles of Distributed Database Systems, fourth edition, Springer, 2020, Chapter 2, Distributed and Parallel Database Design, the section on vertical fragmentation and the rules of completeness, reconstruction and disjointness
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag XEF5EY Edit this page History Report an error Markdown