Programming Search⌘K

Patterncore

Class Table Inheritance

Also called class table inheritance pattern, joined table inheritance, table per type, TPT, table per subclass, multi-table inheritance.

Class Table Inheritance stores an inheritance hierarchy with one table for each class, so an object is spread over the tables of its class and of each class above it, joined by one key.

Family
architectural
Intent
Represents an inheritance hierarchy of classes with one table for each class.

Intent

Class Table Inheritance "Represents an inheritance hierarchy of classes with one table for each class."1 Each table holds the fields that its class declares. One object is a row in the table of its class and a row in the table of each class above it, all with the same key.

Problem

"A very visible aspect of the object-relational mismatch is the fact that relational databases don't support inheritance. You want database structures that map clearly to the objects and allow links anywhere in the inheritance structure."1 A program has Player, its subclasses Footballer and Cricketer, and Bowler below Cricketer. A single table for all of them has many null columns and cannot make a subclass column NOT NULL. Another table, such as a table of match results, may need a foreign key to any player, or only to cricketers.

Solution

"Class Table Inheritance supports this by using one database table per class in the inheritance structure."1 Each table has the columns of the fields that its class adds. The table of a subclass has the same key as the table of its superclass, and that key is also a foreign key to the superclass table. Entity Framework Core describes it: "Properties that belong solely to a base type or derived type are stored in a table that maps to that type. Tables that map to derived types also store a foreign key that joins the derived table with the base table."2

To save an object, the mapper inserts one row in each table on the path from the root to the class of the object. To load it, the mapper joins these tables on the key. "Querying for a particular subclass in the hierarchy will render as a SQL JOIN along all tables in its inheritance path."3

  classes                       tables (one key: id)
  Player(name)                  player(id, name)            1 Ann | 2 Bo | 3 Cy
   |- Footballer(club)          footballer(id, club)        1 Lions
   |- Cricketer(runs)           cricketer(id, runs)         2 412 | 3 95
       |- Bowler(wickets)       bowler(id, wickets)         3 31
  load bowler 3:  player join cricketer join bowler on id

The participants are the class hierarchy; a table for each class with the fields that the class declares; the shared key, which is the primary key of each table and a foreign key to the table above; and the mapper, which writes and joins the rows of all the tables on the path of a class.

The following program saves a bowler as three rows, and joins them to load it.

import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
create table player (id integer primary key, name text);
create table cricketer (id integer primary key references player(id), runs integer);
create table bowler (id integer primary key references cricketer(id), wickets integer);
""")


class Player:
    def __init__(self, name):
        self.name = name


class Cricketer(Player):
    def __init__(self, name, runs):
        super().__init__(name)
        self.runs = runs


class Bowler(Cricketer):
    def __init__(self, name, runs, wickets):
        super().__init__(name, runs)
        self.wickets = wickets


def insert(p):
    # One row in the table of each class on the path from the root, all with the same key.
    p.id = db.execute("insert into player (name) values (?)", (p.name,)).lastrowid
    if isinstance(p, Cricketer):
        db.execute("insert into cricketer values (?, ?)", (p.id, p.runs))
    if isinstance(p, Bowler):
        db.execute("insert into bowler values (?, ?)", (p.id, p.wickets))


def find_bowler(id):
    sql = """select p.name, c.runs, b.wickets from player p
             join cricketer c on c.id = p.id join bowler b on b.id = c.id where p.id = ?"""
    return Bowler(*db.execute(sql, (id,)).fetchone())


insert(Bowler("Cy", 95, 31))
for table in ("player", "cricketer", "bowler"):
    print(table, db.execute(f"select * from {table}").fetchall())
cy = find_bowler(1)
print(cy.name, cy.runs, cy.wickets)
Output
player [(1, 'Cy')]
cricketer [(1, 95)]
bowler [(1, 31)]
Cy 95 31

Example

Each example file saves a footballer, a cricketer and a bowler and prints the four tables. The footballer has rows in two tables, and the bowler has rows in three. It then loads each player by its key. The root row has no type column, so the mapper looks for the key in the subclass tables to find the class, and prints the tables that it used. A query for cricketers joins the player and cricketer tables and finds Bo and Cy, because the bowler also has a cricketer row. The last line deletes the bowler, which removes three rows, children first. The Python file uses SQLite with foreign keys on. The JavaScript, Java, Go and Rust files keep a map for each table, all keyed by the same id.

PythonGitHub
import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
pragma foreign_keys = on;
create table player (id integer primary key, name text not null);
create table footballer (id integer primary key references player(id), club text not null);
create table cricketer (id integer primary key references player(id), runs integer not null);
create table bowler (id integer primary key references cricketer(id), wickets integer not null);
""")


class Player:
    def __init__(self, name, id=None):
        self.id, self.name = id, name


class Footballer(Player):
    def __init__(self, name, club, id=None):
        super().__init__(name, id)
        self.club = club

    def describe(self):
        return f"Footballer {self.name}, club {self.club}"


class Cricketer(Player):
    def __init__(self, name, runs, id=None):
        super().__init__(name, id)
        self.runs = runs

    def describe(self):
        return f"Cricketer {self.name}, runs {self.runs}"


class Bowler(Cricketer):
    def __init__(self, name, runs, wickets, id=None):
        super().__init__(name, runs, id)
        self.wickets = wickets

    def describe(self):
        return f"Bowler {self.name}, runs {self.runs}, wickets {self.wickets}"


def insert(p):
    # One row in the table of each class on the path from the root, all with the same key.
    p.id = db.execute("insert into player (name) values (?)", (p.name,)).lastrowid
    if isinstance(p, Footballer):
        db.execute("insert into footballer values (?, ?)", (p.id, p.club))
    if isinstance(p, Cricketer):
        db.execute("insert into cricketer values (?, ?)", (p.id, p.runs))
    if isinstance(p, Bowler):
        db.execute("insert into bowler values (?, ?)", (p.id, p.wickets))


def find(id):
    # The root row has no type, so the mapper looks for the key in the tables of the subclasses.
    (name,) = db.execute("select name from player where id = ?", (id,)).fetchone()
    tables = ["player"]
    footballer = db.execute("select club from footballer where id = ?", (id,)).fetchone()
    if footballer:
        return Footballer(name, footballer[0], id), tables + ["footballer"]
    (runs,) = db.execute("select runs from cricketer where id = ?", (id,)).fetchone()
    bowler = db.execute("select wickets from bowler where id = ?", (id,)).fetchone()
    if bowler:
        return Bowler(name, runs, bowler[0], id), tables + ["cricketer", "bowler"]
    return Cricketer(name, runs, id), tables + ["cricketer"]


def delete(p):
    count = 0
    for table in ("bowler", "cricketer", "footballer", "player"):  # Children first.
        count += db.execute(f"delete from {table} where id = ?", (p.id,)).rowcount
    return count


def show(table):
    rows = db.execute(f"select * from {table} order by id")
    return " | ".join(" ".join(str(v) for v in row) for row in rows)


ann, bo, cy = Footballer("Ann", "Lions"), Cricketer("Bo", 412), Bowler("Cy", 95, 31)
for p in (ann, bo, cy):
    insert(p)
for table in ("player", "footballer", "cricketer", "bowler"):
    print(f"{table}: {show(table)}")
for id in (1, 2, 3):
    p, tables = find(id)
    print(f"loaded: {p.describe()} (tables: {', '.join(tables)})")
sql = "select p.name from player p join cricketer c on c.id = p.id order by p.id"
print("cricketers:", ", ".join(n for (n,) in db.execute(sql)))
print("delete Cy: rows deleted", delete(cy))
Output
player: 1 Ann | 2 Bo | 3 Cy
footballer: 1 Lions
cricketer: 2 412 | 3 95
bowler: 3 31
loaded: Footballer Ann, club Lions (tables: player, footballer)
loaded: Cricketer Bo, runs 412 (tables: player, cricketer)
loaded: Bowler Cy, runs 95, wickets 31 (tables: player, cricketer, bowler)
cricketers: Bo, Cy
delete Cy: rows deleted 3
  • Verdict: idiom. Each table has the key of the player row as its primary key and as a foreign key to the table above, and pragma foreign_keys = on makes SQLite check it. insert writes one row for each class on the path, with isinstance tests.
  • The root table has no type column, so find looks for the key in the footballer and bowler tables to choose the class.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    // One table for each class, all keyed by the same id.
    static final Map<Long, String> PLAYER = new TreeMap<>();
    static final Map<Long, String> FOOTBALLER = new TreeMap<>();
    static final Map<Long, Integer> CRICKETER = new TreeMap<>();
    static final Map<Long, Integer> BOWLER = new TreeMap<>();
    static long lastId = 0;

    abstract static class Player {
        Long id;
        final String name;

        Player(String name) {
            this.name = name;
        }

        abstract String describe();
    }

    static class Footballer extends Player {
        final String club;

        Footballer(String name, String club) {
            super(name);
            this.club = club;
        }

        String describe() {
            return "Footballer " + name + ", club " + club;
        }
    }

    static class Cricketer extends Player {
        final int runs;

        Cricketer(String name, int runs) {
            super(name);
            this.runs = runs;
        }

        String describe() {
            return "Cricketer " + name + ", runs " + runs;
        }
    }

    static class Bowler extends Cricketer {
        final int wickets;

        Bowler(String name, int runs, int wickets) {
            super(name, runs);
            this.wickets = wickets;
        }

        @Override
        String describe() {
            return "Bowler " + name + ", runs " + runs + ", wickets " + wickets;
        }
    }

    record Loaded(Player player, List<String> tables) {}

    static void insert(Player p) {
        // One row in the table of each class on the path from the root, all with the same key.
        p.id = ++lastId;
        PLAYER.put(p.id, p.name);
        if (p instanceof Footballer f) {
            FOOTBALLER.put(p.id, f.club);
        }
        if (p instanceof Cricketer c) {
            CRICKETER.put(p.id, c.runs);
        }
        if (p instanceof Bowler b) {
            BOWLER.put(p.id, b.wickets);
        }
    }

    static Loaded find(long id) {
        // The root row has no type, so the mapper looks for the key in the tables of the subclasses.
        String name = PLAYER.get(id);
        Player p;
        List<String> used;
        if (FOOTBALLER.containsKey(id)) {
            p = new Footballer(name, FOOTBALLER.get(id));
            used = List.of("player", "footballer");
        } else if (BOWLER.containsKey(id)) {
            p = new Bowler(name, CRICKETER.get(id), BOWLER.get(id));
            used = List.of("player", "cricketer", "bowler");
        } else {
            p = new Cricketer(name, CRICKETER.get(id));
            used = List.of("player", "cricketer");
        }
        p.id = id;
        return new Loaded(p, used);
    }

    static int delete(Player p) {
        int count = 0;
        for (Map<Long, ?> table : List.of(BOWLER, CRICKETER, FOOTBALLER, PLAYER)) { // Children first.
            if (table.remove(p.id) != null) {
                count++;
            }
        }
        return count;
    }

    static String show(Map<Long, ?> table) {
        List<String> parts = new ArrayList<>();
        for (var e : table.entrySet()) {
            parts.add(e.getKey() + " " + e.getValue());
        }
        return String.join(" | ", parts);
    }

    public static void main(String[] args) {
        Player ann = new Footballer("Ann", "Lions");
        Player bo = new Cricketer("Bo", 412);
        Player cy = new Bowler("Cy", 95, 31);
        for (Player p : List.of(ann, bo, cy)) {
            insert(p);
        }
        System.out.println("player: " + show(PLAYER));
        System.out.println("footballer: " + show(FOOTBALLER));
        System.out.println("cricketer: " + show(CRICKETER));
        System.out.println("bowler: " + show(BOWLER));
        for (long id = 1; id <= 3; id++) {
            Loaded l = find(id);
            System.out.println("loaded: " + l.player().describe() + " (tables: " + String.join(", ", l.tables()) + ")");
        }
        List<String> names = new ArrayList<>();
        for (long id : CRICKETER.keySet()) {
            names.add(PLAYER.get(id));
        }
        System.out.println("cricketers: " + String.join(", ", names));
        System.out.println("delete Cy: rows deleted " + delete(cy));
    }
}
Output
player: 1 Ann | 2 Bo | 3 Cy
footballer: 1 Lions
cricketer: 2 412 | 3 95
bowler: 3 31
loaded: Footballer Ann, club Lions (tables: player, footballer)
loaded: Cricketer Bo, runs 412 (tables: player, cricketer)
loaded: Bowler Cy, runs 95, wickets 31 (tables: player, cricketer, bowler)
cricketers: Bo, Cy
delete Cy: rows deleted 3
  • Verdict: idiom. Each table is a TreeMap keyed by the shared id, and insert uses pattern matching for instanceof, so a Bowler also gets a cricketer row.
  • With JPA or Hibernate, @Inheritance(strategy = InheritanceType.JOINED) on the root class gives the same tables, and the provider writes and joins the rows.
JavaScriptGitHub
// A stand-in for the database: one table for each class, all keyed by the same id.
const tables = { player: new Map(), footballer: new Map(), cricketer: new Map(), bowler: new Map() };
let lastId = 0;

class Player {
  constructor(name, id = null) {
    this.id = id;
    this.name = name;
  }
}

class Footballer extends Player {
  constructor(name, club, id = null) {
    super(name, id);
    this.club = club;
  }
  describe() {
    return `Footballer ${this.name}, club ${this.club}`;
  }
}

class Cricketer extends Player {
  constructor(name, runs, id = null) {
    super(name, id);
    this.runs = runs;
  }
  describe() {
    return `Cricketer ${this.name}, runs ${this.runs}`;
  }
}

class Bowler extends Cricketer {
  constructor(name, runs, wickets, id = null) {
    super(name, runs, id);
    this.wickets = wickets;
  }
  describe() {
    return `Bowler ${this.name}, runs ${this.runs}, wickets ${this.wickets}`;
  }
}

function insert(p) {
  // One row in the table of each class on the path from the root, all with the same key.
  p.id = ++lastId;
  tables.player.set(p.id, [p.name]);
  if (p instanceof Footballer) tables.footballer.set(p.id, [p.club]);
  if (p instanceof Cricketer) tables.cricketer.set(p.id, [p.runs]);
  if (p instanceof Bowler) tables.bowler.set(p.id, [p.wickets]);
}

function find(id) {
  // The root row has no type, so the mapper looks for the key in the tables of the subclasses.
  const [name] = tables.player.get(id);
  if (tables.footballer.has(id)) {
    return [new Footballer(name, tables.footballer.get(id)[0], id), ["player", "footballer"]];
  }
  const [runs] = tables.cricketer.get(id);
  if (tables.bowler.has(id)) {
    return [new Bowler(name, runs, tables.bowler.get(id)[0], id), ["player", "cricketer", "bowler"]];
  }
  return [new Cricketer(name, runs, id), ["player", "cricketer"]];
}

function remove(p) {
  let count = 0;
  for (const t of ["bowler", "cricketer", "footballer", "player"]) {
    if (tables[t].delete(p.id)) count++; // Children first.
  }
  return count;
}

function show(t) {
  return [...tables[t]].map(([id, cols]) => [id, ...cols].join(" ")).join(" | ");
}

const ann = new Footballer("Ann", "Lions");
const bo = new Cricketer("Bo", 412);
const cy = new Bowler("Cy", 95, 31);
for (const p of [ann, bo, cy]) insert(p);
for (const t of ["player", "footballer", "cricketer", "bowler"]) console.log(`${t}: ${show(t)}`);
for (const id of [1, 2, 3]) {
  const [p, used] = find(id);
  console.log(`loaded: ${p.describe()} (tables: ${used.join(", ")})`);
}
const cricketers = [...tables.cricketer.keys()].map((id) => tables.player.get(id)[0]);
console.log(`cricketers: ${cricketers.join(", ")}`);
console.log(`delete Cy: rows deleted ${remove(cy)}`);
Output
player: 1 Ann | 2 Bo | 3 Cy
footballer: 1 Lions
cricketer: 2 412 | 3 95
bowler: 3 31
loaded: Footballer Ann, club Lions (tables: player, footballer)
loaded: Cricketer Bo, runs 412 (tables: player, cricketer)
loaded: Bowler Cy, runs 95, wickets 31 (tables: player, cricketer, bowler)
cricketers: Bo, Cy
delete Cy: rows deleted 3
  • Verdict: idiom. Each table is a Map from the shared id to the columns that its class declares. insert uses instanceof, so a Bowler gets a row in the cricketer table too.
  • remove deletes the rows from the bowler table first and from the player table last, in the order that the foreign keys need.
package main

import (
	"fmt"
	"sort"
	"strings"
)

// One table for each class, all keyed by the same id.
var (
	playerTable     = map[int64]string{}
	footballerTable = map[int64]string{}
	cricketerTable  = map[int64]int{}
	bowlerTable     = map[int64]int{}
	lastID          int64
)

// Player is the interface of the hierarchy; Go has no class inheritance, so
// Bowler embeds Cricketer to reuse its fields.
type Player interface{ Describe() string }

type Footballer struct {
	ID   int64
	Name string
	Club string
}

type Cricketer struct {
	ID   int64
	Name string
	Runs int
}

type Bowler struct {
	Cricketer
	Wickets int
}

func (f *Footballer) Describe() string { return fmt.Sprintf("Footballer %s, club %s", f.Name, f.Club) }
func (c *Cricketer) Describe() string  { return fmt.Sprintf("Cricketer %s, runs %d", c.Name, c.Runs) }
func (b *Bowler) Describe() string {
	return fmt.Sprintf("Bowler %s, runs %d, wickets %d", b.Name, b.Runs, b.Wickets)
}

// insert writes one row in the table of each class on the path from the root.
func insert(p Player) int64 {
	lastID++
	switch v := p.(type) {
	case *Footballer:
		v.ID = lastID
		playerTable[lastID] = v.Name
		footballerTable[lastID] = v.Club
	case *Cricketer:
		v.ID = lastID
		playerTable[lastID] = v.Name
		cricketerTable[lastID] = v.Runs
	case *Bowler:
		v.ID = lastID
		playerTable[lastID] = v.Name
		cricketerTable[lastID] = v.Runs
		bowlerTable[lastID] = v.Wickets
	}
	return lastID
}

// find looks for the key in the tables of the subclasses, because the root row has no type.
func find(id int64) (Player, []string) {
	name := playerTable[id]
	if club, ok := footballerTable[id]; ok {
		return &Footballer{id, name, club}, []string{"player", "footballer"}
	}
	runs := cricketerTable[id]
	if wickets, ok := bowlerTable[id]; ok {
		return &Bowler{Cricketer{id, name, runs}, wickets}, []string{"player", "cricketer", "bowler"}
	}
	return &Cricketer{id, name, runs}, []string{"player", "cricketer"}
}

func deletePlayer(id int64) int {
	count := 0
	if _, ok := bowlerTable[id]; ok { // Children first.
		delete(bowlerTable, id)
		count++
	}
	if _, ok := cricketerTable[id]; ok {
		delete(cricketerTable, id)
		count++
	}
	if _, ok := footballerTable[id]; ok {
		delete(footballerTable, id)
		count++
	}
	if _, ok := playerTable[id]; ok {
		delete(playerTable, id)
		count++
	}
	return count
}

func show[V any](table map[int64]V) string {
	keys := make([]int64, 0, len(table))
	for k := range table {
		keys = append(keys, k)
	}
	sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
	parts := make([]string, len(keys))
	for i, k := range keys {
		parts[i] = fmt.Sprint(k, " ", table[k])
	}
	return strings.Join(parts, " | ")
}

func main() {
	insert(&Footballer{Name: "Ann", Club: "Lions"})
	insert(&Cricketer{Name: "Bo", Runs: 412})
	cy := insert(&Bowler{Cricketer{Name: "Cy", Runs: 95}, 31})
	fmt.Println("player:", show(playerTable))
	fmt.Println("footballer:", show(footballerTable))
	fmt.Println("cricketer:", show(cricketerTable))
	fmt.Println("bowler:", show(bowlerTable))
	for id := int64(1); id <= 3; id++ {
		p, used := find(id)
		fmt.Printf("loaded: %s (tables: %s)\n", p.Describe(), strings.Join(used, ", "))
	}
	var names []string
	for id := int64(1); id <= lastID; id++ {
		if _, ok := cricketerTable[id]; ok {
			names = append(names, playerTable[id])
		}
	}
	fmt.Println("cricketers:", strings.Join(names, ", "))
	fmt.Println("delete Cy: rows deleted", deletePlayer(cy))
}
Output
player: 1 Ann | 2 Bo | 3 Cy
footballer: 1 Lions
cricketer: 2 412 | 3 95
bowler: 3 31
loaded: Footballer Ann, club Lions (tables: player, footballer)
loaded: Cricketer Bo, runs 412 (tables: player, cricketer)
loaded: Bowler Cy, runs 95, wickets 31 (tables: player, cricketer, bowler)
cricketers: Bo, Cy
delete Cy: rows deleted 3
  • Verdict: idiom. Go has no class inheritance, so Bowler embeds Cricketer, and a type switch in insert writes the rows for each type. find reads the maps with the two-value form to test for a row.
  • show is generic over the value type of the map and sorts the keys, because Go maps have no order.
RustGitHub
use std::collections::BTreeMap;

// Rust has no class inheritance, so the hierarchy is an enum with one variant
// for each concrete class.
enum Player {
    Footballer { name: String, club: String },
    Cricketer { name: String, runs: i64 },
    Bowler { name: String, runs: i64, wickets: i64 },
}

impl Player {
    fn describe(&self) -> String {
        match self {
            Player::Footballer { name, club } => format!("Footballer {}, club {}", name, club),
            Player::Cricketer { name, runs } => format!("Cricketer {}, runs {}", name, runs),
            Player::Bowler { name, runs, wickets } => format!("Bowler {}, runs {}, wickets {}", name, runs, wickets),
        }
    }
}

// One table for each class, all keyed by the same id.
#[derive(Default)]
struct Db {
    player: BTreeMap<i64, String>,
    footballer: BTreeMap<i64, String>,
    cricketer: BTreeMap<i64, i64>,
    bowler: BTreeMap<i64, i64>,
    last_id: i64,
}

impl Db {
    // One row in the table of each class on the path from the root, all with the same key.
    fn insert(&mut self, p: &Player) -> i64 {
        self.last_id += 1;
        let id = self.last_id;
        match p {
            Player::Footballer { name, club } => {
                self.player.insert(id, name.clone());
                self.footballer.insert(id, club.clone());
            }
            Player::Cricketer { name, runs } => {
                self.player.insert(id, name.clone());
                self.cricketer.insert(id, *runs);
            }
            Player::Bowler { name, runs, wickets } => {
                self.player.insert(id, name.clone());
                self.cricketer.insert(id, *runs);
                self.bowler.insert(id, *wickets);
            }
        }
        id
    }

    // The root row has no type, so the mapper looks for the key in the tables of the subclasses.
    fn find(&self, id: i64) -> (Player, Vec<&'static str>) {
        let name = self.player[&id].clone();
        if let Some(club) = self.footballer.get(&id) {
            return (Player::Footballer { name, club: club.clone() }, vec!["player", "footballer"]);
        }
        let runs = self.cricketer[&id];
        if let Some(wickets) = self.bowler.get(&id) {
            return (Player::Bowler { name, runs, wickets: *wickets }, vec!["player", "cricketer", "bowler"]);
        }
        (Player::Cricketer { name, runs }, vec!["player", "cricketer"])
    }

    fn delete(&mut self, id: i64) -> usize {
        // Children first.
        self.bowler.remove(&id).is_some() as usize
            + self.cricketer.remove(&id).is_some() as usize
            + self.footballer.remove(&id).is_some() as usize
            + self.player.remove(&id).is_some() as usize
    }
}

fn show<V: std::fmt::Display>(table: &BTreeMap<i64, V>) -> String {
    table.iter().map(|(k, v)| format!("{} {}", k, v)).collect::<Vec<_>>().join(" | ")
}

fn main() {
    let mut db = Db::default();
    db.insert(&Player::Footballer { name: "Ann".into(), club: "Lions".into() });
    db.insert(&Player::Cricketer { name: "Bo".into(), runs: 412 });
    let cy = db.insert(&Player::Bowler { name: "Cy".into(), runs: 95, wickets: 31 });
    println!("player: {}", show(&db.player));
    println!("footballer: {}", show(&db.footballer));
    println!("cricketer: {}", show(&db.cricketer));
    println!("bowler: {}", show(&db.bowler));
    for id in 1..=3 {
        let (p, used) = db.find(id);
        println!("loaded: {} (tables: {})", p.describe(), used.join(", "));
    }
    let names: Vec<&str> = db.cricketer.keys().map(|id| db.player[id].as_str()).collect();
    println!("cricketers: {}", names.join(", "));
    println!("delete Cy: rows deleted {}", db.delete(cy));
}
Output
player: 1 Ann | 2 Bo | 3 Cy
footballer: 1 Lions
cricketer: 2 412 | 3 95
bowler: 3 31
loaded: Footballer Ann, club Lions (tables: player, footballer)
loaded: Cricketer Bo, runs 412 (tables: player, cricketer)
loaded: Bowler Cy, runs 95, wickets 31 (tables: player, cricketer, bowler)
cricketers: Bo, Cy
delete Cy: rows deleted 3
  • Verdict: idiom. The hierarchy is an enum, and each table is a BTreeMap keyed by the shared id. find uses get and if let to test for a row in a subclass table.
  • delete adds up remove(&id).is_some() for each table, children first, to count the deleted rows.

Consequences

Benefits.

  • Each table is normalized. Each column belongs to one class, so no column is null only because a row holds another class. The database can make the subclass columns NOT NULL.
  • Links anywhere in the hierarchy. A foreign key can refer to the player table for any player, or to the cricketer table for cricketers only.
  • The tables match the classes. The schema is easy to read for a person who knows the class diagram.

Liabilities.

Joins for each load. An object of a deep class needs a join of all the tables on its path, and a query for the base class needs an outer join to all the subclass tables to find the class of each row. "The joined table inheritance polymorphic queries can use several JOINS which might affect performance when fetching a large number of entities."4 Entity Framework Core warns: "In many cases, TPT shows inferior performance when compared to TPH."2

The mapper must find the class of a row. Fowler's book notes two ways: a type column in the root table, or a look for the key in each subclass table.5 SQLAlchemy uses the first: "the ultimate class to instantiate for a given row is determined by a discriminator column or SQL expression, defined on the base class".3 Hibernate uses the second by default: "A discriminator column is not required for this mapping strategy."4

Each level needs its row. An object of a class must have a row in the table of every class above it. In the following program, the mapper of Bowler writes the root row and its own row, but not the cricketer row. A query for cricketers does not find the bowler.

This code runs but gives a wrong answer on purpose.

import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
create table player (id integer primary key, name text);
create table cricketer (id integer primary key references player(id), runs integer);
create table bowler (id integer primary key references cricketer(id), runs integer, wickets integer);
insert into player values (1, 'Bo'), (2, 'Cy');
insert into cricketer values (1, 412);
-- The bowler mapper writes the root row and its own row, and puts runs in the bowler table.
-- It skips the row in the cricketer table.
insert into bowler values (2, 95, 31);
""")

sql = "select p.name from player p join cricketer c on c.id = p.id order by p.id"
print("cricketers:", db.execute(sql).fetchall())
Output
cricketers: [('Bo',)]

The fix is a mapper that writes a row for each class on the path, as in the insert above, in one transaction.

The superclass tables are hot spots. Each insert, update and delete touches the root table, and changes to the hierarchy change the tables.

When not to use it

When most queries load objects of many classes. Each such query joins many tables. Use Single Table Inheritance, which reads one table.

When most queries load one concrete class. A table for each concrete class needs no join. Use Concrete Table Inheritance.

For a flat hierarchy with few fields in the subclasses. The joins cost more than the null columns that they avoid.

A type column in the root. A discriminator in the root table tells the mapper which tables to join, so it does not need to look in each table. SQLAlchemy and Entity Framework Core use one; Hibernate and Django do not need one.

Multi-table inheritance in Django. "Each model corresponds to its own database table and can be queried and created individually. The inheritance relationship introduces links between the child model and each of its parents (via an automatically-created OneToOneField )."6

The other strategies. Single Table Inheritance puts the hierarchy in one table, and Concrete Table Inheritance gives each concrete class one table with all its fields. Entity Framework Core gives this advice: "Use TPT only if constrained to do so by external factors."2 Inheritance Mappers organizes the mapper classes for any of the three.

Known uses

  • Django: a model that inherits from a concrete model. In base.py at 5.2.8, ModelBase.__new__ adds a OneToOneField to the parent with the name <parent>_ptr, on_delete=CASCADE, auto_created=True and parent_link=True, unless the model declares its own parent link.7
  • SQLAlchemy: joined table inheritance, with a subclass table whose primary key is a foreign key to the base table.3
  • Entity Framework Core, for .NET: UseTptMappingStrategy or ToTable on each type maps the hierarchy as table-per-type.2
  • Hibernate and Jakarta Persistence: @Inheritance(strategy = InheritanceType.JOINED). "Each subclass can also be mapped to its own table. This is also called table-per-subclass mapping strategy. An inherited state is retrieved by joining with the table of the superclass."4

References

  1. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Class Table Inheritance, pattern summary
  2. Entity Framework Core documentation, Inheritance, Table-per-type configuration; Summary and guidance
  3. SQLAlchemy 2.0 documentation, Mapping Class Inheritance Hierarchies, Joined Table Inheritance
  4. Hibernate ORM 6.6 User Guide, 3.14.3. Joined table
  5. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 12, Object-Relational Structural Patterns, Class Table Inheritance
  6. Django 5.2 documentation, Models, Model inheritance, Multi-table inheritance
  7. Django 5.2.8 source, django/db/models/base.py, ModelBase.__new__, the automatic parent link, lines 277 to 290

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/CDC2SN/text.yaml