Programming Search⌘K

Patterncore

Identity Field

Also called identity field pattern, id field, primary key field.

An Identity Field stores the primary key of a database row in a field of the object that holds the row's data, so the program can find the row again to update or delete it.

Family
architectural
Intent
Saves a database ID field in an object to maintain identity between an in-memory object and a database row.

Intent

An Identity Field "Saves a database ID field in an object to maintain identity between an in-memory object and a database row."1 The object keeps the primary key of its row. The program uses that key to find the row again when it updates or deletes the object.

Problem

"Relational databases tell one row from another by using key - in particular, the primary key. However, in-memory objects don't need such a key, as the object system ensures the correct identity under the covers".1 A program that only reads rows can ignore this difference. A program that also writes changes back must know which row each object came from. Fowler puts it this way: "in order to write data back you need to tie the database to the in-memory object system."1

The object's other fields cannot always do this. A name or an email can change, and two rows can have the same name. If the program finds the row by data that the user can edit, an update can miss the row or change the wrong one.

Solution

"In essence, Identity Field is mind-numbingly simple. All you do is store the primary key of the relational database table in the object's fields."1 The field is empty while the object is new. When the program inserts the row, it gets the key that the database made and puts it in the field. After that, each UPDATE and DELETE finds the row by that key.

  new Person            insert            database             Person after save
  id   = None   --->  INSERT ... ---->  row id 1 created  --->  id   = 1
  name = Ann                          lastrowid = 1           name = Ann

  change the email, then save:
  UPDATE person SET ... WHERE id = 1    (the key, not the data, finds the row)

The participants are the domain object, which has the key field; the table, whose primary key the field copies; and the mapper or the object itself, which reads the key after an insert and puts it in each WHERE clause.

The database usually makes the key. In SQLite, if the INTEGER PRIMARY KEY column "is not explicitly given a value, then it will be filled automatically with an unused integer, usually one more than the largest ROWID currently in use."2 Python's sqlite3 gives the new key to the program: lastrowid is a "Read-only attribute that provides the row id of the last inserted row."3

The following program saves two new people, changes the email of one, and saves again. The second save finds the row by its key, although the data changed.

import sqlite3

db = sqlite3.connect(":memory:")
db.execute("create table person (id integer primary key, name text, email text)")


class Person:
    def __init__(self, name, email):
        self.id = None  # The Identity Field: None until the row exists.
        self.name, self.email = name, email


class PersonMapper:
    def save(self, p):
        if p.id is None:
            sql = "insert into person (name, email) values (?, ?)"
            p.id = db.execute(sql, (p.name, p.email)).lastrowid  # Keep the new key.
        else:
            sql = "update person set name = ?, email = ? where id = ?"
            db.execute(sql, (p.name, p.email, p.id))

    def find(self, id):
        sql = "select id, name, email from person where id = ?"
        id, name, email = db.execute(sql, (id,)).fetchone()
        p = Person(name, email)
        p.id = id
        return p


mapper = PersonMapper()
ann, bo = Person("Ann", "ann@example.com"), Person("Bo", "bo@example.com")
print("before save:", ann.id, bo.id)
mapper.save(ann)
mapper.save(bo)
print("after save:", ann.id, bo.id)
ann.email = "ann@new.example"
mapper.save(ann)  # The key finds the row, even though the email changed.
print(db.execute("select * from person order by id").fetchall())
found = mapper.find(1)
print("find(1):", found.id, found.name, found.email)
Output
before save: None None
after save: 1 2
[(1, 'Ann', 'ann@new.example'), (2, 'Bo', 'bo@example.com')]
find(1): 1 Ann ann@new.example

Example

Each example file saves two new people and prints their keys before and after the insert. It then changes the email of the first person and saves again: the update finds the row by its key. It loads row 1 twice and shows that the two loads give two different objects with equal keys, so the key, not the object reference, tells that they stand for the same row. The last line makes the same change in a table that uses the email as the key, and the update finds no row. The Python file uses SQLite. The JavaScript, Java, Go and Rust files keep the tables in memory and use a counter in place of the generated key.

PythonGitHub
import sqlite3

db = sqlite3.connect(":memory:")
db.execute("create table person (id integer primary key, name text, email text)")
db.execute("create table person_by_email (email text primary key, name text)")


class Person:
    def __init__(self, name, email, id=None):
        self.id = id  # The Identity Field: the primary key of the row.
        self.name, self.email = name, email

    def show_id(self):
        return "none" if self.id is None else str(self.id)


def save(p):
    if p.id is None:
        cur = db.execute("insert into person (name, email) values (?, ?)", (p.name, p.email))
        p.id = cur.lastrowid
        return 1
    cur = db.execute("update person set name = ?, email = ? where id = ?", (p.name, p.email, p.id))
    return cur.rowcount


def find(id):
    row = db.execute("select name, email, id from person where id = ?", (id,)).fetchone()
    return Person(*row)


ann, bo = Person("Ann", "ann@example.com"), Person("Bo", "bo@example.com")
print(f"new: Ann id={ann.show_id()} | Bo id={bo.show_id()}")
save(ann)
save(bo)
print(f"saved: Ann id={ann.show_id()} | Bo id={bo.show_id()}")

ann.email = "ann@new.example"
rows = save(ann)
row = db.execute("select id, name, email from person where id = ?", (ann.id,)).fetchone()
print(f"update by id: rows {rows} | {row[0]} {row[1]} {row[2]}")

b = find(2)
print(f"find(2): id={b.id} {b.name} {b.email}")

first, second = find(1), find(1)
objects = "same" if first is second else "different"
ids = "equal" if first.id == second.id else "different"
print(f"two loads of row 1: {objects} objects, {ids} ids")

# The same change with a meaningful key: the email is the key.
db.execute("insert into person_by_email values ('cy@example.com', 'Cy')")
cy = Person("Cy", "cy@example.com")
cy.email = "cy@new.example"
cur = db.execute("update person_by_email set name = ? where email = ?", (cy.name, cy.email))
print(f"update by email key: rows {cur.rowcount}")
Output
new: Ann id=none | Bo id=none
saved: Ann id=1 | Bo id=2
update by id: rows 1 | 1 Ann ann@new.example
find(2): id=2 Bo bo@example.com
two loads of row 1: different objects, equal ids
update by email key: rows 0
  • Verdict: idiom. The key field starts as None. After the INSERT, cursor.lastrowid gives the key that SQLite made for the INTEGER PRIMARY KEY column, and each UPDATE uses it in the WHERE clause.
  • cursor.rowcount shows how many rows an UPDATE changed. It is 0 for the table whose key is the email, because the changed email no longer matches the row.
JavaGitHub
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class Main {
    record Row(String name, String email) {}

    // A stand-in for the database: a table keyed by id, and a counter like AUTOINCREMENT.
    static final Map<Long, Row> PERSON = new HashMap<>();
    static long lastRowId = 0;
    // A second table keyed by a meaningful value, the email.
    static final Map<String, String> PERSON_BY_EMAIL = new HashMap<>(Map.of("cy@example.com", "Cy"));

    static class Person {
        Long id; // The Identity Field: null until the row exists.
        String name;
        String email;

        Person(String name, String email, Long id) {
            this.name = name;
            this.email = email;
            this.id = id;
        }

        String showId() {
            return id == null ? "none" : id.toString();
        }
    }

    static int save(Person p) {
        if (p.id == null) {
            lastRowId++;
            PERSON.put(lastRowId, new Row(p.name, p.email));
            p.id = lastRowId;
            return 1;
        }
        if (!PERSON.containsKey(p.id)) {
            return 0;
        }
        PERSON.put(p.id, new Row(p.name, p.email));
        return 1;
    }

    static Person find(long id) {
        Row row = PERSON.get(id);
        return new Person(row.name(), row.email(), id);
    }

    public static void main(String[] args) {
        Person ann = new Person("Ann", "ann@example.com", null);
        Person bo = new Person("Bo", "bo@example.com", null);
        System.out.println("new: Ann id=" + ann.showId() + " | Bo id=" + bo.showId());
        save(ann);
        save(bo);
        System.out.println("saved: Ann id=" + ann.showId() + " | Bo id=" + bo.showId());

        ann.email = "ann@new.example";
        int rows = save(ann);
        Row row = PERSON.get(ann.id);
        System.out.println("update by id: rows " + rows + " | " + ann.id + " " + row.name() + " " + row.email());

        Person b = find(2);
        System.out.println("find(2): id=" + b.id + " " + b.name + " " + b.email);

        Person first = find(1);
        Person second = find(1);
        String objects = first == second ? "same" : "different";
        String ids = Objects.equals(first.id, second.id) ? "equal" : "different";
        System.out.println("two loads of row 1: " + objects + " objects, " + ids + " ids");

        // The same change with a meaningful key: the email is the key.
        Person cy = new Person("Cy", "cy@example.com", null);
        cy.email = "cy@new.example";
        int updated = 0;
        if (PERSON_BY_EMAIL.containsKey(cy.email)) {
            PERSON_BY_EMAIL.put(cy.email, cy.name);
            updated = 1;
        }
        System.out.println("update by email key: rows " + updated);
    }
}
Output
new: Ann id=none | Bo id=none
saved: Ann id=1 | Bo id=2
update by id: rows 1 | 1 Ann ann@new.example
find(2): id=2 Bo bo@example.com
two loads of row 1: different objects, equal ids
update by email key: rows 0
  • Verdict: idiom. The key is a Long and not a long, so null can mean that the object is not saved yet. == compares references, and Objects.equals compares the key values.
  • With JDBC, the new key comes from Statement.RETURN_GENERATED_KEYS and getGeneratedKeys(). Entity Framework Core and JPA set the key field after the insert.
JavaScriptGitHub
// A stand-in for the database: a table keyed by id, and a counter like AUTOINCREMENT.
const personTable = new Map();
let lastRowId = 0;
// A second table keyed by a meaningful value, the email.
const personByEmail = new Map([["cy@example.com", { name: "Cy" }]]);

class Person {
  constructor(name, email, id = null) {
    this.id = id; // The Identity Field: the primary key of the row.
    this.name = name;
    this.email = email;
  }

  showId() {
    return this.id === null ? "none" : String(this.id);
  }
}

function save(p) {
  if (p.id === null) {
    lastRowId += 1;
    personTable.set(lastRowId, { name: p.name, email: p.email });
    p.id = lastRowId;
    return 1;
  }
  if (!personTable.has(p.id)) return 0;
  personTable.set(p.id, { name: p.name, email: p.email });
  return 1;
}

function find(id) {
  const row = personTable.get(id);
  return new Person(row.name, row.email, id);
}

const ann = new Person("Ann", "ann@example.com");
const bo = new Person("Bo", "bo@example.com");
console.log(`new: Ann id=${ann.showId()} | Bo id=${bo.showId()}`);
save(ann);
save(bo);
console.log(`saved: Ann id=${ann.showId()} | Bo id=${bo.showId()}`);

ann.email = "ann@new.example";
const rows = save(ann);
const row = personTable.get(ann.id);
console.log(`update by id: rows ${rows} | ${ann.id} ${row.name} ${row.email}`);

const b = find(2);
console.log(`find(2): id=${b.id} ${b.name} ${b.email}`);

const first = find(1);
const second = find(1);
const objects = first === second ? "same" : "different";
const ids = first.id === second.id ? "equal" : "different";
console.log(`two loads of row 1: ${objects} objects, ${ids} ids`);

// The same change with a meaningful key: the email is the key.
const cy = new Person("Cy", "cy@example.com");
cy.email = "cy@new.example";
let updated = 0;
if (personByEmail.has(cy.email)) {
  personByEmail.set(cy.email, { name: cy.name });
  updated = 1;
}
console.log(`update by email key: rows ${updated}`);
Output
new: Ann id=none | Bo id=none
saved: Ann id=1 | Bo id=2
update by id: rows 1 | 1 Ann ann@new.example
find(2): id=2 Bo bo@example.com
two loads of row 1: different objects, equal ids
update by email key: rows 0
  • Verdict: idiom. The key field starts as null, and the save function sets it from a counter that stands for the generated key. === on two loaded objects compares references, so the two loads of row 1 are different objects with equal keys.
  • With a database driver, the new key comes from the result of the insert, for example from an INSERT ... RETURNING id statement.
package main

import (
	"fmt"
	"strconv"
)

type row struct{ name, email string }

// A stand-in for the database: a table keyed by id, and a counter like AUTOINCREMENT.
var personTable = map[int64]row{}
var lastRowID int64

// A second table keyed by a meaningful value, the email.
var personByEmail = map[string]string{"cy@example.com": "Cy"}

type Person struct {
	ID    *int64 // The Identity Field: nil until the row exists.
	Name  string
	Email string
}

func (p *Person) showID() string {
	if p.ID == nil {
		return "none"
	}
	return strconv.FormatInt(*p.ID, 10)
}

func save(p *Person) int {
	if p.ID == nil {
		lastRowID++
		personTable[lastRowID] = row{p.Name, p.Email}
		id := lastRowID
		p.ID = &id
		return 1
	}
	if _, ok := personTable[*p.ID]; !ok {
		return 0
	}
	personTable[*p.ID] = row{p.Name, p.Email}
	return 1
}

func find(id int64) *Person {
	r := personTable[id]
	return &Person{ID: &id, Name: r.name, Email: r.email}
}

func main() {
	ann := &Person{Name: "Ann", Email: "ann@example.com"}
	bo := &Person{Name: "Bo", Email: "bo@example.com"}
	fmt.Printf("new: Ann id=%s | Bo id=%s\n", ann.showID(), bo.showID())
	save(ann)
	save(bo)
	fmt.Printf("saved: Ann id=%s | Bo id=%s\n", ann.showID(), bo.showID())

	ann.Email = "ann@new.example"
	rows := save(ann)
	r := personTable[*ann.ID]
	fmt.Printf("update by id: rows %d | %d %s %s\n", rows, *ann.ID, r.name, r.email)

	b := find(2)
	fmt.Printf("find(2): id=%d %s %s\n", *b.ID, b.Name, b.Email)

	first, second := find(1), find(1)
	objects := "different"
	if first == second {
		objects = "same"
	}
	ids := "different"
	if *first.ID == *second.ID {
		ids = "equal"
	}
	fmt.Printf("two loads of row 1: %s objects, %s ids\n", objects, ids)

	// The same change with a meaningful key: the email is the key.
	cy := &Person{Name: "Cy", Email: "cy@example.com"}
	cy.Email = "cy@new.example"
	updated := 0
	if _, ok := personByEmail[cy.Email]; ok {
		personByEmail[cy.Email] = cy.Name
		updated = 1
	}
	fmt.Printf("update by email key: rows %d\n", updated)
}
Output
new: Ann id=none | Bo id=none
saved: Ann id=1 | Bo id=2
update by id: rows 1 | 1 Ann ann@new.example
find(2): id=2 Bo bo@example.com
two loads of row 1: different objects, equal ids
update by email key: rows 0
  • Verdict: idiom. The key is a *int64, so nil means that the object is not saved yet. A plain int64 would need 0 as the marker. == on two pointers is true only if they point to the same variable, so the two loads of row 1 are different objects.
  • With database/sql, Result.LastInsertId gives the new key for drivers that support it.
RustGitHub
use std::collections::HashMap;

struct Row {
    name: String,
    email: String,
}

// A stand-in for the database: a table keyed by id, and a counter like AUTOINCREMENT.
struct Db {
    person: HashMap<i64, Row>,
    last_row_id: i64,
    // A second table keyed by a meaningful value, the email.
    person_by_email: HashMap<String, String>,
}

struct Person {
    id: Option<i64>, // The Identity Field: None until the row exists.
    name: String,
    email: String,
}

impl Person {
    fn new(name: &str, email: &str) -> Person {
        Person { id: None, name: name.to_string(), email: email.to_string() }
    }

    fn show_id(&self) -> String {
        match self.id {
            None => "none".to_string(),
            Some(id) => id.to_string(),
        }
    }
}

impl Db {
    fn save(&mut self, p: &mut Person) -> usize {
        let row = Row { name: p.name.clone(), email: p.email.clone() };
        match p.id {
            None => {
                self.last_row_id += 1;
                self.person.insert(self.last_row_id, row);
                p.id = Some(self.last_row_id);
                1
            }
            Some(id) => match self.person.get_mut(&id) {
                Some(r) => {
                    *r = row;
                    1
                }
                None => 0,
            },
        }
    }

    fn find(&self, id: i64) -> Person {
        let r = &self.person[&id];
        Person { id: Some(id), name: r.name.clone(), email: r.email.clone() }
    }
}

fn main() {
    let mut db = Db {
        person: HashMap::new(),
        last_row_id: 0,
        person_by_email: HashMap::from([("cy@example.com".to_string(), "Cy".to_string())]),
    };
    let mut ann = Person::new("Ann", "ann@example.com");
    let mut bo = Person::new("Bo", "bo@example.com");
    println!("new: Ann id={} | Bo id={}", ann.show_id(), bo.show_id());
    db.save(&mut ann);
    db.save(&mut bo);
    println!("saved: Ann id={} | Bo id={}", ann.show_id(), bo.show_id());

    ann.email = "ann@new.example".to_string();
    let rows = db.save(&mut ann);
    let id = ann.id.unwrap();
    let r = &db.person[&id];
    println!("update by id: rows {} | {} {} {}", rows, id, r.name, r.email);

    let b = db.find(2);
    println!("find(2): id={} {} {}", b.id.unwrap(), b.name, b.email);

    let first = db.find(1);
    let second = db.find(1);
    let objects = if std::ptr::eq(&first, &second) { "same" } else { "different" };
    let ids = if first.id == second.id { "equal" } else { "different" };
    println!("two loads of row 1: {} objects, {} ids", objects, ids);

    // The same change with a meaningful key: the email is the key.
    let mut cy = Person::new("Cy", "cy@example.com");
    cy.email = "cy@new.example".to_string();
    let mut updated = 0;
    if let Some(name) = db.person_by_email.get_mut(&cy.email) {
        *name = cy.name.clone();
        updated = 1;
    }
    println!("update by email key: rows {}", updated);
}
Output
new: Ann id=none | Bo id=none
saved: Ann id=1 | Bo id=2
update by id: rows 1 | 1 Ann ann@new.example
find(2): id=2 Bo bo@example.com
two loads of row 1: different objects, equal ids
update by email key: rows 0
  • Verdict: idiom. The key is an Option<i64>, so the type shows that a new object has no key. std::ptr::eq compares addresses, and == on the two Option values compares the keys.
  • The Db struct owns the tables, and save takes &mut Person so that it can set the key after the insert.

Consequences

Benefits.

  • The object can find its row after any change to its data. The key of a generated key column does not depend on the data. "Surrogate keys typically do not change while the row exists", so "Applications cannot lose their reference to a row in the database (since the identifier does not change)."4
  • Equality across loads. Two objects that hold the same key stand for the same row. An Identity Map uses the key to keep only one object for each row.
  • Simple references. A reference from one object to another is saved as the other object's key. See Foreign Key Mapping.
  • Frameworks add it for the programmer. In Django, if a model has no primary key field, "Django will automatically add a field to hold the primary key."5 In Entity Framework Core, "By convention, a property named Id or Id will be configured as the primary key of an entity."6

Liabilities.

A meaningful key can change. If the key is data that the user can edit, such as an email, a change to the data is also a change to the key. Wikipedia notes that "Attributes that uniquely identify an entity might change, which might invalidate the suitability of natural keys."4 In the following program the object keeps only its email, so after the change the update looks for the new email and finds no row. The row keeps the old data, and the program sees no error.

This code runs but gives a wrong answer on purpose.

import sqlite3

db = sqlite3.connect(":memory:")
db.execute("create table person (email text primary key, name text)")
db.execute("insert into person values ('ann@example.com', 'Ann')")


class Person:
    def __init__(self, email, name):
        self.email, self.name = email, name  # The email is also the key.


def save(p):
    sql = "update person set name = ? where email = ?"
    return db.execute(sql, (p.name, p.email)).rowcount


ann = Person(*db.execute("select email, name from person").fetchone())
ann.email = "ann@new.example"  # A change to the data is also a change to the key.
ann.name = "Anna"
print("rows updated:", save(ann))
print(db.execute("select email, name from person").fetchall())
Output
rows updated: 0
[('ann@example.com', 'Ann')]

The key exists only after the insert. A new object has no key until it is saved. Code that compares new objects by key, or that saves a reference to a new object, must save that object first.

Duplicates of the real entity. A generated key makes every row unique, even two rows for the same person. "Surrogate keys can result in duplicate values in any natural keys", and Wikipedia adds that to prevent this "one must preserve the role of the natural keys as unique constraints".4

Old keys can come back. In SQLite without AUTOINCREMENT, "ROWIDs from previously deleted rows might be reused when creating new rows".2 An object that kept the key of a deleted row can then update a different row.

The key can leak information. "Proprietary information can be leaked if surrogate keys are generated sequentially."4 A visible order number tells how many orders came before it.

When not to use it

For objects that have no row of their own. A value that is stored in the columns of its owner, such as a date range or an amount of money, has no key. It is an embedded value, and its identity is its data.

When the program only reads. A report that never writes rows back does not need to find them again, and a row can be read into plain values.

When the key must change with the data. Fowler's book advises against meaningful keys, because people make mistakes in the data and the key must then change.7 If a table must use such a key, the object must keep the old value until the update is written.

How to fix it

Give the table a generated key that has no meaning, and keep the natural data, such as the email, in ordinary columns with a unique constraint. Set the key field once, from the database, after the insert. Django makes the field read-only in effect: "If you change the value of the primary key on an existing object and then save it, a new object will be created alongside the old one."5

How the key is made. Fowler's book describes three ways to get a new key: let the database generate it, use a GUID, or make the key in the program, for example from a key table.7 Entity Framework Core uses the first way by convention: "non-composite primary keys of type short, int, long, or Guid are set up to have values generated for inserted entities if a value isn't provided by the application."8

Simple and compound keys. A simple key is one column. A compound key has several columns, and the object then often holds a key object that compares all of them. Entity Framework Core calls this a composite key and sets one up by convention "only" in specific cases.6

Table-unique and database-unique keys. A key can be unique in one table, or across all tables. A database-unique key lets one map hold the objects of all tables.7

Identity Map. The map uses the identity field as its key. See Identity Map.

Foreign Key Mapping. A reference between objects is saved as the identity field of the referenced object. See Foreign Key Mapping.

Known uses

  • Django: every model has a pk property. In base.py at 5.2.8, _get_pk_val reads the attribute of the primary key field, and _set_pk_val sets it.9 After an insert, _save_table reads the values that the database returns, such as the new key, and calls setattr(self, field.attname, value) for each one.10
  • SQLAlchemy: Mapper.identity_key_from_instance in mapper.py at 2.0.57 will "Return the identity key for the given instance, based on its primary key attributes." The key is a tuple of the class, the primary key values and an identity token.11
  • Entity Framework Core, for .NET: a property named Id or <type name>Id is the key by convention, and an int key gets a generated value on insert.68

References

  1. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Identity Field, pattern summary
  2. SQLite documentation, SQLite Autoincrement, 1. Summary; 2. Background
  3. The Python Standard Library, sqlite3, Cursor.lastrowid
  4. Surrogate key, Wikipedia, Advantages, Stability and Requirement changes; Disadvantages, Normalization and Inadvertent disclosure
  5. Django 5.2 documentation, Model field reference, Field.primary_key
  6. Entity Framework Core documentation, Keys, Configuring a primary key
  7. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 12, Object-Relational Structural Patterns, Identity Field
  8. Entity Framework Core documentation, Generated Values, Primary keys
  9. Django 5.2.8 source, django/db/models/base.py, Model._get_pk_val, Model._set_pk_val and the pk property, lines 655 to 665
  10. Django 5.2.8 source, django/db/models/base.py, Model._save_table, the insert branch, lines 1168 to 1174
  11. SQLAlchemy 2.0.57 source, lib/sqlalchemy/orm/mapper.py, Mapper.identity_key_from_instance and Mapper._identity_key_from_state, lines 3505 to 3537

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/W7RCK2/text.yaml