Programming Search⌘K

Patterncore

Active Record

Also called active record pattern.

An Active Record is an object that wraps one row of a table. It holds the data of the row, the code that reads and writes the row, and the domain logic on that data.

Family
architectural
Intent
An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.

Intent

"An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data."1 One object stands for one row. It knows its data, it knows how to load and save itself, and it knows the business rules of that data.

Problem

A program has domain objects such as products and orders. Each object has data and behaviour, and most of the data must be stored in a database. The rules are simple and close to the data: a product cannot be sold when it has no stock, and the stock must never be negative. The tables match the objects one to one.

In this case a separate layer between the objects and the tables adds classes and code with little gain. Fowler's catalogue states the simple answer: "Active Record uses the most obvious approach, putting data access logic in the domain object."1 Then each developer knows where the code that reads and writes the data is.

Solution

Make one class for each table. The fields of the class are the columns. The class has finders, usually static methods, that read rows and make one object for each row. Each object has save and delete methods, and the domain methods that work on its fields.12 A framework usually puts the finders and save in a base class, so a model class only names its table, its columns and its rules.

  application code
      p = Product.find(1); p.sell(2); p.save()
            |
            v
  Record (base class)                 Product (one object per row)
      find(id), all()   static            name, price, stock
      save()            INSERT or UPDATE   validate()   stock >= 0
      delete()          DELETE             sell(n), needs_restock()
            |
            v
  products table

The participants are the active record class, which holds the finders, the active record object, which holds the row, the save and delete methods and the domain logic, and the callers. The Rails guide quotes Fowler and adds that "Active Record classes match very closely to the record structure of the underlying database."3

The following program uses SQLite. Product is the Active Record. The rule that the stock cannot be negative is in save, so each write through the object checks it.

import sqlite3


class Product:
    """An Active Record: one object per row, with the data access and the domain logic together."""

    db: sqlite3.Connection

    def __init__(self, name: str, price: int, stock: int = 0, id: int | None = None) -> None:
        self.id, self.name, self.price, self.stock = id, name, price, stock

    # data access: finders are class methods, saving is an instance method
    @classmethod
    def find(cls, product_id: int) -> "Product | None":
        row = cls.db.execute("SELECT name, price, stock, id FROM products WHERE id = ?", (product_id,)).fetchone()
        return cls(*row) if row else None

    @classmethod
    def low_stock(cls, limit: int) -> list["Product"]:
        rows = cls.db.execute("SELECT name, price, stock, id FROM products WHERE stock < ? ORDER BY id", (limit,))
        return [cls(*row) for row in rows]

    def save(self) -> None:
        if self.stock < 0:
            raise ValueError(f"{self.name}: stock cannot be negative")
        if self.id is None:
            self.id = self.db.execute("INSERT INTO products (name, price, stock) VALUES (?, ?, ?)", (self.name, self.price, self.stock)).lastrowid
        else:
            self.db.execute("UPDATE products SET name = ?, price = ?, stock = ? WHERE id = ?", (self.name, self.price, self.stock, self.id))

    # domain logic on the same object
    def sell(self, quantity: int) -> int:
        if quantity > self.stock:
            raise ValueError(f"{self.name}: only {self.stock} in stock")
        self.stock -= quantity
        return quantity * self.price

    def restock(self, amount: int) -> None:
        self.stock += amount


Product.db = sqlite3.connect(":memory:")
Product.db.execute("CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT NOT NULL, price INTEGER NOT NULL, stock INTEGER NOT NULL)")
for name, price, stock in [("pen", 120, 3), ("ink", 450, 40), ("pad", 300, 0)]:
    Product(name, price, stock).save()

pen = Product.find(1)
print("sold 2 pens for", pen.sell(2))
pen.save()
for product in Product.low_stock(5):
    product.restock(20)
    product.save()
print([(p.id, p.name, p.stock) for p in map(Product.find, [1, 2, 3])])
try:
    Product.find(3).sell(50)
except ValueError as e:
    print("refused:", e)
Output
sold 2 pens for 240
[(1, 'pen', 21), (2, 'ink', 40), (3, 'pad', 20)]
refused: pad: only 20 in stock

The caller does not see SQL. It finds a product, calls a domain method, and saves the product.

Example

Each example file has a Product Active Record with the finders find and all, a save method that runs validate first, and the domain methods sell and needsRestock. The Python file has a small Record base class, which holds the finders and save for any table, as a framework does. It uses SQLite. The JavaScript, Java, Go and Rust files keep the table in memory, as a map from id to the stored columns, because the standard libraries of these languages have no database driver. A change of a field reaches the table only through save, as with a database.

PythonGitHub
import sqlite3
from typing import Any, Self


class Record:
    """A base class for Active Records. Each subclass is one table, and each object is one row."""

    db: sqlite3.Connection
    table: str
    columns: tuple[str, ...]

    def __init__(self, id: int | None = None, **values: Any) -> None:
        self.id = id
        for column in self.columns:
            setattr(self, column, values[column])

    @classmethod
    def _load(cls, row: tuple) -> Self:
        return cls(row[0], **dict(zip(cls.columns, row[1:])))

    @classmethod
    def _select(cls) -> str:
        return f"SELECT id, {', '.join(cls.columns)} FROM {cls.table}"

    @classmethod
    def find(cls, id: int) -> Self | None:
        row = cls.db.execute(f"{cls._select()} WHERE id = ?", (id,)).fetchone()
        return cls._load(row) if row else None

    @classmethod
    def all(cls) -> list[Self]:
        return [cls._load(row) for row in cls.db.execute(f"{cls._select()} ORDER BY id")]

    def validate(self) -> None:
        """A subclass raises ValueError here when the object must not be saved."""

    def save(self) -> None:
        self.validate()
        values = [getattr(self, column) for column in self.columns]
        if self.id is None:
            marks = ", ".join("?" for _ in self.columns)
            self.id = self.db.execute(f"INSERT INTO {self.table} ({', '.join(self.columns)}) VALUES ({marks})", values).lastrowid
        else:
            sets = ", ".join(f"{column} = ?" for column in self.columns)
            self.db.execute(f"UPDATE {self.table} SET {sets} WHERE id = ?", [*values, self.id])

    def delete(self) -> None:
        self.db.execute(f"DELETE FROM {self.table} WHERE id = ?", (self.id,))


class Product(Record):
    """One row of the products table, with the domain logic of a product."""

    table = "products"
    columns = ("name", "price", "stock")

    def validate(self) -> None:
        if self.stock < 0:
            raise ValueError(f"{self.name}: stock cannot be negative")

    def needs_restock(self) -> bool:
        return self.stock < 5

    def sell(self, quantity: int) -> int:
        if quantity > self.stock:
            raise ValueError(f"{self.name}: only {self.stock} in stock")
        self.stock -= quantity
        return quantity * self.price

    def __str__(self) -> str:
        return f"{self.id} {self.name} {self.stock}"


Record.db = sqlite3.connect(":memory:")
Record.db.execute("CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT NOT NULL, price INTEGER NOT NULL, stock INTEGER NOT NULL)")
for name, price, stock in [("pen", 120, 3), ("ink", 450, 40), ("pad", 300, 0)]:
    Product(name=name, price=price, stock=stock).save()

pen = Product.find(1)
print("sold 2 pens for", pen.sell(2))
pen.save()
restocked = []
for product in Product.all():
    if product.needs_restock():
        product.stock += 20
        product.save()
        restocked.append(product.name)
print("restocked:", ", ".join(restocked))
print("rows:", " | ".join(map(str, Product.all())))
ink = Product.find(2)
ink.stock -= 45
try:
    ink.save()
except ValueError as e:
    print("not saved:", e)
print("find(9):", Product.find(9) or "none")
Output
sold 2 pens for 240
restocked: pen, pad
rows: 1 pen 21 | 2 ink 40 | 3 pad 20
not saved: ink: stock cannot be negative
find(9): none
  • Verdict: idiom. A small Record base class holds the finders and save, and Product adds the columns, the validation and the domain methods, as a Rails or Django model does.
  • The SQL is built from the column list of the subclass. Only column names from the class go into the SQL text, and all values are ? parameters.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.TreeMap;

public class Main {
    // What the table stores for one row.
    record Row(String name, int price, int stock) {}

    // A stand-in for the products table: rows by id, with an id counter.
    // The test image has no database driver.
    static final class Table {
        final TreeMap<Integer, Row> rows = new TreeMap<>();
        int nextId = 1;
    }

    // An Active Record: one object per row, with the data access and the domain logic together.
    static final class Product {
        static final Table TABLE = new Table();

        Integer id;
        String name;
        int price;
        int stock;

        Product(Integer id, String name, int price, int stock) {
            this.id = id;
            this.name = name;
            this.price = price;
            this.stock = stock;
        }

        // Data access: the finders are static, and saving is an instance method.
        static Optional<Product> find(int id) {
            Row r = TABLE.rows.get(id);
            return r == null ? Optional.empty() : Optional.of(new Product(id, r.name(), r.price(), r.stock()));
        }

        static List<Product> all() {
            List<Product> out = new ArrayList<>();
            for (int id : TABLE.rows.keySet()) out.add(find(id).orElseThrow());
            return out;
        }

        void validate() {
            if (stock < 0) throw new IllegalStateException(name + ": stock cannot be negative");
        }

        void save() {
            validate();
            if (id == null) id = TABLE.nextId++;
            TABLE.rows.put(id, new Row(name, price, stock));
        }

        void delete() {
            TABLE.rows.remove(id);
        }

        // Domain logic on the same object.
        boolean needsRestock() {
            return stock < 5;
        }

        int sell(int quantity) {
            if (quantity > stock) throw new IllegalStateException(name + ": only " + stock + " in stock");
            stock -= quantity;
            return quantity * price;
        }

        @Override
        public String toString() {
            return id + " " + name + " " + stock;
        }
    }

    public static void main(String[] args) {
        new Product(null, "pen", 120, 3).save();
        new Product(null, "ink", 450, 40).save();
        new Product(null, "pad", 300, 0).save();

        Product pen = Product.find(1).orElseThrow();
        System.out.println("sold 2 pens for " + pen.sell(2));
        pen.save();
        List<String> restocked = new ArrayList<>();
        for (Product product : Product.all()) {
            if (product.needsRestock()) {
                product.stock += 20;
                product.save();
                restocked.add(product.name);
            }
        }
        System.out.println("restocked: " + String.join(", ", restocked));
        List<String> rows = new ArrayList<>();
        for (Product product : Product.all()) rows.add(product.toString());
        System.out.println("rows: " + String.join(" | ", rows));
        Product ink = Product.find(2).orElseThrow();
        ink.stock -= 45;
        try {
            ink.save();
        } catch (IllegalStateException e) {
            System.out.println("not saved: " + e.getMessage());
        }
        System.out.println("find(9): " + Product.find(9).map(Product::toString).orElse("none"));
    }
}
Output
sold 2 pens for 240
restocked: pen, pad
rows: 1 pen 21 | 2 ink 40 | 3 pad 20
not saved: ink: stock cannot be negative
find(9): none
  • Verdict: idiom. The finders are static methods and find returns an Optional, because a row may not exist.
  • A TreeMap from id to a Row record stands in for the table, because the test image has no database driver.
JavaScriptGitHub
// A stand-in for the database: one table of rows by id, with an id counter.
// The JavaScript standard library has no database driver.
class Table {
  constructor() {
    this.rows = new Map();
    this.nextId = 1;
  }
}

// The base class of Active Records. A subclass names its table and columns.
class Record {
  constructor(values, id = null) {
    this.id = id;
    for (const column of this.constructor.columns) this[column] = values[column];
  }

  static find(id) {
    const row = this.table.rows.get(id);
    return row ? new this(row, id) : null;
  }

  static all() {
    return [...this.table.rows.keys()].sort((a, b) => a - b).map((id) => this.find(id));
  }

  validate() {} // a subclass throws here when the object must not be saved

  save() {
    this.validate();
    const table = this.constructor.table;
    if (this.id === null) this.id = table.nextId++;
    const row = {};
    for (const column of this.constructor.columns) row[column] = this[column];
    table.rows.set(this.id, row);
  }

  delete() {
    this.constructor.table.rows.delete(this.id);
  }
}

// One row of the products table, with the domain logic of a product.
class Product extends Record {
  static table = new Table();
  static columns = ["name", "price", "stock"];

  validate() {
    if (this.stock < 0) throw new Error(`${this.name}: stock cannot be negative`);
  }

  needsRestock() {
    return this.stock < 5;
  }

  sell(quantity) {
    if (quantity > this.stock) throw new Error(`${this.name}: only ${this.stock} in stock`);
    this.stock -= quantity;
    return quantity * this.price;
  }

  toString() {
    return `${this.id} ${this.name} ${this.stock}`;
  }
}

for (const [name, price, stock] of [["pen", 120, 3], ["ink", 450, 40], ["pad", 300, 0]]) {
  new Product({ name, price, stock }).save();
}

const pen = Product.find(1);
console.log("sold 2 pens for " + pen.sell(2));
pen.save();
const restocked = [];
for (const product of Product.all()) {
  if (product.needsRestock()) {
    product.stock += 20;
    product.save();
    restocked.push(product.name);
  }
}
console.log("restocked: " + restocked.join(", "));
console.log("rows: " + Product.all().join(" | "));
const ink = Product.find(2);
ink.stock -= 45;
try {
  ink.save();
} catch (e) {
  console.log("not saved: " + e.message);
}
console.log("find(9): " + (Product.find(9) ?? "none"));
Output
sold 2 pens for 240
restocked: pen, pad
rows: 1 pen 21 | 2 ink 40 | 3 pad 20
not saved: ink: stock cannot be negative
find(9): none
  • Verdict: idiom. Static methods on the class are the finders, and this.constructor lets the base class reach the table and columns of the subclass.
  • The standard library has no database driver, so a Map of rows stands in for the table.
package main

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

// row is what the table stores for one product.
type row struct {
	name         string
	price, stock int
}

// products is a stand-in for the products table. The Go standard library
// has database/sql, but no driver for a real database.
var products = struct {
	rows   map[int]row
	nextID int
}{rows: map[int]row{}, nextID: 1}

// Product is an Active Record: one value per row, with the data access and
// the domain logic together.
type Product struct {
	ID           int // 0 means not saved yet
	Name         string
	Price, Stock int
}

// FindProduct and AllProducts are the finders.
func FindProduct(id int) (*Product, bool) {
	r, ok := products.rows[id]
	if !ok {
		return nil, false
	}
	return &Product{id, r.name, r.price, r.stock}, true
}

func AllProducts() []*Product {
	var ids []int
	for id := range products.rows {
		ids = append(ids, id)
	}
	sort.Ints(ids)
	var out []*Product
	for _, id := range ids {
		p, _ := FindProduct(id)
		out = append(out, p)
	}
	return out
}

func (p *Product) Validate() error {
	if p.Stock < 0 {
		return fmt.Errorf("%s: stock cannot be negative", p.Name)
	}
	return nil
}

func (p *Product) Save() error {
	if err := p.Validate(); err != nil {
		return err
	}
	if p.ID == 0 {
		p.ID = products.nextID
		products.nextID++
	}
	products.rows[p.ID] = row{p.Name, p.Price, p.Stock}
	return nil
}

func (p *Product) Delete() { delete(products.rows, p.ID) }

// The domain logic is on the same type.
func (p *Product) NeedsRestock() bool { return p.Stock < 5 }

func (p *Product) Sell(quantity int) (int, error) {
	if quantity > p.Stock {
		return 0, errors.New(p.Name + ": only " + fmt.Sprint(p.Stock) + " in stock")
	}
	p.Stock -= quantity
	return quantity * p.Price, nil
}

func (p *Product) String() string { return fmt.Sprintf("%d %s %d", p.ID, p.Name, p.Stock) }

func main() {
	for _, p := range []Product{{Name: "pen", Price: 120, Stock: 3}, {Name: "ink", Price: 450, Stock: 40}, {Name: "pad", Price: 300, Stock: 0}} {
		if err := p.Save(); err != nil {
			panic(err)
		}
	}

	pen, _ := FindProduct(1)
	total, _ := pen.Sell(2)
	fmt.Println("sold 2 pens for", total)
	pen.Save()
	var restocked []string
	for _, p := range AllProducts() {
		if p.NeedsRestock() {
			p.Stock += 20
			p.Save()
			restocked = append(restocked, p.Name)
		}
	}
	fmt.Println("restocked: " + strings.Join(restocked, ", "))
	var rows []string
	for _, p := range AllProducts() {
		rows = append(rows, p.String())
	}
	fmt.Println("rows: " + strings.Join(rows, " | "))
	ink, _ := FindProduct(2)
	ink.Stock -= 45
	if err := ink.Save(); err != nil {
		fmt.Println("not saved:", err)
	}
	if _, ok := FindProduct(9); !ok {
		fmt.Println("find(9): none")
	}
}
Output
sold 2 pens for 240
restocked: pen, pad
rows: 1 pen 21 | 2 ink 40 | 3 pad 20
not saved: ink: stock cannot be negative
find(9): none
  • Verdict: idiom. The finders are package functions, and Save returns an error, so a failed validation is a value that the caller checks.
  • A map in a package variable stands in for the table. AllProducts sorts the ids, because the iteration order of a Go map is not fixed.
RustGitHub
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::fmt;

// What the table stores for one product.
#[derive(Clone)]
struct Row {
    name: String,
    price: u32,
    stock: i32,
}

// A stand-in for the products table: rows by id, with an id counter.
// The Rust standard library has no database driver.
struct Table {
    rows: BTreeMap<u32, Row>,
    next_id: u32,
}

thread_local! {
    static PRODUCTS: RefCell<Table> = RefCell::new(Table { rows: BTreeMap::new(), next_id: 1 });
}

// An Active Record: one value per row, with the data access and the domain logic together.
struct Product {
    id: Option<u32>,
    name: String,
    price: u32,
    stock: i32,
}

impl Product {
    fn new(name: &str, price: u32, stock: i32) -> Self {
        Product { id: None, name: name.to_string(), price, stock }
    }

    // Data access: the finders are associated functions, and saving is a method.
    fn find(id: u32) -> Option<Product> {
        PRODUCTS.with_borrow(|t| t.rows.get(&id).map(|r| Product { id: Some(id), name: r.name.clone(), price: r.price, stock: r.stock }))
    }

    fn all() -> Vec<Product> {
        let ids: Vec<u32> = PRODUCTS.with_borrow(|t| t.rows.keys().copied().collect());
        ids.into_iter().filter_map(Product::find).collect()
    }

    fn validate(&self) -> Result<(), String> {
        if self.stock < 0 {
            return Err(format!("{}: stock cannot be negative", self.name));
        }
        Ok(())
    }

    fn save(&mut self) -> Result<(), String> {
        self.validate()?;
        let row = Row { name: self.name.clone(), price: self.price, stock: self.stock };
        PRODUCTS.with_borrow_mut(|t| {
            let id = *self.id.get_or_insert_with(|| {
                t.next_id += 1;
                t.next_id - 1
            });
            t.rows.insert(id, row);
        });
        Ok(())
    }

    #[allow(dead_code)]
    fn delete(&self) {
        if let Some(id) = self.id {
            PRODUCTS.with_borrow_mut(|t| t.rows.remove(&id));
        }
    }

    // The domain logic is on the same type.
    fn needs_restock(&self) -> bool {
        self.stock < 5
    }

    fn sell(&mut self, quantity: i32) -> Result<u32, String> {
        if quantity > self.stock {
            return Err(format!("{}: only {} in stock", self.name, self.stock));
        }
        self.stock -= quantity;
        Ok(quantity as u32 * self.price)
    }
}

impl fmt::Display for Product {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} {} {}", self.id.unwrap_or(0), self.name, self.stock)
    }
}

fn main() -> Result<(), String> {
    for (name, price, stock) in [("pen", 120, 3), ("ink", 450, 40), ("pad", 300, 0)] {
        Product::new(name, price, stock).save()?;
    }

    let mut pen = Product::find(1).ok_or("no pen")?;
    println!("sold 2 pens for {}", pen.sell(2)?);
    pen.save()?;
    let mut restocked = Vec::new();
    for mut product in Product::all() {
        if product.needs_restock() {
            product.stock += 20;
            product.save()?;
            restocked.push(product.name);
        }
    }
    println!("restocked: {}", restocked.join(", "));
    let rows: Vec<String> = Product::all().iter().map(|p| p.to_string()).collect();
    println!("rows: {}", rows.join(" | "));
    let mut ink = Product::find(2).ok_or("no ink")?;
    ink.stock -= 45;
    if let Err(e) = ink.save() {
        println!("not saved: {e}");
    }
    match Product::find(9) {
        Some(p) => println!("find(9): {p}"),
        None => println!("find(9): none"),
    }
    Ok(())
}
Output
sold 2 pens for 240
restocked: pen, pad
rows: 1 pen 21 | 2 ink 40 | 3 pad 20
not saved: ink: stock cannot be negative
find(9): none
  • Verdict: idiom. The finders are associated functions, and save returns Result<(), String>, so a failed validation is an error value.
  • A thread_local RefCell holds the stand-in table, so the records can reach a shared table without passing it to each call, as an Active Record reaches its connection.

Consequences

Benefits.

  • It is simple. Each table has one class, and each developer knows where the data access is.1 TypeORM's guide says that the Active Record approach "helps keep things simple which works well in smaller apps."4
  • The rules sit next to the data. sell and the stock check are methods of Product, so a reader finds the data and its rules in one class.
  • Frameworks support it well. A base class gives each model the finders, save and delete, so a model class can be a few lines long.34

Liabilities.

The rules in save do not cover every write. A rule that is checked in save protects only the writes that go through save. A bulk update is one SQL statement, and it makes no objects. The Rails guide lists methods such as update_all, update_column and insert_all, and states: "The following methods skip validations, and will save the object to the database regardless of its validity."5 Django says the same of the update() method of a query set: "It doesn’t run any save() methods on your models".6

This code runs but gives a wrong answer on purpose.

import sqlite3


class Product:
    db = sqlite3.connect(":memory:")

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

    def save(self):
        if self.stock < 0:  # the rule lives in save
            raise ValueError(f"{self.name}: stock cannot be negative")
        if self.id is None:
            self.id = self.db.execute("INSERT INTO products (name, stock) VALUES (?, ?)", (self.name, self.stock)).lastrowid
        else:
            self.db.execute("UPDATE products SET stock = ? WHERE id = ?", (self.stock, self.id))

    @classmethod
    def update_all(cls, change):
        # a fast bulk update: one statement, no objects, so save() never runs
        cls.db.execute("UPDATE products SET stock = stock + ?", (change,))


Product.db.execute("CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, stock INTEGER)")
Product("pen", 3).save()
Product("ink", 40).save()
Product.update_all(-5)  # bug: the rule in save() is skipped
print(Product.db.execute("SELECT name, stock FROM products").fetchall())
Output
[('pen', -2), ('ink', 35)]

The stock of the pen is now negative. The fixes are a database constraint, for example CHECK (stock >= 0), which holds for each write from any code, or a loop that loads each object and calls save, which is slower but runs the rule. Django recommends the loop when each save must run.6

The objects follow the tables. The fields of the class are the columns, so the class has the shape of the schema. A domain model with inheritance, collections and objects that do not match tables one to one is hard to build in this way.7

Tests need the database. The domain logic and the database access are in one object, so a test of a rule must load and save rows. Fowler's catalogue names this cost of database code in domain objects: "tests are slower to run because of all the database access."8

When not to use it

When the domain logic is complex. When the object model and the schema differ, use a Data Mapper, which keeps the domain objects free of database code.7 TypeORM's guide says that the Data Mapper approach "helps with maintainability, which is more effective in larger apps."4

When the code has no domain logic. Objects that only hold columns and save them are a Row Data Gateway. A Table Data Gateway or plain queries are simpler for reports and batch work on many rows.

When the important rules must hold for every write. Put them in the database as constraints, and keep the checks in the record as a second line, because bulk writes skip the record.5

Row Data Gateway. The same object without the domain logic. A row gateway that gets business methods becomes an Active Record.8 See Row Data Gateway.

Data Mapper. The domain objects know nothing of the database, and a separate mapper loads and saves them. With Data Mapper "the in-memory objects needn't know even that there's a database present".7 See Data Mapper.

Table Data Gateway. One object for the whole table, which returns plain rows. See Table Data Gateway.

Repository. A collection-like interface for domain objects. TypeORM offers both forms: an entity that extends BaseEntity is an Active Record, and its Data Mapper form uses repositories.4 See Repository pattern.

Known uses

  • Ruby on Rails names its ORM Active Record. Its guide defines the pattern with Fowler's words, and its models get save, the finders and validations from the base class.3 In persistence.rb at 8.1.4.1, create_or_update calls _create_record for a new record and _update_record for a stored one.9
  • Django models follow the pattern. Its design philosophy says: "Models should encapsulate every aspect of an “object,” following Martin Fowler’s Active Record design pattern."10 In base.py at 5.2, Model._save_table tries an UPDATE of the row first when the object has a primary key, and runs an INSERT when the update changed no row.11
  • TypeORM, an ORM for TypeScript, supports Active Record entities: "Using the Active Record approach, you define all your query methods inside the model itself, and you save, remove, and load objects using model methods."4

References

  1. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Active Record, pattern summary; the book's Chapter 10
  2. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 10, Data Source Architectural Patterns, Active Record
  3. Rails Guides, Active Record Basics, 1.1 The Active Record Pattern; 5 Validations
  4. TypeORM documentation, Active Record vs Data Mapper, What is the Active Record pattern; Which one should I choose
  5. Rails Guides, Active Record Validations, Skipping Validations
  6. Django documentation, Making queries, Updating multiple objects at once
  7. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Data Mapper, pattern summary
  8. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Row Data Gateway, pattern summary
  9. Rails 8.1.4.1 source, activerecord/lib/active_record/persistence.rb, create_or_update, lines 923 to 928
  10. Django documentation, Design philosophies, Models, Include all relevant domain logic
  11. Django 5.2 source, django/db/models/base.py, Model._save_table, lines 1081 to 1175

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