Algorithm Search⌘K

Algorithmcore

Tableau test for lossless join

Also called Aho-Beeri-Ullman lossless join test, chase test for lossless join.

Decide if a decomposition into any number of parts has a lossless join under FDs. Chase a tableau with one row per part; the join is lossless exactly when some row becomes all distinguished.

Time
O(k^2 a (1 + m log k)) worst
Space
O(k a + m) extra
Where
a = the number of attributes; k = the number of parts; m = the total size of the functional dependencies
Properties
deterministicexactnot externalnot in placeofflineiterative
Origin
Alfred V. Aho, Catriel Beeri, Jeffrey D. Ullman, 1979

The tableau test decides whether a decomposition of a schema into kk parts has a lossless join under a set of functional dependencies. It builds a table of symbols with one row for each part and applies the dependencies to it as repair rules. The lossless join page defines the property and proves the test for two parts, which is one attribute closure. This page is the general test for any number of parts, due to Aho, Beeri and Ullman (1979). It is the chase with functional dependencies only, which is why it runs in polynomial time.

In plain words

You split a table into smaller tables and want to know if joining them always gives back exactly the original rows.

Make a small grid with one line for each smaller table and one column for each column of the original. On each line, mark the columns its smaller table keeps as "known". Fill the other places with "unknown" marks of that line only.

Now apply the rules. If a rule says that rows which agree on some columns must also agree on another column, and two lines agree on those columns, make their marks in the other column the same. Prefer "known" when one of the two is known. Repeat until nothing changes.

If some line is now known in every column, the split is always safe. If not, the grid itself is a table that obeys the rules and gains a row when you split and join it.

The problem

Let UU be a set of aa attributes and FF a finite set of functional dependencies (FDs) over UU, with total size mm. We use set semantics: a relation is a finite set of tuples. A decomposition is a list ρ=(R1,…,Rk)\rho = (R_1, \ldots, R_k) of subsets of UU with R1∪⋯∪Rk=UR_1 \cup \cdots \cup R_k = U. For a relation rr over UU write

mρ(r)=πR1(r)⋈πR2(r)⋈⋯⋈πRk(r).m_\rho(r) = \pi_{R_1}(r) \bowtie \pi_{R_2}(r) \bowtie \cdots \bowtie \pi_{R_k}(r).

Always r⊆mρ(r)r \subseteq m_\rho(r). The decomposition is lossless under FF when mρ(r)=rm_\rho(r) = r for each relation rr that satisfies FF. In the notation of join dependencies, the question is whether FF implies the join dependency ⋈[R1,…,Rk]\bowtie[R_1, \ldots, R_k].

Input: UU, FF and ρ\rho. Output: lossless or lossy. When the answer is lossy, the test can also return a relation that satisfies FF and is not equal to mρm_\rho of itself.

The algorithm

A tableau is a table with kk rows and one column for each attribute of UU. Its entries are symbols. Each column has its own symbols, and two columns never share one. The symbol 00 is the distinguished symbol of a column (the textbooks write aja_j), and the positive integers are the other symbols (the textbooks write bijb_{ij}).

  1. LOSSLESS-JOIN-TEST(U, F, R₁, …, Rₖ)
  2. 1T ← k rows over U; row i has 0 in each column of Rᵢ and the symbol i elsewhere
  3. 2repeat
  4. 3changed ← false
  5. 4for each FD X → Y in F do
  6. 5for each group G of rows of T that agree on every column of X do
  7. 6for each A ∈ Y such that the rows of G have two or more symbols in column A do
  8. 7s ← the smallest of these symbols
  9. 8in column A of every row of T, replace each of these symbols by s; changed ← true
  10. 9until not changed
  11. 10if some row of T is all 0 then return (lossless, T)
  12. 11return (lossy, T)

Line L1 encodes the decomposition: row ii stands for a tuple that agrees with the target tuple on RiR_i and is free elsewhere. Lines L5 to L8 are the FD rule. Rows that agree on XX must agree on YY in any relation that satisfies X→YX \to Y, so their symbols in each column of YY are made equal. Line L7 keeps the smallest symbol, so 00 always wins and a known value is never lost. Line L8 renames in the whole column, not only in GG, because equal symbols stand for equal values everywhere.

Example

Let U=ABCDEU = ABCDE, F={A→C, B→C, C→D, DE→C, CE→A}F = \{A \to C,\ B \to C,\ C \to D,\ DE \to C,\ CE \to A\} and ρ=(AD,AB,BE,CDE,AE)\rho = (AD, AB, BE, CDE, AE). The table lists the rows after each FD that changes the tableau. The columns are A,B,C,D,EA, B, C, D, E.

step row 1 (ADAD) row 2 (ABAB) row 3 (BEBE) row 4 (CDECDE) row 5 (AEAE)
start (L1) 0 1 1 0 1 0 0 2 2 2 3 0 3 3 0 4 4 0 0 0 0 5 5 5 0
A→CA \to C: rows 1, 2, 5 agree on AA 0 1 1 0 1 0 0 1 2 2 3 0 3 3 0 4 4 0 0 0 0 5 1 5 0
B→CB \to C: rows 2, 3 agree on BB 0 1 1 0 1 0 0 1 2 2 3 0 1 3 0 4 4 0 0 0 0 5 1 5 0
C→DC \to D: rows 1, 2, 3, 5 agree on CC 0 1 1 0 1 0 0 1 0 2 3 0 1 0 0 4 4 0 0 0 0 5 1 0 0
DE→CDE \to C: rows 3, 4, 5 agree on DEDE 0 1 0 0 1 0 0 0 0 2 3 0 0 0 0 4 4 0 0 0 0 5 0 0 0
CE→ACE \to A: rows 3, 4, 5 agree on CECE 0 1 0 0 1 0 0 0 0 2 0 0 0 0 0 0 4 0 0 0 0 5 0 0 0

In the step for DE→CDE \to C, the group holds the symbols 00 and 11 in column CC, and the symbol 11 is replaced in all four rows that hold it, rows 1 and 2 included. The second round changes nothing. Row 3 is all 00, so the decomposition is lossless.

Each of the five FDs is needed. Without CE→ACE \to A, the chase stops one step earlier with row 3 equal to (3,0,0,0,0)(3, 0, 0, 0, 0) and no row all 00. The five final rows, read as tuples, satisfy the other four FDs. Their projections on ADAD, ABAB, BEBE, CDECDE and AEAE (from rows 1, 2, 3, 4 and 5) all contain an all-00 tuple, so (0,0,0,0,0)(0,0,0,0,0) is in the join and not in the relation.

Correctness

The proof has two directions and rests on one invariant.

Lossless answer. Let rr satisfy FF and let w∈mρ(r)w \in m_\rho(r), with tuples ti∈rt_i \in r that agree with ww on RiR_i. Map the symbol 00 of column AA to w[A]w[A] and the symbol ii to ti[A]t_i[A]. Then row ii of the start maps to ti∈rt_i \in r. A step merges symbols that occur in rows which agree on XX. Their images are tuples of rr that agree on XX, so they agree on YY, and the merged symbols already had the same image. So after each step every row still maps into rr. If a row ends all 00, it maps to ww, so w∈rw \in r.

Lossy answer. The final tableau satisfies FF, because the last round finds no group with two symbols in a column of a right side. The symbol 00 is never replaced, so row ii still holds 00 on RiR_i. So the all-00 tuple is in mρ(T)m_\rho(T), and it is not a row of TT. Thus TT is a counterexample.

Two parts. For k=2k = 2 the two rows agree exactly on the columns of the closure (R1∩R2)+(R_1 \cap R_2)^+ at the end, so the test reduces to the closure test of the lossless join page. The proof file has all the details and the bound on the rounds.

Proof: The tableau test stops and decides whether a decomposition has a lossless join under functional dependenciesfull

We use the pseudocode of the page and set semantics. UU is a set of aa attributes, FF is a finite set of functional dependencies (FDs) over UU of total size mm, and ρ=(R1,…,Rk)\rho = (R_1, \ldots, R_k) is a decomposition with R1∪⋯∪Rk=UR_1 \cup \cdots \cup R_k = U. For a relation rr over UU write mρ(r)=πR1(r)⋈⋯⋈πRk(r)m_\rho(r) = \pi_{R_1}(r) \bowtie \cdots \bowtie \pi_{R_k}(r). The decomposition is lossless under FF when mρ(r)=rm_\rho(r) = r for each finite relation rr over UU that satisfies FF. For each rr we have r⊆mρ(r)r \subseteq m_\rho(r), since each tuple t∈rt \in r agrees with itself on each RiR_i. So the decomposition is lossless exactly when mρ(r)⊆rm_\rho(r) \subseteq r for each such rr.

The tableau TT has the rows 1,…,k1, \ldots, k. Each column has its own symbols: 00, the distinguished symbol, and the positive integers. Line L1 gives row ii the symbol 00 in each column of RiR_i and the symbol ii in each other column. A step is one execution of line L8: in one column AA it replaces a set SS of two or more symbols, which occur in column AA of rows that agree on the left side XX of an FD X→YX \to Y with A∈YA \in Y, by s=min⁡Ss = \min S in each row.

Claim. LOSSLESS-JOIN-TEST(U,F,R1,…,Rk)(U, F, R_1, \ldots, R_k) stops after at most a(k−1)+1a(k-1) + 1 rounds of line L2. It returns lossless exactly when ρ\rho is lossless under FF. When it returns lossy, the final tableau T∗T^*, read as a relation whose values are the symbols, satisfies FF and has mρ(T∗)≠T∗m_\rho(T^*) \ne T^*.

Lemma 1 (symbols). (a) A step removes at least one symbol from column AA, and no step adds a symbol to a column. (b) The symbol 00 is never replaced. (c) If row ii holds 00 in column AA at some time, it holds 00 there at each later time.

Proof. (a) The step replaces each symbol of SS by s∈Ss \in S, so the symbols of S−{s}S - \{s\}, at least one, leave column AA, and no new symbol appears. (b) 00 is the smallest symbol, so if 0∈S0 \in S then s=0s = 0. (c) follows from (b). □\square

Lemma 2 (termination and round bound). Column AA starts with at most kk symbols, one in each row. A column with one symbol allows no step. By Lemma 1(a), each step lowers the number of symbols in its column by at least one, so there are at most k−1k - 1 steps in each column and at most a(k−1)a(k-1) steps in all. Each round of line L2 other than the last one sets changed at line L8, so it makes a step. So there are at most a(k−1)+1a(k-1) + 1 rounds. □\square

Lemma 3 (the final tableau satisfies FF). In the last round, changed stays false, so line L8 does not run. So for each FD X→YX \to Y (line L4) and each group GG of rows that agree on XX (line L5), the rows of GG have one symbol in each column of YY (line L6). The tableau does not change in this round, so these checks are on T∗T^*. So any two rows of T∗T^* that agree on XX agree on YY, and T∗T^* satisfies X→YX \to Y. □\square

Lemma 4 (one step keeps an embedding). A valuation hh maps each symbol of column AA to a value of attribute AA, and maps a row ww to the tuple h(w)h(w) with h(w)[A]=h(w[A])h(w)[A] = h(w[A]). Say that hh embeds TT in rr when h(w)∈rh(w) \in r for each row ww. Let rr satisfy FF, let hh embed TT in rr, and let a step change TT into T′T'. Then hh maps all symbols of SS to the same value, so hh embeds T′T' in rr.

Proof. The rows of GG agree on XX, so their images under hh are tuples of rr that agree on XX. As rr satisfies X→YX \to Y and A∈YA \in Y, these tuples agree on AA. Each symbol of SS occurs in column AA of some row of GG, so hh maps all of SS to one value, and in particular h(x)=h(s)h(x) = h(s) for each x∈Sx \in S. Each row of T′T' is a row of TT with some entries x∈Sx \in S changed to ss, so it has the same image under hh, which is in rr. □\square

Proof of the claim: a lossless answer is right. Suppose some row of T∗T^* is all 00. Let rr satisfy FF and let w∈mρ(r)w \in m_\rho(r). Then there are tuples t1,…,tk∈rt_1, \ldots, t_k \in r with ti[Ri]=w[Ri]t_i[R_i] = w[R_i]. In column AA let h(0)=w[A]h(0) = w[A] and h(i)=ti[A]h(i) = t_i[A]. The symbol ii occurs only in row ii at the start, so hh is well defined. Row ii maps to tit_i: on RiR_i the entry is 00 and h(0)=w[A]=ti[A]h(0) = w[A] = t_i[A], and off RiR_i the entry is ii and h(i)=ti[A]h(i) = t_i[A]. So hh embeds the start in rr. By Lemma 4 and induction on the steps, hh embeds T∗T^* in rr, and h(0)=w[A]h(0) = w[A] is not changed. So the all-00 row of T∗T^* maps to ww, and w∈rw \in r. Thus mρ(r)⊆rm_\rho(r) \subseteq r, and ρ\rho is lossless under FF. □\square

Proof of the claim: a lossy answer is right. Suppose no row of T∗T^* is all 00. By Lemma 3, T∗T^* satisfies FF. By Lemma 1(c), row ii of T∗T^* holds 00 in each column of RiR_i, so the projection of row ii on RiR_i is all 00. These projections agree on all common attributes, since all entries are 00, so the all-00 tuple is in mρ(T∗)m_\rho(T^*). It is not in T∗T^*. So T∗T^* is a finite relation that satisfies FF with mρ(T∗)≠T∗m_\rho(T^*) \ne T^*, and ρ\rho is not lossless under FF. □\square

The case k=2k = 2. Let ρ=(R1,R2)\rho = (R_1, R_2) and X=R1∩R2X = R_1 \cap R_2. Each column holds 00 in at least one row, because the parts cover UU. The rows agree on a set of columns, the agreement set, which starts as XX, and both rows hold 00 in each column of it. A step for V→WV \to W applies exactly when VV is in the agreement set and some column of WW is not, and it adds the columns of WW to the agreement set. This is one step of the attribute closure of XX under FF, so at the end the agreement set is X+X^+. Row 11 is all 00 exactly when R2−R1⊆X+R_2 - R_1 \subseteq X^+, that is X→R2X \to R_2, and row 22 is all 00 exactly when X→R1X \to R_1. So the test agrees with the binary test of the lossless-join page.

Complexity. Store TT as kk rows of aa small integers, O(ka)O(ka) space, built in O(ka)O(ka) time at line L1. In one round, take one FD X→YX \to Y. Grouping the rows by their entries on XX (line L5) takes O(k∣X∣log⁡k)O(k|X| \log k) time by sorting, or O(k∣X∣)O(k|X|) expected time with a hash table. Line L6 looks at each row once for each attribute of YY, O(k∣Y∣)O(k|Y|) time in all. Line L8 costs O(k)O(k) for one step, and there are at most a(k−1)a(k-1) steps over the whole run by Lemma 2, so all steps together cost O(ak2)O(a k^2). So one round costs O(kmlog⁡k)O(k m \log k) apart from the steps, and with at most a(k−1)+1a(k-1) + 1 rounds the total time is

O(ka+ak2mlog⁡k+ak2)=O(k2a (1+mlog⁡k))O\bigl(ka + a k^2 m \log k + a k^2\bigr) = O\bigl(k^2 a\,(1 + m \log k)\bigr)

in the worst case. With hashing the expected time is O(k2a(1+m))O(k^2 a (1 + m)). The extra space is O(ka+m)O(ka + m) for the tableau, the groups and the FDs as column indexes. □\square

Complexity

Let kk be the number of parts, aa the number of attributes and mm the total size of FF.

  • Rounds. Each column starts with at most kk symbols, one per row, and each change at line L8 removes at least one of them. So there are at most a(k−1)a(k-1) changes, and at most a(k−1)+1a(k-1) + 1 rounds, since each round except the last one makes a change.
  • One round. Grouping the rows on XX by sorting costs O(k∣X∣log⁡k)O(k |X| \log k) for one FD, so a round costs O(kmlog⁡k)O(k m \log k) apart from line L8. One change at line L8 costs O(k)O(k), and all changes together cost O(ak2)O(a k^2).
  • Total. O(k2a(1+mlog⁡k))O(k^2 a (1 + m \log k)) time in the worst case, or O(k2a(1+m))O(k^2 a (1 + m)) expected time with a hash table for the groups. The extra space is O(ka+m)O(ka + m) for the tableau and the FDs.

This is polynomial in the size of the input. The answer does not need mρ(r)m_\rho(r) for any real relation, which can have up to ∣r∣k|r|^k tuples.

Properties

  • Exact. A lossless answer is a proof for every relation that satisfies FF, and a lossy answer comes with a counterexample of kk tuples.
  • Independent of the order. The order of the FDs and of the parts does not change the answer, because the final tableau of the chase is unique up to a renaming of the symbols.
  • Small counterexamples. If a decomposition into kk parts is lossy under FF, there is a counterexample with at most kk tuples, and the final tableau is one.
  • No preprocessing. FF need not be a minimal cover, and implied FDs need not be listed.

Variants and improvements

  • FDs and MVDs or JDs. If the constraints include multivalued dependencies or join dependencies, add the JD rule of the chase, which adds rows. The test then still decides the question, but the tableau can grow, and the polynomial bound is lost.
  • Union-find. Keep the symbols of each column in a union-find structure. Line L8 then merges two classes and does not rewrite the column, and the groups are found on the class representatives.
  • Two parts. For k=2k = 2, compute (R1∩R2)+(R_1 \cap R_2)^+ with the attribute closure algorithm in linear time. This is Heath's theorem together with its converse for FDs.
  • Decompositions that are lossless by construction. BCNF decomposition splits on an FD at each step, so each split is lossless by Heath's theorem and the whole result is lossless. 3NF synthesis adds a part that holds a key, and the row of that part becomes all 00 in the test.

When to use it

Use the test when a designer proposes a decomposition with three or more parts, or when parts are merged or split by hand after an algorithm has run. For two parts, the closure test is simpler and faster. For a decomposition produced by the BCNF or 3NF algorithms, the test is not needed, but it is a good check of an implementation of those algorithms. When the answer is lossy, show the final tableau: its rows are a small instance that loses information, which helps to explain the problem.

Pitfalls

  • Testing two parts at a time. With F={A→B, C→D}F = \{A \to B,\ C \to D\} and ρ=(AB,CD,AC)\rho = (AB, CD, AC), the pair ABAB, CDCD has no common attribute, so its join is a cross product. Yet the three parts together are lossless. A lossless join is a property of the whole decomposition, not of each pair.
  • Keeping the wrong symbol. If a free symbol replaces 00, the test can miss an all-00 row and answer lossy for a lossless decomposition.
  • Renaming only inside the group. The replacement at line L8 must cover the whole column. Otherwise a later FD sees two different symbols for one value.
  • Stopping after one pass. A later FD can create agreement that an earlier FD needs. The loop must run until a whole round changes nothing.
  • Using only the FDs that fit in one part. The test needs FF over all of UU. In the example, A→CA \to C, B→CB \to C and CE→ACE \to A fit in no part, and without any one of them the answer is lossy.

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.

lossless_join.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lossless-join-test/. The authors are listed in prov/R7WCET.jsonl.
"""The tableau test of Aho, Beeri and Ullman (1979) for a lossless join under functional dependencies.

A tableau is a list of rows, one row per part of the decomposition. Each entry is a
symbol of its column: 0 is the distinguished symbol, and the positive integer i is the
symbol that row i - 1 has at the start. Symbols of different columns are never compared.
"""


def start_tableau(attrs, parts):
    """Row i has 0 in each column of parts[i] and the symbol i + 1 in each other column."""
    return [[0 if a in p else i + 1 for a in attrs] for i, p in enumerate(parts)]  # @line L1


def chase_fds(tableau, fds):
    """Apply the FD rule until no FD is violated, in place.

    fds holds pairs (lhs, rhs) of lists of column indexes. Returns the number of rounds,
    the last round included (it changes nothing).
    """
    rounds = 0
    changed = True
    while changed:  # @line L2
        changed = False  # @line L3
        rounds += 1
        for lhs, rhs in fds:  # @line L4
            groups = {}
            for row in tableau:  # @line L5: group the rows by their symbols on X
                groups.setdefault(tuple(row[j] for j in lhs), []).append(row)
            for key in sorted(groups):
                rows = groups[key]
                for j in rhs:  # @line L6
                    syms = {row[j] for row in rows}
                    if len(syms) > 1:
                        s = min(syms)  # @line L7
                        for row in tableau:  # @line L8: rename in the whole column
                            if row[j] in syms:
                                row[j] = s
                        changed = True
    return rounds  # @line L9: the last round changed nothing


def lossless_join_test(attrs, fds, parts):
    """Decide whether the decomposition parts of the attributes attrs is lossless under fds.

    attrs: a sequence of distinct attribute names, the columns in order.
    fds: a sequence of pairs (lhs, rhs); each side is an iterable of attribute names.
    parts: a nonempty sequence of iterables of attribute names whose union is attrs.
    Returns (lossless, tableau). If lossless is False, the final tableau, read as a relation
    with one tuple per row, satisfies fds and is not the join of its projections on the parts.
    """
    attrs = list(attrs)
    col = {a: j for j, a in enumerate(attrs)}
    if len(col) != len(attrs):
        raise ValueError("the attribute names must be distinct")
    ps = [frozenset(p) for p in parts]
    if not ps or frozenset().union(*ps) != frozenset(attrs):
        raise ValueError("the parts must cover exactly the attributes")
    idx = []
    for lhs, rhs in fds:
        names = set(lhs) | set(rhs)
        if not names <= col.keys():
            raise ValueError("an FD uses an unknown attribute")
        idx.append((sorted(col[a] for a in set(lhs)), sorted(col[a] for a in set(rhs))))
    tableau = start_tableau(attrs, ps)
    chase_fds(tableau, idx)
    for row in tableau:
        if all(x == 0 for x in row):  # @line L10
            return True, tableau
    return False, tableau  # @line L11
lossless_join_test.py 8 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lossless-join-test/. The authors are listed in prov/R7WCET.jsonl.
"""Entry point named after the slug. The code is in lossless_join.py,
because the tools treat a file whose name ends in _test as a test file."""

from lossless_join import chase_fds, lossless_join_test, start_tableau

__all__ = ["chase_fds", "lossless_join_test", "start_tableau"]
test_lossless_join_test.py 240 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lossless-join-test/. The authors are listed in prov/R7WCET.jsonl.

import random
from itertools import product

import pytest

from lossless_join_test import chase_fds, lossless_join_test, start_tableau


def closure(x, fds):
    res = set(x)
    changed = True
    while changed:
        changed = False
        for lhs, rhs in fds:
            if set(lhs) <= res and not set(rhs) <= res:
                res |= set(rhs)
                changed = True
    return res


def satisfies(rel, fds):
    """rel is a set of tuples over the columns 0 .. a - 1; fds use column indexes."""
    for lhs, rhs in fds:
        seen = {}
        for t in rel:
            key = tuple(t[j] for j in lhs)
            val = tuple(t[j] for j in rhs)
            if seen.setdefault(key, val) != val:
                return False
    return True


def join_of_projections(rel, parts, a):
    """The natural join of the projections of rel on parts, built one part at a time."""
    partial = {tuple([None] * a)}
    for p in parts:
        cols = sorted(p)
        proj = {tuple(t[j] for j in cols) for t in rel}
        nxt = set()
        for u in partial:
            for v in proj:
                if all(u[j] is None or u[j] == x for j, x in zip(cols, v)):
                    w = list(u)
                    for j, x in zip(cols, v):
                        w[j] = x
                    nxt.add(tuple(w))
        partial = nxt
    return partial


def rgs(k):
    """All set partitions of k rows, as restricted growth strings."""
    out = []

    def rec(prefix, top):
        if len(prefix) == k:
            out.append(tuple(prefix))
            return
        for x in range(top + 2):
            rec(prefix + [x], max(top, x))

    rec([], -1)
    return out


def all_small_relations(a, k):
    """Each relation with at most k tuples over a columns, up to a renaming of each column."""
    cols = rgs(k)
    for choice in product(cols, repeat=a):
        yield {tuple(choice[j][i] for j in range(a)) for i in range(k)}


def random_instance(rng, a, k, nfd):
    attrs = [chr(ord("A") + j) for j in range(a)]
    fds = []
    for _ in range(nfd):
        lhs = rng.sample(attrs, rng.randint(0 if rng.random() < 0.1 else 1, 2))
        rhs = rng.sample(attrs, rng.randint(1, 2))
        fds.append(("".join(lhs), "".join(rhs)))
    parts = [set(rng.sample(attrs, rng.randint(1, a - 1))) for _ in range(k)]
    for x in attrs:
        if not any(x in p for p in parts):
            parts[rng.randrange(k)].add(x)
    return attrs, fds, ["".join(sorted(p)) for p in parts]


def to_cols(attrs, fds, parts):
    col = {x: j for j, x in enumerate(attrs)}
    f = [([col[x] for x in lhs], [col[x] for x in rhs]) for lhs, rhs in fds]
    p = [{col[x] for x in q} for q in parts]
    return f, p


def brute_lossless(attrs, fds, parts):
    a, k = len(attrs), len(parts)
    f, p = to_cols(attrs, fds, parts)
    for rel in all_small_relations(a, k):
        if satisfies(rel, f) and join_of_projections(rel, p, a) != rel:
            return False
    return True


def test_ullman_five_parts():
    attrs = "ABCDE"
    fds = [("A", "C"), ("B", "C"), ("C", "D"), ("DE", "C"), ("CE", "A")]
    parts = ["AD", "AB", "BE", "CDE", "AE"]
    ok, t = lossless_join_test(attrs, fds, parts)
    assert ok
    assert t[2] == [0, 0, 0, 0, 0]
    assert t == [[0, 1, 0, 0, 1], [0, 0, 0, 0, 2], [0, 0, 0, 0, 0], [0, 4, 0, 0, 0], [0, 5, 0, 0, 0]]
    for drop in range(len(fds)):
        assert not lossless_join_test(attrs, fds[:drop] + fds[drop + 1:], parts)[0]


def test_abcd_cases():
    fds = [("A", "B"), ("C", "D")]
    ok, t = lossless_join_test("ABCD", fds, ["AB", "CD", "AC"])
    assert ok and [0, 0, 0, 0] in t
    ok, t = lossless_join_test("ABCD", fds, ["AB", "CD", "BD"])
    assert not ok
    assert t == [[0, 0, 1, 1], [2, 2, 0, 0], [3, 0, 3, 0]]


def test_no_fds():
    rng = random.Random(1)
    for _ in range(200):
        a = rng.randint(1, 6)
        k = rng.randint(1, 4)
        attrs, _, parts = random_instance(rng, a, k, 0) if a > 1 else (["A"], [], ["A"] * k)
        if rng.random() < 0.2:
            parts.append("".join(attrs))
        ok, _ = lossless_join_test(attrs, [], parts)
        assert ok == any(set(p) == set(attrs) for p in parts)


def test_two_parts_match_closure():
    rng = random.Random(2)
    for _ in range(400):
        a = rng.randint(2, 6)
        attrs, fds, parts = random_instance(rng, a, 2, rng.randint(0, 5))
        common = set(parts[0]) & set(parts[1])
        c = closure(common, fds)
        expect = set(parts[0]) <= c or set(parts[1]) <= c
        assert lossless_join_test(attrs, fds, parts)[0] == expect


def test_lossy_tableau_is_counterexample():
    rng = random.Random(3)
    seen = 0
    for _ in range(300):
        a = rng.randint(2, 6)
        k = rng.randint(2, 5)
        attrs, fds, parts = random_instance(rng, a, k, rng.randint(0, 6))
        ok, t = lossless_join_test(attrs, fds, parts)
        if ok:
            continue
        seen += 1
        f, p = to_cols(attrs, fds, parts)
        rel = {tuple(row) for row in t}
        assert satisfies(rel, f)
        zero = tuple([0] * a)
        assert zero not in rel
        assert zero in join_of_projections(rel, p, a)
    assert seen > 50


@pytest.mark.parametrize("a,k,count,seed", [(3, 3, 40, 4), (4, 2, 60, 5), (4, 3, 15, 6), (5, 2, 40, 7)])
def test_brute_force_small(a, k, count, seed):
    rng = random.Random(seed)
    for _ in range(count):
        attrs, fds, parts = random_instance(rng, a, k, rng.randint(0, 4))
        assert lossless_join_test(attrs, fds, parts)[0] == brute_lossless(attrs, fds, parts)


def test_random_legal_relations():
    rng = random.Random(8)
    hits = 0
    for _ in range(300):
        a = rng.randint(2, 5)
        k = rng.randint(2, 4)
        attrs, fds, parts = random_instance(rng, a, k, rng.randint(1, 5))
        ok, _ = lossless_join_test(attrs, fds, parts)
        if not ok:
            continue
        f, p = to_cols(attrs, fds, parts)
        rel = set()
        for _ in range(8):
            t = tuple(rng.randrange(3) for _ in range(a))
            if satisfies(rel | {t}, f):
                rel.add(t)
        assert join_of_projections(rel, p, a) == rel
        hits += 1
    assert hits > 30


def test_round_bound_and_fixpoint():
    rng = random.Random(9)
    for _ in range(300):
        a = rng.randint(1, 7)
        k = rng.randint(1, 6)
        if a == 1:
            attrs, fds, parts = ["A"], [("A", "A")], ["A"] * k
        else:
            attrs, fds, parts = random_instance(rng, a, k, rng.randint(0, 8))
        f, p = to_cols(attrs, fds, parts)
        t = start_tableau(attrs, [set(q) for q in parts])
        rounds = chase_fds(t, f)
        assert 1 <= rounds <= a * (k - 1) + 1
        assert satisfies({tuple(row) for row in t}, f)
        assert chase_fds(t, f) == 1


def test_order_does_not_matter():
    rng = random.Random(10)
    for _ in range(300):
        a = rng.randint(2, 6)
        k = rng.randint(2, 5)
        attrs, fds, parts = random_instance(rng, a, k, rng.randint(0, 6))
        ok = lossless_join_test(attrs, fds, parts)[0]
        fds2 = fds[:]
        parts2 = parts[:]
        rng.shuffle(fds2)
        rng.shuffle(parts2)
        assert lossless_join_test(attrs, fds2, parts2)[0] == ok


def test_bad_input():
    with pytest.raises(ValueError):
        lossless_join_test("AAB", [], ["AB"])
    with pytest.raises(ValueError):
        lossless_join_test("ABC", [], ["AB"])
    with pytest.raises(ValueError):
        lossless_join_test("AB", [], ["AB", "BX"])
    with pytest.raises(ValueError):
        lossless_join_test("AB", [("A", "Z")], ["AB"])
    with pytest.raises(ValueError):
        lossless_join_test("AB", [], [])

History

Aho, Beeri and Ullman (1979) studied when the natural join of projections gives back a relation, and gave this test for functional dependencies in their paper on the theory of joins. In the same year Maier, Mendelzon and Sagiv defined the chase, which applies functional and join dependencies to a tableau, and showed that it decides the implication of these dependencies. The lossless-join test is the case of the chase with FDs only and a start with one row per part. The textbooks of Ullman (1988) and of Garcia-Molina, Ullman and Widom present it as the standard test, and Abiteboul, Hull and Vianu (1995) present it as an instance of the chase.

References

  1. Alfred V. Aho, Catriel Beeri and Jeffrey D. Ullman, The theory of joins in relational databases, ACM Transactions on Database Systems 4(3), 297 to 314 (1979), the tableau test for a lossless join under functional dependencies and its proof
  2. David Maier, Alberto O. Mendelzon and Yehoshua Sagiv, Testing implications of data dependencies, ACM Transactions on Database Systems 4(4), 455 to 469 (1979), the chase, of which the test is the case with functional dependencies only
  3. Serge Abiteboul, Richard Hull and Victor Vianu, Foundations of Databases, Addison-Wesley (1995), Chapter 8 (functional and join dependency, the chase) and Chapter 11 (design and dependencies)
  4. Jeffrey D. Ullman, Principles of Database and Knowledge-Base Systems, Volume I, Computer Science Press (1988), Chapter 7 (design theory for relational databases), the test for a lossless join with a tableau
  5. Hector Garcia-Molina, Jeffrey D. Ullman and Jennifer Widom, Database Systems, The Complete Book, second edition, Pearson (2009), Section 3.4 (the chase test for a lossless join)

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/R7WCET/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)
WritingW2 basic
  • a scene preset for the example