Patterncore
Concrete Table Inheritance
Also called concrete table inheritance pattern, table per concrete class, TPC, leaf table inheritance, union subclass mapping.
Concrete Table Inheritance stores an inheritance hierarchy with one table for each concrete class, and each table has columns for all the fields of its class, the inherited ones too.
- Family
- architectural
- Intent
- Represents an inheritance hierarchy of classes with one table per concrete class in the hierarchy.
Intent
Concrete Table Inheritance "Represents an inheritance hierarchy of classes with one table per concrete class in the hierarchy."1 Each table holds all the fields of its class, the fields that the class inherits too, so one object is one row in one table.
Problem
Relational databases have no inheritance. Fowler starts from the object: "Thinking of tables from an object instance point of view, a sensible route is to take each object in memory and map it to a single database row. This implies Concrete Table Inheritance, where there's a table for each concrete class in the inheritance hierarchy."1 A program has Footballer, Cricketer and Bowler, which share the fields of Player. Most code loads one kind of player at a time, and should read one table without a join and without null columns of other classes.
Solution
Give each concrete class a table with a column for each of its fields, inherited or not. An abstract class gets no table. SQLAlchemy describes it: "Concrete inheritance maps each subclass to its own distinct table, each of which contains all columns necessary to produce an instance of that class."2 Fowler notes the name: "Most people think of it as leaf oriented since you usually have one table per leaf class in a hierarchy." But "a concrete class that isn't a leaf usually gets a table as well".1
Two things need care. First, the key of an object must be unique in the whole hierarchy and not only in its table, so the tables take their keys from one source. Entity Framework Core says that it "requires that all entities in a hierarchy have a unique key value, even if the entities have different types", and that "there is no common table that can act as the single place where key values live and can be generated."3 Second, a query for the superclass must read all the tables, usually with a UNION.
classes tables (keys from one source)
Player(name) no table for the abstract class
|- Footballer(club) footballer(id, name, club) 1 Ann Lions
|- Cricketer(runs) cricketer(id, name, runs) 2 Bo 412
|- Bowler(wickets) bowler(id, name, runs, wickets) 3 Cy 95 31
all players: select ... from footballer union all select ... from cricketer union all ... bowler
The participants are the class hierarchy; a table for each concrete class with all the fields of the class; a key source shared by all the tables; and the mapper, which writes each object to the table of its class and reads all the tables for a query on a superclass.
The following program saves a footballer and a cricketer in their own tables with keys from one source, and reads both with a union.
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
create table footballer (id integer primary key, name text, club text);
create table cricketer (id integer primary key, name text, runs integer);
create table key_source (next_id integer);
insert into key_source values (1);
""")
class Footballer:
def __init__(self, name, club):
self.name, self.club = name, club
class Cricketer:
def __init__(self, name, runs):
self.name, self.runs = name, runs
def next_key():
# One key source for all the tables, so that a key is unique in the whole hierarchy.
(id,) = db.execute("select next_id from key_source").fetchone()
db.execute("update key_source set next_id = next_id + 1")
return id
def insert(p):
# Each concrete class has a table with all its fields, the inherited ones too.
p.id = next_key()
if isinstance(p, Footballer):
db.execute("insert into footballer values (?, ?, ?)", (p.id, p.name, p.club))
else:
db.execute("insert into cricketer values (?, ?, ?)", (p.id, p.name, p.runs))
insert(Footballer("Ann", "Lions"))
insert(Cricketer("Bo", 412))
print(db.execute("select * from footballer").fetchall(), db.execute("select * from cricketer").fetchall())
print(db.execute("""select id, name, 'footballer' from footballer
union all select id, name, 'cricketer' from cricketer order by id""").fetchall())
[(1, 'Ann', 'Lions')] [(2, 'Bo', 412)]
[(1, 'Ann', 'footballer'), (2, 'Bo', 'cricketer')]
Example
Each example file saves a footballer, a cricketer and a bowler, and prints the three tables. Each row has all the fields of its class, and no column is null. It then finds the player with key 3. The key does not say which table holds the row, so the mapper tries the footballer, cricketer and bowler tables in turn. A union of the three tables, with the name of each table as a type, lists all the players. A query for cricketers must read the cricketer table and the bowler table, because a bowler is a cricketer. The last line shows the next key of the shared key source. The Python file uses SQLite with a key table. The JavaScript, Java, Go and Rust files keep a map for each table and one counter for the keys.
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
create table footballer (id integer primary key, name text not null, club text not null);
create table cricketer (id integer primary key, name text not null, runs integer not null);
create table bowler (id integer primary key, name text not null, runs integer not null,
wickets integer not null);
create table key_source (next_id integer not null);
insert into key_source values (1);
""")
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 next_key():
# One key source for all the tables, so that a key is unique in the whole hierarchy.
(id,) = db.execute("select next_id from key_source").fetchone()
db.execute("update key_source set next_id = next_id + 1")
return id
def insert(p):
# Each concrete class has one table with all its fields, the inherited ones too.
p.id = next_key()
if isinstance(p, Bowler):
db.execute("insert into bowler values (?, ?, ?, ?)", (p.id, p.name, p.runs, p.wickets))
elif isinstance(p, Cricketer):
db.execute("insert into cricketer values (?, ?, ?)", (p.id, p.name, p.runs))
else:
db.execute("insert into footballer values (?, ?, ?)", (p.id, p.name, p.club))
def find(id):
# A key alone does not say which table holds the row, so the mapper tries each table.
searched = []
for table, make in (("footballer", Footballer), ("cricketer", Cricketer), ("bowler", Bowler)):
searched.append(table)
row = db.execute(f"select * from {table} where id = ?", (id,)).fetchone()
if row:
return make(*row[1:], id=row[0]), searched
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)
for p in (Footballer("Ann", "Lions"), Cricketer("Bo", 412), Bowler("Cy", 95, 31)):
insert(p)
for table in ("footballer", "cricketer", "bowler"):
print(f"{table}: {show(table)}")
p, searched = find(3)
print(f"find 3: {p.describe()} (tables searched: {', '.join(searched)})")
everyone = db.execute("""select id, name, 'footballer' from footballer
union all select id, name, 'cricketer' from cricketer
union all select id, name, 'bowler' from bowler order by id""")
print("all players:", " | ".join(f"{i} {n} {t}" for i, n, t in everyone))
cricketers = db.execute("""select name from cricketer
union all select name from bowler order by name""")
print("cricketers:", ", ".join(n for (n,) in cricketers))
print("next key:", db.execute("select next_id from key_source").fetchone()[0])
footballer: 1 Ann Lions
cricketer: 2 Bo 412
bowler: 3 Cy 95 31
find 3: Bowler Cy, runs 95, wickets 31 (tables searched: footballer, cricketer, bowler)
all players: 1 Ann footballer | 2 Bo cricketer | 3 Cy bowler
cricketers: Bo, Cy
next key: 4
- Verdict: idiom. Each concrete class has a SQLite table with all its columns, and each column is
not null.next_keyreads and increments the one row ofkey_source, so the three tables never share a key. - The query for all players is a
union allof the three tables with the table name as a literal type column, as SQLAlchemy builds it withpolymorphic_union.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Main {
// One table for each concrete class, with all its fields, the inherited ones too.
record FootballerRow(String name, String club) {}
record CricketerRow(String name, int runs) {}
record BowlerRow(String name, int runs, int wickets) {}
static final Map<Long, FootballerRow> FOOTBALLER = new TreeMap<>();
static final Map<Long, CricketerRow> CRICKETER = new TreeMap<>();
static final Map<Long, BowlerRow> BOWLER = new TreeMap<>();
static long nextId = 1; // One key source for all the tables.
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 Found(Player player, List<String> searched) {}
record Summary(long id, String name, String table) {}
static void insert(Player p) {
p.id = nextId++;
if (p instanceof Bowler b) {
BOWLER.put(p.id, new BowlerRow(b.name, b.runs, b.wickets));
} else if (p instanceof Cricketer c) {
CRICKETER.put(p.id, new CricketerRow(c.name, c.runs));
} else {
Footballer f = (Footballer) p;
FOOTBALLER.put(p.id, new FootballerRow(f.name, f.club));
}
}
static Found find(long id) {
// A key alone does not say which table holds the row, so the mapper tries each table.
List<String> searched = new ArrayList<>();
Player p = null;
searched.add("footballer");
if (FOOTBALLER.containsKey(id)) {
FootballerRow r = FOOTBALLER.get(id);
p = new Footballer(r.name(), r.club());
} else {
searched.add("cricketer");
if (CRICKETER.containsKey(id)) {
CricketerRow r = CRICKETER.get(id);
p = new Cricketer(r.name(), r.runs());
} else {
searched.add("bowler");
BowlerRow r = BOWLER.get(id);
p = new Bowler(r.name(), r.runs(), r.wickets());
}
}
p.id = id;
return new Found(p, searched);
}
public static void main(String[] args) {
for (Player p : List.of(new Footballer("Ann", "Lions"), new Cricketer("Bo", 412), new Bowler("Cy", 95, 31))) {
insert(p);
}
List<String> parts = new ArrayList<>();
FOOTBALLER.forEach((id, r) -> parts.add(id + " " + r.name() + " " + r.club()));
System.out.println("footballer: " + String.join(" | ", parts));
parts.clear();
CRICKETER.forEach((id, r) -> parts.add(id + " " + r.name() + " " + r.runs()));
System.out.println("cricketer: " + String.join(" | ", parts));
parts.clear();
BOWLER.forEach((id, r) -> parts.add(id + " " + r.name() + " " + r.runs() + " " + r.wickets()));
System.out.println("bowler: " + String.join(" | ", parts));
Found f = find(3);
System.out.println("find 3: " + f.player().describe() + " (tables searched: " + String.join(", ", f.searched()) + ")");
// The union of all the tables, as a polymorphic query does it.
List<Summary> everyone = new ArrayList<>();
FOOTBALLER.forEach((id, r) -> everyone.add(new Summary(id, r.name(), "footballer")));
CRICKETER.forEach((id, r) -> everyone.add(new Summary(id, r.name(), "cricketer")));
BOWLER.forEach((id, r) -> everyone.add(new Summary(id, r.name(), "bowler")));
everyone.sort(Comparator.comparingLong(Summary::id));
parts.clear();
for (Summary s : everyone) {
parts.add(s.id() + " " + s.name() + " " + s.table());
}
System.out.println("all players: " + String.join(" | ", parts));
List<String> cricketers = new ArrayList<>();
CRICKETER.values().forEach(r -> cricketers.add(r.name()));
BOWLER.values().forEach(r -> cricketers.add(r.name()));
Collections.sort(cricketers);
System.out.println("cricketers: " + String.join(", ", cricketers));
System.out.println("next key: " + nextId);
}
}
footballer: 1 Ann Lions
cricketer: 2 Bo 412
bowler: 3 Cy 95 31
find 3: Bowler Cy, runs 95, wickets 31 (tables searched: footballer, cricketer, bowler)
all players: 1 Ann footballer | 2 Bo cricketer | 3 Cy bowler
cricketers: Bo, Cy
next key: 4
- Verdict: idiom. Each table is a
TreeMapof records with all the fields of the class, andinsertuses pattern matching forinstanceofto choose the table. - With JPA or Hibernate,
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)on the root class gives the same tables, and a polymorphic query becomes aUNION.
// A stand-in for the database: one table for each concrete class, with all its fields.
const tables = { footballer: new Map(), cricketer: new Map(), bowler: new Map() };
let nextId = 1; // One key source for all the tables.
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) {
// Each concrete class has one table with all its fields, the inherited ones too.
p.id = nextId++;
if (p instanceof Bowler) tables.bowler.set(p.id, [p.name, p.runs, p.wickets]);
else if (p instanceof Cricketer) tables.cricketer.set(p.id, [p.name, p.runs]);
else tables.footballer.set(p.id, [p.name, p.club]);
}
const MAKERS = [
["footballer", (id, [name, club]) => new Footballer(name, club, id)],
["cricketer", (id, [name, runs]) => new Cricketer(name, runs, id)],
["bowler", (id, [name, runs, wickets]) => new Bowler(name, runs, wickets, id)],
];
function find(id) {
// A key alone does not say which table holds the row, so the mapper tries each table.
const searched = [];
for (const [table, make] of MAKERS) {
searched.push(table);
if (tables[table].has(id)) return [make(id, tables[table].get(id)), searched];
}
return [null, searched];
}
function show(t) {
return [...tables[t]].map(([id, cols]) => [id, ...cols].join(" ")).join(" | ");
}
for (const p of [new Footballer("Ann", "Lions"), new Cricketer("Bo", 412), new Bowler("Cy", 95, 31)]) {
insert(p);
}
for (const t of ["footballer", "cricketer", "bowler"]) console.log(`${t}: ${show(t)}`);
const [p, searched] = find(3);
console.log(`find 3: ${p.describe()} (tables searched: ${searched.join(", ")})`);
// The union of all the tables, as a polymorphic query does it.
const everyone = MAKERS.flatMap(([t]) => [...tables[t]].map(([id, cols]) => [id, cols[0], t]));
everyone.sort((a, b) => a[0] - b[0]);
console.log(`all players: ${everyone.map((r) => r.join(" ")).join(" | ")}`);
const cricketers = [...tables.cricketer.values(), ...tables.bowler.values()].map((c) => c[0]).sort();
console.log(`cricketers: ${cricketers.join(", ")}`);
console.log(`next key: ${nextId}`);
footballer: 1 Ann Lions
cricketer: 2 Bo 412
bowler: 3 Cy 95 31
find 3: Bowler Cy, runs 95, wickets 31 (tables searched: footballer, cricketer, bowler)
all players: 1 Ann footballer | 2 Bo cricketer | 3 Cy bowler
cricketers: Bo, Cy
next key: 4
- Verdict: idiom. Each table is a
Mapfrom the key to all the columns of its class, and onenextIdcounter gives the keys for all the tables. findwalks theMAKERSlist, because the key alone does not say which table holds the row. A query for cricketers reads the cricketer map and the bowler map.
package main
import (
"fmt"
"sort"
"strings"
)
// One table for each concrete class, with all its fields, the inherited ones too.
type footballerRow struct {
Name, Club string
}
type cricketerRow struct {
Name string
Runs int
}
type bowlerRow struct {
Name string
Runs, Wickets int
}
var (
footballerTable = map[int64]footballerRow{}
cricketerTable = map[int64]cricketerRow{}
bowlerTable = map[int64]bowlerRow{}
nextID int64 = 1 // One key source for all the tables.
)
// 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)
}
func insert(p Player) {
id := nextID
nextID++
switch v := p.(type) {
case *Footballer:
v.ID = id
footballerTable[id] = footballerRow{v.Name, v.Club}
case *Cricketer:
v.ID = id
cricketerTable[id] = cricketerRow{v.Name, v.Runs}
case *Bowler:
v.ID = id
bowlerTable[id] = bowlerRow{v.Name, v.Runs, v.Wickets}
}
}
// find tries each table, because a key alone does not say which table holds the row.
func find(id int64) (Player, []string) {
searched := []string{"footballer"}
if r, ok := footballerTable[id]; ok {
return &Footballer{id, r.Name, r.Club}, searched
}
searched = append(searched, "cricketer")
if r, ok := cricketerTable[id]; ok {
return &Cricketer{id, r.Name, r.Runs}, searched
}
searched = append(searched, "bowler")
if r, ok := bowlerTable[id]; ok {
return &Bowler{Cricketer{id, r.Name, r.Runs}, r.Wickets}, searched
}
return nil, searched
}
func sortedKeys[V any](m map[int64]V) []int64 {
keys := make([]int64, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
return keys
}
type summary struct {
ID int64
Name, Table string
}
func main() {
insert(&Footballer{Name: "Ann", Club: "Lions"})
insert(&Cricketer{Name: "Bo", Runs: 412})
insert(&Bowler{Cricketer{Name: "Cy", Runs: 95}, 31})
var parts []string
for _, id := range sortedKeys(footballerTable) {
r := footballerTable[id]
parts = append(parts, fmt.Sprintf("%d %s %s", id, r.Name, r.Club))
}
fmt.Println("footballer:", strings.Join(parts, " | "))
parts = nil
for _, id := range sortedKeys(cricketerTable) {
r := cricketerTable[id]
parts = append(parts, fmt.Sprintf("%d %s %d", id, r.Name, r.Runs))
}
fmt.Println("cricketer:", strings.Join(parts, " | "))
parts = nil
for _, id := range sortedKeys(bowlerTable) {
r := bowlerTable[id]
parts = append(parts, fmt.Sprintf("%d %s %d %d", id, r.Name, r.Runs, r.Wickets))
}
fmt.Println("bowler:", strings.Join(parts, " | "))
p, searched := find(3)
fmt.Printf("find 3: %s (tables searched: %s)\n", p.Describe(), strings.Join(searched, ", "))
// The union of all the tables, as a polymorphic query does it.
var everyone []summary
for id, r := range footballerTable {
everyone = append(everyone, summary{id, r.Name, "footballer"})
}
for id, r := range cricketerTable {
everyone = append(everyone, summary{id, r.Name, "cricketer"})
}
for id, r := range bowlerTable {
everyone = append(everyone, summary{id, r.Name, "bowler"})
}
sort.Slice(everyone, func(i, j int) bool { return everyone[i].ID < everyone[j].ID })
parts = nil
for _, s := range everyone {
parts = append(parts, fmt.Sprintf("%d %s %s", s.ID, s.Name, s.Table))
}
fmt.Println("all players:", strings.Join(parts, " | "))
var cricketers []string
for _, r := range cricketerTable {
cricketers = append(cricketers, r.Name)
}
for _, r := range bowlerTable {
cricketers = append(cricketers, r.Name)
}
sort.Strings(cricketers)
fmt.Println("cricketers:", strings.Join(cricketers, ", "))
fmt.Println("next key:", nextID)
}
footballer: 1 Ann Lions
cricketer: 2 Bo 412
bowler: 3 Cy 95 31
find 3: Bowler Cy, runs 95, wickets 31 (tables searched: footballer, cricketer, bowler)
all players: 1 Ann footballer | 2 Bo cricketer | 3 Cy bowler
cricketers: Bo, Cy
next key: 4
- Verdict: idiom. Go has no class inheritance, so
BowlerembedsCricketer, and a type switch ininsertchooses the table. Each row struct holds all the fields of its type. sortedKeysis generic over the value type of the map, because Go maps have no order and the output must be stable.
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 concrete class, with all its fields, the inherited ones too.
struct Db {
footballer: BTreeMap<i64, (String, String)>,
cricketer: BTreeMap<i64, (String, i64)>,
bowler: BTreeMap<i64, (String, i64, i64)>,
next_id: i64, // One key source for all the tables.
}
impl Db {
fn insert(&mut self, p: &Player) {
let id = self.next_id;
self.next_id += 1;
match p {
Player::Footballer { name, club } => {
self.footballer.insert(id, (name.clone(), club.clone()));
}
Player::Cricketer { name, runs } => {
self.cricketer.insert(id, (name.clone(), *runs));
}
Player::Bowler { name, runs, wickets } => {
self.bowler.insert(id, (name.clone(), *runs, *wickets));
}
}
}
// A key alone does not say which table holds the row, so the mapper tries each table.
fn find(&self, id: i64) -> (Option<Player>, Vec<&'static str>) {
let mut searched = vec!["footballer"];
if let Some((name, club)) = self.footballer.get(&id) {
return (Some(Player::Footballer { name: name.clone(), club: club.clone() }), searched);
}
searched.push("cricketer");
if let Some((name, runs)) = self.cricketer.get(&id) {
return (Some(Player::Cricketer { name: name.clone(), runs: *runs }), searched);
}
searched.push("bowler");
if let Some((name, runs, wickets)) = self.bowler.get(&id) {
return (Some(Player::Bowler { name: name.clone(), runs: *runs, wickets: *wickets }), searched);
}
(None, searched)
}
}
fn main() {
let mut db = Db { footballer: BTreeMap::new(), cricketer: BTreeMap::new(), bowler: BTreeMap::new(), next_id: 1 };
db.insert(&Player::Footballer { name: "Ann".into(), club: "Lions".into() });
db.insert(&Player::Cricketer { name: "Bo".into(), runs: 412 });
db.insert(&Player::Bowler { name: "Cy".into(), runs: 95, wickets: 31 });
let f: Vec<String> = db.footballer.iter().map(|(id, (n, c))| format!("{} {} {}", id, n, c)).collect();
println!("footballer: {}", f.join(" | "));
let c: Vec<String> = db.cricketer.iter().map(|(id, (n, r))| format!("{} {} {}", id, n, r)).collect();
println!("cricketer: {}", c.join(" | "));
let b: Vec<String> = db.bowler.iter().map(|(id, (n, r, w))| format!("{} {} {} {}", id, n, r, w)).collect();
println!("bowler: {}", b.join(" | "));
let (p, searched) = db.find(3);
println!("find 3: {} (tables searched: {})", p.expect("player 3").describe(), searched.join(", "));
// The union of all the tables, as a polymorphic query does it.
let mut everyone: Vec<(i64, &str, &str)> = Vec::new();
everyone.extend(db.footballer.iter().map(|(id, (n, _))| (*id, n.as_str(), "footballer")));
everyone.extend(db.cricketer.iter().map(|(id, (n, _))| (*id, n.as_str(), "cricketer")));
everyone.extend(db.bowler.iter().map(|(id, (n, _, _))| (*id, n.as_str(), "bowler")));
everyone.sort();
let all: Vec<String> = everyone.iter().map(|(id, n, t)| format!("{} {} {}", id, n, t)).collect();
println!("all players: {}", all.join(" | "));
let mut cricketers: Vec<&str> = db.cricketer.values().map(|(n, _)| n.as_str()).collect();
cricketers.extend(db.bowler.values().map(|(n, _, _)| n.as_str()));
cricketers.sort();
println!("cricketers: {}", cricketers.join(", "));
println!("next key: {}", db.next_id);
}
footballer: 1 Ann Lions
cricketer: 2 Bo 412
bowler: 3 Cy 95 31
find 3: Bowler Cy, runs 95, wickets 31 (tables searched: footballer, cricketer, bowler)
all players: 1 Ann footballer | 2 Bo cricketer | 3 Cy bowler
cricketers: Bo, Cy
next key: 4
- Verdict: idiom. The hierarchy is an
enumwith one variant for each concrete class, and each table is aBTreeMapof tuples with all the fields of the variant. findreturns anOption<Player>and the list of tables that it searched, andif lettests each table in turn.
Consequences
Benefits.
- One row for each object. A load of a known class reads one table with no join, and each column of the table belongs to the class.
- Each column can be NOT NULL. No row holds an object of another class, so the database can check all the fields.
- The tables are self-contained. Code that reads one table sees whole objects of one class.
Liabilities.
Queries on the superclass read all the tables. SQLAlchemy builds a special select for them, "typically is produced as a UNION of all the tables", and warns that "When used polymorphically it produces very large queries with UNIONS that won’t perform as well as simple joins."2 The Hibernate guide says: "Polymorphic queries require multiple UNION queries, so be aware of the performance implications of a large class hierarchy."4
Keys must be unique across the tables. If each table makes its own keys, two objects of different classes get the same key. In the following program, a footballer and a cricketer both have key 1, and a record that refers to player 1 matches two rows.
This code runs but gives a wrong answer on purpose.
import sqlite3
db = sqlite3.connect(":memory:")
# Each table makes its own keys, so a footballer and a cricketer can get the same key.
db.executescript("""
create table footballer (id integer primary key, name text, club text);
create table cricketer (id integer primary key, name text, runs integer);
insert into footballer (name, club) values ('Ann', 'Lions');
insert into cricketer (name, runs) values ('Bo', 412);
""")
# A match record refers to player 1. Which player is that?
sql = """select 'footballer', id, name from footballer where id = 1
union all select 'cricketer', id, name from cricketer where id = 1"""
print(db.execute(sql).fetchall())
[('footballer', 1, 'Ann'), ('cricketer', 1, 'Bo')]
The fix is one key source for the whole hierarchy, such as a key table or a database sequence. Entity Framework Core uses "a single sequence referenced in the default constraint for each table".3
No foreign key to the superclass. A column that refers to any player cannot have a foreign key constraint, because players are in many tables. "This means an FK constraint cannot be created for this relationship."3
A change to a superclass changes many tables. A new field in Player is a new column in each concrete table. Fowler's book lists this with the key and the foreign key problems.5
When not to use it
When code often queries the superclass. Each such query is a union of all the tables. Use Single Table Inheritance. Entity Framework Core gives this advice: "if your code will mostly query for entities of many types, such as writing queries against the base type, then lean towards TPH over TPC."3
When other tables must refer to the superclass. A foreign key to any player needs one table for players. Use Class Table Inheritance.
When the superclass changes often. Each change touches all the concrete tables.
Variants and related patterns
Shared fields without polymorphism. Some frameworks copy the fields of a base class into each table, but do not load the classes through the base class. In Django, an abstract base class "will then not be used to create any database table. Instead, when it is used as a base class for other models, its fields will be added to those of the child class."6 Hibernate notes that "it is not necessary to explicitly map such inheritance hierarchies. You can map each class as a separate entity root."4
The other strategies. Single Table Inheritance puts the hierarchy in one table, and Class Table Inheritance gives each class a table with the fields that it declares. Inheritance Mappers organizes the mapper classes for any of the three.
Known uses
- SQLAlchemy: concrete table inheritance with
ConcreteBaseorAbstractConcreteBase.2 polymorphic_union in util.py at 2.0.57 builds aUNION ALLwith oneSELECTfor each table. It fills each column that a table lacks with a typedNULL, and adds a literal type column with the polymorphic identity of the table.7 - Entity Framework Core, for .NET:
UseTpcMappingStrategymaps a hierarchy as table-per-concrete-type, with keys from one database sequence.3 - Hibernate and Jakarta Persistence:
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS). "This is called the table-per-concrete-class strategy. Each table defines all persistent states of the class, including the inherited state."4
References
- Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Concrete Table Inheritance, pattern summary
- SQLAlchemy 2.0 documentation, Mapping Class Inheritance Hierarchies, Concrete Table Inheritance
- Entity Framework Core documentation, Inheritance, Table-per-concrete-type configuration; Key generation; Foreign key constraints; Summary and guidance
- Hibernate ORM 6.6 User Guide, 3.14.4. Table per class
- Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 12, Object-Relational Structural Patterns, Concrete Table Inheritance
- Django 5.2 documentation, Models, Model inheritance, Abstract base classes
- SQLAlchemy 2.0.57 source, lib/sqlalchemy/orm/util.py, polymorphic_union, lines 320 to 398
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 2N96RH Edit this page History Report an error Markdown