Programming Search⌘K

Patterncore

Data Mapper

Also called data mapper pattern.

A Data Mapper is a layer that moves data between domain objects and a database. The objects know nothing of the database, and the database knows nothing of the objects.

Family
architectural
Intent
A layer of mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself.

Intent

"A layer of mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself."1 The domain objects hold the data and the business rules. A separate mapper reads rows into objects and writes objects back into rows.

Problem

A program has a rich domain model, with lists, value objects and inheritance. The database has tables, columns and foreign keys. The two do not match. Fowler's catalogue says: "Many parts of an object, such as collections and inheritance, aren't present in relational databases."1 When each side is designed for its own job, the object schema and the relational schema differ.

Something must still move the data between the two. If the domain objects do this work, as an Active Record does, they must know the tables and the SQL. Then "changes in one tend to ripple to the other."1 A change of a column changes a domain class, and a test of a business rule needs a database.

Solution

Put all the database code in mapper classes, one for each kind of domain object. The mapper has methods such as find, insert, update and delete. It reads rows, makes domain objects and fills their fields, and it turns the fields of an object back into rows. The domain classes have no SQL and no reference to the mapper. "With Data Mapper the in-memory objects needn't know even that there's a database present".12

  domain layer                          data source layer
  Product                               ProductMapper
      name, price, stock, tags              find(id)    SELECT products + product_tags
      sell(n)                               insert(p)   INSERT into both tables
      (no SQL, no mapper)                   update(p)   UPDATE products, rewrite tags
            ^                               delete(p)
            |  makes and reads objects          |
            +-------------------------------+   v
                                            products (id, title, price_cents, qty)
                                            product_tags (product_id, tag)

The participants are the domain objects, the mapper, which knows both the objects and the schema, and the callers, which ask the mapper for objects and give changed objects back to it.

The following program uses SQLite. The field names of Product differ from the column names, and its tags list is stored as rows of a second table. Only ProductMapper knows this.

import sqlite3
from dataclasses import dataclass, field


@dataclass
class Product:
    """A domain object. It has no SQL, no connection and no idea that a database exists."""

    name: str
    price: int
    stock: int
    tags: list[str] = field(default_factory=list)
    id: int | None = None

    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


class ProductMapper:
    """Moves products between objects and two tables. The tags list becomes rows of product_tags."""

    def __init__(self, db: sqlite3.Connection) -> None:
        self._db = db

    def find(self, product_id: int) -> Product | None:
        row = self._db.execute("SELECT id, title, price_cents, qty FROM products WHERE id = ?", (product_id,)).fetchone()
        if row is None:
            return None
        tags = [t for (t,) in self._db.execute("SELECT tag FROM product_tags WHERE product_id = ? ORDER BY tag", (product_id,))]
        return Product(name=row[1], price=row[2], stock=row[3], tags=tags, id=row[0])

    def insert(self, p: Product) -> None:
        p.id = self._db.execute("INSERT INTO products (title, price_cents, qty) VALUES (?, ?, ?)", (p.name, p.price, p.stock)).lastrowid
        self._write_tags(p)

    def update(self, p: Product) -> None:
        self._db.execute("UPDATE products SET title = ?, price_cents = ?, qty = ? WHERE id = ?", (p.name, p.price, p.stock, p.id))
        self._db.execute("DELETE FROM product_tags WHERE product_id = ?", (p.id,))
        self._write_tags(p)

    def _write_tags(self, p: Product) -> None:
        self._db.executemany("INSERT INTO product_tags (product_id, tag) VALUES (?, ?)", [(p.id, t) for t in p.tags])


db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE products (id INTEGER PRIMARY KEY, title TEXT NOT NULL, price_cents INTEGER NOT NULL, qty INTEGER NOT NULL);
CREATE TABLE product_tags (product_id INTEGER REFERENCES products(id), tag TEXT NOT NULL);
""")
mapper = ProductMapper(db)
mapper.insert(Product("pen", 120, 3, ["office"]))

pen = mapper.find(1)
print("sold:", pen.sell(2))          # domain logic, no database involved
pen.tags.append("sale")
mapper.update(pen)                   # the mapper writes both tables
print("object:", mapper.find(1))
print("products:", db.execute("SELECT * FROM products").fetchall())
print("product_tags:", db.execute("SELECT * FROM product_tags ORDER BY tag").fetchall())
Output
sold: 240
object: Product(name='pen', price=120, stock=1, tags=['office', 'sale'], id=1)
products: [(1, 'pen', 120, 1)]
product_tags: [(1, 'office'), (1, 'sale')]

Product.sell can be tested with no database at all. The object has a list, and the database has a second table, and neither side had to change its shape for the other.

Example

Each example file has a plain Product class with the domain method sell, and a ProductMapper with find, insert, update and delete. The stored rows have other names than the fields (title, price_cents, qty), and the tags are rows of a second table. The Python file uses SQLite. The JavaScript, Java, Go and Rust files keep the two tables in memory, because the standard libraries of these languages have no database driver. The domain class in each file has no reference to the tables.

PythonGitHub
import sqlite3
from dataclasses import dataclass, field


@dataclass
class Product:
    """A domain object. It has no SQL and no connection."""

    name: str
    price: int
    stock: int
    tags: list[str] = field(default_factory=list)
    id: int | None = None

    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.price} {self.stock} [{', '.join(self.tags)}]"


class ProductMapper:
    """Moves products between objects and two tables: products, and product_tags for the tags list."""

    def __init__(self, db: sqlite3.Connection) -> None:
        self._db = db

    def find(self, product_id: int) -> Product | None:
        row = self._db.execute("SELECT id, title, price_cents, qty FROM products WHERE id = ?", (product_id,)).fetchone()
        if row is None:
            return None
        tags = [t for (t,) in self._db.execute("SELECT tag FROM product_tags WHERE product_id = ? ORDER BY tag", (product_id,))]
        return Product(name=row[1], price=row[2], stock=row[3], tags=tags, id=row[0])

    def insert(self, p: Product) -> None:
        p.id = self._db.execute("INSERT INTO products (title, price_cents, qty) VALUES (?, ?, ?)", (p.name, p.price, p.stock)).lastrowid
        self._write_tags(p)

    def update(self, p: Product) -> None:
        self._db.execute("UPDATE products SET title = ?, price_cents = ?, qty = ? WHERE id = ?", (p.name, p.price, p.stock, p.id))
        self._db.execute("DELETE FROM product_tags WHERE product_id = ?", (p.id,))
        self._write_tags(p)

    def delete(self, p: Product) -> None:
        self._db.execute("DELETE FROM product_tags WHERE product_id = ?", (p.id,))
        self._db.execute("DELETE FROM products WHERE id = ?", (p.id,))

    def _write_tags(self, p: Product) -> None:
        self._db.executemany("INSERT INTO product_tags (product_id, tag) VALUES (?, ?)", [(p.id, t) for t in p.tags])


db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE products (id INTEGER PRIMARY KEY, title TEXT NOT NULL, price_cents INTEGER NOT NULL, qty INTEGER NOT NULL);
CREATE TABLE product_tags (product_id INTEGER NOT NULL REFERENCES products(id), tag TEXT NOT NULL);
""")
mapper = ProductMapper(db)
mapper.insert(Product("pen", 120, 3, ["office"]))
ink = Product("ink", 450, 40, ["office"])
mapper.insert(ink)

pen = mapper.find(1)
print("sold:", pen.sell(2))
pen.tags.append("sale")
mapper.update(pen)
print("object:", mapper.find(1))
print("products:", " | ".join(" ".join(map(str, r)) for r in db.execute("SELECT * FROM products ORDER BY id")))
print("product_tags:", " | ".join(f"{i} {t}" for i, t in db.execute("SELECT * FROM product_tags ORDER BY product_id, tag")))
mapper.delete(ink)
products, tags = (db.execute(f"SELECT count(*) FROM {t}").fetchone()[0] for t in ("products", "product_tags"))
print(f"after delete: {products} product, {tags} tags")
print("find(2):", mapper.find(2) or "none")
Output
sold: 240
object: 1 pen 120 1 [office, sale]
products: 1 pen 120 1 | 2 ink 450 40
product_tags: 1 office | 1 sale | 2 office
after delete: 1 product, 2 tags
find(2): none
  • Verdict: idiom. Product is a plain dataclass with a domain method, and ProductMapper holds all the SQL for the two tables.
  • The column names (title, price_cents, qty) differ from the field names, and the tags list is stored as rows of a second table. Only the mapper knows this.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.TreeMap;

public class Main {
    // A domain object. It has no storage code and no idea that a database exists.
    static final class Product {
        Integer id;
        final String name;
        final int price;
        int stock;
        final List<String> tags;

        Product(String name, int price, int stock, List<String> tags) {
            this.name = name;
            this.price = price;
            this.stock = stock;
            this.tags = new ArrayList<>(tags);
        }

        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 + " " + price + " " + stock + " [" + String.join(", ", tags) + "]";
        }
    }

    // A stand-in for the database, because the test image has no database driver.
    // Two tables with their own column names: products and product_tags.
    record ProductRow(String title, int priceCents, int qty) {}
    record TagRow(int productId, String tag) {}

    static final class Database {
        final TreeMap<Integer, ProductRow> products = new TreeMap<>();
        final List<TagRow> productTags = new ArrayList<>();
        int nextId = 1;
    }

    // The mapper moves products between objects and the two tables.
    static final class ProductMapper {
        private final Database db;

        ProductMapper(Database db) {
            this.db = db;
        }

        Optional<Product> find(int id) {
            ProductRow row = db.products.get(id);
            if (row == null) return Optional.empty();
            List<String> tags = db.productTags.stream().filter(t -> t.productId() == id).map(TagRow::tag).sorted().toList();
            Product p = new Product(row.title(), row.priceCents(), row.qty(), tags);
            p.id = id;
            return Optional.of(p);
        }

        void insert(Product p) {
            p.id = db.nextId++;
            update(p);
        }

        void update(Product p) {
            db.products.put(p.id, new ProductRow(p.name, p.price, p.stock));
            deleteTags(p.id);
            for (String tag : p.tags) db.productTags.add(new TagRow(p.id, tag));
        }

        void delete(Product p) {
            deleteTags(p.id);
            db.products.remove(p.id);
        }

        private void deleteTags(int id) {
            db.productTags.removeIf(t -> t.productId() == id);
        }
    }

    public static void main(String[] args) {
        Database db = new Database();
        ProductMapper mapper = new ProductMapper(db);
        mapper.insert(new Product("pen", 120, 3, List.of("office")));
        Product ink = new Product("ink", 450, 40, List.of("office"));
        mapper.insert(ink);

        Product pen = mapper.find(1).orElseThrow();
        System.out.println("sold: " + pen.sell(2));
        pen.tags.add("sale");
        mapper.update(pen);
        System.out.println("object: " + mapper.find(1).orElseThrow());
        List<String> rows = new ArrayList<>();
        db.products.forEach((id, r) -> rows.add(id + " " + r.title() + " " + r.priceCents() + " " + r.qty()));
        System.out.println("products: " + String.join(" | ", rows));
        List<String> tagRows = db.productTags.stream().map(t -> t.productId() + " " + t.tag()).sorted().toList();
        System.out.println("product_tags: " + String.join(" | ", tagRows));
        mapper.delete(ink);
        System.out.println("after delete: " + db.products.size() + " product, " + db.productTags.size() + " tags");
        System.out.println("find(2): " + mapper.find(2).map(Product::toString).orElse("none"));
    }
}
Output
sold: 240
object: 1 pen 120 1 [office, sale]
products: 1 pen 120 1 | 2 ink 450 40
product_tags: 1 office | 1 sale | 2 office
after delete: 1 product, 2 tags
find(2): none
  • Verdict: idiom. Product has no import of any storage type, and find returns an Optional, because a row may not exist.
  • Two records, ProductRow and TagRow, are the stored rows of the stand-in tables, because the test image has no database driver.
JavaScriptGitHub
// A domain object. It has no storage code and no idea that a database exists.
class Product {
  constructor(name, price, stock, tags = [], id = null) {
    Object.assign(this, { name, price, stock, tags, id });
  }

  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.price} ${this.stock} [${this.tags.join(", ")}]`;
  }
}

// A stand-in for the database, because the standard library has no driver.
// Two tables with their own column names: products and product_tags.
const db = { products: new Map(), productTags: [], nextId: 1 };

// The mapper moves products between objects and the two tables.
class ProductMapper {
  constructor(db) {
    this.db = db;
  }

  find(id) {
    const row = this.db.products.get(id);
    if (!row) return null;
    const tags = this.db.productTags.filter((t) => t.productId === id).map((t) => t.tag).sort();
    return new Product(row.title, row.priceCents, row.qty, tags, id);
  }

  insert(p) {
    p.id = this.db.nextId++;
    this.update(p);
  }

  update(p) {
    this.db.products.set(p.id, { title: p.name, priceCents: p.price, qty: p.stock });
    this.deleteTags(p.id);
    for (const tag of p.tags) this.db.productTags.push({ productId: p.id, tag });
  }

  delete(p) {
    this.deleteTags(p.id);
    this.db.products.delete(p.id);
  }

  deleteTags(id) {
    this.db.productTags = this.db.productTags.filter((t) => t.productId !== id);
  }
}

const mapper = new ProductMapper(db);
mapper.insert(new Product("pen", 120, 3, ["office"]));
const ink = new Product("ink", 450, 40, ["office"]);
mapper.insert(ink);

const pen = mapper.find(1);
console.log("sold: " + pen.sell(2));
pen.tags.push("sale");
mapper.update(pen);
console.log("object: " + mapper.find(1));
const rows = [...db.products].sort((a, b) => a[0] - b[0]).map(([id, r]) => `${id} ${r.title} ${r.priceCents} ${r.qty}`);
console.log("products: " + rows.join(" | "));
const tagRows = db.productTags.map((t) => `${t.productId} ${t.tag}`).sort();
console.log("product_tags: " + tagRows.join(" | "));
mapper.delete(ink);
console.log(`after delete: ${db.products.size} product, ${db.productTags.length} tags`);
console.log("find(2): " + (mapper.find(2) ?? "none"));
Output
sold: 240
object: 1 pen 120 1 [office, sale]
products: 1 pen 120 1 | 2 ink 450 40
product_tags: 1 office | 1 sale | 2 office
after delete: 1 product, 2 tags
find(2): none
  • Verdict: idiom. Product is a plain class, and ProductMapper copies its fields to and from the stored rows.
  • The standard library has no database driver, so an object with a Map and an array stands in for the two tables.
package main

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

// Product is a domain object. It has no storage code and no idea that a database exists.
type Product struct {
	ID           int // 0 means not stored yet
	Name         string
	Price, Stock int
	Tags         []string
}

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 %d [%s]", p.ID, p.Name, p.Price, p.Stock, strings.Join(p.Tags, ", "))
}

// A stand-in for the database. The Go standard library has database/sql,
// but no driver for a real database. The two tables have their own column names.
type productRow struct {
	title           string
	priceCents, qty int
}

type tagRow struct {
	productID int
	tag       string
}

type Database struct {
	products    map[int]productRow
	productTags []tagRow
	nextID      int
}

// ProductMapper moves products between objects and the two tables.
type ProductMapper struct{ db *Database }

func (m ProductMapper) Find(id int) (*Product, bool) {
	row, ok := m.db.products[id]
	if !ok {
		return nil, false
	}
	var tags []string
	for _, t := range m.db.productTags {
		if t.productID == id {
			tags = append(tags, t.tag)
		}
	}
	sort.Strings(tags)
	return &Product{id, row.title, row.priceCents, row.qty, tags}, true
}

func (m ProductMapper) Insert(p *Product) {
	p.ID = m.db.nextID
	m.db.nextID++
	m.Update(p)
}

func (m ProductMapper) Update(p *Product) {
	m.db.products[p.ID] = productRow{p.Name, p.Price, p.Stock}
	m.deleteTags(p.ID)
	for _, tag := range p.Tags {
		m.db.productTags = append(m.db.productTags, tagRow{p.ID, tag})
	}
}

func (m ProductMapper) Delete(p *Product) {
	m.deleteTags(p.ID)
	delete(m.db.products, p.ID)
}

func (m ProductMapper) deleteTags(id int) {
	m.db.productTags = slices.DeleteFunc(m.db.productTags, func(t tagRow) bool { return t.productID == id })
}

func main() {
	db := &Database{products: map[int]productRow{}, nextID: 1}
	mapper := ProductMapper{db}
	mapper.Insert(&Product{Name: "pen", Price: 120, Stock: 3, Tags: []string{"office"}})
	ink := &Product{Name: "ink", Price: 450, Stock: 40, Tags: []string{"office"}}
	mapper.Insert(ink)

	pen, _ := mapper.Find(1)
	total, _ := pen.Sell(2)
	fmt.Println("sold:", total)
	pen.Tags = append(pen.Tags, "sale")
	mapper.Update(pen)
	stored, _ := mapper.Find(1)
	fmt.Println("object:", stored)
	var ids []int
	for id := range db.products {
		ids = append(ids, id)
	}
	sort.Ints(ids)
	var rows []string
	for _, id := range ids {
		r := db.products[id]
		rows = append(rows, fmt.Sprintf("%d %s %d %d", id, r.title, r.priceCents, r.qty))
	}
	fmt.Println("products: " + strings.Join(rows, " | "))
	var tagRows []string
	for _, t := range db.productTags {
		tagRows = append(tagRows, fmt.Sprintf("%d %s", t.productID, t.tag))
	}
	sort.Strings(tagRows)
	fmt.Println("product_tags: " + strings.Join(tagRows, " | "))
	mapper.Delete(ink)
	fmt.Printf("after delete: %d product, %d tags\n", len(db.products), len(db.productTags))
	if _, ok := mapper.Find(2); !ok {
		fmt.Println("find(2): none")
	}
}
Output
sold: 240
object: 1 pen 120 1 [office, sale]
products: 1 pen 120 1 | 2 ink 450 40
product_tags: 1 office | 1 sale | 2 office
after delete: 1 product, 2 tags
find(2): none
  • Verdict: idiom. Product is a plain struct, and ProductMapper is the only type that knows the row types.
  • slices.DeleteFunc removes the old tag rows before Update writes the new ones. The ids are sorted for printing, because the iteration order of a Go map is not fixed.
RustGitHub
use std::collections::BTreeMap;
use std::fmt;

// A domain object. It has no storage code and no idea that a database exists.
struct Product {
    id: Option<u32>,
    name: String,
    price: u32,
    stock: u32,
    tags: Vec<String>,
}

impl Product {
    fn new(name: &str, price: u32, stock: u32, tags: &[&str]) -> Self {
        Product { id: None, name: name.into(), price, stock, tags: tags.iter().map(|t| t.to_string()).collect() }
    }

    fn sell(&mut self, quantity: u32) -> Result<u32, String> {
        if quantity > self.stock {
            return Err(format!("{}: only {} in stock", self.name, self.stock));
        }
        self.stock -= quantity;
        Ok(quantity * 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.price, self.stock, self.tags.join(", "))
    }
}

// A stand-in for the database, because the standard library has no driver.
// The two tables have their own column names.
struct ProductRow {
    title: String,
    price_cents: u32,
    qty: u32,
}

struct TagRow {
    product_id: u32,
    tag: String,
}

#[derive(Default)]
struct Database {
    products: BTreeMap<u32, ProductRow>,
    product_tags: Vec<TagRow>,
    next_id: u32,
}

// The mapper moves products between objects and the two tables.
struct ProductMapper<'a> {
    db: &'a mut Database,
}

impl ProductMapper<'_> {
    fn find(&self, id: u32) -> Option<Product> {
        let row = self.db.products.get(&id)?;
        let mut tags: Vec<String> = self.db.product_tags.iter().filter(|t| t.product_id == id).map(|t| t.tag.clone()).collect();
        tags.sort();
        Some(Product { id: Some(id), name: row.title.clone(), price: row.price_cents, stock: row.qty, tags })
    }

    fn insert(&mut self, p: &mut Product) {
        self.db.next_id += 1;
        p.id = Some(self.db.next_id);
        self.update(p);
    }

    fn update(&mut self, p: &Product) {
        let id = p.id.expect("update needs a stored product");
        self.db.products.insert(id, ProductRow { title: p.name.clone(), price_cents: p.price, qty: p.stock });
        self.delete_tags(id);
        for tag in &p.tags {
            self.db.product_tags.push(TagRow { product_id: id, tag: tag.clone() });
        }
    }

    fn delete(&mut self, p: &Product) {
        if let Some(id) = p.id {
            self.delete_tags(id);
            self.db.products.remove(&id);
        }
    }

    fn delete_tags(&mut self, id: u32) {
        self.db.product_tags.retain(|t| t.product_id != id);
    }
}

fn main() -> Result<(), String> {
    let mut db = Database::default();
    let mut mapper = ProductMapper { db: &mut db };
    mapper.insert(&mut Product::new("pen", 120, 3, &["office"]));
    let mut ink = Product::new("ink", 450, 40, &["office"]);
    mapper.insert(&mut ink);

    let mut pen = mapper.find(1).ok_or("no pen")?;
    println!("sold: {}", pen.sell(2)?);
    pen.tags.push("sale".into());
    mapper.update(&pen);
    println!("object: {}", mapper.find(1).ok_or("no pen")?);
    let rows: Vec<String> = mapper.db.products.iter().map(|(id, r)| format!("{id} {} {} {}", r.title, r.price_cents, r.qty)).collect();
    println!("products: {}", rows.join(" | "));
    let mut tag_rows: Vec<String> = mapper.db.product_tags.iter().map(|t| format!("{} {}", t.product_id, t.tag)).collect();
    tag_rows.sort();
    println!("product_tags: {}", tag_rows.join(" | "));
    mapper.delete(&ink);
    println!("after delete: {} product, {} tags", mapper.db.products.len(), mapper.db.product_tags.len());
    match mapper.find(2) {
        Some(p) => println!("find(2): {p}"),
        None => println!("find(2): none"),
    }
    Ok(())
}
Output
sold: 240
object: 1 pen 120 1 [office, sale]
products: 1 pen 120 1 | 2 ink 450 40
product_tags: 1 office | 1 sale | 2 office
after delete: 1 product, 2 tags
find(2): none
  • Verdict: idiom. Product has no reference to the database, and ProductMapper borrows the database mutably for its lifetime.
  • find uses ? on the Option of the row lookup, so a missing row gives None.

Consequences

Benefits.

  • The domain model and the schema can differ. Each side uses its own structures: lists and value objects in memory, tables and keys in the database. Only the mapper changes when one side changes.1
  • The domain logic is testable without a database. The domain objects need no SQL interface code and no knowledge of the schema.1
  • It scales to large models. TypeORM's guide says that the Data Mapper approach "helps with maintainability, which is more effective in larger apps."3

Liabilities.

A change in memory is not saved by itself. The domain object has no save method, so a changed object reaches the database only when some code gives it to the mapper. A function that loads an object, changes it and returns has lost the change.

This code runs but gives a wrong answer on purpose.

import sqlite3
from dataclasses import dataclass


@dataclass
class Product:
    name: str
    stock: int
    id: int

    def sell(self, quantity):
        self.stock -= quantity


class ProductMapper:
    def __init__(self, db):
        self.db = db

    def find(self, id):
        return Product(*self.db.execute("SELECT name, stock, id FROM products WHERE id = ?", (id,)).fetchone())

    def update(self, p):
        self.db.execute("UPDATE products SET name = ?, stock = ? WHERE id = ?", (p.name, p.stock, p.id))


def checkout(mapper, product_id, quantity):
    product = mapper.find(product_id)
    product.sell(quantity)  # bug: the change stays in memory; nothing calls mapper.update
    return product


db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, stock INTEGER)")
db.execute("INSERT INTO products VALUES (1, 'pen', 3)")
mapper = ProductMapper(db)
print("in memory:", checkout(mapper, 1, 2).stock)
print("in the table:", mapper.find(1).stock)
Output
in memory: 1
in the table: 3

The fix is a call of mapper.update, or a Unit of Work, which "Maintains a list of objects affected by a business transaction and coordinates the writing out of changes".4 SQLAlchemy uses one. Its Session records each change of an attribute and writes the pending changes before the next query or the commit: "This is known as the unit of work pattern."5

More code. Each domain class has a mapper, and the mapper repeats the field list in its SQL. ORMs remove most of this code with mapping metadata, but then the mapping is one more thing to learn. TypeORM's guide puts Active Record on the other side: it "helps keep things simple which works well in smaller apps."3

The mapper must reach private state. The mapper sets and reads the fields of the domain objects, so the domain classes must expose their fields, or the mapper uses reflection, as ORMs do.

When not to use it

When the objects match the tables. If each class is one table with the same columns, and the rules are simple, Active Record is less code. Fowler's catalogue describes Active Record as "the most obvious approach".6

When there is little domain logic. A program that mostly reads and writes rows, for example a report or an admin screen, gains little from a separate domain model. A Table Data Gateway or plain queries are enough.

Active Record. The domain object holds its own data access. See Active Record.

Row Data Gateway and Table Data Gateway. Gateways that hold the SQL for one row or one table and return plain data, with no domain model. See Row Data Gateway and Table Data Gateway.

Repository. A collection-like interface over the mappers, which the domain code uses to get and add objects. TypeORM says that with Data Mapper "you define all your query methods in separate classes called "repositories"".3 See Repository pattern.

Unit of Work and Identity Map. Mappers are usually used with a Unit of Work, which tracks changed objects and writes them at the end of a business transaction,4 and with an Identity Map, which keeps one object for each row. The SQLAlchemy Session holds its objects "inside a structure called the identity map".5

Metadata mapping. An ORM describes the mapping as data, for example a table object and a class, and a generic mapper reads that data. SQLAlchemy says that "the ORM considers the user-defined class, the associated table metadata, and the mapping of the two to be entirely separate."7

Known uses

  • SQLAlchemy, the Python ORM, can map any plain class to a table. Its imperative mapping "originates from the very first releases of SQLAlchemy in 2006".8 In decl_api.py at 2.0.57, registry.map_imperatively takes a class and a table and builds a Mapper for them. The class itself "is not scanned for any mapping information".9
  • Doctrine ORM, for PHP: "It uses the Data Mapper pattern at the heart, aiming for a complete separation of your domain/business logic from the persistence in a relational database management system."10 An entity "can be any regular PHP class" within a few restrictions.11
  • TypeORM supports both forms. In its Data Mapper form, "your entities are very dumb - they just define their properties and may have some "dummy" methods."3

References

  1. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Data Mapper, pattern summary; the book's Chapter 10
  2. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 10, Data Source Architectural Patterns, Data Mapper
  3. TypeORM documentation, Active Record vs Data Mapper, What is the Data Mapper pattern; Which one should I choose
  4. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Unit of Work, pattern summary
  5. SQLAlchemy documentation, Session Basics, What does the Session do
  6. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Active Record, pattern summary
  7. SQLAlchemy, Key Features of SQLAlchemy, Unit Of Work; Separate mapping and class design
  8. SQLAlchemy 2.0 documentation, ORM Mapped Class Overview, Imperative Mapping
  9. SQLAlchemy 2.0.57 source, lib/sqlalchemy/orm/decl_api.py, registry.map_imperatively, lines 1839 to 1895
  10. Doctrine ORM 3.7 documentation, Getting Started with Doctrine, What is Doctrine?
  11. Doctrine ORM 3.7 documentation, Architecture, Terminology, Entities

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