Algorithm Search⌘K

Algorithmadvanced

Conjunctive query minimization

Also called tableau minimization, query core computation.

Find the smallest equivalent conjunctive query by deleting atoms while the query still maps homomorphically into the smaller one.

Time
O(a k^(k+1)) worst
Space
O(a k^2) extra
Where
a = the largest arity of a relation; k = the number of atoms of the query

Conjunctive query minimization takes a conjunctive query and returns an equivalent conjunctive query with the smallest number of atoms. It tries each atom once: if the query has a homomorphism into the query without that atom, the atom is redundant, and it goes. Chandra and Merlin (1977) showed that the result is the core of the query, which is unique up to a renaming of the variables, and that no equivalent conjunctive query has fewer atoms. A query with fewer atoms needs fewer joins, so this is the classic step of semantic query optimization. Each test is an NP-complete homomorphism problem, and the whole task is NP-hard.

In plain words

A query asks for rows that match a pattern of conditions. Sometimes one condition says nothing new: every row that matches the other conditions also matches it, after you rename some helper variables. You can then delete that condition and the answers stay the same.

The algorithm goes through the conditions one at a time. For each one, it asks: can I send the whole query into the query without this condition, so that each condition lands on a condition that is still there and the output columns stay fixed? If yes, the condition goes. At the end, no condition can go, and no smaller query gives the same answers.

The problem

We use set semantics: a relation is a set of tuples, and a query returns a set of tuples. A conjunctive query is a rule

Q(xˉ): ⁣−R1(uˉ1),…,Rk(uˉk),Q(\bar x) \mathbin{:\!-} R_1(\bar u_1), \ldots, R_k(\bar u_k),

where each uˉi\bar u_i is a tuple of variables and constants and each variable of the head xˉ\bar x occurs in the body. Two queries are equivalent, Q≡Q′Q \equiv Q', if Q(D)=Q′(D)Q(D) = Q'(D) for every database DD. A homomorphism from QQ to Q′Q' is a map hh from the variables of QQ to the terms of Q′Q', the identity on constants, with h(xˉ)=xˉ′h(\bar x) = \bar x' and h(Ri(uˉi))h(R_i(\bar u_i)) an atom of the body of Q′Q' for each ii. By the Chandra-Merlin theorem, Q′⊆QQ' \subseteq Q if and only if there is a homomorphism from QQ to Q′Q'.

Input. A conjunctive query QQ with kk atoms. Output. A conjunctive query Q′≡QQ' \equiv Q with the smallest number of atoms among all conjunctive queries equivalent to QQ.

For a set SS of atoms of QQ, write QSQ_S for the query with the head of QQ and the body SS.

The algorithm

MINIMIZE tries each atom once, in the order of the body. HOM is a backtracking search for a homomorphism, one source atom at a time.

  1. MINIMIZE(Q)
  2. 1S ← the body of Q
  3. 2for each atom α of the body of Q, in order
  4. 3if HOM(Q_S, Q_{S − {α}}) succeeds then
  5. 4S ← S − {α} ▷ α is redundant
  6. 5return Q_S
  7. HOM(P, P')
  8. 6h ← the map that sends the head of P to the head of P' (fail on a clash)
  9. SEARCH(1, h), with α_1, ..., α_n the atoms of P:
  10. 7if i > n then return h
  11. 8for each atom β of P' with the relation name of α_i
  12. 9g ← h extended so that h(α_i) = β (skip β on a clash)
  13. 10if SEARCH(i + 1, g) succeeds then return its map
  14. 11fail

Line L4 is safe for any α found at line L3. The identity map is a homomorphism from QS−{α}Q_{S - \{\alpha\}} to QSQ_S, so QS⊆QS−{α}Q_S \subseteq Q_{S - \{\alpha\}}, and the map found at line L3 gives the other direction. A head variable is mapped to itself, so it still occurs in S−{α}S - \{\alpha\}, and the query stays safe. If the body has two equal atoms, line L4 deletes one copy.

The code sorts the atoms of PP so that atoms with fewer candidates in P′P' come first, which cuts the search but does not change the answer.

Example

Take Q(x,z): ⁣−E(x,y),E(y,z),E(x,w),E(w,z),E(x,u)Q(x, z) \mathbin{:\!-} E(x, y), E(y, z), E(x, w), E(w, z), E(x, u). It asks for pairs joined by a path of length two, twice, and for an edge out of xx.

atom tried homomorphism into the rest result body after the step
E(x,y)E(x, y) y↦wy \mapsto w, u↦wu \mapsto w removed E(y,z),E(x,w),E(w,z),E(x,u)E(y, z), E(x, w), E(w, z), E(x, u)
E(y,z)E(y, z) y↦wy \mapsto w removed E(x,w),E(w,z),E(x,u)E(x, w), E(w, z), E(x, u)
E(x,w)E(x, w) E(x,w)E(x, w) must go to E(x,u)E(x, u), then E(u,z)E(u, z) is missing kept the same
E(w,z)E(w, z) no atom left of the form E(⋅,z)E(\cdot, z) kept the same
E(x,u)E(x, u) u↦wu \mapsto w removed E(x,w),E(w,z)E(x, w), E(w, z)

The result is Q′(x,z): ⁣−E(x,w),E(w,z)Q'(x, z) \mathbin{:\!-} E(x, w), E(w, z). It has two atoms, and no conjunctive query with one atom is equivalent, because none of the three atoms can go. Here a different order of the body would keep E(x,y),E(y,z)E(x, y), E(y, z) instead, which is the same query up to the renaming y↔wy \leftrightarrow w.

The head matters. For Q(x,y): ⁣−E(x,z),E(y,z)Q(x, y) \mathbin{:\!-} E(x, z), E(y, z) nothing can go, since xx and yy are fixed. The Boolean query Q(): ⁣−E(x,z),E(y,z)Q() \mathbin{:\!-} E(x, z), E(y, z) folds yy onto xx and keeps one atom.

Correctness

The proofs are in the correctness proof. There are three steps.

  • Each step keeps equivalence. This is the argument under the pseudocode. So QS≡QQ_S \equiv Q at each point.
  • At the end, no single atom can be deleted. Let α\alpha be kept when the set was SαS_\alpha, and let SS be the final set, so S⊆SαS \subseteq S_\alpha. Suppose gg is a homomorphism from QSQ_S to QS−{α}Q_{S - \{\alpha\}}. Since QS≡QSαQ_S \equiv Q_{S_\alpha}, there is a homomorphism ff from QSαQ_{S_\alpha} to QSQ_S. Then g∘fg \circ f maps QSαQ_{S_\alpha} into QS−{α}Q_{S - \{\alpha\}}, whose atoms are all in Sα−{α}S_\alpha - \{\alpha\}. So the test at line L3 would have succeeded for α\alpha, a contradiction. One pass is enough.
  • If no single atom can be deleted, the query has the fewest atoms. Let Q′≡QSQ' \equiv Q_S have fewer atoms than SS. Homomorphisms ff from QSQ_S to Q′Q' and gg from Q′Q' to QSQ_S give the map g∘fg \circ f from QSQ_S to itself, whose image has at most as many atoms as Q′Q'. So some atom α∈S\alpha \in S is not in the image, and g∘fg \circ f is a homomorphism from QSQ_S to QS−{α}Q_{S - \{\alpha\}}.

Chandra and Merlin also showed that two minimal equivalent queries are the same up to a renaming of the variables. This minimal query is the core of QQ.

Proof: MINIMIZE returns an equivalent conjunctive query with the fewest atomsfull

We use set semantics and the pseudocode of the page. QQ has the head xˉ\bar x and the body BB, a list of kk atoms. For a sublist SS of BB, QSQ_S is the query with the head xˉ\bar x and the body SS. A homomorphism from PP to P′P' maps the variables of PP to the terms of P′P', is the identity on constants, sends the head of PP to the head of P′P', and sends each atom of PP to an atom of P′P'. We use the Chandra-Merlin theorem: P′⊆PP' \subseteq P if and only if there is a homomorphism from PP to P′P'. Homomorphisms compose, and a composition of homomorphisms is a homomorphism.

Termination. Line L2 runs kk times. HOM is a depth-first search of depth at most nn, with at most ∣P′∣|P'| choices at each level, so it stops.

Lemma 1 (HOM is correct). HOM(P,P′)(P, P') succeeds if and only if there is a homomorphism from PP to P′P', and then it returns one.

Proof. Line L6 fixes the image of the head variables, as each homomorphism must, and fails if one variable must go to two different terms or a constant of the head of PP is not equal to the term at that place in the head of P′P'. By induction on ii, SEARCH(i,h)(i, h) succeeds if and only if hh extends to a map that sends αi,…,αn\alpha_i, \ldots, \alpha_n to atoms of P′P' and agrees with hh: line L8 tries every atom β\beta that αi\alpha_i can go to, and line L9 keeps exactly the extensions that send αi\alpha_i to β\beta. For i=n+1i = n + 1 there is nothing left, and line L7 returns hh. □\square

Lemma 2 (each step keeps equivalence and safety). At each point, QS≡QQ_S \equiv Q, and each head variable occurs in SS.

Proof. At the start S=BS = B. Suppose it holds for SS, and line L4 sets S←S−{α}S \leftarrow S - \{\alpha\} after line L3 found a homomorphism hh from QSQ_S to QS−{α}Q_{S - \{\alpha\}}. The identity is a homomorphism from QS−{α}Q_{S - \{\alpha\}} to QSQ_S, since each atom of S−{α}S - \{\alpha\} is in SS and the heads are equal. So QS⊆QS−{α}Q_S \subseteq Q_{S - \{\alpha\}}, and hh gives QS−{α}⊆QSQ_{S - \{\alpha\}} \subseteq Q_S. For safety, let xx be a head variable. It occurs in some atom γ∈S\gamma \in S, and h(x)=xh(x) = x because hh sends the head to the head. So xx occurs in h(γ)h(\gamma), an atom of S−{α}S - \{\alpha\}. □\square

Lemma 3 (one pass is enough). Let SS be the final body. For no atom α∈S\alpha \in S is there a homomorphism from QSQ_S to QS−{α}Q_{S - \{\alpha\}}.

Proof. Each atom of SS was tried at line L3 and kept. Let SαS_\alpha be the body at the time of that test, so S⊆SαS \subseteq S_\alpha (as lists, with SS obtained from SαS_\alpha by deletions) and α∈S\alpha \in S. Suppose gg is a homomorphism from QSQ_S to QS−{α}Q_{S - \{\alpha\}}. By Lemma 2, QS≡QSαQ_S \equiv Q_{S_\alpha}, so QS⊆QSαQ_S \subseteq Q_{S_\alpha} and there is a homomorphism ff from QSαQ_{S_\alpha} to QSQ_S. Then g∘fg \circ f is a homomorphism from QSαQ_{S_\alpha} to QS−{α}Q_{S - \{\alpha\}}. Each atom of S−{α}S - \{\alpha\} is an atom of Sα−{α}S_\alpha - \{\alpha\}, so g∘fg \circ f is also a homomorphism from QSαQ_{S_\alpha} to QSα−{α}Q_{S_\alpha - \{\alpha\}}. By Lemma 1, the test at line L3 then succeeds for α\alpha, and α\alpha is not kept, a contradiction. □\square

Lemma 4 (no deletable atom means fewest atoms). Let PP be a conjunctive query with body SS such that for no α∈S\alpha \in S there is a homomorphism from PP to PS−{α}P_{S - \{\alpha\}}. Then every conjunctive query P′≡PP' \equiv P has at least ∣S∣|S| atoms.

Proof. Let P′≡PP' \equiv P have the body S′S'. By the Chandra-Merlin theorem there are homomorphisms ff from PP to P′P' and gg from P′P' to PP. The map e=g∘fe = g \circ f is a homomorphism from PP to PP. Each atom of SS goes under ff to an atom of S′S', and then under gg to one atom of SS, so the set e(S)e(S) of image atoms has at most ∣S′∣|S'| distinct atoms. If ∣S′∣<∣S∣|S'| < |S|, some atom α\alpha of SS is not in e(S)e(S), and ee is a homomorphism from PP to PS−{α}P_{S - \{\alpha\}}. This is not possible, so ∣S′∣≥∣S∣|S'| \ge |S|. If SS has two equal atoms, the identity sends PP to PP with one copy deleted, so the hypothesis already excludes equal atoms, and ∣S∣|S| counts distinct atoms. □\square

Theorem. MINIMIZE(Q)(Q) returns a conjunctive query QS≡QQ_S \equiv Q, whose body is a sublist of the body of QQ and whose head variables occur in the body, such that no conjunctive query equivalent to QQ has fewer atoms.

Proof. By Lemma 2, QS≡QQ_S \equiv Q and QSQ_S is safe. By Lemma 3, QSQ_S meets the hypothesis of Lemma 4. Each query equivalent to QQ is equivalent to QSQ_S, so by Lemma 4 it has at least ∣S∣|S| atoms. ■\blacksquare

Uniqueness up to renaming. Let QSQ_S and QTQ_T be two results, for example from two orders of the body. Both are minimum, so ∣S∣=∣T∣|S| = |T|. Take homomorphisms ff from QSQ_S to QTQ_T and gg from QTQ_T to QSQ_S. The map g∘fg \circ f sends QSQ_S to itself, and by the proof of Lemma 4 its image has all ∣S∣|S| atoms, so it is a permutation of the atoms of SS. Some power ere^r of e=g∘fe = g \circ f, with r≥1r \ge 1, fixes each atom of SS. Each variable of SS is at some place of some atom, and ere^r fixes that atom, so ere^r fixes the variable too. So ere^r is the identity, and ff is injective on the variables of SS. The image f(S)f(S) is a set of atoms of TT, and it has ∣S∣=∣T∣|S| = |T| atoms because ee is a bijection on the atoms of SS, so f(S)=Tf(S) = T, and ff maps the variables of SS onto the variables of TT. So ff is a bijection between the variables that maps the body of QSQ_S onto the body of QTQ_T and fixes the head and the constants. The two results differ only in the names of the existential variables. □\square

Complexity

Let kk be the number of atoms of QQ and aa the largest arity. The bounds are in the word RAM model and are combined complexity: the query is the input, and there is no database.

  • One test (theorem). HOM visits at most kk levels and tries at most kk target atoms per level, so its search tree has O(kk)O(k^k) nodes. Each extension costs O(a)O(a) time with a dictionary. That is O(akk)O(a k^k) time per test.
  • The whole algorithm (theorem). kk tests, so O(akk+1)O(a k^{k+1}) time in the worst case. The search keeps one map of at most aka k variables per level, which is O(ak2)O(a k^2) extra space.
  • Hardness (theorem). For a graph GG, let QGQ_G be the Boolean query with the atoms E(u,v)E(u, v) and E(v,u)E(v, u) for each edge uvuv. Take the Boolean query QK3∧QGQ_{K_3} \wedge Q_G on disjoint variables, where GG has no loops. If GG is 3-colorable, the GG part maps into the triangle and the core has 6 atoms. If the core has 6 atoms, it is the image of the triangle, so GG maps into a triangle and is 3-colorable. So computing the size of the core is NP-hard, and no polynomial algorithm is expected.
  • Polynomial cases (theorem). For acyclic queries and for queries of bounded query width, containment and minimization take polynomial time (Chekuri and Rajaraman 2000). The homomorphism test is then a constraint satisfaction problem with an acyclic or bounded treewidth structure.

Real queries have few atoms, so the exponential bound is rarely a problem in practice. This is a common observation, not a theorem.

Properties

  • The result is unique up to renaming. Every order of the atoms gives a query with the same number of atoms, and all of them are isomorphic. The atoms that stay can differ.
  • The result is a subquery. Its body is a subset of the body of QQ. No new variables or atoms come in.
  • The result is minimum, not only minimal. No conjunctive query equivalent to QQ has fewer atoms, even one with atoms that are not in QQ.
  • Constants and head variables are fixed. A homomorphism can rename only the existential variables.

Variants and improvements

  • Tableau minimization. Aho, Sagiv and Ullman (1979) write a select-project-join expression as a tableau, one row per atom, and minimize the tableau by deleting rows. This is the same algorithm. For their class of simple tableaux, they gave a polynomial-time method.
  • Minimization under dependencies. With functional or tuple-generating dependencies, first apply the chase to the query, then minimize. Atoms that the dependencies make redundant then also go.
  • Unions of conjunctive queries. Delete each member that is contained in another member, then minimize each member. The Sagiv-Yannakakis theorem shows that this gives a smallest equivalent union.
  • Cores in data exchange. The same retraction step computes the core of a universal solution, an instance with labeled nulls instead of variables. See data exchange core computation.
  • Acyclic queries. Chekuri and Rajaraman replace the backtracking search by a polynomial test when the query is acyclic or has bounded query width.

When to use it

Use it in an optimizer for queries with set semantics, such as SQL queries with SELECT DISTINCT, Datalog rule bodies, and queries over views that a user or a tool has built by combining smaller queries. Generated queries often have redundant joins, and each atom that goes saves one join. Use it also before a containment or equivalence test that you run many times, since the core is a small canonical form.

Pitfalls

  • Bag semantics. Under bag semantics, which plain SQL uses, the number of copies of each answer counts. Chaudhuri and Vardi (1993) showed that two conjunctive queries are then equivalent if and only if they are isomorphic, so no atom is redundant, and containment is much harder, with cases that are still open. Do not minimize a query without DISTINCT this way.
  • Deleting by a subset test. An atom is not redundant because its variables occur in other atoms. In Q(x): ⁣−E(x,y),E(y,x)Q(x) \mathbin{:\!-} E(x, y), E(y, x) both atoms share all variables, but neither can go. Only a homomorphism into the smaller query is a correct test.
  • Renaming a head variable. The map must send the head to itself. A search that lets x↦yx \mapsto y for a head variable xx deletes atoms that are needed.
  • Built-in predicates. With ≠\neq or << in the body the homomorphism test is no longer correct. Containment of such queries needs other methods.

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.

conjunctive_query_minimization.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/conjunctive-query-minimization/. The authors are listed in prov/PG64E9.jsonl.
"""Minimization of conjunctive queries under set semantics (Chandra and Merlin 1977).

A term is a variable (a str) or a constant (an int). An atom is (relation name, tuple of
terms). A conjunctive query is (head, body): head is a tuple of terms and body is a list of
atoms, and every variable of the head occurs in the body. The query Q(x) :- R(x, y), S(y, 3)
is (("x",), [("R", ("x", "y")), ("S", ("y", 3))]).
"""


def is_var(t) -> bool:
    return isinstance(t, str)


def variables(atoms) -> list:
    out = []
    for _, terms in atoms:
        for t in terms:
            if is_var(t) and t not in out:
                out.append(t)
    return out


def _extend(h: dict, terms, target_terms):
    """Extend the map h so that it sends terms to target_terms, or return None."""
    if len(terms) != len(target_terms):
        return None
    g = dict(h)
    for s, t in zip(terms, target_terms):
        if is_var(s):
            if s in g and g[s] != t:
                return None
            g[s] = t
        elif s != t:
            return None
    return g


def homomorphism(source, target):
    """Find a homomorphism from the query source to the query target.

    It is a map h from the variables of source to the terms of target, the identity on
    constants, with h(head of source) = head of target and h(atom) in the body of target for
    each atom of the body of source. Return the map as a dict, or None. Backtracking search,
    one source atom at a time."""
    head_s, body_s = source
    head_t, body_t = target
    start = _extend({}, head_s, head_t)                             # @line L6
    if start is None:
        return None
    by_name = {}
    for name, terms in body_t:
        by_name.setdefault(name, []).append(terms)
    order = sorted(range(len(body_s)), key=lambda i: len(by_name.get(body_s[i][0], ())))

    def search(k: int, h: dict):
        if k == len(order):                                          # @line L7
            return h
        name, terms = body_s[order[k]]
        for target_terms in by_name.get(name, ()):                   # @line L8
            g = _extend(h, terms, target_terms)                      # @line L9
            if g is not None:
                found = search(k + 1, g)                             # @line L10
                if found is not None:
                    return found
        return None                                                  # @line L11

    return search(0, start)


def is_contained(q1, q2) -> bool:
    """Q1 is contained in Q2 under set semantics iff there is a homomorphism from Q2 to Q1."""
    return homomorphism(q2, q1) is not None


def is_equivalent(q1, q2) -> bool:
    return is_contained(q1, q2) and is_contained(q2, q1)


def minimize(query, trace=None):
    """Return a minimal conjunctive query equivalent to query whose body is a subset of the
    body of query. The atoms are tried once each, in the order of the body. If trace is a list,
    append (atom, removed) for each atom tried."""
    head, body = query
    keep = list(body)                                                # @line L1
    for atom in body:                                                # @line L2
        rest = list(keep)
        rest.remove(atom)
        removed = homomorphism((head, keep), (head, rest)) is not None  # @line L3
        if removed:
            keep = rest                                              # @line L4
        if trace is not None:
            trace.append((atom, removed))
    return head, keep                                                # @line L5


def evaluate(query, db) -> set:
    """Evaluate a conjunctive query on a database under set semantics.

    db maps a relation name to a set of tuples of constants. Backtracking over the atoms."""
    head, body = query

    def search(k: int, h: dict, out: set) -> None:
        if k == len(body):
            out.add(tuple(h[t] if is_var(t) else t for t in head))
            return
        name, terms = body[k]
        for row in db.get(name, ()):
            g = _extend(h, terms, row)
            if g is not None:
                search(k + 1, g, out)

    out = set()
    search(0, {}, out)
    return out
test_conjunctive_query_minimization.py 179 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/conjunctive-query-minimization/. The authors are listed in prov/PG64E9.jsonl.

import itertools
import random

from conjunctive_query_minimization import (
    evaluate,
    homomorphism,
    is_equivalent,
    is_var,
    minimize,
    variables,
)


def brute_homomorphism(source, target) -> bool:
    """The definition: try every map from the variables of source to the terms of target."""
    head_s, body_s = source
    head_t, body_t = target
    vs = variables(body_s)
    terms = sorted({t for _, ts in body_t for t in ts} | set(head_t), key=repr)
    facts = set(body_t)
    for values in itertools.product(terms, repeat=len(vs)):
        h = dict(zip(vs, values))

        def image(ts):
            return tuple(h[t] if is_var(t) else t for t in ts)

        if image(head_s) != tuple(head_t):
            continue
        if all((name, image(ts)) in facts for name, ts in body_s):
            return True
    return False


def safe(head, body) -> bool:
    return all(not is_var(t) or t in variables(body) for t in head)


def brute_force_minimum(query) -> int:
    """The smallest number of atoms of an equivalent subquery, by trying all subsets."""
    head, body = query
    for size in range(len(body) + 1):
        for sub in itertools.combinations(body, size):
            sub = list(sub)
            if not safe(head, sub):
                continue
            q = (head, sub)
            if brute_homomorphism(query, q) and brute_homomorphism(q, query):
                return size
    return len(body)


def random_query(rng, names=("x", "y", "z", "u", "v")):
    names = list(names)
    k = rng.randint(1, 5)
    body = []
    for _ in range(k):
        if rng.random() < 0.7:
            terms = (rng.choice(names), rng.choice(names))
            body.append(("E", terms))
        else:
            terms = (rng.choice(names), rng.choice(names + [1]))
            body.append(("R", terms))
    vs = variables(body)
    head = tuple(rng.sample(vs, rng.randint(0, min(2, len(vs)))))
    return head, body


def random_db(rng):
    dom = [1, 2, 3]
    return {
        "E": {(rng.choice(dom), rng.choice(dom)) for _ in range(rng.randint(0, 6))},
        "R": {(rng.choice(dom), rng.choice(dom)) for _ in range(rng.randint(0, 4))},
    }


def edge_atoms(edges, prefix):
    body = []
    for a, b in edges:
        body.append(("E", (f"{prefix}{a}", f"{prefix}{b}")))
        body.append(("E", (f"{prefix}{b}", f"{prefix}{a}")))
    return body


def test_page_example():
    q = (("x", "z"), [
        ("E", ("x", "y")), ("E", ("y", "z")), ("E", ("x", "w")), ("E", ("w", "z")), ("E", ("x", "u")),
    ])
    trace = []
    head, body = minimize(q, trace)
    assert body == [("E", ("x", "w")), ("E", ("w", "z"))]
    assert [removed for _, removed in trace] == [True, True, False, False, True]
    assert is_equivalent(q, (head, body))


def test_constants_and_head():
    # The constant 1 blocks the map y -> 2.
    q = (("x",), [("R", ("x", "y")), ("R", ("x", 1))])
    assert minimize(q)[1] == [("R", ("x", 1))]
    q = (("x",), [("R", ("x", 2)), ("R", ("x", 1))])
    assert minimize(q)[1] == q[1]
    # A head variable can not be renamed, so nothing goes.
    q = (("x", "y"), [("E", ("x", "z")), ("E", ("y", "z"))])
    assert minimize(q)[1] == q[1]
    # The Boolean version folds y onto x.
    q = ((), [("E", ("x", "z")), ("E", ("y", "z"))])
    assert len(minimize(q)[1]) == 1
    # Duplicate atoms.
    q = (("x",), [("E", ("x", "y")), ("E", ("x", "y"))])
    assert minimize(q)[1] == [("E", ("x", "y"))]


def test_homomorphism_against_brute_force():
    rng = random.Random(11)
    for _ in range(300):
        q1, q2 = random_query(rng), random_query(rng)
        if len(q1[0]) != len(q2[0]):
            continue
        found = homomorphism(q1, q2)
        assert (found is not None) == brute_homomorphism(q1, q2)
        if found is not None:
            image = lambda ts: tuple(found[t] if is_var(t) else t for t in ts)
            assert image(q1[0]) == q2[0]
            assert all((n, image(ts)) in set(q2[1]) for n, ts in q1[1])


def test_minimize_against_brute_force():
    rng = random.Random(20261118)
    for _ in range(200):
        q = random_query(rng, ("x", "y", "z", "u"))
        head, body = minimize(q)
        rest = list(q[1])
        for atom in body:
            rest.remove(atom)
        assert safe(head, body)
        assert brute_homomorphism(q, (head, body)) and brute_homomorphism((head, body), q)
        assert len(body) == brute_force_minimum(q), q
        # No single atom of the result can go: it is minimal.
        for atom in body:
            smaller = list(body)
            smaller.remove(atom)
            assert not (safe(head, smaller) and brute_homomorphism((head, body), (head, smaller)))


def test_same_answers_on_random_databases():
    rng = random.Random(5)
    for _ in range(150):
        q = random_query(rng)
        m = minimize(q)
        for _ in range(4):
            db = random_db(rng)
            assert evaluate(q, db) == evaluate(m, db)


def test_core_size_decides_three_coloring():
    # The core of Q_G and Q_K3 together has 6 atoms iff G is 3-colorable.
    triangle = [(0, 1), (1, 2), (2, 0)]
    c5 = [(i, (i + 1) % 5) for i in range(5)]
    k4 = [(a, b) for a in range(4) for b in range(a + 1, 4)]
    for edges, colorable in ((c5, True), (k4, False), ([(0, 1), (1, 2)], True)):
        q = ((), edge_atoms(triangle, "t") + edge_atoms(edges, "g"))
        size = len(minimize(q)[1])
        assert (size == 6) == colorable
    q = ((), edge_atoms(k4, "g") + edge_atoms(triangle, "t"))
    assert len(minimize(q)[1]) == 12


def test_order_changes_the_atoms_not_the_size():
    rng = random.Random(9)
    for _ in range(100):
        head, body = random_query(rng)
        sizes = set()
        for _ in range(3):
            shuffled = list(body)
            rng.shuffle(shuffled)
            sizes.add(len(minimize((head, shuffled))[1]))
        assert len(sizes) == 1

History

Chandra and Merlin (1977) defined conjunctive queries, proved the homomorphism criterion for containment, and showed that every conjunctive query has a unique minimal equivalent query, found by deleting atoms. Aho, Sagiv and Ullman (1979) stated the method for tableaux of select-project-join expressions, proved NP-completeness for the general case, and gave polynomial methods for simple tableaux. Chaudhuri and Vardi (1993) showed that the picture changes under bag semantics. Chekuri and Rajaraman (1997, journal version 2000) gave polynomial containment and minimization for acyclic queries and for bounded query width.

References

  1. Ashok K. Chandra and Philip M. Merlin, Optimal implementation of conjunctive queries in relational data bases, Proceedings of the 9th Annual ACM Symposium on Theory of Computing (STOC), 77 to 90 (1977), the minimization of conjunctive queries by homomorphisms and the uniqueness of the minimal query up to renaming
  2. Alfred V. Aho, Yehoshua Sagiv and Jeffrey D. Ullman, Efficient optimization of a class of relational expressions, ACM Transactions on Database Systems 4(4), 435 to 454 (1979), tableau minimization, and the polynomial-time method for simple tableaux
  3. Alfred V. Aho, Yehoshua Sagiv and Jeffrey D. Ullman, Equivalences among relational expressions, SIAM Journal on Computing 8(2), 218 to 246 (1979), tableaux for select-project-join expressions and the NP-completeness of their equivalence
  4. Chandra Chekuri and Anand Rajaraman, Conjunctive query containment revisited, Theoretical Computer Science 239(2), 211 to 229 (2000), polynomial-time containment and minimization for acyclic queries and for queries of bounded query width
  5. Surajit Chaudhuri and Moshe Y. Vardi, Optimization of real conjunctive queries, Proceedings of the 12th ACM Symposium on Principles of Database Systems (PODS), 59 to 70 (1993), containment and equivalence of conjunctive queries under bag semantics
  6. Serge Abiteboul, Richard Hull and Victor Vianu, Foundations of Databases, Addison-Wesley (1995), Chapter 6 (static analysis and optimization), the section on query minimization and tableaux

About this page

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example