Algorithm Search⌘K

Data structurecore

N-ary storage model

Also called NSM, row-oriented storage, row store.

Store each record contiguously in a slotted page, so that a whole row costs one page read. A scan of one column still reads every byte of every row.

Space
O(N + k) extra
Counts
io ⌈N/m⌉ worst · average
Where
N = the number of records; k = the number of attributes; m = the number of records that fit in one page

The N-ary storage model (NSM) stores a table as whole records. All kk attribute values of a record lie next to each other in one slotted page, and the pages of the table form a heap file. It is the layout of most row stores. The decomposition storage model is the opposite choice: it stores each attribute in its own file, so a scan of one attribute reads only that attribute, but a whole record must be put together from kk files. The PAX layout is in between: it keeps the records of a page in that page, as NSM does, but groups their values by attribute inside the page.

In plain words

Think of a table as a pile of forms, one form per person, with the name, the age and the city on each form. NSM keeps each form whole and puts the forms in folders.

If you want everything about one person, you open one folder and take out one form. This is fast.

If you want only the ages of everybody, you must still take out every form and look at one line on each. You carry the names and cities around for nothing. A column store would keep a separate sheet with only the ages on it.

The abstract type

An NSM file is a table of records over a schema of kk attributes, with record ids.

  • insert(t): store the record tt and return its record id (page, slot).
  • get(rid): return all kk values of the record.
  • attr(rid, j): return value jj of the record.
  • delete(rid): remove the record.
  • scan(J): return the values of the attributes in the set JJ for every record.

Representation

A page is a slotted page: a header (n,e)(n, e) with the number of slots and the start of the record area, then nn slots of 4 bytes, each with the offset and the length of one record, then free space, and the records at the end of the page. A deleted record has the slot (0,0)(0, 0).

A record is a fixed part followed by a text part. The fixed part has one field per attribute, in schema order. In the sample code, an int field holds the value in 8 bytes. A text field holds, in 2 bytes, the offset inside the record where the text of that attribute ends. The text part holds the bytes of the text values in schema order.

Let fjf_j be the offset of field jj inside the fixed part and FF the size of the fixed part. These numbers depend only on the schema. A text value jj starts where the text value before it ends, or at FF if it is the first text value. So any attribute is found in a constant number of steps from the start of its record, and no field of another attribute is read on the way.

Operations

  1. ENCODE(t)
  2. 1fixed ← empty; text ← empty
  3. 2for j ← 0 to k - 1 do
  4. 3if attribute j is an int then append t[j] to fixed (8 bytes)
  5. 4else append t[j] to text; append F + |text| to fixed (2 bytes)
  6. 5return fixed followed by text
  7. INSERT(P, t)
  8. 6r ← ENCODE(t)
  9. 7if |r| + 4 > e - 4 - 4n then fail: page full
  10. 8e ← e - |r|; copy r to bytes [e, e + |r|)
  11. 9slot[n] ← (e, |r|); n ← n + 1
  12. 10return n - 1
  13. ATTR(P, s, j)
  14. 11(o, ℓ) ← slot[s]
  15. 12if attribute j is an int then return bytes [o + f_j, o + f_j + 8)
  16. 13a ← F if j is the first text attribute, else the end stored in the field of the text attribute before j
  17. 14b ← the end stored at o + f_j
  18. 15return bytes [o + a, o + b)
  19. SCAN(R, J)
  20. 16for each page P of R do
  21. 17for s ← 0 to n - 1 do
  22. 18if slot s is live then output ATTR(P, s, j) for each j in J

The file inserts into its last page and starts a new page when the last page is full. get is ATTR for every jj. delete frees the slot; the bytes of the record stay as a hole until the page is compacted, as described on the slotted page.

Example

Take a page of 64 bytes and the schema (id int, name text, age int). The fixed part has f=(0,8,10)f = (0, 8, 10) and F=18F = 18.

step record bytes nn ee slots free bytes
start 0 64 60
insert (962, Jane, 30) 22 at offset 42 1 42 0: (42, 22) 34
insert (7658, John, 45) 22 at offset 20 2 20 0: (42, 22), 1: (20, 22) 8

The first record holds 962 at bytes 42 to 49, the end 22 at bytes 50 and 51, the age 30 at bytes 52 to 59, and "Jane" at bytes 60 to 63. The end 22 is relative to the record: FF plus the 4 bytes of "Jane". A third record of 22 bytes needs 26 bytes with its slot, and only 8 are free, so the insert fails and the file starts a new page.

To read the age of record (page, 1), ATTR reads slot 1 at bytes 8 to 11, which gives o=20o = 20, and then the 8 bytes at 20+10=3020 + 10 = 30. It reads no other byte of the page. A scan of all the ages reads the slots and one 8-byte field of each record, but the cache brings in whole cache lines, and these lines hold the ids and names too.

Correctness

The invariant of the page is the one of the slotted page: the header, the slots and the records do not overlap, and the bytes of a live slot are the encoding of the record stored with it. Line L7 keeps it, since it allows a record only if the record and its new slot fit in the gap between the slots and the records.

The encoding is decodable because the field offsets fjf_j are the same for every record and each text field stores where its text ends. The texts are stored in schema order, so the text of attribute jj is between the end of the text attribute before it, or FF, and its own end, which is what lines L13 to L15 read. A scan visits each page and each slot once, and skips the free slots, so it returns every live record once, in record id order. The proof is in the proof file.

Proof: An NSM page returns every attribute of every stored record, and a scan reads the number of pages and cache lines given on the pagefull

We use the notation of the page. The schema has kk attributes. Attribute jj has a field at offset fjf_j of the fixed part, of wj=8w_j = 8 bytes for an int and 2 bytes for a str, and F=∑jwjF = \sum_j w_j is the size of the fixed part. A page of pp bytes has a header (n,e)(n, e) and slots 0,…,n−10, \ldots, n - 1 of 4 bytes each; a live slot holds (os,ℓs)(o_s, \ell_s) with os≠0o_s \ne 0.

Lemma 1 (the encoding). Let r=ENCODE(t)r = \text{ENCODE}(t). For every attribute jj, ATTR applied to rr at offset 0 returns t[j]t[j].

Proof. Lines L2 to L4 append the fields in schema order, so field jj starts at fjf_j in rr, and ∣r∣=F+∑j str∣t[j]∣|r| = F + \sum_{j \text{ str}} |t[j]|. For an int, field jj is t[j]t[j] itself, which line L12 reads. For a str, let j1<j2<…j_1 < j_2 < \ldots be the str attributes. When line L4 runs for jij_i, the text part holds t[j1]…t[ji]t[j_1] \ldots t[j_i], so the stored end bi=F+∑m≤i∣t[jm]∣b_i = F + \sum_{m \le i} |t[j_m]|, and the bytes [bi−1,bi)[b_{i-1}, b_i) of rr (with b0=Fb_0 = F) are t[ji]t[j_i]. Lines L13 and L14 read exactly a=bi−1a = b_{i-1} and b=bib = b_i, and line L15 returns those bytes. □\square

Lemma 2 (the page). After any sequence of INSERT and DELETE, (a) 4+4n≤e≤p4 + 4n \le e \le p; (b) the byte ranges [os,os+ℓs)[o_s, o_s + \ell_s) of the live slots are disjoint and lie in [e,p)[e, p); (c) the bytes of a live slot ss are the encoding of the record inserted with slot ss.

Proof. An empty page has n=0n = 0 and e=pe = p. INSERT runs line L8 only after the test of line L7, so ∣r∣+4≤e−4−4n|r| + 4 \le e - 4 - 4n. The new range [e−∣r∣,e)[e - |r|, e) lies above the new slot, which ends at 4+4(n+1)≤e−∣r∣4 + 4(n + 1) \le e - |r|, and below all older ranges, which lie in [e,p)[e, p). So (a) and (b) hold for the new values of nn and ee, no older byte changes, and (c) holds. DELETE writes only the 4 bytes of one slot and makes it not live, which keeps (a) to (c). □\square

Theorem 1 (round trip). For every live record id (P,s)(P, s) and attribute jj, ATTR(P,s,j)\text{ATTR}(P, s, j) returns t[j]t[j], where tt is the record inserted as (P,s)(P, s). SCAN outputs the attributes JJ of every live record exactly once, in record id order.

Proof. Line L11 gives oso_s, and by Lemma 2(c) the bytes at oso_s are ENCODE(t)(t). All offsets of lines L12 to L15 are relative to oso_s, so Lemma 1 applies. SCAN visits the pages in order and, in each, the slots 0,…,n−10, \ldots, n - 1 in order, and line L18 skips exactly the slots that are not live. INSERT never gives a new record a slot that was used before, so each live record has one slot. □\square

Theorem 2 (pages). If every record has the same length ss and records are only inserted, the file has ⌈N/m⌉\lceil N / m \rceil pages for NN records, where m=⌊(p−4)/(s+4)⌋m = \lfloor (p - 4) / (s + 4) \rfloor.

Proof. A page with cc records has e=p−cse = p - cs, so by line L7 it takes one more record if and only if s+4≤p−cs−4−4cs + 4 \le p - cs - 4 - 4c, that is, if and only if (c+1)(s+4)≤p−4(c + 1)(s + 4) \le p - 4, which is c+1≤mc + 1 \le m. So each page takes exactly mm records. The file opens a new page only when the last one refuses a record, so all pages but the last hold mm records, and the last holds from 1 to mm. □\square

Theorem 3 (cache lines). Assume all attributes are ints, so s=8ks = 8k, and that the line size LL is a power of 2, at least 8, that divides both ss and pp. A scan of one attribute of a page with cc records reads c+⌈(4+4c)/L⌉c + \lceil (4 + 4c) / L \rceil distinct cache lines, and a scan of all attributes reads cs/L+⌈(4+4c)/L⌉cs / L + \lceil (4 + 4c) / L \rceil.

Proof. The header and the slots are the bytes [0,4+4c)[0, 4 + 4c), which meet ⌈(4+4c)/L⌉\lceil (4 + 4c) / L \rceil lines. Record ii lies at p−(i+1)sp - (i + 1)s, which is a multiple of LL, so its ss bytes fill exactly s/Ls / L whole lines, and the lines of different records differ. An 8-byte field at an offset that is a multiple of 8 lies in one line, because 8 divides LL; so the one attribute costs one line per record, and all attributes cost s/Ls / L lines per record. The record lines start at e=p−cse = p - cs, a multiple of LL with e≥4+4ce \ge 4 + 4c, so they are disjoint from the lines of the slots. □\square

So the scan of one attribute reads one line per record, while a dense array of the same values would need only 8/L8 / L lines per record. That gap is the cost that the PAX layout removes.

Complexity

The page I/O is counted in the external memory model, with one page per block. In the external memory model, the memory holds M/B blocks; this is the number of buffer pages B of this page. Every operation here needs only one buffer page. The costs do not count the output, and they do not separate sequential and random I/O; a scan reads the pages in file order, which is sequential when the file is contiguous on disk.

operation page reads CPU work
insert 1 (plus a write) O(k+r)O(k + r) for a record of rr bytes
get 1 O(k+r)O(k + r)
attr 1 O(1)O(1) plus the length of the value
scan(J) ⌈N/m⌉\lceil N/m \rceil O(N⋅∣J∣)O(N \cdot \lvert J \rvert) plus the bytes returned

When every record has ss bytes, a page holds m=⌊(p−4)/(s+4)⌋m = \lfloor (p - 4)/(s + 4) \rfloor records, so the scan reads ⌈N/m⌉\lceil N/m \rceil pages whatever JJ is. A scan of one attribute costs as much I/O as a scan of all kk.

The same waste happens between memory and the CPU cache. Take ints only, s=8ks = 8k, and a cache line of LL bytes that divides ss and the page size. A scan of one attribute of a page with cc records reads c+⌈(4+4c)/L⌉c + \lceil (4 + 4c)/L \rceil cache lines, one line per record plus the slots, while the full scan reads cs/L+⌈(4+4c)/L⌉cs/L + \lceil (4 + 4c)/L \rceil. A dense array of the one attribute would take only 8c/L8c/L lines. With p=4096p = 4096, k=8k = 8 and L=32L = 32, a page holds 60 records, and the scan of one attribute reads 68 lines against 128 for all attributes and 15 for a dense array.

The space overhead is 4 bytes of slot per record and 2 bytes per text field, plus the header of each page.

Variants

  • Null bitmap. Most systems start a record with a bitmap of one bit per attribute that says whether the value is null, and leave out the fields of null values. PostgreSQL does this in its tuple header.
  • Records from the start of the page. The records can also grow from the start of the page and the slots from the end. The choice does not change the costs.
  • Offsets for all fields. Instead of the end of each text value, a record can store the start of every field. This costs more bytes but removes the dependency on the text attribute before.
  • Vertical partitions. A table can be split into groups of attributes that queries read together, each stored in NSM. This is vertical fragmentation, and DSM is the extreme with one attribute per group.

When to use it

Use NSM when queries read or change whole records, or many attributes of few records: online transaction processing, inserts of single rows, and lookups by key through an index. A record is one page read, and an insert writes one page. Use a column layout, DSM or PAX, when most queries scan a few attributes of many records.

Pitfalls

  • Wide records and narrow scans. A query that sums one int of a table with 50 attributes reads all 50 from disk and brings them through the cache. Adding an index on that attribute or a column copy helps; a faster disk does not change the ratio.
  • The field offsets depend on the text before. If a record stores only lengths, as in a simple length-prefixed format, finding attribute jj needs a walk over all the text values before it. Store ends or offsets, as here.
  • Alignment. Values that are not aligned to their size can cross a cache line or need slower loads on some CPUs. Systems often pad the fixed part, which costs space.
  • Records that grow. An update that makes a record longer may not fit in its page; the slotted page then needs a forwarding address.

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.

n_ary_storage_model.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/n-ary-storage-model/. The authors are listed in prov/HJWXRS.jsonl.

"""The N-ary storage model: whole records, one after another, in slotted pages.

A schema is a list of attribute types, "int" (8 bytes, signed) or "str"
(UTF-8 text of variable length). A record is encoded as a fixed part with one
field per attribute, followed by the bytes of its text values. An int field
holds the value. A str field holds, in 2 bytes, the offset inside the record of
the end of the value, so that any attribute is found in O(1) steps.

A page has a 4-byte header (n, e): the number of slots and the start of the
record area. The slots follow, 4 bytes each (offset, length), with (0, 0) for
a deleted record. Records grow from the end of the page toward the slots.

Every read of page bytes goes through Page.read, which logs the byte range, so
that tests can count the cache lines that a scan touches.
"""

import struct
from typing import Iterator, List, Optional, Sequence, Set, Tuple

HEADER = struct.Struct("<HH")
SLOT = struct.Struct("<HH")
INT = struct.Struct("<q")
END = struct.Struct("<H")


class PageFull(Exception):
    """The record does not fit in the free space of the page."""


class Schema:
    def __init__(self, types: Sequence[str]) -> None:
        if not types or any(t not in ("int", "str") for t in types):
            raise ValueError("a schema is a non-empty list of 'int' and 'str'")
        self.types = list(types)
        self.field: List[int] = []          # f_j, the offset of field j in the fixed part
        self.prev: List[Optional[int]] = []  # the str attribute before j, if any
        off, last = 0, None
        for j, t in enumerate(self.types):
            self.field.append(off)
            self.prev.append(last)
            off += INT.size if t == "int" else END.size
            if t == "str":
                last = j
        self.fixed = off                    # F, the size of the fixed part

    @property
    def k(self) -> int:
        return len(self.types)

    def encode(self, t: Sequence[object]) -> bytes:
        if len(t) != self.k:
            raise ValueError("wrong number of attributes")
        fixed, var = bytearray(), bytearray()                 # @line L1
        for j, typ in enumerate(self.types):                  # @line L2
            if typ == "int":                                  # @line L3
                fixed += INT.pack(t[j])                       # @line L3
            else:
                var += str(t[j]).encode("utf-8")              # @line L4
                fixed += END.pack(self.fixed + len(var))      # @line L4
        return bytes(fixed + var)                             # @line L5


class Page:
    def __init__(self, size: int) -> None:
        if not 8 <= size <= 65536:
            raise ValueError("page size must be from 8 to 65536 bytes")
        self.size = size
        self.data = bytearray(size)
        self._set_header(0, size if size < 65536 else 65535)
        self.log: List[Tuple[int, int]] = []

    def _set_header(self, n: int, e: int) -> None:
        HEADER.pack_into(self.data, 0, n, e)

    def read(self, off: int, length: int) -> bytes:
        self.log.append((off, length))
        return bytes(self.data[off:off + length])

    def header(self) -> Tuple[int, int]:
        return HEADER.unpack(self.read(0, HEADER.size))

    def slot(self, s: int) -> Tuple[int, int]:
        return SLOT.unpack(self.read(HEADER.size + SLOT.size * s, SLOT.size))

    def free(self) -> int:
        n, e = HEADER.unpack_from(self.data, 0)
        return e - HEADER.size - SLOT.size * n

    def insert(self, schema: Schema, t: Sequence[object]) -> int:
        r = schema.encode(t)                                  # @line L6
        n, e = HEADER.unpack_from(self.data, 0)
        if len(r) + SLOT.size > self.free():                  # @line L7
            raise PageFull(len(r))                            # @line L7
        e -= len(r)                                           # @line L8
        self.data[e:e + len(r)] = r                           # @line L8
        SLOT.pack_into(self.data, HEADER.size + SLOT.size * n, e, len(r))  # @line L9
        self._set_header(n + 1, e)                            # @line L9
        return n                                              # @line L10

    def delete(self, s: int) -> None:
        """Free slot s. The bytes become a hole; see the slotted page for compaction."""
        n, _ = HEADER.unpack_from(self.data, 0)
        if not 0 <= s < n or SLOT.unpack_from(self.data, HEADER.size + SLOT.size * s)[0] == 0:
            raise KeyError(s)
        SLOT.pack_into(self.data, HEADER.size + SLOT.size * s, 0, 0)

    def attr(self, schema: Schema, s: int, j: int, o: Optional[int] = None) -> object:
        if o is None:
            o, _ = self.slot(s)                               # @line L11
        f = schema.field[j]
        if schema.types[j] == "int":                          # @line L12
            return INT.unpack(self.read(o + f, INT.size))[0]  # @line L12
        prev = schema.prev[j]
        if prev is not None:                                  # @line L13
            a = END.unpack(self.read(o + schema.field[prev], END.size))[0]  # @line L13
        else:
            a = schema.fixed                                  # @line L13
        b = END.unpack(self.read(o + f, END.size))[0]         # @line L14
        return self.read(o + a, b - a).decode("utf-8")        # @line L15

    def live(self) -> Iterator[Tuple[int, int]]:
        n, _ = self.header()
        for s in range(n):                                    # @line L17
            o, _ = self.slot(s)
            if o != 0:                                        # @line L18
                yield s, o


class NSMFile:
    """A table in NSM pages. New records go to the last page, or to a new page."""

    def __init__(self, schema: Sequence[str], page_size: int = 4096) -> None:
        self.schema = Schema(schema)
        self.page_size = page_size
        self.pages: List[Page] = []

    def insert(self, t: Sequence[object]) -> Tuple[int, int]:
        """Store t and return its record id (page, slot)."""
        if self.pages:
            try:
                return len(self.pages) - 1, self.pages[-1].insert(self.schema, t)
            except PageFull:
                pass
        page = Page(self.page_size)
        s = page.insert(self.schema, t)   # raises PageFull if t is bigger than a page
        self.pages.append(page)
        return len(self.pages) - 1, s

    def delete(self, rid: Tuple[int, int]) -> None:
        self.pages[rid[0]].delete(rid[1])

    def get(self, rid: Tuple[int, int]) -> Tuple[object, ...]:
        page = self.pages[rid[0]]
        o, _ = page.slot(rid[1])
        if o == 0:
            raise KeyError(rid)
        return tuple(page.attr(self.schema, rid[1], j, o) for j in range(self.schema.k))

    def scan(self, cols: Optional[Sequence[int]] = None) -> Iterator[Tuple[object, ...]]:
        """Yield the values of the attributes cols of every live record, in record id order."""
        cols = range(self.schema.k) if cols is None else cols
        for page in self.pages:                               # @line L16
            for s, o in page.live():                          # @line L17 L18
                yield tuple(page.attr(self.schema, s, j, o) for j in cols)  # @line L18

    # ------------------------------------------------------------ measures

    def clear_logs(self) -> None:
        for page in self.pages:
            page.log.clear()

    def lines_touched(self, line: int) -> int:
        """The number of distinct (page, cache line) pairs read since the last clear_logs."""
        seen: Set[Tuple[int, int]] = set()
        for i, page in enumerate(self.pages):
            for off, length in page.log:
                for x in range(off // line, (off + max(length, 1) - 1) // line + 1):
                    seen.add((i, x))
        return len(seen)

    def check(self) -> None:
        for page in self.pages:
            n, e = HEADER.unpack_from(page.data, 0)
            assert HEADER.size + SLOT.size * n <= e <= page.size
            spans = sorted(SLOT.unpack_from(page.data, HEADER.size + SLOT.size * s) for s in range(n))
            spans = [x for x in spans if x[0] != 0]
            for (o1, l1), (o2, _) in zip(spans, spans[1:]):
                assert o1 + l1 <= o2
            assert all(e <= o and o + ln <= page.size for o, ln in spans)


def records_per_page(page_size: int, record_length: int) -> int:
    """How many records of one length fit in an empty page."""
    usable = min(page_size, 65535) - HEADER.size
    return usable // (record_length + SLOT.size)
test_n_ary_storage_model.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/n-ary-storage-model/. The authors are listed in prov/HJWXRS.jsonl.

import math
import random
import unittest

from n_ary_storage_model import NSMFile, Page, PageFull, Schema, records_per_page


def random_tuple(rng, types):
    out = []
    for t in types:
        if t == "int":
            out.append(rng.randrange(-2 ** 63, 2 ** 63))
        else:
            out.append("".join(rng.choice("abcxyzé") for _ in range(rng.randrange(0, 12))))
    return tuple(out)


class TestNSM(unittest.TestCase):
    def test_worked_example(self):
        schema = Schema(["int", "str", "int"])
        page = Page(64)
        self.assertEqual(page.insert(schema, (962, "Jane", 30)), 0)
        self.assertEqual(page.insert(schema, (7658, "John", 45)), 1)
        page.log.clear()
        self.assertEqual(page.header(), (2, 20))
        self.assertEqual(page.slot(0), (42, 22))
        self.assertEqual(page.slot(1), (20, 22))
        self.assertEqual(page.free(), 8)
        self.assertEqual(bytes(page.data[60:64]), b"Jane")
        page.log.clear()
        self.assertEqual(page.attr(schema, 1, 2), 45)
        self.assertEqual(page.log, [(8, 4), (30, 8)])
        self.assertEqual(page.attr(schema, 0, 1), "Jane")
        with self.assertRaises(PageFull):
            page.insert(schema, (1, "Ann", 2))

    def test_round_trip_against_a_list(self):
        for seed in range(30):
            rng = random.Random(seed)
            types = [rng.choice(["int", "str"]) for _ in range(rng.randrange(1, 6))]
            f = NSMFile(types, page_size=rng.choice([128, 256, 4096]))
            model = {}
            for _ in range(300):
                if model and rng.random() < 0.2:
                    rid = rng.choice(sorted(model))
                    f.delete(rid)
                    del model[rid]
                else:
                    t = random_tuple(rng, types)
                    rid = f.insert(t)
                    self.assertNotIn(rid, model)
                    model[rid] = t
                f.check()
            self.assertEqual(list(f.scan()), [model[r] for r in sorted(model)])
            for rid in rng.sample(sorted(model), min(10, len(model))):
                self.assertEqual(f.get(rid), model[rid])
            cols = sorted(rng.sample(range(len(types)), rng.randrange(1, len(types) + 1)))
            self.assertEqual(list(f.scan(cols)),
                             [tuple(model[r][j] for j in cols) for r in sorted(model)])

    def test_page_count(self):
        for k in (1, 2, 8, 16):
            s = 8 * k
            for n_records in (0, 1, 59, 60, 61, 1000):
                f = NSMFile(["int"] * k, page_size=4096)
                for i in range(n_records):
                    f.insert(tuple(range(i, i + k)))
                m = records_per_page(4096, s)
                self.assertEqual(m, (4096 - 4) // (s + 4))
                self.assertEqual(len(f.pages), math.ceil(n_records / m))

    def test_cache_lines_of_a_scan(self):
        p, line, k = 4096, 32, 8
        s = 8 * k
        m = (p - 4) // (s + 4)
        self.assertEqual(m, 60)
        for n_records in (60, 150, 600):
            f = NSMFile(["int"] * k, page_size=p)
            for i in range(n_records):
                f.insert(tuple(range(i, i + k)))
            sizes = [min(m, n_records - m * i) for i in range(len(f.pages))]
            slot_lines = sum(math.ceil((4 + 4 * c) / line) for c in sizes)
            f.clear_logs()
            self.assertEqual(sum(1 for _ in f.scan([3])), n_records)
            self.assertEqual(f.lines_touched(line), n_records + slot_lines)
            f.clear_logs()
            list(f.scan())
            self.assertEqual(f.lines_touched(line), n_records * s // line + slot_lines)

    def test_records_do_not_overlap_after_many_pages(self):
        f = NSMFile(["str", "int"], page_size=64)
        rids = [f.insert(("x" * (i % 30), i)) for i in range(200)]
        f.check()
        self.assertEqual([f.get(r)[1] for r in rids], list(range(200)))
        with self.assertRaises(PageFull):
            f.insert(("y" * 60, 0))

    def test_bad_schema(self):
        with self.assertRaises(ValueError):
            Schema([])
        with self.assertRaises(ValueError):
            Schema(["float"])


if __name__ == "__main__":
    unittest.main()

History

Copeland and Khoshafian (1985) proposed the decomposition storage model as the alternative to the usual layout of whole records. Ailamaki, DeWitt, Hill and Skounakis (2001) call the usual layout the N-ary storage model, "a.k.a., slotted pages", measure its cache behavior, and propose PAX. Row stores such as PostgreSQL, MySQL with InnoDB and SQLite keep whole rows in their pages, in heap pages or in the leaves of B+ trees. Abadi, Boncz, Harizopoulos, Idreos and Madden (2013) survey the column stores that replaced NSM for analytic workloads.

References

  1. A decomposition storage model, the comparison of the decomposed layout with the usual layout of whole records
  2. Weaving relations for cache performance, the section on NSM, its page layout and its cache behavior when a query reads one attribute
  3. Raghu Ramakrishnan and Johannes Gehrke, Database Management Systems, third edition, McGraw-Hill (2003), Chapter 9 (storing data: disks and files), the sections on record formats and page formats
  4. The design and implementation of modern column-oriented database systems, the introduction, the comparison of row stores and column stores

Where this leads

About this page

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of space.extra
  • a full proof of io.average
  • a full proof of io.worst
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/HJWXRS/text.yaml