Programming Search⌘K

Patternadvanced

Database access layer

Also called data access layer, DAL, relational database access layer, persistence layer.

A database access layer puts all database access of an application in one layer, with a logical part that the application uses and a physical part that knows the tables.

Family
architectural
Intent
Separate the application from the database with a layer that holds all database access.
Also called
data access layer

Intent

A database access layer holds all the code of an application that talks to the database. The rest of the application, which Keller and Coldewey call the application kernel, uses the interface of the layer and has no SQL and no table names. Their pattern language starts from one question: "How do you access the relational database?"1 POSA4 includes the pattern as the first pattern of its chapter on database access, and the other patterns of the chapter refine it.2

Problem

Database code and business code are both hard, and they are hard in different ways. Keller and Coldewey put the first force like this: "Database programming is complex and so is application logic. Both call for clever solutions. Mixing them will add up to more than just the combined complexity."1

The other forces pull against each other. The database must be tuned, and tuning changes the tables, the indexes and the access paths, many times in the life of a system. The application kernel must not change each time. Old data in legacy systems often has a structure that does not fit the new design, and a new system must still read it. A layer that hides the database costs classes and design work, and it must still be powerful enough for the queries that the application needs.1

Solution

"Use a layered architecture consisting of two layers."1 The logical access layer gives the application kernel a stable interface. The physical access layer knows the database: the tables, the SQL and the calls of the database interface. When the database is tuned, the physical layer changes, and the logical layer and the kernel do not.

The participants in the Keller and Coldewey form are:1

  • Transaction. The kernel starts, commits and aborts work through it.
  • View factory and view cache. The kernel gets each logical view, such as an order with its lines, by a key. The cache keeps the views of the transaction, so a second read of the same view does not go to the database, and the commit writes the changed views.
  • Physical views. "wraps one physical database table".1 A physical view can also hide a tuning change, such as a table whose columns were copied into another table, and it can be generated from the metadata of the database.
  • Database. It wraps the connection and the administrative calls of the database system.
  • Query broker. An optional part that connects the logical views to the physical views. Without it, the connection is written in the code.

The physical views also translate the error codes of the database into errors of the application.1

  application kernel          invoice(10)        no SQL, no tables
  ----------------------------------------------------------------
  logical access layer        Transaction, ViewFactory, ViewCache
                              get_order(10) -> Order
  ----------------------------------------------------------------
  physical access layer       NormalizedOrderView | DenormalizedOrderView
                              Database (connection, statements)
  ----------------------------------------------------------------
  database API                SQL on customer, orders, order_line

The following program has the three parts in their smallest form. Only the physical part, the set-up of the tables and read_order, has SQL in it.

import sqlite3

# Physical access layer: the only code that knows the tables and the SQL.
db = sqlite3.connect(":memory:")
db.executescript("""
create table customer (id integer primary key, name text);
create table orders (id integer primary key, customer_id integer);
insert into customer values (1, 'Acme Ltd');
insert into orders values (10, 1);
""")


def read_order(order_id):
    sql = "select c.name from orders o join customer c on c.id = o.customer_id where o.id = ?"
    return db.execute(sql, (order_id,)).fetchone()


# Logical access layer: the interface of the application kernel.
def customer_of_order(order_id):
    row = read_order(order_id)
    return row[0] if row else None


# Application kernel: no SQL, no table names.
print("order 10 is for", customer_of_order(10))
Output
order 10 is for Acme Ltd

Example

Each example file has an application kernel, invoice, that prints the customer and the lines of an order. It uses only the logical layer, AccessLayer, which has the start and the commit of a transaction, a cache of the orders read, and the error AccessError. Under it are two physical views of the same orders. NormalizedOrderView reads three tables: customer, orders and order_line. DenormalizedOrderView reads two, because a tuning step copied the customer name into orders. The program runs the same kernel on each layout. It prints the invoice twice, and the count of physical reads shows that the second came from the cache. It changes a quantity, commits, reads the order in a new transaction, and asks for an order that does not exist. The output is the same for the two layouts except for the list of tables. The Python file runs SQL in SQLite; the other files keep the tables in memory.

PythonGitHub
import sqlite3


class AccessError(Exception):
    # The error that the application kernel sees, whatever the database says.
    pass


# ---- Physical access layer: knows the tables and the SQL. ----

class Database:
    # Wraps the connection and runs the statements.
    def __init__(self, script):
        self.conn = sqlite3.connect(":memory:")
        self.conn.executescript(script)

    def query(self, sql, args):
        return self.conn.execute(sql, args).fetchall()

    def execute(self, sql, args):
        self.conn.execute(sql, args)

    def commit(self):
        self.conn.commit()


NORMALIZED = """
create table customer (id integer primary key, name text);
create table orders (id integer primary key, customer_id integer);
create table order_line (order_id integer, item text, qty integer);
insert into customer values (1, 'Acme Ltd');
insert into orders values (10, 1);
insert into order_line values (10, 'bolt', 2), (10, 'nut', 5);
"""

# After tuning: the customer name is copied into the orders table.
DENORMALIZED = """
create table orders (id integer primary key, customer_name text);
create table order_line (order_id integer, item text, qty integer);
insert into orders values (10, 'Acme Ltd');
insert into order_line values (10, 'bolt', 2), (10, 'nut', 5);
"""


class OrderView:
    # The protocol of a physical view of orders: read an order, write a line.
    def __init__(self, db):
        self.db = db

    def write_line(self, order_id, item, qty):
        self.db.execute("update order_line set qty = ? where order_id = ? and item = ?", (qty, order_id, item))


class NormalizedOrderView(OrderView):
    # Reads an order from the normalized tables.
    tables = "customer, orders, order_line"

    def read(self, order_id):
        head = self.db.query("select c.name from orders o join customer c on c.id = o.customer_id where o.id = ?", (order_id,))
        lines = self.db.query("select item, qty from order_line where order_id = ? order by item", (order_id,))
        return head, lines


class DenormalizedOrderView(OrderView):
    # Reads an order from the tuned tables: one table less to read.
    tables = "orders, order_line"

    def read(self, order_id):
        head = self.db.query("select customer_name from orders where id = ?", (order_id,))
        lines = self.db.query("select item, qty from order_line where order_id = ? order by item", (order_id,))
        return head, lines


# ---- Logical access layer: the interface of the application kernel. ----

class Order:
    # The logical view of an order. It has no SQL in it.
    def __init__(self, order_id, customer, lines):
        self.id, self.customer, self.lines = order_id, customer, dict(lines)
        self.changed = set()

    def set_qty(self, item, qty):
        self.lines[item] = qty
        self.changed.add(item)


class AccessLayer:
    def __init__(self, physical):
        self.physical, self.cache, self.reads = physical, {}, 0

    def start(self):
        self.cache, self.reads = {}, 0

    def get_order(self, order_id):
        if order_id not in self.cache:
            head, lines = self.physical.read(order_id)
            self.reads += 1
            if not head:
                raise AccessError(f"no order {order_id}")
            self.cache[order_id] = Order(order_id, head[0][0], lines)
        return self.cache[order_id]

    def commit(self):
        written = []
        for order in self.cache.values():
            for item in sorted(order.changed):
                self.physical.write_line(order.id, item, order.lines[item])
                written.append(f"order {order.id} {item} x {order.lines[item]}")
            order.changed.clear()
        self.physical.db.commit()
        return written


# ---- Application kernel: uses only the logical access layer. ----

def invoice(layer, order_id):
    o = layer.get_order(order_id)
    return " | ".join([o.customer] + [f"{item} x {qty}" for item, qty in sorted(o.lines.items())])


def run(name, script, view_class):
    layer = AccessLayer(view_class(Database(script)))
    print("physical layout:", name)
    layer.start()
    print("invoice 10:", invoice(layer, 10))
    print("invoice 10:", invoice(layer, 10))
    print(f"physical reads: {layer.reads}, tables {view_class.tables}")
    layer.get_order(10).set_qty("bolt", 3)
    print("commit:", ", ".join(layer.commit()))
    layer.start()
    print("invoice 10 in a new transaction:", invoice(layer, 10))
    try:
        invoice(layer, 99)
    except AccessError as e:
        print("error:", e)


run("normalized", NORMALIZED, NormalizedOrderView)
run("denormalized", DENORMALIZED, DenormalizedOrderView)
Output
physical layout: normalized
invoice 10: Acme Ltd | bolt x 2 | nut x 5
invoice 10: Acme Ltd | bolt x 2 | nut x 5
physical reads: 1, tables customer, orders, order_line
commit: order 10 bolt x 3
invoice 10 in a new transaction: Acme Ltd | bolt x 3 | nut x 5
error: no order 99
physical layout: denormalized
invoice 10: Acme Ltd | bolt x 2 | nut x 5
invoice 10: Acme Ltd | bolt x 2 | nut x 5
physical reads: 1, tables orders, order_line
commit: order 10 bolt x 3
invoice 10 in a new transaction: Acme Ltd | bolt x 3 | nut x 5
error: no order 99
  • Verdict: idiom. The physical views hold all the SQL. AccessLayer is the logical layer, with the start and commit of a transaction and a cache of the views read in it. invoice is the application kernel and has no SQL.
  • AccessError replaces the empty result of the database, so the kernel does not depend on how SQLite reports a missing row.
  • The two physical views read the same logical order from two table layouts. Only the class given to AccessLayer changes.
JavaGitHub
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;

public class Main {
    // The error that the application kernel sees, whatever the database says.
    static class AccessError extends RuntimeException {
        AccessError(String m) { super(m); }
    }

    // ---- Physical access layer: knows the tables. ----

    // The example has no database: Database holds tables as lists of rows.
    static class Database {
        final Map<String, List<Map<String, Object>>> tables = new LinkedHashMap<>();

        List<Map<String, Object>> rows(String table) { return tables.get(table); }

        void insert(String table, Object... kv) {
            Map<String, Object> row = new LinkedHashMap<>();
            for (int i = 0; i < kv.length; i += 2) row.put((String) kv[i], kv[i + 1]);
            tables.computeIfAbsent(table, t -> new ArrayList<>()).add(row);
        }

        void commit() {}
    }

    static Database normalized() {
        Database db = new Database();
        db.insert("customer", "id", 1, "name", "Acme Ltd");
        db.insert("orders", "id", 10, "customer_id", 1);
        db.insert("order_line", "order_id", 10, "item", "bolt", "qty", 2);
        db.insert("order_line", "order_id", 10, "item", "nut", "qty", 5);
        return db;
    }

    // After tuning: the customer name is copied into the orders table.
    static Database denormalized() {
        Database db = new Database();
        db.insert("orders", "id", 10, "customer_name", "Acme Ltd");
        db.insert("order_line", "order_id", 10, "item", "bolt", "qty", 2);
        db.insert("order_line", "order_id", 10, "item", "nut", "qty", 5);
        return db;
    }

    record Read(String customer, Map<String, Integer> lines) {}

    // The protocol of a physical view of orders: read an order, write a line.
    abstract static class OrderView {
        final Database db;

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

        abstract String tables();

        abstract Read read(int orderId);

        Map<String, Integer> lines(int orderId) {
            Map<String, Integer> lines = new TreeMap<>();
            for (Map<String, Object> r : db.rows("order_line")) {
                if (r.get("order_id").equals(orderId)) lines.put((String) r.get("item"), (Integer) r.get("qty"));
            }
            return lines;
        }

        void writeLine(int orderId, String item, int qty) {
            for (Map<String, Object> r : db.rows("order_line")) {
                if (r.get("order_id").equals(orderId) && r.get("item").equals(item)) r.put("qty", qty);
            }
        }
    }

    // Reads an order from the normalized tables.
    static class NormalizedOrderView extends OrderView {
        NormalizedOrderView(Database db) { super(db); }

        String tables() { return "customer, orders, order_line"; }

        Read read(int orderId) {
            for (Map<String, Object> o : db.rows("orders")) {
                if (!o.get("id").equals(orderId)) continue;
                for (Map<String, Object> c : db.rows("customer")) {
                    if (c.get("id").equals(o.get("customer_id"))) return new Read((String) c.get("name"), lines(orderId));
                }
            }
            return null;
        }
    }

    // Reads an order from the tuned tables: one table less to read.
    static class DenormalizedOrderView extends OrderView {
        DenormalizedOrderView(Database db) { super(db); }

        String tables() { return "orders, order_line"; }

        Read read(int orderId) {
            for (Map<String, Object> o : db.rows("orders")) {
                if (o.get("id").equals(orderId)) return new Read((String) o.get("customer_name"), lines(orderId));
            }
            return null;
        }
    }

    // ---- Logical access layer: the interface of the application kernel. ----

    // The logical view of an order. It knows nothing of tables.
    static class Order {
        final int id;
        final String customer;
        final Map<String, Integer> lines;
        final TreeSet<String> changed = new TreeSet<>();

        Order(int id, String customer, Map<String, Integer> lines) {
            this.id = id;
            this.customer = customer;
            this.lines = new TreeMap<>(lines);
        }

        void setQty(String item, int qty) {
            lines.put(item, qty);
            changed.add(item);
        }
    }

    static class AccessLayer {
        final OrderView physical;
        Map<Integer, Order> cache = new LinkedHashMap<>();
        int reads;

        AccessLayer(OrderView physical) { this.physical = physical; }

        void start() {
            cache = new LinkedHashMap<>();
            reads = 0;
        }

        Order getOrder(int orderId) {
            if (!cache.containsKey(orderId)) {
                Read r = physical.read(orderId);
                reads++;
                if (r == null) throw new AccessError("no order " + orderId);
                cache.put(orderId, new Order(orderId, r.customer(), r.lines()));
            }
            return cache.get(orderId);
        }

        List<String> commit() {
            List<String> written = new ArrayList<>();
            for (Order o : cache.values()) {
                for (String item : o.changed) {
                    physical.writeLine(o.id, item, o.lines.get(item));
                    written.add("order " + o.id + " " + item + " x " + o.lines.get(item));
                }
                o.changed.clear();
            }
            physical.db.commit();
            return written;
        }
    }

    // ---- Application kernel: uses only the logical access layer. ----

    static String invoice(AccessLayer layer, int orderId) {
        Order o = layer.getOrder(orderId);
        List<String> parts = new ArrayList<>(List.of(o.customer));
        o.lines.forEach((item, qty) -> parts.add(item + " x " + qty));
        return String.join(" | ", parts);
    }

    static void run(String name, OrderView view) {
        AccessLayer layer = new AccessLayer(view);
        System.out.println("physical layout: " + name);
        layer.start();
        System.out.println("invoice 10: " + invoice(layer, 10));
        System.out.println("invoice 10: " + invoice(layer, 10));
        System.out.println("physical reads: " + layer.reads + ", tables " + view.tables());
        layer.getOrder(10).setQty("bolt", 3);
        System.out.println("commit: " + String.join(", ", layer.commit()));
        layer.start();
        System.out.println("invoice 10 in a new transaction: " + invoice(layer, 10));
        try {
            invoice(layer, 99);
        } catch (AccessError e) {
            System.out.println("error: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        run("normalized", new NormalizedOrderView(normalized()));
        run("denormalized", new DenormalizedOrderView(denormalized()));
    }
}
Output
physical layout: normalized
invoice 10: Acme Ltd | bolt x 2 | nut x 5
invoice 10: Acme Ltd | bolt x 2 | nut x 5
physical reads: 1, tables customer, orders, order_line
commit: order 10 bolt x 3
invoice 10 in a new transaction: Acme Ltd | bolt x 3 | nut x 5
error: no order 99
physical layout: denormalized
invoice 10: Acme Ltd | bolt x 2 | nut x 5
invoice 10: Acme Ltd | bolt x 2 | nut x 5
physical reads: 1, tables orders, order_line
commit: order 10 bolt x 3
invoice 10 in a new transaction: Acme Ltd | bolt x 3 | nut x 5
error: no order 99
  • Verdict: idiom. OrderView is an abstract class with the shared line access, and each layout is a subclass. In a JDBC application, the physical views would hold the PreparedStatement code, and Database would hold the Connection.
  • AccessError is an unchecked exception, as Spring's DataAccessException is.
JavaScriptGitHub
// The error that the application kernel sees, whatever the database says.
class AccessError extends Error {}

// ---- Physical access layer: knows the tables. ----

// The example has no database: Database holds tables as arrays of rows.
class Database {
  constructor(tables) {
    this.tables = tables;
  }
  rows(table) {
    return this.tables[table];
  }
  commit() {}
}

const normalized = () =>
  new Database({
    customer: [{ id: 1, name: "Acme Ltd" }],
    orders: [{ id: 10, customer_id: 1 }],
    order_line: [{ order_id: 10, item: "bolt", qty: 2 }, { order_id: 10, item: "nut", qty: 5 }],
  });

// After tuning: the customer name is copied into the orders table.
const denormalized = () =>
  new Database({
    orders: [{ id: 10, customer_name: "Acme Ltd" }],
    order_line: [{ order_id: 10, item: "bolt", qty: 2 }, { order_id: 10, item: "nut", qty: 5 }],
  });

// The protocol of a physical view of orders: read an order, write a line.
class OrderView {
  constructor(db) {
    this.db = db;
  }
  lines(orderId) {
    return this.db.rows("order_line").filter((r) => r.order_id === orderId)
      .sort((a, b) => (a.item < b.item ? -1 : 1)).map((r) => [r.item, r.qty]);
  }
  writeLine(orderId, item, qty) {
    for (const r of this.db.rows("order_line")) {
      if (r.order_id === orderId && r.item === item) r.qty = qty;
    }
  }
}

// Reads an order from the normalized tables.
class NormalizedOrderView extends OrderView {
  static tables = "customer, orders, order_line";
  read(orderId) {
    const head = [];
    for (const o of this.db.rows("orders").filter((o) => o.id === orderId)) {
      for (const c of this.db.rows("customer").filter((c) => c.id === o.customer_id)) head.push([c.name]);
    }
    return [head, this.lines(orderId)];
  }
}

// Reads an order from the tuned tables: one table less to read.
class DenormalizedOrderView extends OrderView {
  static tables = "orders, order_line";
  read(orderId) {
    const head = this.db.rows("orders").filter((o) => o.id === orderId).map((o) => [o.customer_name]);
    return [head, this.lines(orderId)];
  }
}

// ---- Logical access layer: the interface of the application kernel. ----

// The logical view of an order. It knows nothing of tables.
class Order {
  constructor(id, customer, lines) {
    Object.assign(this, { id, customer, lines: new Map(lines), changed: new Set() });
  }
  setQty(item, qty) {
    this.lines.set(item, qty);
    this.changed.add(item);
  }
}

class AccessLayer {
  constructor(physical) {
    this.physical = physical;
    this.start();
  }
  start() {
    this.cache = new Map();
    this.reads = 0;
  }
  getOrder(orderId) {
    if (!this.cache.has(orderId)) {
      const [head, lines] = this.physical.read(orderId);
      this.reads += 1;
      if (head.length === 0) throw new AccessError(`no order ${orderId}`);
      this.cache.set(orderId, new Order(orderId, head[0][0], lines));
    }
    return this.cache.get(orderId);
  }
  commit() {
    const written = [];
    for (const order of this.cache.values()) {
      for (const item of [...order.changed].sort()) {
        this.physical.writeLine(order.id, item, order.lines.get(item));
        written.push(`order ${order.id} ${item} x ${order.lines.get(item)}`);
      }
      order.changed.clear();
    }
    this.physical.db.commit();
    return written;
  }
}

// ---- Application kernel: uses only the logical access layer. ----

function invoice(layer, orderId) {
  const o = layer.getOrder(orderId);
  const lines = [...o.lines].sort((a, b) => (a[0] < b[0] ? -1 : 1)).map(([item, qty]) => `${item} x ${qty}`);
  return [o.customer, ...lines].join(" | ");
}

function run(name, db, ViewClass) {
  const layer = new AccessLayer(new ViewClass(db));
  console.log("physical layout:", name);
  layer.start();
  console.log("invoice 10:", invoice(layer, 10));
  console.log("invoice 10:", invoice(layer, 10));
  console.log(`physical reads: ${layer.reads}, tables ${ViewClass.tables}`);
  layer.getOrder(10).setQty("bolt", 3);
  console.log("commit:", layer.commit().join(", "));
  layer.start();
  console.log("invoice 10 in a new transaction:", invoice(layer, 10));
  try {
    invoice(layer, 99);
  } catch (e) {
    if (!(e instanceof AccessError)) throw e;
    console.log("error:", e.message);
  }
}

run("normalized", normalized(), NormalizedOrderView);
run("denormalized", denormalized(), DenormalizedOrderView);
Output
physical layout: normalized
invoice 10: Acme Ltd | bolt x 2 | nut x 5
invoice 10: Acme Ltd | bolt x 2 | nut x 5
physical reads: 1, tables customer, orders, order_line
commit: order 10 bolt x 3
invoice 10 in a new transaction: Acme Ltd | bolt x 3 | nut x 5
error: no order 99
physical layout: denormalized
invoice 10: Acme Ltd | bolt x 2 | nut x 5
invoice 10: Acme Ltd | bolt x 2 | nut x 5
physical reads: 1, tables orders, order_line
commit: order 10 bolt x 3
invoice 10 in a new transaction: Acme Ltd | bolt x 3 | nut x 5
error: no order 99
  • Verdict: idiom. The example has no database, so Database holds the tables as arrays of rows, and the physical views do the joins in code. The layers and the output are the same as in the Python file, which runs SQL in SQLite.
  • AccessError is a subclass of Error, and the kernel catches only that class.
package main

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

// ErrAccess is the error that the application kernel sees, whatever the database says.
var ErrAccess = errors.New("access error")

// ---- Physical access layer: knows the tables. ----

type orderRow struct {
	ID         int
	CustomerID int
	Customer   string // used only in the tuned layout
}

type lineRow struct {
	OrderID int
	Item    string
	Qty     int
}

// Database holds the tables in memory; the example has no database.
type Database struct {
	customers map[int]string
	orders    []orderRow
	lines     []lineRow
}

func (db *Database) Commit() {}

func normalized() *Database {
	return &Database{
		customers: map[int]string{1: "Acme Ltd"},
		orders:    []orderRow{{ID: 10, CustomerID: 1}},
		lines:     []lineRow{{10, "bolt", 2}, {10, "nut", 5}},
	}
}

// After tuning: the customer name is copied into the orders table.
func denormalized() *Database {
	return &Database{
		orders: []orderRow{{ID: 10, Customer: "Acme Ltd"}},
		lines:  []lineRow{{10, "bolt", 2}, {10, "nut", 5}},
	}
}

// OrderView is the protocol of a physical view of orders: read an order, write a line.
type OrderView interface {
	Tables() string
	Read(orderID int) (customer string, lines map[string]int, found bool)
	WriteLine(orderID int, item string, qty int)
	DB() *Database
}

type lineAccess struct{ db *Database }

func (v lineAccess) DB() *Database { return v.db }

func (v lineAccess) lines(orderID int) map[string]int {
	out := map[string]int{}
	for _, r := range v.db.lines {
		if r.OrderID == orderID {
			out[r.Item] = r.Qty
		}
	}
	return out
}

func (v lineAccess) WriteLine(orderID int, item string, qty int) {
	for i, r := range v.db.lines {
		if r.OrderID == orderID && r.Item == item {
			v.db.lines[i].Qty = qty
		}
	}
}

// NormalizedOrderView reads an order from the normalized tables.
type NormalizedOrderView struct{ lineAccess }

func (NormalizedOrderView) Tables() string { return "customer, orders, order_line" }

func (v NormalizedOrderView) Read(orderID int) (string, map[string]int, bool) {
	for _, o := range v.db.orders {
		if o.ID == orderID {
			if name, ok := v.db.customers[o.CustomerID]; ok {
				return name, v.lines(orderID), true
			}
		}
	}
	return "", nil, false
}

// DenormalizedOrderView reads an order from the tuned tables: one table less to read.
type DenormalizedOrderView struct{ lineAccess }

func (DenormalizedOrderView) Tables() string { return "orders, order_line" }

func (v DenormalizedOrderView) Read(orderID int) (string, map[string]int, bool) {
	for _, o := range v.db.orders {
		if o.ID == orderID {
			return o.Customer, v.lines(orderID), true
		}
	}
	return "", nil, false
}

// ---- Logical access layer: the interface of the application kernel. ----

// Order is the logical view of an order. It knows nothing of tables.
type Order struct {
	ID       int
	Customer string
	Lines    map[string]int
	changed  map[string]bool
}

func (o *Order) SetQty(item string, qty int) {
	o.Lines[item] = qty
	o.changed[item] = true
}

type AccessLayer struct {
	physical OrderView
	cache    map[int]*Order
	order    []int
	reads    int
}

func (l *AccessLayer) Start() {
	l.cache, l.order, l.reads = map[int]*Order{}, nil, 0
}

func (l *AccessLayer) GetOrder(orderID int) (*Order, error) {
	if o, ok := l.cache[orderID]; ok {
		return o, nil
	}
	customer, lines, found := l.physical.Read(orderID)
	l.reads++
	if !found {
		return nil, fmt.Errorf("%w: no order %d", ErrAccess, orderID)
	}
	o := &Order{orderID, customer, lines, map[string]bool{}}
	l.cache[orderID] = o
	l.order = append(l.order, orderID)
	return o, nil
}

func (l *AccessLayer) Commit() []string {
	var written []string
	for _, id := range l.order {
		o := l.cache[id]
		for _, item := range sortedKeys(o.changed) {
			l.physical.WriteLine(o.ID, item, o.Lines[item])
			written = append(written, fmt.Sprintf("order %d %s x %d", o.ID, item, o.Lines[item]))
		}
		o.changed = map[string]bool{}
	}
	l.physical.DB().Commit()
	return written
}

func sortedKeys[V any](m map[string]V) []string {
	var keys []string
	for k := range m {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	return keys
}

// ---- Application kernel: uses only the logical access layer. ----

func invoice(l *AccessLayer, orderID int) (string, error) {
	o, err := l.GetOrder(orderID)
	if err != nil {
		return "", err
	}
	parts := []string{o.Customer}
	for _, item := range sortedKeys(o.Lines) {
		parts = append(parts, fmt.Sprintf("%s x %d", item, o.Lines[item]))
	}
	return strings.Join(parts, " | "), nil
}

func run(name string, view OrderView) {
	l := &AccessLayer{physical: view}
	fmt.Println("physical layout:", name)
	l.Start()
	s, _ := invoice(l, 10)
	fmt.Println("invoice 10:", s)
	s, _ = invoice(l, 10)
	fmt.Println("invoice 10:", s)
	fmt.Printf("physical reads: %d, tables %s\n", l.reads, view.Tables())
	o, _ := l.GetOrder(10)
	o.SetQty("bolt", 3)
	fmt.Println("commit:", strings.Join(l.Commit(), ", "))
	l.Start()
	s, _ = invoice(l, 10)
	fmt.Println("invoice 10 in a new transaction:", s)
	if _, err := invoice(l, 99); errors.Is(err, ErrAccess) {
		fmt.Println("error:", strings.TrimPrefix(err.Error(), "access error: "))
	}
}

func main() {
	run("normalized", NormalizedOrderView{lineAccess{normalized()}})
	run("denormalized", DenormalizedOrderView{lineAccess{denormalized()}})
}
Output
physical layout: normalized
invoice 10: Acme Ltd | bolt x 2 | nut x 5
invoice 10: Acme Ltd | bolt x 2 | nut x 5
physical reads: 1, tables customer, orders, order_line
commit: order 10 bolt x 3
invoice 10 in a new transaction: Acme Ltd | bolt x 3 | nut x 5
error: no order 99
physical layout: denormalized
invoice 10: Acme Ltd | bolt x 2 | nut x 5
invoice 10: Acme Ltd | bolt x 2 | nut x 5
physical reads: 1, tables orders, order_line
commit: order 10 bolt x 3
invoice 10 in a new transaction: Acme Ltd | bolt x 3 | nut x 5
error: no order 99
  • Verdict: idiom. OrderView is an interface, and both views embed lineAccess for the shared methods. The logical layer wraps the error with %w, so the kernel tests it with errors.Is.
  • The cache keeps a slice of keys next to the map, because the order of a Go map is not fixed and the commit must write in a fixed order.
RustGitHub
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fmt;

// The error that the application kernel sees, whatever the database says.
#[derive(Debug)]
struct AccessError(String);

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

// ---- Physical access layer: knows the tables. ----

struct LineRow {
    order_id: u32,
    item: &'static str,
    qty: u32,
}

// The example has no database: Database holds the tables in memory.
struct Database {
    customers: HashMap<u32, &'static str>,
    // order id to customer id (normalized) or to customer name (tuned)
    orders_by_customer_id: HashMap<u32, u32>,
    orders_with_name: HashMap<u32, &'static str>,
    lines: Vec<LineRow>,
}

impl Database {
    fn commit(&mut self) {}
}

fn lines() -> Vec<LineRow> {
    vec![LineRow { order_id: 10, item: "bolt", qty: 2 }, LineRow { order_id: 10, item: "nut", qty: 5 }]
}

fn normalized() -> Database {
    Database {
        customers: HashMap::from([(1, "Acme Ltd")]),
        orders_by_customer_id: HashMap::from([(10, 1)]),
        orders_with_name: HashMap::new(),
        lines: lines(),
    }
}

// After tuning: the customer name is copied into the orders table.
fn denormalized() -> Database {
    Database {
        customers: HashMap::new(),
        orders_by_customer_id: HashMap::new(),
        orders_with_name: HashMap::from([(10, "Acme Ltd")]),
        lines: lines(),
    }
}

// The protocol of a physical view of orders: read an order, write a line.
trait OrderView {
    fn db(&mut self) -> &mut Database;
    fn tables(&self) -> &'static str;
    fn read(&mut self, order_id: u32) -> Option<(String, BTreeMap<String, u32>)>;

    fn lines(&mut self, order_id: u32) -> BTreeMap<String, u32> {
        self.db().lines.iter().filter(|r| r.order_id == order_id).map(|r| (r.item.to_string(), r.qty)).collect()
    }

    fn write_line(&mut self, order_id: u32, item: &str, qty: u32) {
        for r in self.db().lines.iter_mut().filter(|r| r.order_id == order_id && r.item == item) {
            r.qty = qty;
        }
    }
}

// Reads an order from the normalized tables.
struct NormalizedOrderView(Database);

impl OrderView for NormalizedOrderView {
    fn db(&mut self) -> &mut Database {
        &mut self.0
    }
    fn tables(&self) -> &'static str {
        "customer, orders, order_line"
    }
    fn read(&mut self, order_id: u32) -> Option<(String, BTreeMap<String, u32>)> {
        let customer_id = *self.0.orders_by_customer_id.get(&order_id)?;
        let name = self.0.customers.get(&customer_id)?.to_string();
        Some((name, self.lines(order_id)))
    }
}

// Reads an order from the tuned tables: one table less to read.
struct DenormalizedOrderView(Database);

impl OrderView for DenormalizedOrderView {
    fn db(&mut self) -> &mut Database {
        &mut self.0
    }
    fn tables(&self) -> &'static str {
        "orders, order_line"
    }
    fn read(&mut self, order_id: u32) -> Option<(String, BTreeMap<String, u32>)> {
        let name = self.0.orders_with_name.get(&order_id)?.to_string();
        Some((name, self.lines(order_id)))
    }
}

// ---- Logical access layer: the interface of the application kernel. ----

// The logical view of an order. It knows nothing of tables.
struct Order {
    id: u32,
    customer: String,
    lines: BTreeMap<String, u32>,
    changed: BTreeSet<String>,
}

impl Order {
    fn set_qty(&mut self, item: &str, qty: u32) {
        self.lines.insert(item.to_string(), qty);
        self.changed.insert(item.to_string());
    }
}

struct AccessLayer {
    physical: Box<dyn OrderView>,
    cache: BTreeMap<u32, Order>,
    reads: u32,
}

impl AccessLayer {
    fn start(&mut self) {
        self.cache.clear();
        self.reads = 0;
    }

    fn get_order(&mut self, order_id: u32) -> Result<&mut Order, AccessError> {
        if !self.cache.contains_key(&order_id) {
            self.reads += 1;
            let (customer, lines) =
                self.physical.read(order_id).ok_or_else(|| AccessError(format!("no order {}", order_id)))?;
            self.cache.insert(order_id, Order { id: order_id, customer, lines, changed: BTreeSet::new() });
        }
        Ok(self.cache.get_mut(&order_id).unwrap())
    }

    fn commit(&mut self) -> Vec<String> {
        let mut written = Vec::new();
        for order in self.cache.values_mut() {
            for item in &order.changed {
                let qty = order.lines[item];
                self.physical.write_line(order.id, item, qty);
                written.push(format!("order {} {} x {}", order.id, item, qty));
            }
            order.changed.clear();
        }
        self.physical.db().commit();
        written
    }
}

// ---- Application kernel: uses only the logical access layer. ----

fn invoice(layer: &mut AccessLayer, order_id: u32) -> Result<String, AccessError> {
    let o = layer.get_order(order_id)?;
    let mut parts = vec![o.customer.clone()];
    for (item, qty) in &o.lines {
        parts.push(format!("{} x {}", item, qty));
    }
    Ok(parts.join(" | "))
}

fn run(name: &str, view: Box<dyn OrderView>) {
    let tables = view.tables();
    let mut layer = AccessLayer { physical: view, cache: BTreeMap::new(), reads: 0 };
    println!("physical layout: {}", name);
    layer.start();
    println!("invoice 10: {}", invoice(&mut layer, 10).unwrap());
    println!("invoice 10: {}", invoice(&mut layer, 10).unwrap());
    println!("physical reads: {}, tables {}", layer.reads, tables);
    layer.get_order(10).unwrap().set_qty("bolt", 3);
    println!("commit: {}", layer.commit().join(", "));
    layer.start();
    println!("invoice 10 in a new transaction: {}", invoice(&mut layer, 10).unwrap());
    if let Err(e) = invoice(&mut layer, 99) {
        println!("error: {}", e);
    }
}

fn main() {
    run("normalized", Box::new(NormalizedOrderView(normalized())));
    run("denormalized", Box::new(DenormalizedOrderView(denormalized())));
}
Output
physical layout: normalized
invoice 10: Acme Ltd | bolt x 2 | nut x 5
invoice 10: Acme Ltd | bolt x 2 | nut x 5
physical reads: 1, tables customer, orders, order_line
commit: order 10 bolt x 3
invoice 10 in a new transaction: Acme Ltd | bolt x 3 | nut x 5
error: no order 99
physical layout: denormalized
invoice 10: Acme Ltd | bolt x 2 | nut x 5
invoice 10: Acme Ltd | bolt x 2 | nut x 5
physical reads: 1, tables orders, order_line
commit: order 10 bolt x 3
invoice 10 in a new transaction: Acme Ltd | bolt x 3 | nut x 5
error: no order 99
  • Verdict: idiom. OrderView is a trait with default methods for the shared line access, and the logical layer holds a Box<dyn OrderView>. read returns an Option, and the logical layer turns None into an AccessError.
  • BTreeMap and BTreeSet keep the lines and the changed items in order, so the output is the same on each run.

Consequences

Benefits.

  • Separation of concerns. "The access layer forms a well-encapsulated subsystem for transactions, database access and caching."1
  • The database can be tuned. Keller and Coldewey note that the application code stays the same while the physical database is changed for tuning.1 In the examples, the change to the tables changes one class.
  • Legacy data can be moved in steps. The layer is put in first, and then the database and the application are rewritten in separate projects.1
  • Fewer reads. The cache of the transaction reads each view once.

Liabilities.

Writes that go around the layer make the cache wrong. Keller and Coldewey warn that mass updates, of the form "update .. where", are "hard to integrate" with the view cache, and that stored procedures and triggers that change data "may cause cache consistency problems".1 In the following program, a mass update goes to the database directly, and the layer still gives the old value from its cache.

This code runs but gives a wrong answer on purpose.

import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
create table order_line (order_id integer, item text, qty integer);
insert into order_line values (10, 'bolt', 2);
""")

cache = {}


def get_qty(order_id, item):
    # The logical access layer keeps each line that it read in a cache.
    if (order_id, item) not in cache:
        sql = "select qty from order_line where order_id = ? and item = ?"
        cache[(order_id, item)] = db.execute(sql, (order_id, item)).fetchone()[0]
    return cache[(order_id, item)]


print("before:", get_qty(10, "bolt"))
# Wrong: a mass update goes to the database directly, not through the layer.
db.execute("update order_line set qty = qty + 1 where item = 'bolt'")
print("in the database:", db.execute("select qty from order_line").fetchone()[0])
print("from the layer:", get_qty(10, "bolt"))
Output
before: 2
in the database: 3
from the layer: 2

Effort. Keller and Coldewey give a range of "0,5 to 35 person years" to build such a layer, depending on the features: generators and hard-wired connections are cheap, and a query broker with tools is expensive.1

The kernel sees relational data. The relational form of the layer is not an object model. "The access layer does not transform the relational model to an object-oriented view."1 For a rich domain model, an object-relational layer with a Data Mapper fits better.

One more level of calls. Each access goes through two layers. Keller and Coldewey call the run-time cost minor, compared with the time of the database.1

When not to use it

When a framework already gives the layer. An ORM or a database toolkit is a database access layer: it has a logical part, the session and the mapped classes, and a physical part for each database product. Write the application against it, and do not add a second layer of the same kind on top.

For a small program with one database and no tuning. A few functions with SQL, or a Table Data Gateway, are enough.

Without the cache. For simple dialogs that change one record in each transaction, the view cache can be left out.1

Over non-relational storage. The physical access layer can also hide databases and file formats that are not relational, such as IMS-DB, CODASYL or VSAM, and so give access to legacy data.1

With an object view. The layer can give the kernel objects in place of relational views. Then the logical layer holds the object-relational mapping, with a Data Mapper, an Identity Map and a Unit of Work.

Related patterns. "The pattern is an application of Layers".1 The Data access object objects of an application together form a database access layer, and a Query Object is one form of the query broker. In POSA4, Data Mapper, Row Data Gateway, Table Data Gateway and Active Record are ways to design the layer.2 The view cache of a transaction is close to an Identity Map, and its commit is close to a Unit of Work.

Known uses

  • Keller and Coldewey list the VAA Data Manager specification of the German insurance industry, and projects at sd&m for Thyssen, Deutsche Bahn and HYPO Bank.1
  • SQLAlchemy: the ORM and the SQL expression language are the logical part, and each dialect is a physical part. "The dialect is the system SQLAlchemy uses to communicate with various types of DBAPI implementations and databases."3
  • Django: the ORM is the same for each database, and a backend for each database product does the physical work. "Django attempts to support as many features as possible on all database backends."4

References

  1. Wolfgang Keller and Jens Coldewey, Relational Database Access Layers, A Pattern Language, The Key Patterns, sd&m, 1996, Pattern Relational Database Access Layer; Context; Problem; Forces; Solution; Participants; Implementation; Consequences; Variants; Known Uses
  2. Frank Buschmann, Kevlin Henney and Douglas C. Schmidt, Pattern-Oriented Software Architecture, Volume 4, A Pattern Language for Distributed Computing, Wiley, 2007, Chapter 21, Database Access, Database Access Layer, page 538
  3. SQLAlchemy 2.0 documentation, Dialects, introduction
  4. Django 5.2 documentation, Databases, introduction

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