Patterncore
Row Data Gateway
Also called row gateway.
A Row Data Gateway is an object for one row of a table. It has one field for each column and methods to insert, update and delete its row, and it has no business logic.
- Family
- architectural
- Intent
- An object that acts as a gateway to a single record in a data source. There is one instance per row.
- Also called
- Row Gateway
Intent
"An object that acts as a gateway to a single record in a data source. There is one instance per row."1 The object looks like the row: it has one field for each column. It also knows how to write itself back to the table.
Problem
A program works with one product at a time: it reads the product, changes the stock, and saves it. With a Table Data Gateway, the program passes ids and column values to methods of one object for the whole table. The code reads like a list of SQL calls with the SQL removed. The program would be clearer if a product were an object with fields, and if a changed product could save itself.
The forces are these. The program wants the data of a row in the normal form of the language: fields that it reads and writes. The database code should be in one place and not in the business rules. Fowler's catalogue names the cost of the other way, where database code sits inside objects that also have business logic: the objects become more complex, and tests become slower, because the objects need a database.1 So the row object holds the data and the database access, and nothing else.
Solution
Make one class whose fields are the columns of the table. Give it the methods insert, update and delete, each with the SQL for one row. Put the finders, which read rows and make one gateway object for each row, in a separate finder class or in static methods. The business logic stays outside, in transaction scripts that read and set the fields.12
application code (transaction scripts)
for p in finder.find_low_stock(5): p.stock += 20; p.update()
| |
v v
ProductFinder ProductRow (one object per row)
find(id) id, name, price, stock
find_low_stock(n) insert() INSERT ...
makes ProductRow objects update() UPDATE ... WHERE id = ?
| delete() DELETE ... WHERE id = ?
v |
products table <---------------------+
The participants are the row gateway, with fields and the write methods, the finder, which holds the read queries and creates gateways, and the callers. A row gateway "gives you objects that look exactly like the record in your record structure but can be accessed with the regular mechanisms of your programming language".1
The following program uses SQLite. ProductRow is the gateway, ProductFinder holds the queries that read rows, and restock is the business rule.
import sqlite3
class ProductRow:
"""A gateway to one row of the products table. It has the columns as fields, and no business logic."""
def __init__(self, db: sqlite3.Connection, name: str, price: int, stock: int, id: int | None = None) -> None:
self._db = db
self.id, self.name, self.price, self.stock = id, name, price, stock
def insert(self) -> None:
cur = self._db.execute("INSERT INTO products (name, price, stock) VALUES (?, ?, ?)", (self.name, self.price, self.stock))
self.id = cur.lastrowid
def update(self) -> None:
self._db.execute("UPDATE products SET name = ?, price = ?, stock = ? WHERE id = ?", (self.name, self.price, self.stock, self.id))
def delete(self) -> None:
self._db.execute("DELETE FROM products WHERE id = ?", (self.id,))
class ProductFinder:
"""The finders are static in spirit: they make one ProductRow for each row that they read."""
def __init__(self, db: sqlite3.Connection) -> None:
self._db = db
def _load(self, row: tuple) -> ProductRow:
id, name, price, stock = row
return ProductRow(self._db, name, price, stock, id)
def find(self, product_id: int) -> ProductRow | None:
row = self._db.execute("SELECT id, name, price, stock FROM products WHERE id = ?", (product_id,)).fetchone()
return self._load(row) if row else None
def find_low_stock(self, limit: int) -> list[ProductRow]:
rows = self._db.execute("SELECT id, name, price, stock FROM products WHERE stock < ? ORDER BY id", (limit,))
return [self._load(row) for row in rows]
def restock(finder: ProductFinder, limit: int, amount: int) -> list[str]:
"""A transaction script. It changes the fields of each row object and tells the row to save itself."""
done = []
for product in finder.find_low_stock(limit):
before = product.stock
product.stock += amount
product.update()
done.append(f"{product.name} {before} -> {product.stock}")
return done
db = sqlite3.connect(":memory:")
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)]:
ProductRow(db, name, price, stock).insert()
finder = ProductFinder(db)
with db:
print("restocked:", "; ".join(restock(finder, limit=5, amount=20)))
finder.find(2).delete()
print("rows:", db.execute("SELECT * FROM products ORDER BY id").fetchall())
print("find(9):", finder.find(9))
restocked: pen 3 -> 23; pad 0 -> 20
rows: [(1, 'pen', 120, 23), (3, 'pad', 300, 20)]
find(9): None
The rule changes a field and calls update. It does not know the SQL or the column list.
Example
Each example file has a ProductRow gateway with insert, update and delete, a ProductFinder with find, findAll and findLowStock, and the transaction script restock. The Python file 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. The gateway copies its fields into the table on update, so a changed field reaches the table only through that call, as with a database.
import sqlite3
class ProductRow:
"""A gateway to one row: the columns are fields, and the row saves itself."""
def __init__(self, db: sqlite3.Connection, name: str, price: int, stock: int, id: int | None = None) -> None:
self._db = db
self.id, self.name, self.price, self.stock = id, name, price, stock
def insert(self) -> int:
self.id = self._db.execute("INSERT INTO products (name, price, stock) VALUES (?, ?, ?)", (self.name, self.price, self.stock)).lastrowid
return self.id
def update(self) -> None:
self._db.execute("UPDATE products SET name = ?, price = ?, stock = ? WHERE id = ?", (self.name, self.price, self.stock, self.id))
def delete(self) -> None:
self._db.execute("DELETE FROM products WHERE id = ?", (self.id,))
def __str__(self) -> str:
return f"{self.id} {self.name} {self.price} {self.stock}"
class ProductFinder:
"""Reads rows and makes one ProductRow for each of them."""
COLUMNS = "SELECT id, name, price, stock FROM products"
def __init__(self, db: sqlite3.Connection) -> None:
self._db = db
def _load(self, row: tuple) -> ProductRow:
id, name, price, stock = row
return ProductRow(self._db, name, price, stock, id)
def find(self, product_id: int) -> ProductRow | None:
row = self._db.execute(self.COLUMNS + " WHERE id = ?", (product_id,)).fetchone()
return self._load(row) if row else None
def find_all(self) -> list[ProductRow]:
return [self._load(r) for r in self._db.execute(self.COLUMNS + " ORDER BY id")]
def find_low_stock(self, limit: int) -> list[ProductRow]:
return [self._load(r) for r in self._db.execute(self.COLUMNS + " WHERE stock < ? ORDER BY id", (limit,))]
def restock(finder: ProductFinder, limit: int, amount: int) -> list[str]:
done = []
for product in finder.find_low_stock(limit):
before = product.stock
product.stock += amount
product.update()
done.append(f"{product.name} {before} -> {product.stock}")
return done
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT NOT NULL, price INTEGER NOT NULL, stock INTEGER NOT NULL)")
ProductRow(db, "pen", 120, 3).insert()
ink = ProductRow(db, "ink", 450, 40).insert()
ProductRow(db, "pad", 300, 0).insert()
finder = ProductFinder(db)
with db:
print("restocked:", "; ".join(restock(finder, 5, 20)))
finder.find(ink).delete()
print("rows:", " | ".join(str(p) for p in finder.find_all()))
print("find(9):", finder.find(9) or "none")
restocked: pen 3 -> 23; pad 0 -> 20
rows: 1 pen 120 23 | 3 pad 300 20
find(9): none
- Verdict: idiom. A plain class with one attribute per column and
insert,updateanddeletemethods that run SQL on SQLite. - The finder is a separate class. It holds the read queries, and it makes one
ProductRowfor each row that it reads.
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class Main {
// A stand-in for one database table: the stored columns by id, and an id counter.
static final class Table {
final TreeMap<Integer, Object[]> rows = new TreeMap<>();
int nextId = 1;
}
// A gateway to one row: the columns are fields, and the row saves itself.
static final class ProductRow {
private final Table table;
int id;
String name;
int price;
int stock;
ProductRow(Table table, int id, String name, int price, int stock) {
this.table = table;
this.id = id;
this.name = name;
this.price = price;
this.stock = stock;
}
int insert() {
id = table.nextId++;
update();
return id;
}
void update() {
table.rows.put(id, new Object[] {name, price, stock});
}
void delete() {
table.rows.remove(id);
}
@Override
public String toString() {
return id + " " + name + " " + price + " " + stock;
}
}
// Reads rows and makes one ProductRow for each of them.
static final class ProductFinder {
private final Table table;
ProductFinder(Table table) {
this.table = table;
}
private ProductRow load(int id, Object[] c) {
return new ProductRow(table, id, (String) c[0], (Integer) c[1], (Integer) c[2]);
}
Optional<ProductRow> find(int id) {
return Optional.ofNullable(table.rows.get(id)).map(c -> load(id, c));
}
List<ProductRow> findAll() {
return table.rows.entrySet().stream().map(e -> load(e.getKey(), e.getValue())).toList();
}
List<ProductRow> findLowStock(int limit) {
return findAll().stream().filter(p -> p.stock < limit).toList();
}
}
static List<String> restock(ProductFinder finder, int limit, int amount) {
List<String> done = new ArrayList<>();
for (ProductRow product : finder.findLowStock(limit)) {
int before = product.stock;
product.stock += amount;
product.update();
done.add(product.name + " " + before + " -> " + product.stock);
}
return done;
}
public static void main(String[] args) {
Table table = new Table();
new ProductRow(table, 0, "pen", 120, 3).insert();
int ink = new ProductRow(table, 0, "ink", 450, 40).insert();
new ProductRow(table, 0, "pad", 300, 0).insert();
ProductFinder finder = new ProductFinder(table);
System.out.println("restocked: " + String.join("; ", restock(finder, 5, 20)));
finder.find(ink).ifPresent(ProductRow::delete);
System.out.println("rows: " + finder.findAll().stream().map(ProductRow::toString).collect(Collectors.joining(" | ")));
System.out.println("find(9): " + finder.find(9).map(ProductRow::toString).orElse("none"));
}
}
restocked: pen 3 -> 23; pad 0 -> 20
rows: 1 pen 120 23 | 3 pad 300 20
find(9): none
- Verdict: idiom. The gateway has mutable fields, one per column, because a row gateway is changed in place and then saved.
- A
TreeMapfrom id to the stored columns stands in for the table, because the test image has no database driver.
// A stand-in for one database table: rows by id and an id counter.
class Table {
constructor() {
this.rows = new Map();
this.nextId = 1;
}
}
// A gateway to one row: the columns are fields, and the row saves itself.
class ProductRow {
constructor(table, name, price, stock, id = null) {
this.table = table;
Object.assign(this, { id, name, price, stock });
}
record() {
return { id: this.id, name: this.name, price: this.price, stock: this.stock };
}
insert() {
this.id = this.table.nextId++;
this.table.rows.set(this.id, this.record());
return this.id;
}
update() {
this.table.rows.set(this.id, this.record());
}
delete() {
this.table.rows.delete(this.id);
}
toString() {
return `${this.id} ${this.name} ${this.price} ${this.stock}`;
}
}
// Reads rows and makes one ProductRow for each of them.
class ProductFinder {
constructor(table) {
this.table = table;
}
load(r) {
return new ProductRow(this.table, r.name, r.price, r.stock, r.id);
}
find(id) {
const r = this.table.rows.get(id);
return r ? this.load(r) : null;
}
findAll() {
return [...this.table.rows.values()].sort((a, b) => a.id - b.id).map((r) => this.load(r));
}
findLowStock(limit) {
return this.findAll().filter((p) => p.stock < limit);
}
}
function restock(finder, limit, amount) {
const done = [];
for (const product of finder.findLowStock(limit)) {
const before = product.stock;
product.stock += amount;
product.update();
done.push(`${product.name} ${before} -> ${product.stock}`);
}
return done;
}
const table = new Table();
new ProductRow(table, "pen", 120, 3).insert();
const ink = new ProductRow(table, "ink", 450, 40).insert();
new ProductRow(table, "pad", 300, 0).insert();
const finder = new ProductFinder(table);
console.log("restocked: " + restock(finder, 5, 20).join("; "));
finder.find(ink).delete();
console.log("rows: " + finder.findAll().join(" | "));
console.log("find(9): " + (finder.find(9) ?? "none"));
restocked: pen 3 -> 23; pad 0 -> 20
rows: 1 pen 120 23 | 3 pad 300 20
find(9): none
- Verdict: idiom.
Object.assigncopies the columns into fields, andrecord()copies them back out for the table. - The standard library has no database driver, so a
Mapof rows stands in for the table.
package main
import (
"fmt"
"sort"
"strings"
)
// record is what the table stores for one row.
type record struct {
name string
price, stock int
}
// Table is a stand-in for one database table.
type Table struct {
rows map[int]record
nextID int
}
// ProductRow is a gateway to one row: the columns are fields, and the row saves itself.
type ProductRow struct {
table *Table
ID int
Name string
Price, Stock int
}
func (p *ProductRow) Insert() int {
p.ID = p.table.nextID
p.table.nextID++
p.Update()
return p.ID
}
func (p *ProductRow) Update() { p.table.rows[p.ID] = record{p.Name, p.Price, p.Stock} }
func (p *ProductRow) Delete() { delete(p.table.rows, p.ID) }
func (p *ProductRow) String() string {
return fmt.Sprintf("%d %s %d %d", p.ID, p.Name, p.Price, p.Stock)
}
// ProductFinder reads rows and makes one ProductRow for each of them.
type ProductFinder struct{ table *Table }
func (f ProductFinder) load(id int, r record) *ProductRow {
return &ProductRow{f.table, id, r.name, r.price, r.stock}
}
func (f ProductFinder) Find(id int) *ProductRow {
if r, ok := f.table.rows[id]; ok {
return f.load(id, r)
}
return nil
}
func (f ProductFinder) FindAll() []*ProductRow {
var out []*ProductRow
for id, r := range f.table.rows {
out = append(out, f.load(id, r))
}
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
return out
}
func (f ProductFinder) FindLowStock(limit int) []*ProductRow {
var out []*ProductRow
for _, p := range f.FindAll() {
if p.Stock < limit {
out = append(out, p)
}
}
return out
}
func restock(finder ProductFinder, limit, amount int) []string {
var done []string
for _, p := range finder.FindLowStock(limit) {
before := p.Stock
p.Stock += amount
p.Update()
done = append(done, fmt.Sprintf("%s %d -> %d", p.Name, before, p.Stock))
}
return done
}
func main() {
table := &Table{rows: map[int]record{}, nextID: 1}
(&ProductRow{table: table, Name: "pen", Price: 120, Stock: 3}).Insert()
ink := (&ProductRow{table: table, Name: "ink", Price: 450, Stock: 40}).Insert()
(&ProductRow{table: table, Name: "pad", Price: 300, Stock: 0}).Insert()
finder := ProductFinder{table}
fmt.Println("restocked: " + strings.Join(restock(finder, 5, 20), "; "))
finder.Find(ink).Delete()
var rows []string
for _, p := range finder.FindAll() {
rows = append(rows, p.String())
}
fmt.Println("rows: " + strings.Join(rows, " | "))
if finder.Find(9) == nil {
fmt.Println("find(9): none")
}
}
restocked: pen 3 -> 23; pad 0 -> 20
rows: 1 pen 120 23 | 3 pad 300 20
find(9): none
- Verdict: idiom. The finder returns pointers, so a caller changes the fields of one gateway and calls
Updateon the same value. FindAllsorts by id, because the iteration order of a Go map is not fixed.
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::fmt;
use std::rc::Rc;
// A stand-in for one database table: the stored columns by id, and an id counter.
#[derive(Default)]
struct Table {
rows: BTreeMap<u32, (String, u32, u32)>,
next_id: u32,
}
type Db = Rc<RefCell<Table>>;
// A gateway to one row: the columns are fields, and the row saves itself.
struct ProductRow {
db: Db,
id: u32,
name: String,
price: u32,
stock: u32,
}
impl ProductRow {
fn new(db: &Db, name: &str, price: u32, stock: u32) -> Self {
ProductRow { db: Rc::clone(db), id: 0, name: name.to_string(), price, stock }
}
fn insert(&mut self) -> u32 {
let mut t = self.db.borrow_mut();
t.next_id += 1;
self.id = t.next_id;
t.rows.insert(self.id, (self.name.clone(), self.price, self.stock));
self.id
}
fn update(&self) {
self.db.borrow_mut().rows.insert(self.id, (self.name.clone(), self.price, self.stock));
}
fn delete(&self) {
self.db.borrow_mut().rows.remove(&self.id);
}
}
impl fmt::Display for ProductRow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {} {} {}", self.id, self.name, self.price, self.stock)
}
}
// Reads rows and makes one ProductRow for each of them.
struct ProductFinder {
db: Db,
}
impl ProductFinder {
fn load(&self, id: u32, (name, price, stock): &(String, u32, u32)) -> ProductRow {
ProductRow { db: Rc::clone(&self.db), id, name: name.clone(), price: *price, stock: *stock }
}
fn find(&self, id: u32) -> Option<ProductRow> {
let t = self.db.borrow();
t.rows.get(&id).map(|r| self.load(id, r))
}
fn find_all(&self) -> Vec<ProductRow> {
let t = self.db.borrow();
t.rows.iter().map(|(id, r)| self.load(*id, r)).collect()
}
fn find_low_stock(&self, limit: u32) -> Vec<ProductRow> {
self.find_all().into_iter().filter(|p| p.stock < limit).collect()
}
}
fn restock(finder: &ProductFinder, limit: u32, amount: u32) -> Vec<String> {
let mut done = Vec::new();
for mut product in finder.find_low_stock(limit) {
let before = product.stock;
product.stock += amount;
product.update();
done.push(format!("{} {} -> {}", product.name, before, product.stock));
}
done
}
fn main() {
let db: Db = Rc::new(RefCell::new(Table::default()));
ProductRow::new(&db, "pen", 120, 3).insert();
let ink = ProductRow::new(&db, "ink", 450, 40).insert();
ProductRow::new(&db, "pad", 300, 0).insert();
let finder = ProductFinder { db: Rc::clone(&db) };
println!("restocked: {}", restock(&finder, 5, 20).join("; "));
if let Some(p) = finder.find(ink) {
p.delete();
}
let rows: Vec<String> = finder.find_all().iter().map(|p| p.to_string()).collect();
println!("rows: {}", rows.join(" | "));
match finder.find(9) {
Some(p) => println!("find(9): {p}"),
None => println!("find(9): none"),
}
}
restocked: pen 3 -> 23; pad 0 -> 20
rows: 1 pen 120 23 | 3 pad 300 20
find(9): none
- Verdict: idiom. Each gateway holds an
Rc<RefCell<Table>>, because many row objects share one table and each must be able to write to it. restocktakes each row by value asmut product, changes the field, and callsupdate.
Consequences
Benefits.
- The data has the form of the language. A caller reads
product.stockand sets it, and the type system of the language can check the fields. - The SQL of a row is in one class. The insert, update and delete statements exist once.2
- The pattern is simple. A code generator or a small base class can make the gateways from the schema, because each class follows the columns of one table.
Liabilities.
Two objects for one row. Each call of a finder makes a new object. Two parts of a program can load the same row, change different fields, and both save. The last save wins, and it writes back the old values of the fields that it did not change. Fowler's catalogue describes this risk: "If you aren't careful you can load the data from the same database record into two different objects."3
This code runs but gives a wrong answer on purpose.
import sqlite3
class ProductRow:
def __init__(self, db, id, name, price, stock):
self._db = db
self.id, self.name, self.price, self.stock = id, name, price, stock
def update(self):
self._db.execute("UPDATE products SET name = ?, price = ?, stock = ? WHERE id = ?", (self.name, self.price, self.stock, self.id))
def find(db, product_id):
return ProductRow(db, *db.execute("SELECT id, name, price, stock FROM products WHERE id = ?", (product_id,)).fetchone())
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, price INTEGER, stock INTEGER)")
db.execute("INSERT INTO products VALUES (1, 'pen', 120, 3)")
stock_job = find(db, 1) # one part of the program loads row 1
price_job = find(db, 1) # another part loads row 1 again: a second object
stock_job.stock += 20
stock_job.update()
price_job.price = 150
price_job.update() # bug: writes back the old stock, 3
print(db.execute("SELECT * FROM products").fetchone())
(1, 'pen', 150, 3)
The stock change is lost. The fixes are an Identity Map, which returns the same object for the same row within one business transaction,3 an update that writes only the changed columns, or an optimistic lock that refuses a save when the row changed after it was read.
The business logic has nowhere to go. The rules sit in scripts around the gateways. When a rule is about one row, for example the price of a product with a discount, it is natural to put it on the gateway. Then the gateway has become an Active Record.4
The objects follow the tables. A gateway class has the columns of its table, so a change of the schema changes the class and its callers.
When not to use it
When the rows carry domain logic. Use Active Record, which is the same object with the business rules added, or a Data Mapper with a separate domain model.4
When the program works on sets of rows. A report or a batch job that reads many rows and computes totals does not need one object per row. A Table Data Gateway that returns rows or a record set is simpler and faster.
When an ORM is in use. An ORM gives each table a class, often in the Active Record or Data Mapper form, and a hand-written row gateway on top of it adds a second class for the same row.
Variants and related patterns
Table Data Gateway. One object for the whole table, which returns plain data. The finder of a Row Data Gateway design is a table gateway that returns row objects.2 See Table Data Gateway.
Active Record. A row gateway with domain logic. Fowler's catalogue describes Active Record as an object that "wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data".4 See Active Record.
Data Mapper. The domain objects know nothing of the database, and a separate mapper loads and saves them. See Data Mapper.
Identity Map. Keeps one object for each row that a business transaction has loaded, which removes the lost update of the example above.3
Generated gateways. A tool reads the schema and writes one gateway class for each table. The gateways have no hand-written logic, so a regenerated class loses nothing.
Known uses
- laminas-db, a PHP database library, has a RowGateway subcomponent that "implements the Row Data Gateway pattern described in the book Patterns of Enterprise Application Architecture".5 Its interface has two methods,
saveanddelete. In AbstractRowGateway.php at 2.22.0,saveruns an UPDATE with the primary key in the WHERE clause when the row came from the database, and an INSERT otherwise. Then it reads the row again, so the fields hold what the database stored.6 The documentation shows how a custom class with business behaviour turns the row gateway into objects in the Active Record style.5
References
- Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Row Data Gateway, pattern summary; the book's Chapter 10
- Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 10, Data Source Architectural Patterns, Row Data Gateway
- Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Identity Map, pattern summary; the book's Chapter 11
- Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Active Record, pattern summary; the book's Chapter 10
- Laminas documentation, laminas-db, Row Gateways, first section; ActiveRecord Style Objects
- laminas-db 2.22.0 source, src/RowGateway/AbstractRowGateway.php, save, lines 110 to 180
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 01FS9B Edit this page History Report an error Markdown