Programming Search⌘K

Patterncore

Table Data Gateway

Also called table gateway.

A Table Data Gateway is one object that holds all the SQL for one table or view. Its methods find, insert, update and delete rows, and they return plain data, not domain objects.

Family
architectural
Intent
An object that acts as a gateway to a database table. One instance handles all the rows in the table.
Also called
Table Gateway

Intent

"An object that acts as a gateway to a database table. One instance handles all the rows in the table."1 The rest of the program calls the methods of the gateway, and it never writes SQL for that table itself.

Problem

A small stock system has a products table. The order code reads the stock of a product. The restock job finds the products with low stock and adds to them. A report lists all products. In the first version, each of these places writes its own SQL. The query for "products with low stock" exists three times, with small differences. A change to a column name needs a search through the whole code base.

The forces are these. The business rules should be readable without SQL around them. The SQL should be in one place, so that a person who tunes or changes the database can find all of it. Fowler's catalogue gives the same two reasons: many developers do not write SQL well, and database administrators "need to be able to find SQL easily so they can figure out how to tune and evolve the database".1 And the program does not need objects with behaviour for each row: the rules are simple procedures.

Solution

Make one class for each table or view. Give it one method for each operation that the program needs on that table: find by key, find by a criterion, insert, update and delete. Each method holds its SQL and binds the arguments as parameters. The finders return plain data, such as rows, records or a record set. The gateway has no state of its own except the connection, so one instance serves all the rows of the table.12

  application code (transaction scripts, a table module)
      restock(products, limit, amount)
            |
            v
  ProductGateway           one instance for the whole table
      find(id)             SELECT ... WHERE id = ?
      find_low_stock(n)    SELECT ... WHERE stock < ?
      insert(...)          INSERT ...
      update_stock(id, n)  UPDATE ... WHERE id = ?
      delete(id)           DELETE ... WHERE id = ?
            |
            v
  products table           rows go out as plain data

The participants are the gateway, the table behind it, and the callers. In Fowler's catalogue, the callers are often transaction scripts, procedures that each handle one request, or a table module, a single instance that holds the business logic for all rows of a table.3 The gateway is a special case of the base pattern Gateway: "An object that encapsulates access to an external system or resource."3

The following program has one gateway for a products table in SQLite. The function restock is the business rule. It uses the gateway and contains no SQL. Every query binds its values with ? placeholders, as the Python documentation requires for values that come from outside the code.4

import sqlite3


class ProductGateway:
    """All the SQL for the products table. It returns rows, not objects."""

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

    def find(self, product_id: int) -> sqlite3.Row | None:
        return self._db.execute("SELECT id, name, price, stock FROM products WHERE id = ?", (product_id,)).fetchone()

    def find_low_stock(self, limit: int) -> list[sqlite3.Row]:
        return self._db.execute("SELECT id, name, price, stock FROM products WHERE stock < ? ORDER BY id", (limit,)).fetchall()

    def insert(self, name: str, price: int, stock: int) -> int:
        return self._db.execute("INSERT INTO products (name, price, stock) VALUES (?, ?, ?)", (name, price, stock)).lastrowid

    def update_stock(self, product_id: int, stock: int) -> None:
        self._db.execute("UPDATE products SET stock = ? WHERE id = ?", (stock, product_id))

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


def restock(products: ProductGateway, limit: int, amount: int) -> list[str]:
    """A transaction script: the business rule is here, the SQL is in the gateway."""
    done = []
    for row in products.find_low_stock(limit):
        products.update_stock(row["id"], row["stock"] + amount)
        done.append(f"{row['name']} {row['stock']} -> {row['stock'] + amount}")
    return done


db = sqlite3.connect(":memory:")
db.row_factory = sqlite3.Row
db.execute("CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT NOT NULL, price INTEGER NOT NULL, stock INTEGER NOT NULL)")
products = ProductGateway(db)
products.insert("pen", 120, 3)
ink = products.insert("ink", 450, 40)
products.insert("pad", 300, 0)
with db:
    print("restocked:", "; ".join(restock(products, limit=5, amount=20)))
products.delete(ink)
print("rows:", [tuple(r) for r in db.execute("SELECT * FROM products ORDER BY id")])
print("find(9):", products.find(9))
Output
restocked: pen 3 -> 23; pad 0 -> 20
rows: [(1, 'pen', 120, 23), (3, 'pad', 300, 20)]
find(9): None

The finders return sqlite3.Row values, which the caller reads by column name. That is the normal shape of this pattern: the gateway passes data, and the caller decides what the data means.

Example

Each example file has a gateway for a products table with the methods find, findAll, findLowStock, insert, updateStock and delete, and a transaction script restock that uses it. The Python file uses SQLite, as the block above does. The JavaScript, Java, Go and Rust files keep the table in memory, as a map of rows and an id counter, because the standard libraries of these languages have no database driver. In those files the gateway is still the only code that touches the table, and it returns copies of rows, so a caller cannot change the table except through a gateway method.

PythonGitHub
import sqlite3


class ProductGateway:
    """One instance handles every row of the products table."""

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

    def find(self, product_id: int) -> sqlite3.Row | None:
        return self._db.execute("SELECT id, name, price, stock FROM products WHERE id = ?", (product_id,)).fetchone()

    def find_all(self) -> list[sqlite3.Row]:
        return self._db.execute("SELECT id, name, price, stock FROM products ORDER BY id").fetchall()

    def find_low_stock(self, limit: int) -> list[sqlite3.Row]:
        return self._db.execute("SELECT id, name, price, stock FROM products WHERE stock < ? ORDER BY id", (limit,)).fetchall()

    def insert(self, name: str, price: int, stock: int) -> int:
        return self._db.execute("INSERT INTO products (name, price, stock) VALUES (?, ?, ?)", (name, price, stock)).lastrowid

    def update_stock(self, product_id: int, stock: int) -> None:
        self._db.execute("UPDATE products SET stock = ? WHERE id = ?", (stock, product_id))

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


def restock(products: ProductGateway, limit: int, amount: int) -> list[str]:
    done = []
    for row in products.find_low_stock(limit):
        products.update_stock(row["id"], row["stock"] + amount)
        done.append(f"{row['name']} {row['stock']} -> {row['stock'] + amount}")
    return done


db = sqlite3.connect(":memory:")
db.row_factory = sqlite3.Row
db.execute("CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT NOT NULL, price INTEGER NOT NULL, stock INTEGER NOT NULL)")
products = ProductGateway(db)
products.insert("pen", 120, 3)
ink = products.insert("ink", 450, 40)
products.insert("pad", 300, 0)
with db:
    print("restocked:", "; ".join(restock(products, 5, 20)))
products.delete(ink)
print("rows:", " | ".join(f"{r['id']} {r['name']} {r['price']} {r['stock']}" for r in products.find_all()))
print("find(9):", products.find(9) or "none")
Output
restocked: pen 3 -> 23; pad 0 -> 20
rows: 1 pen 120 23 | 3 pad 300 20
find(9): none
  • Verdict: idiom. The gateway runs real SQL on SQLite, and every value is bound with a ? placeholder.
  • The finders return sqlite3.Row values, so the caller reads columns by name and the gateway needs no row class.
  • with db: makes the restock run one transaction: it commits when the block ends, and it rolls back on an exception.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class Main {
    // One row of the products table, as plain data.
    record ProductRow(int id, String name, int price, int stock) {}

    // A stand-in for one database table: rows by id and an id counter.
    static final class Table {
        final TreeMap<Integer, ProductRow> rows = new TreeMap<>();
        int nextId = 1;
    }

    // The gateway holds every operation on the products table.
    static final class ProductGateway {
        private final Table table;

        ProductGateway(Table table) {
            this.table = table;
        }

        Optional<ProductRow> find(int id) {
            return Optional.ofNullable(table.rows.get(id));
        }

        List<ProductRow> findAll() {
            return List.copyOf(table.rows.values());
        }

        List<ProductRow> findLowStock(int limit) {
            return table.rows.values().stream().filter(r -> r.stock() < limit).toList();
        }

        int insert(String name, int price, int stock) {
            int id = table.nextId++;
            table.rows.put(id, new ProductRow(id, name, price, stock));
            return id;
        }

        void updateStock(int id, int stock) {
            table.rows.computeIfPresent(id, (k, r) -> new ProductRow(r.id(), r.name(), r.price(), stock));
        }

        void delete(int id) {
            table.rows.remove(id);
        }
    }

    // A transaction script: the rule is here, the data access is in the gateway.
    static List<String> restock(ProductGateway products, int limit, int amount) {
        List<String> done = new ArrayList<>();
        for (ProductRow row : products.findLowStock(limit)) {
            products.updateStock(row.id(), row.stock() + amount);
            done.add(row.name() + " " + row.stock() + " -> " + (row.stock() + amount));
        }
        return done;
    }

    public static void main(String[] args) {
        ProductGateway products = new ProductGateway(new Table());
        products.insert("pen", 120, 3);
        int ink = products.insert("ink", 450, 40);
        products.insert("pad", 300, 0);
        System.out.println("restocked: " + String.join("; ", restock(products, 5, 20)));
        products.delete(ink);
        System.out.println("rows: " + products.findAll().stream()
                .map(r -> r.id() + " " + r.name() + " " + r.price() + " " + r.stock())
                .collect(Collectors.joining(" | ")));
        System.out.println("find(9): " + products.find(9).map(ProductRow::toString).orElse("none"));
    }
}
Output
restocked: pen 3 -> 23; pad 0 -> 20
rows: 1 pen 120 23 | 3 pad 300 20
find(9): none
  • Verdict: idiom. The gateway returns ProductRow records, which are immutable, so a change goes through updateStock.
  • A TreeMap stands in for the table, because the test image has no database driver. The keys stay in order, so findAll needs no sort.
JavaScriptGitHub
// A stand-in for one database table: rows by id and an id counter.
class Table {
  constructor() {
    this.rows = new Map();
    this.nextId = 1;
  }
}

// The gateway holds every operation on the products table.
// It returns plain row records, never domain objects.
class ProductGateway {
  constructor(table) {
    this.table = table;
  }

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

  findAll() {
    return [...this.table.rows.values()].sort((a, b) => a.id - b.id).map((r) => ({ ...r }));
  }

  findLowStock(limit) {
    return this.findAll().filter((r) => r.stock < limit);
  }

  insert(name, price, stock) {
    const id = this.table.nextId++;
    this.table.rows.set(id, { id, name, price, stock });
    return id;
  }

  updateStock(id, stock) {
    const row = this.table.rows.get(id);
    if (row) row.stock = stock;
  }

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

// A transaction script: the rule is here, the data access is in the gateway.
function restock(products, limit, amount) {
  const done = [];
  for (const row of products.findLowStock(limit)) {
    products.updateStock(row.id, row.stock + amount);
    done.push(`${row.name} ${row.stock} -> ${row.stock + amount}`);
  }
  return done;
}

const products = new ProductGateway(new Table());
products.insert("pen", 120, 3);
const ink = products.insert("ink", 450, 40);
products.insert("pad", 300, 0);
console.log("restocked: " + restock(products, 5, 20).join("; "));
products.delete(ink);
console.log("rows: " + products.findAll().map((r) => `${r.id} ${r.name} ${r.price} ${r.stock}`).join(" | "));
console.log("find(9): " + (products.find(9) ?? "none"));
Output
restocked: pen 3 -> 23; pad 0 -> 20
rows: 1 pen 120 23 | 3 pad 300 20
find(9): none
  • Verdict: idiom. A class with one method for each operation on the table. The standard library has no database driver, so a Map of rows stands in for the table.
  • The finders return copies made with spread syntax, so a caller cannot change the table except through a gateway method.
package main

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

// ProductRow is one row of the products table, as plain data.
type ProductRow struct {
	ID, Price, Stock int
	Name             string
}

// Table is a stand-in for one database table.
type Table struct {
	rows   map[int]ProductRow
	nextID int
}

// ProductGateway holds every operation on the products table.
type ProductGateway struct{ table *Table }

func (g ProductGateway) Find(id int) (ProductRow, bool) {
	r, ok := g.table.rows[id]
	return r, ok
}

func (g ProductGateway) FindAll() []ProductRow {
	out := make([]ProductRow, 0, len(g.table.rows))
	for _, r := range g.table.rows {
		out = append(out, r)
	}
	sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
	return out
}

func (g ProductGateway) FindLowStock(limit int) []ProductRow {
	var out []ProductRow
	for _, r := range g.FindAll() {
		if r.Stock < limit {
			out = append(out, r)
		}
	}
	return out
}

func (g ProductGateway) Insert(name string, price, stock int) int {
	id := g.table.nextID
	g.table.nextID++
	g.table.rows[id] = ProductRow{ID: id, Name: name, Price: price, Stock: stock}
	return id
}

func (g ProductGateway) UpdateStock(id, stock int) {
	if r, ok := g.table.rows[id]; ok {
		r.Stock = stock
		g.table.rows[id] = r
	}
}

func (g ProductGateway) Delete(id int) { delete(g.table.rows, id) }

// restock is a transaction script: the rule is here, the data access is in the gateway.
func restock(products ProductGateway, limit, amount int) []string {
	var done []string
	for _, r := range products.FindLowStock(limit) {
		products.UpdateStock(r.ID, r.Stock+amount)
		done = append(done, fmt.Sprintf("%s %d -> %d", r.Name, r.Stock, r.Stock+amount))
	}
	return done
}

func main() {
	products := ProductGateway{&Table{rows: map[int]ProductRow{}, nextID: 1}}
	products.Insert("pen", 120, 3)
	ink := products.Insert("ink", 450, 40)
	products.Insert("pad", 300, 0)
	fmt.Println("restocked: " + strings.Join(restock(products, 5, 20), "; "))
	products.Delete(ink)
	var rows []string
	for _, r := range products.FindAll() {
		rows = append(rows, fmt.Sprintf("%d %s %d %d", r.ID, r.Name, r.Price, r.Stock))
	}
	fmt.Println("rows: " + strings.Join(rows, " | "))
	if _, ok := products.Find(9); !ok {
		fmt.Println("find(9): none")
	}
}
Output
restocked: pen 3 -> 23; pad 0 -> 20
rows: 1 pen 120 23 | 3 pad 300 20
find(9): none
  • Verdict: idiom. The gateway is a struct with methods, and the rows are plain structs that are copied by value.
  • The map stands in for the table, because the standard library has no database driver. FindAll sorts by id, because the iteration order of a Go map is not fixed.
RustGitHub
use std::collections::BTreeMap;

// One row of the products table, as plain data.
#[derive(Clone, Debug)]
struct ProductRow {
    id: u32,
    name: String,
    price: u32,
    stock: u32,
}

// A stand-in for one database table: rows by id and an id counter.
struct Table {
    rows: BTreeMap<u32, ProductRow>,
    next_id: u32,
}

// The gateway holds every operation on the products table.
struct ProductGateway<'a> {
    table: &'a mut Table,
}

impl ProductGateway<'_> {
    fn find(&self, id: u32) -> Option<ProductRow> {
        self.table.rows.get(&id).cloned()
    }

    fn find_all(&self) -> Vec<ProductRow> {
        self.table.rows.values().cloned().collect()
    }

    fn find_low_stock(&self, limit: u32) -> Vec<ProductRow> {
        self.table.rows.values().filter(|r| r.stock < limit).cloned().collect()
    }

    fn insert(&mut self, name: &str, price: u32, stock: u32) -> u32 {
        let id = self.table.next_id;
        self.table.next_id += 1;
        self.table.rows.insert(id, ProductRow { id, name: name.to_string(), price, stock });
        id
    }

    fn update_stock(&mut self, id: u32, stock: u32) {
        if let Some(row) = self.table.rows.get_mut(&id) {
            row.stock = stock;
        }
    }

    fn delete(&mut self, id: u32) {
        self.table.rows.remove(&id);
    }
}

// A transaction script: the rule is here, the data access is in the gateway.
fn restock(products: &mut ProductGateway, limit: u32, amount: u32) -> Vec<String> {
    let mut done = Vec::new();
    for row in products.find_low_stock(limit) {
        products.update_stock(row.id, row.stock + amount);
        done.push(format!("{} {} -> {}", row.name, row.stock, row.stock + amount));
    }
    done
}

fn main() {
    let mut table = Table { rows: BTreeMap::new(), next_id: 1 };
    let mut products = ProductGateway { table: &mut table };
    products.insert("pen", 120, 3);
    let ink = products.insert("ink", 450, 40);
    products.insert("pad", 300, 0);
    println!("restocked: {}", restock(&mut products, 5, 20).join("; "));
    products.delete(ink);
    let rows: Vec<String> = products
        .find_all()
        .iter()
        .map(|r| format!("{} {} {} {}", r.id, r.name, r.price, r.stock))
        .collect();
    println!("rows: {}", rows.join(" | "));
    match products.find(9) {
        Some(row) => println!("find(9): {:?}", row),
        None => println!("find(9): none"),
    }
}
Output
restocked: pen 3 -> 23; pad 0 -> 20
rows: 1 pen 120 23 | 3 pad 300 20
find(9): none
  • Verdict: idiom. The gateway borrows the table mutably, so the borrow checker allows no other access to the table while the gateway exists.
  • The finders return cloned rows, so a caller gets data and not a reference into the table.

Consequences

Benefits.

  • All the SQL of a table is in one class. A person who changes the schema or tunes a query reads one file.1
  • The pattern is simple. It needs no mapping layer and no framework. The gateway is a thin layer over the database API, and a new developer can read it in minutes.
  • It fits procedural business logic. A transaction script or a table module works on rows and record sets, and the gateway gives it exactly that.3
  • It is a seam for tests. A test can replace the gateway with a stub that returns fixed rows, and test the business rules without a database.

Liabilities.

  • The callers still know the columns. The gateway hides the SQL, but its results are rows with the names of the columns. A change of a column name still reaches the callers that read it.
  • No behaviour lives with the data. A rule, for example that a product with zero stock cannot be sold, goes into the procedures that use the rows. When many procedures need the same rule, it is copied. That is the point where Fowler moves to a domain model and a Data Mapper.52
  • The finder list grows. Each new question about the table needs a new method, and the gateway can grow to dozens of finders.

The gateway must not accept SQL from its callers. A method that takes a condition as a string moves the SQL back into the callers, and it lets any value that is pasted into the condition change the query:

This code runs but gives a wrong answer on purpose.

import sqlite3


class ProductGateway:
    def __init__(self, db):
        self._db = db

    def find_where(self, condition):
        # bug: the caller passes SQL, and the gateway pastes it into the query
        return self._db.execute(f"SELECT name FROM products WHERE {condition}").fetchall()


db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, owner TEXT)")
db.executemany("INSERT INTO products (name, owner) VALUES (?, ?)", [("pen", "ana"), ("ink", "bo"), ("pad", "bo")])
products = ProductGateway(db)

owner = "ana"
print(products.find_where(f"owner = '{owner}'"))
owner = "x' OR '1'='1"
print(products.find_where(f"owner = '{owner}'"))
Output
[('pen',)]
[('pen',), ('ink',), ('pad',)]

The second call returns the rows of every owner, because the value of owner closes the quote and adds a condition that is always true. A gateway method takes values as arguments and binds them as parameters, as in the first program.4 See SQL injection.

When not to use it

With a rich domain model. When the business rules live in objects with behaviour, the code that turns rows into objects grows around every call of the gateway. A Data Mapper does that work in one place and keeps the objects independent of the database.5

When the framework already gives you one. An ORM or a query builder gives each table an API for find, insert, update and delete. A hand-written gateway on top of it only renames the calls. A gateway is still useful over raw SQL, or for queries that the ORM cannot express well.

For one row with its own behaviour. When the program works with one row at a time and wants an object for it, Row Data Gateway gives one object per row instead.6

Row Data Gateway. One instance per row instead of one per table. "There is one instance per row."6 The finders of a Row Data Gateway design often live in a separate object that is a Table Data Gateway in all but name. See Row Data Gateway.

Active Record. A row object that also holds the domain logic. See Active Record.

Data Mapper. A layer that maps between domain objects and tables, so that neither knows the other.5 See Data Mapper.

Repository. A collection-like interface for domain objects, usually over a Data Mapper. A repository returns domain objects. A table gateway returns rows. See Repository pattern.

Data access object. The Core J2EE pattern: a DAO is used "to abstract and encapsulate all access to the data source", and one DAO serves one business object.7 A DAO and a table gateway are often the same class with two names. The difference is in what they return: "The DataAccessObject may use a Transfer Object to return data to the client."7

Record Set. "An in-memory representation of tabular data."3 A gateway can return a record set, and the record set can carry the changes back to the gateway.

Facade. A gateway is a facade over the database API for one table. See Facade pattern.

Known uses

  • laminas-db, a PHP database library, has a Table Gateway subcomponent that "provides an object-oriented representation of a database table; its methods mirror the most common table operations".8 Its interface has select, insert, update and delete. In AbstractTableGateway.php at 2.22.0, select builds a Select object for the table of the gateway, adds the condition of the caller, and executes it.9

References

  1. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Table Data Gateway, pattern summary; the book's Chapter 10
  2. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 10, Data Source Architectural Patterns, Table Data Gateway
  3. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Domain Logic Patterns; Data Source Architectural Patterns; Base Patterns
  4. The Python Standard Library, sqlite3, Python 3.14, Tutorial; How to use placeholders to bind values in SQL queries
  5. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Data Mapper, pattern summary; the book's Chapter 10
  6. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Row Data Gateway, pattern summary; the book's Chapter 10
  7. Core J2EE Patterns, Data Access Object, Oracle, Solution; Participants and Responsibilities, TransferObject
  8. Laminas documentation, laminas-db, Table Gateways, first section
  9. laminas-db 2.22.0 source, src/TableGateway/AbstractTableGateway.php, select and selectWith, lines 165 to 199

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