Patterncore
Foreign Key Mapping
Also called foreign key mapping pattern, many-to-one mapping, one-to-many mapping.
A Foreign Key Mapping saves a reference from one object to another as a foreign key column that holds the key of the other object's row, and turns the key back into a reference on load.
- Family
- architectural
- Intent
- Maps an association between objects to a foreign key reference between tables.
Intent
A Foreign Key Mapping "Maps an association between objects to a foreign key reference between tables."1 A reference from one object to another is saved as the key of the other object's row. On load, the mapper reads the key and finds the object again.
Problem
"Objects can refer to each other directly by object references."1 An album refers to its artist, and holds a list of its tracks. Fowler states the difficulty: "To save these objects to a database, it's vital to save these references. However, since the data in them is specific to the specific instance of the running program, you can't just save raw data values."1 A memory address means nothing in the next run of the program.
A collection is harder. Fowler notes that a list of references in one field breaks the first normal form of a relational database, because a column holds one value, not a list.1
Solution
"A Foreign Key Mapping maps an object reference to a foreign key in the database."1 Each object has an Identity Field, so each row has a key. "A foreign key is a set of attributes in a table that refers to the primary key of another table, linking these two tables."2
- A single reference (many-to-one). The table of the referring object gets a column with the key of the referenced row. To save
album.artist, the mapper writesartist.idtoalbum.artist_id. To load it, the mapper readsartist_idand finds the artist, if possible through the Identity Map. - A collection (one-to-many). The key goes on the other side. "A one to many relationship places a foreign key on the child table referencing the parent."3 Each track row holds the key of its album, and the mapper loads
album.trackswith a query ontrack.album_id.
memory database
Album "Kind of Blue" album(id=1, title, artist_id=1)
.artist --> Artist "Miles Davis" artist(id=1, name)
.tracks --> [So What, Blue in Green] track(id=1, title, album_id=1)
track(id=2, title, album_id=1)
save: reference -> key of the referenced row
load: key -> query -> reference
The participants are the referring object and its table, which holds the foreign key column; the referenced object, whose identity field gives the key; and the mapper, which turns references into keys on save and keys into references on load.
The following program saves an album with its artist and two tracks, and then loads it from the keys alone.
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("pragma foreign_keys = on")
db.executescript("""
create table artist (id integer primary key, name text);
create table album (id integer primary key, title text,
artist_id integer references artist(id));
create table track (id integer primary key, title text,
album_id integer references album(id));
""")
class Artist:
def __init__(self, name, id=None):
self.id, self.name = id, name
class Album:
def __init__(self, title, artist, tracks, id=None):
self.id, self.title = id, title
self.artist = artist # An object reference in memory.
self.tracks = tracks # A collection of references in memory.
def save(album):
# Many-to-one: the reference becomes the key of the artist row.
sql = "insert into album (title, artist_id) values (?, ?)"
album.id = db.execute(sql, (album.title, album.artist.id)).lastrowid
# One-to-many: each track row gets the key of the album.
for title in album.tracks:
db.execute("insert into track (title, album_id) values (?, ?)", (title, album.id))
def load(album_id):
sql = "select title, artist_id from album where id = ?"
title, artist_id = db.execute(sql, (album_id,)).fetchone()
name = db.execute("select name from artist where id = ?", (artist_id,)).fetchone()[0]
sql = "select title from track where album_id = ? order by id"
tracks = [t for (t,) in db.execute(sql, (album_id,))]
return Album(title, Artist(name, artist_id), tracks, album_id) # Keys become references.
miles = Artist("Miles Davis")
miles.id = db.execute("insert into artist (name) values (?)", (miles.name,)).lastrowid
save(Album("Kind of Blue", miles, ["So What", "Blue in Green"]))
print(db.execute("select * from album").fetchall())
print(db.execute("select * from track").fetchall())
album = load(1)
print(album.title, "by", album.artist.name, "|", ", ".join(album.tracks))
[(1, 'Kind of Blue', 1)]
[(1, 'So What', 1), (2, 'Blue in Green', 1)]
Kind of Blue by Miles Davis | So What, Blue in Green
Example
Each example file saves an artist, an album and two tracks, and prints the key columns. It loads the album and rebuilds the references from the keys. It then removes one track from the collection, adds a new one, and saves the collection by comparing it with the rows: the mapper inserts the track that has no key and deletes the row that is no longer in the list. The last line tries to save an album that refers to artist 99, which does not exist, and the foreign key constraint stops it. The Python file uses SQLite with pragma foreign_keys = on. The JavaScript, Java, Go and Rust files keep the tables in memory and check the key in the insert function in the same way.
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("pragma foreign_keys = on")
db.executescript("""
create table artist (id integer primary key, name text);
create table album (id integer primary key, title text,
artist_id integer references artist(id));
create table track (id integer primary key, title text,
album_id integer references album(id));
""")
class Artist:
def __init__(self, name, id=None):
self.id, self.name = id, name
class Track:
def __init__(self, title, id=None):
self.id, self.title = id, title
class Album:
def __init__(self, title, artist, tracks, id=None):
self.id, self.title, self.artist, self.tracks = id, title, artist, tracks
def insert_album(album):
# Many-to-one: write the key of the referenced artist.
sql = "insert into album (title, artist_id) values (?, ?)"
album.id = db.execute(sql, (album.title, album.artist.id)).lastrowid
save_tracks(album)
def save_tracks(album):
# One-to-many: find the difference between the collection and the rows.
in_db = {i for (i,) in db.execute("select id from track where album_id = ?", (album.id,))}
in_memory = {t.id for t in album.tracks if t.id is not None}
inserted = 0
for t in album.tracks:
if t.id is None:
sql = "insert into track (title, album_id) values (?, ?)"
t.id = db.execute(sql, (t.title, album.id)).lastrowid
inserted += 1
removed = sorted(in_db - in_memory)
for i in removed:
db.execute("delete from track where id = ?", (i,))
return len(removed), inserted
def load_album(id):
title, artist_id = db.execute("select title, artist_id from album where id = ?", (id,)).fetchone()
(name,) = db.execute("select name from artist where id = ?", (artist_id,)).fetchone()
rows = db.execute("select id, title from track where album_id = ? order by id", (id,))
return Album(title, Artist(name, artist_id), [Track(t, i) for i, t in rows], id)
def show_tracks():
rows = db.execute("select id, title, album_id from track order by id")
return " | ".join(f"{i} {t} album_id={a}" for i, t, a in rows)
miles = Artist("Miles Davis")
miles.id = db.execute("insert into artist (name) values (?)", (miles.name,)).lastrowid
insert_album(Album("Kind of Blue", miles, [Track("So What"), Track("Blue in Green")]))
for i, t, a in db.execute("select id, title, artist_id from album"):
print(f"album rows: {i} {t} artist_id={a}")
print("track rows:", show_tracks())
album = load_album(1)
titles = ", ".join(t.title for t in album.tracks)
print(f"loaded: {album.title} by {album.artist.name} | {titles}")
album.tracks = [t for t in album.tracks if t.title != "Blue in Green"]
album.tracks.append(Track("Freddie Freeloader"))
deleted, inserted = save_tracks(album)
print(f"update tracks: deleted {deleted}, inserted {inserted}")
print("track rows:", show_tracks())
try:
db.execute("insert into album (title, artist_id) values ('Unknown', 99)")
except sqlite3.IntegrityError as e:
print("artist_id 99:", e)
album rows: 1 Kind of Blue artist_id=1
track rows: 1 So What album_id=1 | 2 Blue in Green album_id=1
loaded: Kind of Blue by Miles Davis | So What, Blue in Green
update tracks: deleted 1, inserted 1
track rows: 1 So What album_id=1 | 3 Freddie Freeloader album_id=1
artist_id 99: FOREIGN KEY constraint failed
- Verdict: idiom. The mapper writes
album.artist.idto theartist_idcolumn, and each track row getsalbum.id. On load, it reads the keys and builds theArtistand the list of tracks again. save_trackscompares the keys in memory with the keys in the table. It inserts before it deletes, so SQLite does not give the new track the key of the deleted one. SQLite checks the constraints only because the program runspragma foreign_keys = on.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class Main {
record ArtistRow(String name) {}
record AlbumRow(String title, Long artistId) {}
record TrackRow(String title, Long albumId) {}
// A stand-in for the database: three tables, each keyed by id, and one row counter per table.
static final Map<Long, ArtistRow> ARTIST = new TreeMap<>();
static final Map<Long, AlbumRow> ALBUM = new TreeMap<>();
static final Map<Long, TrackRow> TRACK = new TreeMap<>();
static long lastArtist = 0, lastAlbum = 0, lastTrack = 0;
static long insertArtistRow(ArtistRow row) {
ARTIST.put(++lastArtist, row);
return lastArtist;
}
static long insertAlbumRow(AlbumRow row) {
// Like a FOREIGN KEY constraint: a key that is not null must find its parent row.
if (row.artistId() != null && !ARTIST.containsKey(row.artistId())) {
throw new IllegalStateException("FOREIGN KEY constraint failed");
}
ALBUM.put(++lastAlbum, row);
return lastAlbum;
}
static long insertTrackRow(TrackRow row) {
if (row.albumId() != null && !ALBUM.containsKey(row.albumId())) {
throw new IllegalStateException("FOREIGN KEY constraint failed");
}
TRACK.put(++lastTrack, row);
return lastTrack;
}
static class Artist {
Long id;
String name;
Artist(String name, Long id) {
this.name = name;
this.id = id;
}
}
static class Track {
Long id;
String title;
Track(String title, Long id) {
this.title = title;
this.id = id;
}
}
static class Album {
Long id;
String title;
Artist artist;
List<Track> tracks;
Album(String title, Artist artist, List<Track> tracks, Long id) {
this.title = title;
this.artist = artist;
this.tracks = tracks;
this.id = id;
}
}
static void insertAlbum(Album album) {
// Many-to-one: write the key of the referenced artist.
album.id = insertAlbumRow(new AlbumRow(album.title, album.artist.id));
saveTracks(album);
}
static int[] saveTracks(Album album) {
// One-to-many: find the difference between the collection and the rows.
List<Long> inDb = new ArrayList<>();
TRACK.forEach((id, r) -> {
if (album.id.equals(r.albumId())) {
inDb.add(id);
}
});
Set<Long> inMemory = new HashSet<>();
for (Track t : album.tracks) {
if (t.id != null) {
inMemory.add(t.id);
}
}
int inserted = 0;
for (Track t : album.tracks) {
if (t.id == null) {
t.id = insertTrackRow(new TrackRow(t.title, album.id));
inserted++;
}
}
int deleted = 0;
for (Long id : inDb) {
if (!inMemory.contains(id)) {
TRACK.remove(id);
deleted++;
}
}
return new int[] {deleted, inserted};
}
static Album loadAlbum(long id) {
AlbumRow row = ALBUM.get(id);
Artist artist = new Artist(ARTIST.get(row.artistId()).name(), row.artistId());
List<Track> tracks = new ArrayList<>();
TRACK.forEach((tid, r) -> {
if (r.albumId() == id) {
tracks.add(new Track(r.title(), tid));
}
});
return new Album(row.title(), artist, tracks, id);
}
static String showTracks() {
List<String> parts = new ArrayList<>();
TRACK.forEach((id, r) -> parts.add(id + " " + r.title() + " album_id=" + r.albumId()));
return String.join(" | ", parts);
}
public static void main(String[] args) {
Artist miles = new Artist("Miles Davis", null);
miles.id = insertArtistRow(new ArtistRow(miles.name));
List<Track> tracks = new ArrayList<>(List.of(new Track("So What", null), new Track("Blue in Green", null)));
insertAlbum(new Album("Kind of Blue", miles, tracks, null));
ALBUM.forEach((id, r) -> System.out.println("album rows: " + id + " " + r.title() + " artist_id=" + r.artistId()));
System.out.println("track rows: " + showTracks());
Album album = loadAlbum(1);
List<String> titles = new ArrayList<>();
for (Track t : album.tracks) {
titles.add(t.title);
}
System.out.println("loaded: " + album.title + " by " + album.artist.name + " | " + String.join(", ", titles));
album.tracks.removeIf(t -> t.title.equals("Blue in Green"));
album.tracks.add(new Track("Freddie Freeloader", null));
int[] counts = saveTracks(album);
System.out.println("update tracks: deleted " + counts[0] + ", inserted " + counts[1]);
System.out.println("track rows: " + showTracks());
try {
insertAlbumRow(new AlbumRow("Unknown", 99L));
} catch (IllegalStateException e) {
System.out.println("artist_id 99: " + e.getMessage());
}
}
}
album rows: 1 Kind of Blue artist_id=1
track rows: 1 So What album_id=1 | 2 Blue in Green album_id=1
loaded: Kind of Blue by Miles Davis | So What, Blue in Green
update tracks: deleted 1, inserted 1
track rows: 1 So What album_id=1 | 3 Freddie Freeloader album_id=1
artist_id 99: FOREIGN KEY constraint failed
- Verdict: idiom. The rows are records, and the tables are
TreeMapobjects so that they iterate in key order. A key is aLong, sonullcan stand for a missing reference. - With JPA or Hibernate,
@ManyToOneand@JoinColumndeclare the same mapping, and@OneToMany(mappedBy = ...)declares the collection.
// A stand-in for the database: three tables, each keyed by id, and one row counter per table.
const db = { artist: new Map(), album: new Map(), track: new Map() };
const lastId = { artist: 0, album: 0, track: 0 };
function insert(table, row) {
// Like a FOREIGN KEY constraint: a key that is not null must find its parent row.
if (table === "album" && row.artistId !== null && !db.artist.has(row.artistId)) {
throw new Error("FOREIGN KEY constraint failed");
}
if (table === "track" && row.albumId !== null && !db.album.has(row.albumId)) {
throw new Error("FOREIGN KEY constraint failed");
}
lastId[table] += 1;
db[table].set(lastId[table], row);
return lastId[table];
}
class Artist {
constructor(name, id = null) {
this.id = id;
this.name = name;
}
}
class Track {
constructor(title, id = null) {
this.id = id;
this.title = title;
}
}
class Album {
constructor(title, artist, tracks, id = null) {
this.id = id;
this.title = title;
this.artist = artist;
this.tracks = tracks;
}
}
function insertAlbum(album) {
// Many-to-one: write the key of the referenced artist.
album.id = insert("album", { title: album.title, artistId: album.artist.id });
saveTracks(album);
}
function saveTracks(album) {
// One-to-many: find the difference between the collection and the rows.
const inDb = [...db.track].filter(([, r]) => r.albumId === album.id).map(([id]) => id);
const inMemory = new Set(album.tracks.filter((t) => t.id !== null).map((t) => t.id));
let inserted = 0;
for (const t of album.tracks) {
if (t.id === null) {
t.id = insert("track", { title: t.title, albumId: album.id });
inserted += 1;
}
}
const removed = inDb.filter((id) => !inMemory.has(id));
for (const id of removed) db.track.delete(id);
return [removed.length, inserted];
}
function loadAlbum(id) {
const row = db.album.get(id);
const artist = new Artist(db.artist.get(row.artistId).name, row.artistId);
const tracks = [...db.track]
.filter(([, r]) => r.albumId === id)
.sort(([a], [b]) => a - b)
.map(([tid, r]) => new Track(r.title, tid));
return new Album(row.title, artist, tracks, id);
}
function showTracks() {
return [...db.track]
.sort(([a], [b]) => a - b)
.map(([id, r]) => `${id} ${r.title} album_id=${r.albumId}`)
.join(" | ");
}
const miles = new Artist("Miles Davis");
miles.id = insert("artist", { name: miles.name });
insertAlbum(new Album("Kind of Blue", miles, [new Track("So What"), new Track("Blue in Green")]));
for (const [id, r] of db.album) console.log(`album rows: ${id} ${r.title} artist_id=${r.artistId}`);
console.log(`track rows: ${showTracks()}`);
const album = loadAlbum(1);
const titles = album.tracks.map((t) => t.title).join(", ");
console.log(`loaded: ${album.title} by ${album.artist.name} | ${titles}`);
album.tracks = album.tracks.filter((t) => t.title !== "Blue in Green");
album.tracks.push(new Track("Freddie Freeloader"));
const [deleted, inserted] = saveTracks(album);
console.log(`update tracks: deleted ${deleted}, inserted ${inserted}`);
console.log(`track rows: ${showTracks()}`);
try {
insert("album", { title: "Unknown", artistId: 99 });
} catch (e) {
console.log(`artist_id 99: ${e.message}`);
}
album rows: 1 Kind of Blue artist_id=1
track rows: 1 So What album_id=1 | 2 Blue in Green album_id=1
loaded: Kind of Blue by Miles Davis | So What, Blue in Green
update tracks: deleted 1, inserted 1
track rows: 1 So What album_id=1 | 3 Freddie Freeloader album_id=1
artist_id 99: FOREIGN KEY constraint failed
- Verdict: idiom. The tables are
Mapobjects keyed by id, andinsertchecks each key that is notnullagainst the parent table, like a foreign key constraint. saveTracksfilters the track table byalbumIdto find the rows of the collection, and uses aSetof the keys in memory to find the rows to delete.
package main
import (
"errors"
"fmt"
"sort"
"strings"
)
type artistRow struct{ name string }
type albumRow struct {
title string
artistID *int64
}
type trackRow struct {
title string
albumID *int64
}
// A stand-in for the database: three tables, each keyed by id, and one row counter per table.
var (
artistTable = map[int64]artistRow{}
albumTable = map[int64]albumRow{}
trackTable = map[int64]trackRow{}
lastArtist, lastAlbum, lastTrack int64
)
var errFK = errors.New("FOREIGN KEY constraint failed")
func insertArtistRow(r artistRow) int64 {
lastArtist++
artistTable[lastArtist] = r
return lastArtist
}
func insertAlbumRow(r albumRow) (int64, error) {
// Like a FOREIGN KEY constraint: a key that is not nil must find its parent row.
if r.artistID != nil {
if _, ok := artistTable[*r.artistID]; !ok {
return 0, errFK
}
}
lastAlbum++
albumTable[lastAlbum] = r
return lastAlbum, nil
}
func insertTrackRow(r trackRow) (int64, error) {
if r.albumID != nil {
if _, ok := albumTable[*r.albumID]; !ok {
return 0, errFK
}
}
lastTrack++
trackTable[lastTrack] = r
return lastTrack, nil
}
type Artist struct {
ID *int64
Name string
}
type Track struct {
ID *int64
Title string
}
type Album struct {
ID *int64
Title string
Artist *Artist
Tracks []*Track
}
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
}
func insertAlbum(a *Album) error {
// Many-to-one: write the key of the referenced artist.
id, err := insertAlbumRow(albumRow{a.Title, a.Artist.ID})
if err != nil {
return err
}
a.ID = &id
_, _, err = saveTracks(a)
return err
}
func saveTracks(a *Album) (deleted, inserted int, err error) {
// One-to-many: find the difference between the collection and the rows.
var inDB []int64
for _, id := range sortedKeys(trackTable) {
if r := trackTable[id]; r.albumID != nil && *r.albumID == *a.ID {
inDB = append(inDB, id)
}
}
inMemory := map[int64]bool{}
for _, t := range a.Tracks {
if t.ID != nil {
inMemory[*t.ID] = true
}
}
for _, t := range a.Tracks {
if t.ID == nil {
id, err := insertTrackRow(trackRow{t.Title, a.ID})
if err != nil {
return deleted, inserted, err
}
t.ID = &id
inserted++
}
}
for _, id := range inDB {
if !inMemory[id] {
delete(trackTable, id)
deleted++
}
}
return deleted, inserted, nil
}
func loadAlbum(id int64) *Album {
r := albumTable[id]
artist := &Artist{ID: r.artistID, Name: artistTable[*r.artistID].name}
var tracks []*Track
for _, tid := range sortedKeys(trackTable) {
if t := trackTable[tid]; t.albumID != nil && *t.albumID == id {
tid := tid
tracks = append(tracks, &Track{ID: &tid, Title: t.title})
}
}
return &Album{ID: &id, Title: r.title, Artist: artist, Tracks: tracks}
}
func showTracks() string {
var parts []string
for _, id := range sortedKeys(trackTable) {
r := trackTable[id]
parts = append(parts, fmt.Sprintf("%d %s album_id=%d", id, r.title, *r.albumID))
}
return strings.Join(parts, " | ")
}
func main() {
miles := &Artist{Name: "Miles Davis"}
id := insertArtistRow(artistRow{miles.Name})
miles.ID = &id
if err := insertAlbum(&Album{Title: "Kind of Blue", Artist: miles, Tracks: []*Track{{Title: "So What"}, {Title: "Blue in Green"}}}); err != nil {
fmt.Println(err)
}
for _, id := range sortedKeys(albumTable) {
r := albumTable[id]
fmt.Printf("album rows: %d %s artist_id=%d\n", id, r.title, *r.artistID)
}
fmt.Println("track rows:", showTracks())
album := loadAlbum(1)
var titles []string
for _, t := range album.Tracks {
titles = append(titles, t.Title)
}
fmt.Printf("loaded: %s by %s | %s\n", album.Title, album.Artist.Name, strings.Join(titles, ", "))
var kept []*Track
for _, t := range album.Tracks {
if t.Title != "Blue in Green" {
kept = append(kept, t)
}
}
album.Tracks = append(kept, &Track{Title: "Freddie Freeloader"})
deleted, inserted, err := saveTracks(album)
if err != nil {
fmt.Println(err)
}
fmt.Printf("update tracks: deleted %d, inserted %d\n", deleted, inserted)
fmt.Println("track rows:", showTracks())
bad := int64(99)
if _, err := insertAlbumRow(albumRow{"Unknown", &bad}); err != nil {
fmt.Println("artist_id 99:", err)
}
}
album rows: 1 Kind of Blue artist_id=1
track rows: 1 So What album_id=1 | 2 Blue in Green album_id=1
loaded: Kind of Blue by Miles Davis | So What, Blue in Green
update tracks: deleted 1, inserted 1
track rows: 1 So What album_id=1 | 3 Freddie Freeloader album_id=1
artist_id 99: FOREIGN KEY constraint failed
- Verdict: idiom. A foreign key that can be null is a
*int64. Go maps have no order, sosortedKeyssorts the keys before each scan of a table. - The insert functions return an
errorfor a key that has no parent row, as a database driver returns the error of the constraint.
use std::collections::{BTreeMap, HashSet};
struct AlbumRow {
title: String,
artist_id: Option<i64>,
}
struct TrackRow {
title: String,
album_id: Option<i64>,
}
// A stand-in for the database: three tables, each keyed by id, and one row counter per table.
#[derive(Default)]
struct Db {
artist: BTreeMap<i64, String>,
album: BTreeMap<i64, AlbumRow>,
track: BTreeMap<i64, TrackRow>,
last_artist: i64,
last_album: i64,
last_track: i64,
}
const FK_ERROR: &str = "FOREIGN KEY constraint failed";
impl Db {
fn insert_artist(&mut self, name: &str) -> i64 {
self.last_artist += 1;
self.artist.insert(self.last_artist, name.to_string());
self.last_artist
}
fn insert_album(&mut self, row: AlbumRow) -> Result<i64, &'static str> {
// Like a FOREIGN KEY constraint: a key that is not None must find its parent row.
if let Some(a) = row.artist_id {
if !self.artist.contains_key(&a) {
return Err(FK_ERROR);
}
}
self.last_album += 1;
self.album.insert(self.last_album, row);
Ok(self.last_album)
}
fn insert_track(&mut self, row: TrackRow) -> Result<i64, &'static str> {
if let Some(a) = row.album_id {
if !self.album.contains_key(&a) {
return Err(FK_ERROR);
}
}
self.last_track += 1;
self.track.insert(self.last_track, row);
Ok(self.last_track)
}
fn show_tracks(&self) -> String {
let parts: Vec<String> = self
.track
.iter()
.map(|(id, r)| format!("{} {} album_id={}", id, r.title, r.album_id.unwrap()))
.collect();
parts.join(" | ")
}
}
struct Artist {
id: Option<i64>,
name: String,
}
struct Track {
id: Option<i64>,
title: String,
}
struct Album {
id: Option<i64>,
title: String,
artist: Artist,
tracks: Vec<Track>,
}
fn track(title: &str) -> Track {
Track { id: None, title: title.to_string() }
}
fn insert_album(db: &mut Db, album: &mut Album) -> Result<(), &'static str> {
// Many-to-one: write the key of the referenced artist.
let row = AlbumRow { title: album.title.clone(), artist_id: album.artist.id };
album.id = Some(db.insert_album(row)?);
save_tracks(db, album)?;
Ok(())
}
fn save_tracks(db: &mut Db, album: &mut Album) -> Result<(usize, usize), &'static str> {
// One-to-many: find the difference between the collection and the rows.
let in_db: Vec<i64> = db.track.iter().filter(|(_, r)| r.album_id == album.id).map(|(id, _)| *id).collect();
let in_memory: HashSet<i64> = album.tracks.iter().filter_map(|t| t.id).collect();
let mut inserted = 0;
for t in album.tracks.iter_mut() {
if t.id.is_none() {
t.id = Some(db.insert_track(TrackRow { title: t.title.clone(), album_id: album.id })?);
inserted += 1;
}
}
let mut deleted = 0;
for id in in_db {
if !in_memory.contains(&id) {
db.track.remove(&id);
deleted += 1;
}
}
Ok((deleted, inserted))
}
fn load_album(db: &Db, id: i64) -> Album {
let row = &db.album[&id];
let artist_id = row.artist_id.unwrap();
let artist = Artist { id: Some(artist_id), name: db.artist[&artist_id].clone() };
let tracks = db
.track
.iter()
.filter(|(_, r)| r.album_id == Some(id))
.map(|(tid, r)| Track { id: Some(*tid), title: r.title.clone() })
.collect();
Album { id: Some(id), title: row.title.clone(), artist, tracks }
}
fn main() {
let mut db = Db::default();
let mut miles = Artist { id: None, name: "Miles Davis".to_string() };
miles.id = Some(db.insert_artist(&miles.name));
let mut kind_of_blue = Album {
id: None,
title: "Kind of Blue".to_string(),
artist: miles,
tracks: vec![track("So What"), track("Blue in Green")],
};
if let Err(e) = insert_album(&mut db, &mut kind_of_blue) {
println!("{}", e);
}
for (id, r) in &db.album {
println!("album rows: {} {} artist_id={}", id, r.title, r.artist_id.unwrap());
}
println!("track rows: {}", db.show_tracks());
let mut album = load_album(&db, 1);
let titles: Vec<&str> = album.tracks.iter().map(|t| t.title.as_str()).collect();
println!("loaded: {} by {} | {}", album.title, album.artist.name, titles.join(", "));
album.tracks.retain(|t| t.title != "Blue in Green");
album.tracks.push(track("Freddie Freeloader"));
match save_tracks(&mut db, &mut album) {
Ok((deleted, inserted)) => println!("update tracks: deleted {}, inserted {}", deleted, inserted),
Err(e) => println!("{}", e),
}
println!("track rows: {}", db.show_tracks());
let bad = AlbumRow { title: "Unknown".to_string(), artist_id: Some(99) };
if let Err(e) = db.insert_album(bad) {
println!("artist_id 99: {}", e);
}
}
album rows: 1 Kind of Blue artist_id=1
track rows: 1 So What album_id=1 | 2 Blue in Green album_id=1
loaded: Kind of Blue by Miles Davis | So What, Blue in Green
update tracks: deleted 1, inserted 1
track rows: 1 So What album_id=1 | 3 Freddie Freeloader album_id=1
artist_id 99: FOREIGN KEY constraint failed
- Verdict: idiom. A foreign key is an
Option<i64>, and the tables areBTreeMapvalues so that they iterate in key order. The insert methods returnResult, and?passes the error of the constraint to the caller. save_trackstakes&mut Albumso that it can set the keys of the new tracks.
Consequences
Benefits.
- The database can check the references. With a foreign key constraint, "Attempting to insert a row into the track table that does not correspond to any row in the artist table will fail, as will attempting to delete a row from the artist table when there exist dependent rows in the track table."4
- Normalized tables. Each column holds one value. A one-to-many collection needs no list column, because each child row holds one key.
- Frameworks hide the key. Django stores a
ForeignKeynamedmanufacturerin a column namedmanufacturer_id, and the programmer works with the object: "You’ll always deal with the field names of your model object."5 Entity Framework Core can keep the foreign key as a shadow property, which "exists in the EF model but does not exist on the .NET type."6
Liabilities.
The order of the saves matters. The referenced row must have its key before the referring row is written. If the album is saved first, the artist has no key yet, and the album row gets a null. The constraint does not catch this, because "if the foreign key column for an entry in the track table is NULL, then no corresponding entry in the artist table is required."4 The following program saves the album first. The artist gets its key a moment later, but the album row keeps the null, and the program sees no error.
This code runs but gives a wrong answer on purpose.
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("pragma foreign_keys = on")
db.execute("create table artist (id integer primary key, name text)")
db.execute("create table album (id integer primary key, title text, artist_id integer references artist(id))")
class Artist:
def __init__(self, name):
self.id, self.name = None, name
artist = Artist("Miles Davis")
# The album is saved first, so the artist has no key yet.
db.execute("insert into album (title, artist_id) values (?, ?)", ("Kind of Blue", artist.id))
artist.id = db.execute("insert into artist (name) values (?)", (artist.name,)).lastrowid
print(db.execute("select * from album").fetchall())
[(1, 'Kind of Blue', None)]
Updates to a collection. When the program adds or removes items in a collection, the mapper must find which rows to insert, which to delete and which to change. Fowler's book describes three ways: delete all the child rows and insert them again, keep a reference back to the owner in each child, or compare the collection with the rows that the database holds.7 The examples use the last way.
The constraint may be off. The database checks the keys only if the constraint is declared and enabled. In SQLite, "Foreign key constraints are disabled by default", and each connection must turn them on.4
Queries on the child key. Each load of a collection, and each delete of a parent row, searches the child table by the foreign key. SQLite advises that "in most real systems, an index should be created on the child key columns of each foreign key constraint."4
Loading one object can load many. If the mapper turns every key into an object at once, loading one album loads its artist, the artist's other albums and so on. A Lazy Load keeps the key and loads the object only when the program uses it.
When not to use it
For many-to-many associations. A foreign key column holds one key, so a track that is on many playlists cannot be a single column. Use a link table, as in Association Table Mapping. Entity Framework Core describes many-to-many relationships as "composed of two one-to-many relationships, each of which is itself defined by a foreign key referencing a principal key."6
For values that belong to one owner. A value that has no identity of its own, such as an address that only one customer uses, does not need its own table and key. It can be stored in the columns of its owner, as in Embedded Value.
For data that the database never queries. A structure that the program always reads and writes as a whole can be stored in one column, as in Serialized LOB.
How to fix it
Save the referenced objects first: the artist, then the album, then its tracks. A Unit of Work can sort the inserts in this order. Declare the key column NOT NULL when every row must have a parent, so that a missing key fails at once. Django checks this before it saves: "If the field is nullable, allowing the save would result in silent data loss", so a save with an unsaved related object raises a ValueError.8
Variants and related patterns
Bidirectional associations. The album can hold its tracks and each track can hold its album. Both references map to the same foreign key column, and the mapper must keep the two sides in step. SQLAlchemy links the two sides with the back_populates argument of relationship().3
Dependent Mapping. When the children have no meaning without their owner, such as tracks without an album, the owner's mapper can save and load them, and the children need no mapper of their own. See Dependent Mapping.
Association Table Mapping. A many-to-many association uses a separate table of key pairs. See Association Table Mapping.
Identity Field and Identity Map. The foreign key is the identity field of the referenced object, and the identity map makes sure that two albums of one artist refer to one artist object. See Identity Field and Identity Map.
Known uses
- Django: the ForeignKey class in related.py at 5.2.8 is documented as "Provide a many-to-one relation by adding a column to the local model to hold the remote value."9 When the program writes
child.parent = parent, ForwardManyToOneDescriptor.set copies the key:setattr(instance, lh_field.attname, getattr(value, rh_field.attname)).10 Before a save,_prepare_related_fields_for_saveraises an error if a related object has no key yet.8 - SQLAlchemy:
relationship()together with aForeignKeycolumn. "Many to one places a foreign key in the parent table referencing the child."3 - Entity Framework Core, for .NET: "All one-to-one and one-to-many relationships are defined by a foreign key on the dependent end that references a primary or alternate key on the principal end."6
References
- Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Foreign Key Mapping, pattern summary
- Foreign key, Wikipedia, lead section and Summary
- SQLAlchemy 2.0 documentation, Basic Relationship Patterns, One To Many; Many To One
- SQLite documentation, SQLite Foreign Key Support, 1. Introduction to Foreign Key Constraints; 2. Enabling Foreign Key Support; 3. Required and Suggested Database Indexes
- Django 5.2 documentation, Model field reference, ForeignKey; Database Representation
- Entity Framework Core documentation, Foreign and principal keys in relationships, introduction; Shadow foreign keys
- Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 12, Object-Relational Structural Patterns, Foreign Key Mapping
- Django 5.2.8 source, django/db/models/base.py, Model._prepare_related_fields_for_save, lines 1218 to 1255
- Django 5.2.8 source, django/db/models/fields/related.py, class ForeignKey and its docstring, lines 958 to 965
- Django 5.2.8 source, django/db/models/fields/related_descriptors.py, ForwardManyToOneDescriptor.__set__, lines 277 to 351
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 3HNEAC Edit this page History Report an error Markdown