Ciência da computação · Livro 4 · Graduação — Ano 2

University Computer Science — Year 2

Este livro ainda não está disponível em Português. Edições: English.

University Computer Science — Year 2 · Graduação — Ano 2

30Database Design: Dependencies, Normal Forms and Transactions

For years the library kept its loans in one spreadsheet: one line per loan, with the book’s title and author, the member’s name and street, everything a librarian might want to read on the line. Built as a table from the town’s database, it looks like this, and it shows what happens when member 55 moves house:

-- load: wide_build.sql
SELECT count(*) AS lines, count(DISTINCT member_id) AS members,
       count(DISTINCT book_id) AS books FROM wide;
SELECT street, postcode, count(*) AS lines FROM wide
WHERE member_id = 55 GROUP BY street, postcode;
UPDATE wide SET street = 'Garden Lane', postcode = 'B-110'
WHERE member_id = 55
  AND loan_id < (SELECT max(loan_id) FROM wide WHERE member_id = 55);
SELECT street, postcode, count(*) AS lines FROM wide
WHERE member_id = 55 GROUP BY street, postcode;
Listing 30.1. The wide table, and a move recorded on every line but the last code/bachelor-2/30-database-design/listings/wide_table.sql
$ python sqlrun.py wide_table.sql
sql> SELECT count(*) AS lines, count(DISTINCT member_id) AS members,
...>        count(DISTINCT book_id) AS books FROM wide;
+-------+---------+-------+
| lines | members | books |
+-------+---------+-------+
| 400   | 60      | 80    |
+-------+---------+-------+
(1 row)

sql> SELECT street, postcode, count(*) AS lines FROM wide
...> WHERE member_id = 55 GROUP BY street, postcode;
+--------------+----------+-------+
| street       | postcode | lines |
+--------------+----------+-------+
| River Avenue | B-120    | 12    |
+--------------+----------+-------+
(1 row)

sql> UPDATE wide SET street = 'Garden Lane', postcode = 'B-110'
...> WHERE member_id = 55
...>   AND loan_id < (SELECT max(loan_id) FROM wide WHERE member_id = 55);
OK (11 rows changed)

sql> SELECT street, postcode, count(*) AS lines FROM wide
...> WHERE member_id = 55 GROUP BY street, postcode;
+--------------+----------+-------+
| street       | postcode | lines |
+--------------+----------+-------+
| Garden Lane  | B-110    | 11    |
| River Avenue | B-120    | 1     |
+--------------+----------+-------+
(2 rows)
Output 30.1. Eleven lines changed, one forgotten: the member now lives in two streets at once.

The listing loads wide_build.sql, which builds the table by joining loans, books, members, people and streets. Nothing in the table says that a member has one street: the fact is written twelve times, and the twelve copies can disagree. This chapter makes the intuition precise. Dependencies say which facts determine which; normal forms say when a table stores each fact once; decompositions split a table without losing anything. The second half turns to the other way a database goes wrong, two programs changing it at the same moment, and ends with the index that makes a search fast.

You already know

The Year 1 volume: relations, attributes, keys, candidate and primary keys, foreign keys, relational algebra and its natural join, SQL queries, entity–relationship modelling. The grade 12 volume: the anomalies of a badly designed table, seen on examples.

30.1 Functional dependencies

Definition 30.1 (Functional dependency, trivial dependency)

Let RR be a set of attributes and X,Y⊆RX, Y \subseteq R. A table over RR satisfies the functional dependency X→YX \to Y if any two rows that agree on every attribute of XX also agree on every attribute of YY. The dependency is trivial if Y⊆XY \subseteq X; it is then satisfied by every table.

A dependency is a rule about the world the table describes, not an observation about today’s rows. The library’s rules are that a loan determines its book, its member and its dates; a book determines its title, author, genre and pages; a member determines the name and the street; a street determines its postcode. The 400 lines satisfy other dependencies by accident: no two books have the same title yet, so title →\to book holds in the data, but nothing forbids two books called the same (Exercise 30.9).

The library’s rules over the wide table’s fourteen attributes. Blue: a loan determines its dates, its book and its member. Red: a book determines its title, author, genre and pages. Orange: a member determines the name and the street. Green: a street determines its postcode. Only the blue arrows start from a key.
The library’s rules over the wide table’s fourteen attributes. Blue: a loan determines its dates, its book and its member. Red: a book determines its title, author, genre and pages. Orange: a member determines the name and the street. Green: a street determines its postcode. Only the blue arrows start from a key.

From some dependencies others follow: if a member determines the street and a street the postcode, a member determines the postcode.

Definition 30.2 (Implication, Armstrong’s axioms)

A set FF of dependencies over RR implies X→YX \to Y, written F⊨X→YF \models X \to Y, if every table over RR that satisfies all of FF satisfies X→YX \to Y. Armstrong’s axioms are three rules to derive dependencies, written F⊢X→YF \vdash X \to Y: reflexivity, X→YX \to Y whenever Y⊆XY \subseteq X; augmentation, from X→YX \to Y derive XZ→YZXZ \to YZ; transitivity, from X→YX \to Y and Y→ZY \to Z derive X→ZX \to Z. (We write XZXZ for X∪ZX \cup Z.)

The union rule, from X→YX \to Y and X→ZX \to Z derive X→YZX \to YZ, and the decomposition rule, from X→YZX \to YZ derive X→YX \to Y, follow from the three (Exercise 30.8).

Definition 30.3 (Attribute closure)

The attribute closure of XX under FF is X+={A∈R:F⊨X→A}X^+ = \{A \in R : F \models X \to A\}, the set of attributes that XX determines.

Theorem 30.4 (Armstrong’s axioms are sound and complete)

For every FF, XX and YY: F⊢X→YF \vdash X \to Y if and only if F⊨X→YF \models X \to Y.

Proof. Soundness: each rule turns satisfied dependencies into a satisfied one. Reflexivity: two rows that agree on XX agree on its subset YY. Augmentation: two rows that agree on XZXZ agree on XX, hence on YY, and on ZZ. Transitivity: two rows that agree on XX agree on YY, hence on ZZ. By induction on the length of a derivation, every derived dependency holds in every table satisfying FF.

Completeness: suppose F⊨X→YF \models X \to Y, and let D={A:F⊢X→A}D = \{A : F \vdash X \to A\}; by reflexivity X⊆DX \subseteq D. Build a table of two rows over RR: both rows are 00 on DD; outside DD, the first is 00 and the second 11. It satisfies every V→WV \to W of FF: if the rows agree on VV, then V⊆DV \subseteq D, so F⊢X→VF \vdash X \to V by the union rule, then F⊢X→WF \vdash X \to W by transitivity, so W⊆DW \subseteq D by decomposition and the rows agree on WW. The table therefore satisfies X→YX \to Y; its rows agree on X⊆DX \subseteq D, so they agree on YY, and Y⊆DY \subseteq D. By the union rule, F⊢X→YF \vdash X \to Y. ∎

So the closure can be computed by derivation instead of by imagining every table, and there is a simple algorithm:

def closure(xs, deps):
    """X+: every attribute that X determines under deps."""
    result, changed = set(xs), True
    while changed:
        changed = False
        for left, right in deps:
            if left <= result and not right <= result:
                result |= right  # X determines left, hence right
                changed = True
    return frozenset(result)
Listing 30.2. The closure of a set of attributes: apply every dependency whose left side is already in, until nothing changes code/bachelor-2/30-database-design/listings/fd.py

Proposition 30.5 (The closure algorithm)

The function closure returns X+X^+, after at most ∣F∣+1|F| + 1 passes over FF, so in time O(∣F∣2⋅∣R∣)O(|F|^2 \cdot |R|).

Proof. Exercise 30.11: every attribute added is derivable, and when the loop stops the set is closed under FF, which forces it to contain X+X^+. Each pass but the last adds the right side of at least one dependency not used before. ∎

Corollary 30.6 (A test for keys)

XX is a superkey of RR under FF exactly when X+=RX^+ = R; it is a candidate key when moreover (X∖{A})+≠R(X \setminus \{A\})^+ \neq R for every A∈XA \in X.

Proof. XX is a superkey when it determines every attribute, that is F⊨X→RF \models X \to R, that is R⊆X+R \subseteq X^+. A candidate key is a superkey with no proper subset that is one; since a superset of a superkey is a superkey, it suffices to remove one attribute at a time. ∎

Definition 30.7 (Minimal cover)

A minimal cover of FF is a set GG of dependencies equivalent to FF (each implies every dependency of the other) in which every right side is a single attribute, no attribute can be removed from a left side, and no dependency can be removed, without losing the equivalence.

def keys(attrs, deps):
    """The candidate keys: the minimal sets whose closure is every attribute."""
    attrs = frozenset(attrs)
    found = []
    for size in range(len(attrs) + 1):
        for xs in combinations(sorted(attrs), size):
            xs = frozenset(xs)
            if not any(k <= xs for k in found) and closure(xs, deps) >= attrs:
                found.append(xs)
    return found


def minimal_cover(deps):
    """An equivalent set with one attribute on each right side, no extraneous
    attribute on a left side, and no redundant dependency."""
    out = [(left, frozenset([a])) for left, right in deps for a in sorted(right)]
    for i, (left, right) in enumerate(out):
        for a in sorted(left):
            if len(left) > 1 and right <= closure(left - {a}, out):
                left = left - {a}  # a is extraneous on the left
        out[i] = (left, right)
    out = list(dict.fromkeys(out))
    for d in list(out):
        rest = [e for e in out if e != d]
        if implies(rest, *d):
            out = rest
    return out
Listing 30.3. Candidate keys by increasing size, and a minimal cover code/bachelor-2/30-database-design/listings/fd.py
WIDE = ("loan out due ret book title author genre pages member first last street"
        " postcode").split()
RULES = fds("loan -> book member out due ret; book -> title author genre pages;"
            " member -> first last street; street -> postcode")
Listing 30.4. The wide table’s attributes and the library’s rules code/bachelor-2/30-database-design/listings/fd_demo.py
$ python fd_demo.py
closure of {member}: {member, first, last, street, postcode}
closure of {book}: {book, title, author, genre, pages}
candidate keys: ['{loan}']
minimal cover: 13 dependencies, one attribute on each right side
in 3NF: False
  BCNF table {book, title, author, genre, pages} key {book}
  BCNF table {street, postcode} key {street}
  BCNF table {member, first, last, street} key {member}
  BCNF table {loan, out, due, ret, book, member} key {loan}
lossless: True | preserves the dependencies: True
Output 30.2. Closures, the key, the cover, and the BCNF tables of Section 30.3.

The key search tries the subsets in increasing size, skipping supersets of keys already found: exponential in general, fast here, where one attribute suffices. The wide table’s only candidate key is the loan.

30.2 Normal forms

Definition 30.8 (Update, insertion and deletion anomaly)

A table has an update anomaly when one fact is stored on several rows, so that changing it means changing them all; an insertion anomaly when a fact cannot be recorded without an unrelated one, as a member without a loan; a deletion anomaly when removing a row removes an unrelated fact with it, as the last loan of a book removes the book.

All three come from a dependency whose left side is not a key: book →\to title makes the title a fact about the book, stored once per loan of that book.

Definition 30.9 (Third normal form, Boyce–Codd normal form)

Let FF hold on RR. RR is in Boyce–Codd normal form (BCNF) if for every non-trivial X→AX \to A implied by FF with X∪{A}⊆RX \cup \{A\} \subseteq R, XX is a superkey of RR. It is in third normal form (3NF) if for every such dependency, XX is a superkey or AA belongs to some candidate key of RR.

BCNF says that every fact the table records is a fact about a key; 3NF tolerates one exception, attributes that are part of a key. The wide table is in neither: book, member and street determine other attributes and are not keys.

30.3 Decomposition

Definition 30.10 (Decomposition, lossless join, dependency preservation)

A decomposition of RR is a list of attribute sets R1,…,RmR_1, \dots, R_m whose union is RR; a table TT over RR is stored as its projections πRi(T)\pi_{R_i}(T). The decomposition is lossless for FF if T=πR1(T)⋈⋯⋈πRm(T)T = \pi_{R_1}(T) \bowtie \dots \bowtie \pi_{R_m}(T) for every TT satisfying FF; it preserves the dependencies if the dependencies of FF that hold inside the parts imply all of FF.

The join of the projections always contains TT; a lossy decomposition adds rows that were never there. Preservation matters for checking: a dependency that holds inside a part is enforced by that part’s key, while one that spans two parts can be checked only by a join.

Theorem 30.11 (Heath’s theorem)

Let R=X∪Y∪ZR = X \cup Y \cup Z with X,Y,ZX, Y, Z disjoint. If a table over RR satisfies X→YX \to Y, it is the join of its projections on XYXY and XZXZ.

Proof. Exercise 30.10. ∎

def bcnf_violation(r, deps):
    """A dependency X -> Y that holds in r with X not a superkey of r, or None."""
    r = frozenset(r)
    for xs in subsets(r):
        c = closure(xs, deps) & r
        if c != xs and c != r:
            return xs, c - xs
    return None


def bcnf(r, deps):
    """Split r on a violating X -> Y into XY and r - Y, until no part has one."""
    v = bcnf_violation(r, deps)
    if v is None:
        return [frozenset(r)]
    xs, ys = v
    return bcnf(xs | ys, deps) + bcnf(frozenset(r) - ys, deps)
Listing 30.5. A BCNF violation, and the BCNF decomposition by repeated splits code/bachelor-2/30-database-design/listings/fd.py

Theorem 30.12 (BCNF decomposition)

The function bcnf stops, returns parts that are all in BCNF, and the decomposition is lossless.

Proof. A split of RR on a violation X→YX \to Y, with Y=X+∩R∖XY = X^+ \cap R \setminus X non-empty and X+∩R≠RX^+ \cap R \neq R, produces XYXY and R∖YR \setminus Y, both strictly smaller than RR: the recursion stops. A part is returned only when it has no violation, so it is in BCNF. Each split is lossless by Heath’s theorem with Z=R∖XYZ = R \setminus XY, since X→YX \to Y holds. By induction on the recursion, if R∖YR \setminus Y is replaced by a lossless decomposition of it, the whole stays lossless, because a table satisfying FF projects onto R∖YR \setminus Y as a table that satisfies the dependencies of FF that hold there, and the natural join is associative. ∎

The BCNF decomposition of . Each split takes a violating dependency X Y and makes one table of X with everything it determines, and another of the rest with X kept as the link. The four leaves are the BCNF tables.
The BCNF decomposition of Output 30.2. Each split takes a violating dependency X→YX \to Y and makes one table of XX with everything it determines, and another of the rest with XX kept as the link. The four leaves are the BCNF tables.

The SQL counterpart builds the four tables from the wide one and joins them back:

-- load: wide_build.sql
CREATE TABLE d_loans AS
  SELECT DISTINCT loan_id, out_date, due_date, return_date, book_id, member_id FROM wide;
CREATE TABLE d_books AS SELECT DISTINCT book_id, title, author, genre, pages FROM wide;
CREATE TABLE d_members AS
  SELECT DISTINCT member_id, first_name, last_name, street FROM wide;
CREATE TABLE d_streets AS SELECT DISTINCT street, postcode FROM wide;
SELECT (SELECT count(*) FROM d_loans) AS loans,
       (SELECT count(*) FROM d_books) AS books,
       (SELECT count(*) FROM d_members) AS members,
       (SELECT count(*) FROM d_streets) AS streets,
       (SELECT count(DISTINCT member_id) FROM d_members) AS member_ids,
       (SELECT count(DISTINCT street) FROM d_streets) AS street_names;
CREATE VIEW joined AS
  SELECT l.loan_id, l.out_date, l.due_date, l.return_date,
         b.book_id, b.title, b.author, b.genre, b.pages,
         m.member_id, m.first_name, m.last_name, s.street, s.postcode
  FROM d_loans AS l NATURAL JOIN d_books AS b
  NATURAL JOIN d_members AS m NATURAL JOIN d_streets AS s;
SELECT (SELECT count(*) FROM (SELECT * FROM wide EXCEPT SELECT * FROM joined))
         AS lost,
       (SELECT count(*) FROM (SELECT * FROM joined EXCEPT SELECT * FROM wide))
         AS invented;
Listing 30.6. The four BCNF tables, and the join that should give back the wide table code/bachelor-2/30-database-design/listings/decomposed.sql
$ python sqlrun.py decomposed.sql
sql> CREATE TABLE d_loans AS
...>   SELECT DISTINCT loan_id, out_date, due_date, return_date, book_id, member_id FROM wide;
OK

sql> CREATE TABLE d_books AS SELECT DISTINCT book_id, title, author, genre, pages FROM wide;
OK

sql> CREATE TABLE d_members AS
...>   SELECT DISTINCT member_id, first_name, last_name, street FROM wide;
OK

sql> CREATE TABLE d_streets AS SELECT DISTINCT street, postcode FROM wide;
OK

sql> SELECT (SELECT count(*) FROM d_loans) AS loans,
...>        (SELECT count(*) FROM d_books) AS books,
...>        (SELECT count(*) FROM d_members) AS members,
...>        (SELECT count(*) FROM d_streets) AS streets,
...>        (SELECT count(DISTINCT member_id) FROM d_members) AS member_ids,
...>        (SELECT count(DISTINCT street) FROM d_streets) AS street_names;
+-------+-------+---------+---------+------------+--------------+
| loans | books | members | streets | member_ids | street_names |
+-------+-------+---------+---------+------------+--------------+
| 400   | 80    | 60      | 23      | 60         | 23           |
+-------+-------+---------+---------+------------+--------------+
(1 row)

sql> CREATE VIEW joined AS
...>   SELECT l.loan_id, l.out_date, l.due_date, l.return_date,
...>          b.book_id, b.title, b.author, b.genre, b.pages,
...>          m.member_id, m.first_name, m.last_name, s.street, s.postcode
...>   FROM d_loans AS l NATURAL JOIN d_books AS b
...>   NATURAL JOIN d_members AS m NATURAL JOIN d_streets AS s;
OK

sql> SELECT (SELECT count(*) FROM (SELECT * FROM wide EXCEPT SELECT * FROM joined))
...>          AS lost,
...>        (SELECT count(*) FROM (SELECT * FROM joined EXCEPT SELECT * FROM wide))
...>          AS invented;
+------+----------+
| lost | invented |
+------+----------+
| 0    | 0        |
+------+----------+
(1 row)
Output 30.3. No row lost, none invented, and each key unique in the data.

Only 23 streets appear because no member lives on the 24th. BCNF cannot always keep the dependencies inside the parts.

Example 30.13 (No BCNF decomposition preserves the dependencies)

An address table over street, town and postcode with the rules street town →\to postcode and postcode →\to town. The keys are {street, town} and {street, postcode}, so postcode →\to town violates BCNF; every attribute belongs to a key, so the table is in 3NF. Any BCNF decomposition must separate the three attributes, and street town →\to postcode then lies in no part.

$ python no_preserving.py
keys: {postcode, street} {street, town} | in 3NF: True
BCNF         : {postcode, town} {postcode, street} | lossless True, preserving False
3NF synthesis: {postcode, street, town} | lossless True, preserving True
Output 30.4. The address table: BCNF loses a dependency, 3NF keeps the table whole.
def synthesis_3nf(r, deps):
    """One table per left side of a minimal cover, plus a key if none holds one."""
    groups = {}
    for left, right in minimal_cover(deps):
        groups[left] = groups.get(left, left) | right
    parts = list(dict.fromkeys(groups.values()))
    parts = [p for p in parts if not any(p < q for q in parts)]
    if not any(closure(p, deps) >= frozenset(r) for p in parts):
        parts.append(keys(r, deps)[0])
    return parts
Listing 30.7. 3NF synthesis from a minimal cover code/bachelor-2/30-database-design/listings/fd.py

Theorem 30.14 (3NF synthesis)

The decomposition of Listing 30.7, one table for each left side of a minimal cover with the attributes it determines in the cover, plus a candidate key if no table contains one, preserves the dependencies, is lossless, and has every table in 3NF.

Proof. Every dependency of the minimal cover lies inside the table of its left side, and the cover is equivalent to FF: the dependencies are preserved. For losslessness, let KK be a table containing a key and run the chase of Exercise 30.5: the row of KK starts with the symbol aa on KK, and the cover’s dependencies, applied in the order in which the closure algorithm adds attributes to K+=RK^+ = R, give it aa on each attribute in turn, since each such dependency lies inside a table whose own row has aa everywhere. A row with aa everywhere means the join is lossless. That each table is in 3NF uses the minimality of the cover; we admit it. ∎

So 3NF can always be reached without losing a dependency, and BCNF without losing information but perhaps a dependency. The synthesis often gives BCNF tables anyway, as for the library: its four 3NF tables are the four BCNF tables.

One more kind of redundancy escapes functional dependencies. If a book has several authors and several subject keywords, unrelated to each other, a table (book, author, keyword) must hold every pair: two authors and three keywords make six rows, with each author written three times.

Definition 30.15 (Multivalued dependency, fourth normal form)

A table over RR satisfies the multivalued dependency X↠YX \twoheadrightarrow Y if, with Z=R∖XYZ = R \setminus XY, whenever two rows agree on XX, the row that takes XX and YY from the first and ZZ from the second is also in the table. RR is in fourth normal form if for every non-trivial X↠YX \twoheadrightarrow Y that holds, XX is a superkey.

Here book ↠\twoheadrightarrow author: every author of a book appears with every keyword of it. The table is in BCNF, its only key being all three attributes, but not in 4NF, and splitting it into (book, author) and (book, keyword) is lossless by the same argument as Heath’s theorem. A functional dependency is a special multivalued one; the chase of Exercise 30.5 extends to both, and we leave it at that.

History

Edgar Codd published the relational model in 1970 and defined third normal form in 1971. Raymond Boyce and Codd formally developed the normal form that bears their names in 1974; Ian Heath had described it in 1971.

30.4 Transactions

Design removes the anomalies of one table. The other dangers come from time: a change made of several statements that stops in the middle, or two programs that change the same row at once.

Definition 30.16 (Transaction, commit, rollback)

A transaction is a sequence of reads and writes that the database treats as one unit. It ends with a commit, which makes all its writes permanent and visible to others, or a rollback, which cancels all of them.

Definition 30.17 (Atomicity, consistency, isolation, durability)

A database system guarantees atomicity if a transaction’s writes take effect all or none; consistency if a transaction that starts from a state satisfying the declared constraints and commits leaves one; isolation if concurrent transactions do not see each other’s partial work, to a degree fixed by the isolation level; durability if a committed transaction survives a crash.

In SQLite, BEGIN starts a transaction; without it, each statement is a transaction of its own. The book’s SQL runner commits after every statement, as an interactive tool does, so the transactions of this section are written in Python, which controls them explicitly:

def record_return(day, amount):
    conn.execute("BEGIN")
    try:
        conn.execute("UPDATE loans SET return_date = ? WHERE loan_id = ?", (day, loan))
        conn.execute("INSERT INTO fines VALUES (?, ?)", (loan, amount))
        conn.execute("COMMIT")
        print(f"returned on {day}, fine {amount}: committed")
    except sqlite3.Error as e:
        conn.execute("ROLLBACK")
        print(f"returned on {day}, fine {amount}: {e}; rolled back")
Listing 30.8. A late return recorded in two tables as one transaction code/bachelor-2/30-database-design/listings/rollback.py
$ python rollback.py
   loan 3 (due 2025-01-22): return_date None, fines 0
returned on 2026-02-03, fine 0: CHECK constraint failed: amount > 0; rolled back
   loan 3 (due 2025-01-22): return_date None, fines 0
returned on 2026-02-03, fine 2: committed
   loan 3 (due 2025-01-22): return_date 2026-02-03, fines 1
Output 30.5. The fine of 0 breaks a constraint after the loan was already updated: the rollback undoes the update too.

Without the transaction, the first attempt would have left a loan returned with no fine recorded: the two tables would disagree, the very thing the design was meant to prevent.

History

Theo Härder and Andreas Reuter coined the acronym ACID for these four properties in 1983, in a survey of transaction recovery.

30.5 Isolation

Definition 30.18 (Schedule)

A schedule of a set of transactions is the order in time of all their reads, writes, commits and rollbacks, each transaction’s own operations in their order. It is serial if the transactions do not overlap.

Definition 30.19 (The anomalies of isolation)

In a schedule of two transactions T1T_1 and T2T_2: a dirty read is T2T_2 reading a value written by T1T_1 that T1T_1 has not committed; a non-repeatable read is T1T_1 reading the same row twice and getting two values, because T2T_2 changed it and committed in between; a phantom read is T1T_1 running the same query with a condition twice and getting different sets of rows, because T2T_2 inserted or deleted a matching row; a lost update is T1T_1 and T2T_2 both reading a value and both writing a new value computed from it, so that one write erases the other; a write skew is T1T_1 and T2T_2 each reading the same rows, checking a rule over them, and each writing a different row, so that both checks pass and the result breaks the rule.

Definition 30.20 (Isolation level)

An isolation level is a promise about which of these anomalies a database system lets transactions see. The SQL standard names four: read uncommitted, read committed, repeatable read and serializable, the last promising that every schedule has the same effect as some serial one.

isolation leveldirty readnon-repeatable readphantom read
read uncommittedpossiblepossiblepossible
read committednopossiblepossible
repeatable readnonopossible
serializablenonono
The standard isolation levels, and the anomalies each allows. A system may give more than a level promises: PostgreSQL’s repeatable read shows no phantoms, and its read uncommitted behaves as read committed.

SQLite takes the simplest road: its transactions are serializable, and it allows a single writer at a time. The one way to see an uncommitted change is to share a cache between two connections and turn on read_uncommitted.

In practice

SQLite’s documentation states that its transactions are serializable except for connections that share a cache with read_uncommitted on, and that one connection writes at a time: the others wait their turn.

URI = "file:shelf?mode=memory&cache=shared"
writer = sqlite3.connect(URI, uri=True, isolation_level=None)
reader = sqlite3.connect(URI, uri=True, isolation_level=None)
writer.execute("CREATE TABLE shelf (book_id INTEGER PRIMARY KEY, available INTEGER)")
writer.execute("INSERT INTO shelf VALUES (7, 3)")


def read(label):
    try:
        row = reader.execute("SELECT available FROM shelf WHERE book_id = 7").fetchone()
        n = row[0]
        print(f"{label}: the reader sees {n}")
    except sqlite3.OperationalError as e:
        print(f"{label}: the reader gets an error: {e}")


writer.execute("BEGIN")
writer.execute("UPDATE shelf SET available = 0 WHERE book_id = 7")
read("3 changed to 0, not committed")
reader.execute("PRAGMA read_uncommitted = 1")
read("the same, read_uncommitted on")
writer.execute("ROLLBACK")
read("writer rolled back")
Listing 30.9. Two connections to one shared in-memory database code/bachelor-2/30-database-design/listings/dirty_read.py
$ python dirty_read.py
3 changed to 0, not committed: the reader gets an error: database table is locked: shelf
the same, read_uncommitted on: the reader sees 0
writer rolled back: the reader sees 3
Output 30.6. Refused, then a dirty read, then the value the writer never committed is gone.

The lost update needs no concurrency inside the database at all: it is enough that a program reads a value, computes, and writes, while another does the same. Two lending desks, each with its own connection to the library’s file:

with tempfile.TemporaryDirectory() as folder:
    # 1. Read, then write what was read minus one: each statement on its own.
    a, b = fresh(folder)
    na, nb = available(a), available(b)  # both read 3
    a.execute("UPDATE shelf SET available = ? WHERE book_id = 7", (na - 1,))
    b.execute("UPDATE shelf SET available = ? WHERE book_id = 7", (nb - 1,))
    print("read, then write: two copies lent, available =", available(a))
    a.close()
    b.close()

    # 2. The same inside BEGIN IMMEDIATE: the second desk must wait for the first.
    a, b = fresh(folder)
    a.execute("BEGIN IMMEDIATE")
    na = available(a)
    try:
        b.execute("BEGIN IMMEDIATE")
    except sqlite3.OperationalError as e:
        print("BEGIN IMMEDIATE: the second desk is refused:", e)
    a.execute("UPDATE shelf SET available = ? WHERE book_id = 7", (na - 1,))
    a.execute("COMMIT")
    b.execute("BEGIN IMMEDIATE")  # the desk tries again
    nb = available(b)
    b.execute("UPDATE shelf SET available = ? WHERE book_id = 7", (nb - 1,))
    b.execute("COMMIT")
    print("BEGIN IMMEDIATE: two copies lent, available =", available(a))
    a.close()
    b.close()

    # 3. One statement that reads and writes: nothing to interleave.
    a, b = fresh(folder)
    for conn in (a, b):
        conn.execute("UPDATE shelf SET available = available - 1 WHERE book_id = 7")
    print("update expression: two copies lent, available =", available(a))
    a.close()
    b.close()
Listing 30.10. Read then write, unprotected, inside BEGIN IMMEDIATE, then as one UPDATE code/bachelor-2/30-database-design/listings/lost_update.py
$ python lost_update.py
read, then write: two copies lent, available = 2
BEGIN IMMEDIATE: the second desk is refused: database is locked
BEGIN IMMEDIATE: two copies lent, available = 1
update expression: two copies lent, available = 1
Output 30.7. Three copies, two lent: only the first way records 2 instead of 1.
The lost update of , one step per line. Each write is correct for the value its desk read; the second erases the first. Inside BEGIN IMMEDIATE, desk B could not have started before A committed, and it would have read 2.
The lost update of Output 30.7, one step per line. Each write is correct for the value its desk read; the second erases the first. Inside BEGIN IMMEDIATE, desk B could not have started before A committed, and it would have read 2.

There are two fixes. BEGIN IMMEDIATE takes the right to write at the start of the transaction, so the second desk is refused until the first commits, and then reads the new value. Or the read and the write become one statement, UPDATE shelf SET available = available - 1, which the database executes as a whole (Exercise 30.6).

In practice

BEGIN IMMEDIATE starts a write transaction at once, and may fail with “database is locked” (SQLITE_BUSY) while another connection has one; a program then waits and tries again. A plain BEGIN waits for the first write, and may fail there instead, after reading.

Since SQLite never shows the other anomalies, a small simulator shows them: it runs a schedule of reads and writes under three rules for answering a read, the latest write even if uncommitted, the latest committed value, or a snapshot of the committed values when the transaction began. Under snapshots, a transaction that wants to commit a row that another transaction committed since it began is refused, the rule of “first committer wins”.

def lost_update(db):  # both read x, both write what they read minus one
    a, b = db.read(1, "x"), db.read(2, "x")
    db.write(1, "x", a - 1)
    db.write(2, "x", b - 1)
    if not (db.commit(1) and db.commit(2)):
        return "refused"
    return db.committed["x"] != 1


def write_skew(db):  # the rule a + b >= 1; each checks it, each removes one copy
    s1 = db.read(1, "a") + db.read(1, "b")
    s2 = db.read(2, "a") + db.read(2, "b")
    if s1 >= 2:
        db.write(1, "a", 0)
    if s2 >= 2:
        db.write(2, "b", 0)
    if not (db.commit(1) and db.commit(2)):
        return "refused"
    return db.committed["a"] + db.committed["b"] < 1

Listing 30.11. Two of the five staged schedules: the lost update and the write skew code/bachelor-2/30-database-design/listings/schedules.py
$ python schedules.py
                       uncommitted     committed      snapshot
dirty read                    seen             -             -
non-repeatable read           seen          seen             -
phantom                       seen          seen             -
lost update                   seen          seen       refused
write skew                    seen          seen          seen
Output 30.8. Which anomaly each rule lets through.

Reading committed values removes dirty reads only; snapshots remove the three anomalies of the standard’s table and turn the lost update into a refusal. Write skew survives snapshots: the two transactions write different rows, so no write conflicts with another, yet the rule “at least one copy stays” is broken. Only a serializable level prevents it, for example by detecting that each read what the other wrote.

30.6 Using an index

Definition 30.21 (Index)

An index on columns of a table is a separate structure, kept up to date by the database system on every change, that maps values of those columns to the rows that hold them, in sorted order, so that the rows with a given value or in a given range are found without reading the whole table.

The database chooses for each query whether to use an index. EXPLAIN QUERY PLAN shows the choice:

-- load: town
EXPLAIN QUERY PLAN
SELECT loan_id, out_date FROM loans WHERE member_id = 55;
CREATE INDEX loans_member ON loans (member_id);
EXPLAIN QUERY PLAN
SELECT loan_id, out_date FROM loans WHERE member_id = 55;
EXPLAIN QUERY PLAN
SELECT loan_id, out_date FROM loans WHERE member_id + 0 = 55;
Listing 30.12. The plan of the same query before and after an index code/bachelor-2/30-database-design/listings/explain.sql
$ python sqlrun.py explain.sql
sql> EXPLAIN QUERY PLAN
...> SELECT loan_id, out_date FROM loans WHERE member_id = 55;
+----+--------+---------+------------+
| id | parent | notused | detail     |
+----+--------+---------+------------+
| 2  | 0      | 0       | SCAN loans |
+----+--------+---------+------------+
(1 row)

sql> CREATE INDEX loans_member ON loans (member_id);
OK

sql> EXPLAIN QUERY PLAN
...> SELECT loan_id, out_date FROM loans WHERE member_id = 55;
+----+--------+---------+-----------------------------------------------------+
| id | parent | notused | detail                                              |
+----+--------+---------+-----------------------------------------------------+
| 3  | 0      | 0       | SEARCH loans USING INDEX loans_member (member_id=?) |
+----+--------+---------+-----------------------------------------------------+
(1 row)

sql> EXPLAIN QUERY PLAN
...> SELECT loan_id, out_date FROM loans WHERE member_id + 0 = 55;
+----+--------+---------+------------+
| id | parent | notused | detail     |
+----+--------+---------+------------+
| 2  | 0      | 0       | SCAN loans |
+----+--------+---------+------------+
(1 row)
Output 30.9. SCAN reads every row; SEARCH reads only the matching ones, through the index.

The last query hides the column inside an expression, and the index no longer applies: member_id + 0 is not a value that the index sorts.

In practice

SQLite’s documentation says that SCAN is a full-table scan and SEARCH visits a subset of the rows, and warns that the format of EXPLAIN QUERY PLAN may change between releases: it is for people to read, not for programs to parse.

On 400 loans either way is instant. On generated tables of growing size:

def timed(conn, members, rng):
    """Mean time in microseconds of one query, over 200 random members."""
    ids = [rng.randrange(members) for _ in range(200)]
    t0 = time.perf_counter()
    for m in ids:
        conn.execute("SELECT count(*), max(out_day) FROM loans WHERE member_id = ?",
                     (m,)).fetchone()
    return (time.perf_counter() - t0) / len(ids) * 1e6


rng = random.Random(30)
print("     rows   scan (us)   index (us)   speed-up   index built in (ms)")
for n in [10_000, 100_000, 1_000_000]:
    conn = sqlite3.connect(":memory:")
    conn.execute("CREATE TABLE loans (loan_id INTEGER PRIMARY KEY, member_id INTEGER,"
                 " book_id INTEGER, out_day INTEGER)")
    members = n // 20
    rows = ((i, rng.randrange(members), rng.randrange(5000), rng.randrange(365))
            for i in range(n))
    conn.executemany("INSERT INTO loans VALUES (?, ?, ?, ?)", rows)
    scan = timed(conn, members, rng)
    t0 = time.perf_counter()
    conn.execute("CREATE INDEX loans_member ON loans (member_id)")
    built = (time.perf_counter() - t0) * 1e3
    seek = timed(conn, members, rng)
    print(f"{n:9} {scan:11.0f} {seek:12.1f} {scan / seek:10.0f} {built:21.0f}")
    conn.close()
Listing 30.13. The loans of a member, by scan and by index, timed on generated tables code/bachelor-2/30-database-design/listings/index_timing.py
$ python index_timing.py
     rows   scan (us)   index (us)   speed-up   index built in (ms)
    10000         623         12.3         51                     6
   100000        5977         18.7        320                    69
  1000000       63714         66.3        961                   744
Output 30.10. Mean time of one query on the author’s laptop, in microseconds.
on logarithmic axes, measured on a laptop. The scan grows in proportion to the table; the search through the index grows slowly, with the height of a tree, and with the cost of reaching rows scattered in memory.
Output 30.10 on logarithmic axes, measured on a laptop. The scan grows in proportion to the table; the search through the index grows slowly, with the height of a tree, and with the cost of reaching rows scattered in memory.

The scan time grows tenfold with each tenfold table; the index time grows about fivefold over a table a hundred times larger, and on a million rows the index is about a thousand times faster. It is not free: building it took close to a second, and each later insertion or update of a loan must update it too. How the index is organised, a balanced tree with many keys per node, and how the system chooses among plans, are the subject of the Year 3 volume. An index does not always help either: a query that selects a large fraction of the table reads it faster in order (Exercise 30.12).

30.7 Exercises

Exercise 30.1 ★

With F={a→b, bc→d, d→e, ea→c}F = \{a \to b,\ bc \to d,\ d \to e,\ ea \to c\}, compute by hand the closures of {a}\{a\}, {b,c}\{b, c\} and {c,e}\{c, e\}, then check with exo_closure.py. Is {a,d}\{a, d\} a superkey of {a,b,c,d,e}\{a, b, c, d, e\}?

Solution

Solution of Exercise 30.1.

From {a}\{a\}: a→ba \to b adds bb; no other left side is contained in {a,b}\{a, b\}, so {a}+={a,b}\{a\}^+ = \{a, b\}. From {b,c}\{b, c\}: bc→dbc \to d adds dd, then d→ed \to e adds ee; ea→cea \to c needs aa, so {b,c}+={b,c,d,e}\{b, c\}^+ = \{b, c, d, e\}. From {c,e}\{c, e\} no left side applies. For {a,d}\{a, d\}: a→ba \to b, d→ed \to e, ea→cea \to c give {a,b,c,d,e}\{a, b, c, d, e\}, so it is a superkey; neither {a}+\{a\}^+ nor {d}+={d,e}\{d\}^+ = \{d, e\} is everything, so it is even a candidate key.

$ python exo_closure.py
['a'] -> ['a', 'b']
['b', 'c'] -> ['b', 'c', 'd', 'e']
['c', 'e'] -> ['c', 'e']
Output 30.12. The three closures.

Exercise 30.2 ★

A BCNF step on the wide table’s violation book →\to title author genre pages splits off only {book, title}. What is wrong with the other part? Compare with the step that splits off the whole closure, using exo_bcnf_step.py.

Solution

Solution of Exercise 30.2.

$ python exo_bcnf_step.py
split off {book, title}
    2 attributes; still violated by nothing
    13 attributes; still violated by {book} -> {author, genre, pages}
split off {book, title, author, genre, pages}
    5 attributes; still violated by nothing
    10 attributes; still violated by {member} -> {first, last, street, postcode}
Output 30.13. A step that splits off too little, and one that splits off the closure.

The part {book, title} is fine, but the other part keeps book together with author, genre and pages: book →\to author genre pages still violates BCNF there, and a second and third step will be needed for the same left side. Splitting off X+X^+ removes every attribute that XX determines in one step; what remains in the other part are other violations, such as the member’s.

Exercise 30.3 ★

The reading room’s bookings have attributes seat, day, slot, member and desk, with seat day slot →\to member, member day slot →\to seat and seat →\to desk. Find all the candidate keys by hand, then with exo_keys.py.

Solution

Solution of Exercise 30.3.

day and slot appear on no right side, so every key contains them; desk appears on no left side and is determined by seat, so no key needs it. {day, slot} alone determines nothing more. Adding seat: seat day slot →\to member, seat →\to desk: everything. Adding member: member day slot →\to seat, then the rest. Both are minimal, since {day, slot} is not a key, and any other key would have to contain seat or member, hence one of these.

$ python exo_keys.py
key: ['day', 'member', 'slot']
key: ['day', 'seat', 'slot']
Output 30.14. The two candidate keys.

Exercise 30.4 ★

A schema with nn attributes has exactly one candidate key, of size kk. Prove that it has exactly 2n−k2^{n-k} superkeys.

Solution

Solution of Exercise 30.4.

Let KK be the key. A set SS is a superkey exactly when S⊇KS \supseteq K: if S⊇KS \supseteq K, then S+⊇K+=RS^+ \supseteq K^+ = R; conversely, a superkey contains a candidate key, obtained by removing attributes while it stays a superkey, and KK is the only one. The supersets of KK are K∪TK \cup T for the 2n−k2^{n-k} subsets TT of the other n−kn - k attributes.

Exercise 30.5 ★★

Split the wide table into the member’s attributes and the rest, keeping in both, in turn, the member, the street, or the last name. Which splits are lossless by Heath’s theorem? For the others, explain how a join could invent rows. Check with exo_heath.py, which runs the chase: one row per part, with the symbol aa on the part’s attributes and distinct symbols elsewhere; the dependencies force equal symbols where two rows agree on a left side; the decomposition is lossless exactly when some row ends with aa everywhere.

Solution

Solution of Exercise 30.5.

$ python exo_heath.py
split on member   : lossless True
split on street   : lossless False
split on last name: lossless False
Output 30.15. Only the split that keeps the member in both parts is lossless.

Keeping member in both parts: the common attribute determines the whole member part, member →\to first last street postcode, so Heath’s theorem applies. Keeping street: the street determines only the postcode, not the member, and two members on the same street become interchangeable; the join pairs each loan with every member of its borrower’s street, inventing rows. Keeping last: a last name determines nothing, and the join pairs a loan with every member of that name. In the chase, the row of the second part never gets aa on the loan’s attributes, nor the first row on the member’s.

Exercise 30.6 ★★

In the first part of Listing 30.10, explain the bug as a schedule, and say why each of the two fixes prevents it. Which fix still works if the program must check that a copy is available before lending it?

Solution

Solution of Exercise 30.6.

As a schedule: rA(available)=3r_A(\mathit{available}) = 3, rB(available)=3r_B(\mathit{available}) = 3, wA(2)w_A(2), wB(2)w_B(2), each statement committed on its own. BB’s write is computed from a value that AA’s write made stale: a lost update. With BEGIN IMMEDIATE, the read and the write are in one transaction that holds the right to write from its start, so BB’s transaction cannot begin between AA’s read and AA’s write: the schedule becomes serial. With available = available - 1, the read and the write are one statement, executed by the database as a whole. To check that a copy is available first, the check and the change must be in one unit: either the transaction with BEGIN IMMEDIATE, or the condition inside the statement, UPDATE shelf SET available = available - 1 WHERE book_id = 7 AND available > 0, whose count of changed rows says whether the copy was lent.

Exercise 30.7 ★★

Add a name determined by the member to the bookings of Exercise 30.3, and let seat day slot determine desk as well. Compute a minimal cover and the 3NF synthesis by hand, then check with exo_synthesis.py.

Solution

Solution of Exercise 30.7.

Split the right sides: seat day slot →\to member, seat day slot →\to desk, member day slot →\to seat, seat →\to desk, member →\to name. No left side has an extraneous attribute: {day, slot} determines nothing, and neither {seat, day} nor {seat, slot} determines the member. The dependency seat day slot →\to desk is redundant, implied by seat →\to desk: remove it. The synthesis makes one table per left side: (seat, desk), (seat, day, slot, member), (member, day, slot, seat), the same set as the previous one, so kept once, and (member, name). The second contains a key, so no table is added.

$ python exo_synthesis.py
minimal cover: seat -> desk; day seat slot -> member; day member slot -> seat; member -> name
table ['desk', 'seat'] | 3NF: True
table ['day', 'member', 'seat', 'slot'] | 3NF: True
table ['member', 'name'] | 3NF: True
lossless: True | preserving: True
Output 30.16. The cover, the three tables, and the checks.

Exercise 30.8 ★★

Derive the union rule and the decomposition rule from Armstrong’s three axioms.

Solution

Solution of Exercise 30.8.

Union: from X→YX \to Y, augmentation with XX gives X→XYX \to XY; from X→ZX \to Z, augmentation with YY gives XY→YZXY \to YZ; transitivity gives X→YZX \to YZ. Decomposition: YZ→YYZ \to Y by reflexivity, and transitivity with X→YZX \to YZ gives X→YX \to Y.

Exercise 30.9 ★★

Find, with exo_extra_fds.py, the dependencies between two single attributes that the town’s 400 lines satisfy but the library’s rules do not imply. Which of them would you add to the schema, and what would change?

Solution

Solution of Exercise 30.9.

$ python exo_extra_fds.py
out      -> due
due      -> out
title    -> book, author, genre, pages
Output 30.17. Dependencies of the data that are not rules.

out →\to due is a rule of the library, every loan being due 21 days later: it could be added, and then due is better not stored at all but computed, since a table (out, due) would only store the rule. due →\to out follows from the same rule. title →\to book is an accident of 80 titles that happen to differ; making it a rule would forbid a second copy of a book with another number, or two books with the same title, and should not be added.

Exercise 30.10 ★★★

Prove Theorem 30.11.

Solution

Solution of Exercise 30.10.

Let TT satisfy X→YX \to Y. Every row of TT is in the join, since its projections on XYXY and XZXZ are in the two projections and agree on XX. Conversely, let (x,y,z)(x, y, z) be in the join: there are rows (x,y,z1)(x, y, z_1) and (x,y1,z)(x, y_1, z) in TT, the first giving the part on XYXY, the second the part on XZXZ. They agree on XX, so by X→YX \to Y they agree on YY: y1=yy_1 = y, and the second row is (x,y,z)(x, y, z), which is therefore in TT.

Exercise 30.11 ★★★

Prove Proposition 30.5.

Solution

Solution of Exercise 30.11.

Let S0=XS_0 = X and SiS_i the set after the ii-th addition. Every attribute added is in X+X^+: by induction, F⊢X→SiF \vdash X \to S_i; an addition uses some V→WV \to W of FF with V⊆SiV \subseteq S_i, so X→VX \to V by decomposition, X→WX \to W by transitivity, and X→SiWX \to S_i W by union. By soundness, Si⊆X+S_i \subseteq X^+. At the end, X+⊆SX^+ \subseteq S: when the loop stops, SS contains XX and, for every V→WV \to W in FF with V⊆SV \subseteq S, also WW. The two-row table of the proof of Theorem 30.4, equal on SS and different elsewhere, then satisfies FF; it satisfies X→AX \to A for every A∈X+A \in X^+, its rows agree on X⊆SX \subseteq S, so they agree on AA, and A∈SA \in S. Time: a pass that adds nothing ends the loop; every other pass applies at least one dependency, whose right side then stays in the set for good, so that it is never applied again; so there are at most ∣F∣+1|F| + 1 passes, each of ∣F∣|F| dependencies tested in O(∣R∣)O(|R|).

Exercise 30.12 ★★★

A query selects the loans with out_day below a bound, through an index on out_day or by a full scan. Measure both as the fraction selected grows, with exo_selectivity.py, find where the index stops helping, and explain why.

Solution

Solution of Exercise 30.12.

$ python exo_selectivity.py
selected   index (ms)   scan (ms)
    0.1%          0.4        19.9
    1.0%          4.8        22.2
    5.0%         22.4        23.8
   10.0%         43.3        26.9
   20.0%         99.0        25.6
   30.0%        131.9        28.8
   50.0%        206.4        33.0
  100.0%        423.9        37.2
Output 30.18. Range queries on 400,000 rows on the author’s laptop: best of three runs, in milliseconds.

The scan reads the whole table in order, at a nearly fixed cost, a little more as more rows are summed. The index finds the first matching entry quickly and then, for each matching entry, fetches its row from the table, at a place that has nothing to do with the order of out_day: one random access per row. Its cost grows in proportion to the number of rows selected, about 4 ms per 1 % here, while the scan’s grows by less than 20 ms from one end to the other. On this laptop the two meet between 5 % and 10 % of the table; beyond, the index loses, by a factor of more than ten when everything is selected. A query planner estimates the fraction from statistics on the column and chooses the scan for large ranges.

30.8 Problem: Redesigning the library’s spreadsheet

Problem 30.1

Weekend problem — Redesigning the library’s spreadsheet

The library replaces its spreadsheet by a database. The program below measures the old design, checks the new one and replays member 55’s move in both; Output 30.10 measures the index the desks will need.

# Part I: each fact is stored once per loan line.
for det, column in [("book", "book_id"), ("member", "member_id"), ("street", "street")]:
    sql = f"SELECT count(*), count(DISTINCT {column}) FROM wide"
    lines, values = conn.execute(sql).fetchone()
    print(f"facts of a {det:6}: {values:3} distinct, stored on {lines} lines,"
          f" {lines - values} copies too many")

# Part II: the left sides of the minimal cover that are not keys of the wide table.
bad = sorted({left for left, _ in minimal_cover(RULES)
              if closure(left, RULES) != frozenset(WIDE)}, key=sorted)
print("dependencies violating BCNF, by left side:", ", ".join(show(b) for b in bad))

# Part III: the BCNF tables; each checked, and the decomposition as a whole.
parts = bcnf(WIDE, RULES)
print(len(parts), "tables, violations left:",
      sum(bcnf_violation(p, RULES) is not None for p in parts),
      "| lossless:", lossless(WIDE, parts, RULES),
      "| preserving:", preserves(parts, RULES))

# Part IV: member 55 moves; one UPDATE in each design.
conn.execute("CREATE TABLE d_members AS SELECT DISTINCT member_id, first_name,"
             " last_name, street FROM wide")
wide = conn.execute("UPDATE wide SET street = 'Garden Lane', postcode = 'B-110'"
                    " WHERE member_id = 55").rowcount
one = conn.execute("UPDATE d_members SET street = 'Garden Lane'"
                   " WHERE member_id = 55").rowcount
print(f"the move: {wide} lines changed in the wide table, {one} in the members table")
Listing 30.14. The old design measured, the new one checked code/bachelor-2/30-database-design/listings/redesign.py
$ python redesign.py
facts of a book  :  80 distinct, stored on 400 lines, 320 copies too many
facts of a member:  60 distinct, stored on 400 lines, 340 copies too many
facts of a street:  23 distinct, stored on 400 lines, 377 copies too many
dependencies violating BCNF, by left side: {book}, {member}, {street}
4 tables, violations left: 0 | lossless: True | preserving: True
the move: 12 lines changed in the wide table, 1 in the members table
Output 30.11. Redundancy, violations, the four tables, and the move in each design.

Part I — The dependencies of the wide table.

  1. List the library’s rules as functional dependencies, and say which are about loans, books, members and streets.
  2. Explain the 320 copies too many of the books’ facts: what is stored 400 times, and what should be stored 80 times?
  3. Give an update anomaly, an insertion anomaly and a deletion anomaly of the wide table, with the library’s own facts.
  4. Why is title →\to book, which the data satisfy, not one of the rules?
  5. Does out →\to due hold? Should it be a rule, and what would that mean for the schema?
  6. Compute the closure of {member} and of {street}.

Part II — Keys and normal forms.

  1. Prove with the closure that {loan} is a candidate key of the wide table, and that it is the only one.
  2. Which dependencies violate BCNF? Why exactly three left sides?
  3. Is the wide table in 3NF? Use the definition.
  4. Is the table (member, first, last, street) in BCNF? And (street, postcode)?
  5. What would a table (member, street, postcode) violate?
  6. Give the number of violations before and after the redesign, as the program prints them.

Part III — A lossless decomposition.

  1. Draw the splits that lead to the four tables, naming the dependency used at each.
  2. Prove that each split is lossless with Heath’s theorem.
  3. Is the decomposition dependency-preserving? Check each rule.
  4. What did Output 30.3 check on the town’s data, and why are both counts needed?
  5. Why does the streets table have 23 rows and not 24?
  6. State the problem’s result for the design.

Part IV — Transactions and an index.

  1. How many rows does the move change in each design, and why can the new design not forget one?
  2. A loan and its fine are recorded together. Why must they be one transaction?
  3. Two desks lend the last copy of a book at the same moment. Which anomaly threatens, and how do you prevent it in SQLite?
  4. Which index do the desks need to list a member’s loans, and what does EXPLAIN QUERY PLAN show before and after it?
  5. From Output 30.10, how much faster is the index on a million loans, and what does it cost?
  6. Complete the problem’s result: from one wide table with three violating dependencies to four BCNF tables with none, and an index that is how many times faster on a million loans?
Solution

Solution of Problem 30.1.

1. Loans: loan →\to book member out due ret. Books: book →\to title author genre pages. Members: member →\to first last street. Streets: street →\to postcode.

2. Each of the 400 lines carries its book’s title, author, genre and pages: the facts of 80 books are written 400 times, 320 times more than needed.

3. Update: member 55’s move must change 12 lines, as in the hook. Insertion: a new member, or a newly bought book, cannot be recorded before a first loan, since every line is a loan. Deletion: removing the loans of a book, say to forget old loans, removes the book’s title and author with them.

4. The data satisfy it because the 80 titles happen to be different. The library could buy a second book with the same title, by another author, and the rule would then be false; a rule describes what must always hold.

5. It holds in the data, and it is a rule of the library: every loan is due 21 days after it goes out. Then due need not be stored; if it is, a table (out, due) would be the BCNF answer, which only stores the rule. Most designs compute it instead.

6. {member}+={member,first,last,street,postcode}\{\mathit{member}\}^+ = \{\mathit{member}, \mathit{first}, \mathit{last}, \mathit{street}, \mathit{postcode}\}; {street}+={street,postcode}\{\mathit{street}\}^+ = \{\mathit{street}, \mathit{postcode}\}.

7. {loan}+\{\mathit{loan}\}^+ contains the book and the member, hence their closures, hence all fourteen attributes. loan appears on no right side, so every key contains it, and every set containing it is a superkey: {loan} is the only candidate key.

8. The dependencies with left side book, member or street: those are the three left sides of the cover besides loan, and none of them is a key.

9. No: member →\to street has a left side that is not a superkey, and street is in no candidate key, the only one being {loan}.

10. Yes for both: in (member, first, last, street) the only non-trivial dependencies have member, a key, on the left; in (street, postcode), street is the key.

11. street →\to postcode with street not a key of that table, whose key is member: BCNF, and 3NF too since postcode is in no key. A move would again have to change two attributes.

12. Three violating left sides before, none after.

13. On book: {book, title, author, genre, pages} and the rest; the rest on member: {member, first, last, street, postcode} and the loans; the member part on street: {street, postcode} and {member, first, last, street}. This is the decomposition tree of the chapter.

14. At each split on X→YX \to Y, the part XYXY and the rest share exactly XX, and X→YX \to Y holds: Heath’s theorem applies, with ZZ the rest minus XX. The composition of lossless splits is lossless, as in Theorem 30.12.

15. Yes: each rule lies inside one table, loan →…\to \dots in the loans, book →…\to \dots in the books, member →\to first last street in the members, street →\to postcode in the streets.

16. That the join of the four tables gives back exactly the 400 lines: no line of the wide table is missing (lost) and no line appears that was not there (invented). A join always contains the original, so the second count is the one that tests losslessness; the first guards against an error in the SQL. It also checked that each table’s key is unique in the data.

17. The streets table is built from the wide table, which only knows the streets of members; one street has no member living on it. A real design would load the streets from their own source.

18. From one wide table with three violating dependencies, and 320, 340 and 377 extra copies of facts, to four BCNF tables with none; the decomposition is lossless and preserves every rule.

19. Twelve lines in the wide table, one row in the members table. The street is stored once per member, so there is nothing to forget.

20. If the program stops between the two writes, the loan is marked returned and the fine is missing, or the reverse: atomicity makes the pair all or nothing, as in Output 30.5.

21. A lost update: both desks read one copy available and both lend it. In SQLite, take the write right at the start with BEGIN IMMEDIATE, or make the check part of the update, SET available = available - 1 WHERE available > 0, and look at the count of changed rows.

22. An index on loans(member_id). Before it, the plan says SCAN loans, every row read; after it, SEARCH loans USING INDEX loans_member (member_id=?).

23. On the laptop of Output 30.10, about a thousand times faster on a million rows. It costs the time to build it, close to a second there, the space of a second sorted structure, and some work on each insertion or update of a loan.

24. From one wide table with three violating dependencies to four BCNF tables with none, and an index about a thousand times faster than a scan on a million loans, as measured on that laptop.

Termos definidos neste capítulo

Ver todos os 1050 termos do glossário