Programming Search⌘K

Patterncore

Transaction script

Also called Transaction Script, transaction script pattern, script per request.

A transaction script puts the business logic of one request in one procedure, which reads the database, makes the checks and calculations, and writes the result.

Family
architectural
Intent
Organize business logic by procedures where each procedure handles a single request from the presentation.

Intent

A transaction script "Organizes business logic by procedures where each procedure handles a single request from the presentation."1 There is one script for each thing that a user can do, such as place an order, cancel a booking or show a report. Fowler gives the pattern as the simplest of three ways to organize the domain logic of an Enterprise application. The other two are Domain model and Table module.12

Problem

An application gets requests from its users. Fowler: "Most business applications can be thought of as a series of transactions."1 Each request needs some logic, and the amount varies: "In some cases this can be as simple as displaying information in the database. In others it may involve many steps of validations and calculations."1 The question is where to put that logic.

For a small application with simple rules, a design with many classes costs more than it gives. The developers want code that is easy to read from top to bottom, that maps directly to the requests, and that needs no mapping layer between objects and tables.

Solution

"A Transaction Script organizes all this logic primarily as a single procedure, making calls directly to the database or through a thin database wrapper. Each transaction will have its own Transaction Script, although common subtasks can be broken into subprocedures."1

The parts are:

  • The script. One procedure for one request. It reads the data, checks it, calculates, and writes the result.
  • The database transaction. The script usually runs in one database transaction, so the request succeeds or fails as a whole.
  • Shared subprocedures. Helpers for the steps that many scripts need, such as a format for money or a check of a customer.
  • A thin data wrapper. Optional. A Table Data Gateway or a Row Data Gateway can hold the SQL, so the scripts do not repeat it.
  presentation      place order      show total      cancel order
                         |                |                |
  scripts          place_order()    order_total()   cancel_order()
                         |                |                |
  data access       SQL, or a thin gateway over the tables

The following program has one script. It transfers money between two accounts in one transaction and refuses a transfer that the balance does not cover.

import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
create table account (id integer primary key, balance integer);
insert into account values (1, 100), (2, 0);
""")


# One procedure for one request: it checks, calculates and writes the database.
def transfer(source, target, amount):
    with db:  # the script runs in one database transaction
        (balance,) = db.execute("select balance from account where id = ?", (source,)).fetchone()
        if balance < amount:
            return "refused: balance too low"
        db.execute("update account set balance = balance - ? where id = ?", (amount, source))
        db.execute("update account set balance = balance + ? where id = ?", (amount, target))
    return "done"


print(transfer(1, 2, 30), transfer(1, 2, 90))
print(db.execute("select balance from account order by id").fetchall())
Output
done refused: balance too low
[(70,), (30,)]

Example

Each example file is a small shop with two scripts. place_order checks the customer, the products and the quantities, and then writes the order and its lines. order_total adds the lines and applies the discount rule: a gold customer gets 10 percent off an order of 100.00 or more. The program places two orders, shows their totals, and then tries two orders that are not correct. The last line shows that the failed scripts wrote nothing. The Python file uses SQLite and a database transaction; the other files keep the tables in memory.

PythonGitHub
import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
create table customer (id integer primary key, name text, tier text);
create table product (id integer primary key, name text, price_cents integer);
create table orders (id integer primary key, customer_id integer);
create table order_line (order_id integer, product_id integer, qty integer);
insert into customer values (1, 'Ann', 'gold'), (2, 'Bob', 'regular');
insert into product values (1, 'lamp', 2500), (2, 'desk', 7500), (3, 'pen', 500);
""")


class ScriptError(Exception):
    pass


def cents(n):
    return f"{n // 100}.{n % 100:02d}"


# Transaction script 1: place an order.
def place_order(customer_id, items):
    with db:  # one database transaction for the whole script
        row = db.execute("select name from customer where id = ?", (customer_id,)).fetchone()
        if row is None:
            raise ScriptError(f"no customer {customer_id}")
        for product_id, qty in items:
            if qty <= 0:
                raise ScriptError(f"bad quantity {qty}")
            if db.execute("select 1 from product where id = ?", (product_id,)).fetchone() is None:
                raise ScriptError(f"no product {product_id}")
        order_id = db.execute("insert into orders (customer_id) values (?)", (customer_id,)).lastrowid
        db.executemany(
            "insert into order_line values (?, ?, ?)",
            [(order_id, p, q) for p, q in items],
        )
    return order_id, row[0]


# Transaction script 2: show the total of an order.
def order_total(order_id):
    row = db.execute(
        """select c.tier, sum(l.qty * p.price_cents)
           from orders o join customer c on c.id = o.customer_id
           join order_line l on l.order_id = o.id join product p on p.id = l.product_id
           where o.id = ?""",
        (order_id,),
    ).fetchone()
    if row[1] is None:
        raise ScriptError(f"no order {order_id}")
    tier, subtotal = row
    total = subtotal
    if tier == "gold" and subtotal >= 10000:
        total = subtotal - subtotal // 10
    return subtotal, total


for customer_id, items in [(1, [(1, 2), (2, 1)]), (2, [(1, 1), (3, 3)])]:
    order_id, name = place_order(customer_id, items)
    print(f"placed order {order_id} for {name}")
for order_id in (1, 2):
    subtotal, total = order_total(order_id)
    print(f"order {order_id}: subtotal {cents(subtotal)}, total {cents(total)}")
for customer_id, items in [(1, [(9, 1)]), (2, [(1, 0)])]:
    try:
        place_order(customer_id, items)
    except ScriptError as e:
        print("error:", e)
print("orders in the database:", db.execute("select count(*) from orders").fetchone()[0])
Output
placed order 1 for Ann
placed order 2 for Bob
order 1: subtotal 125.00, total 112.50
order 2: subtotal 40.00, total 40.00
error: no product 9
error: bad quantity 0
orders in the database: 2
  • Verdict: idiom. Each script is a plain function. place_order runs in one transaction with with db:, so an error in the middle writes nothing. order_total does the calculation in one SQL query with a join and a sum, and then applies the discount rule in Python.
  • The scripts share the helper cents and the exception ScriptError. Shared subtasks of this kind are normal in a transaction script design.
JavaGitHub
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Main {
    record Customer(String name, String tier) {}
    record Product(String name, long priceCents) {}
    record OrderLine(int orderId, int productId, int qty) {}

    // The tables of the database, kept in memory for this example.
    static final Map<Integer, Customer> customer = new LinkedHashMap<>();
    static final Map<Integer, Product> product = new LinkedHashMap<>();
    static final Map<Integer, Integer> orders = new LinkedHashMap<>(); // order id to customer id
    static final List<OrderLine> orderLine = new ArrayList<>();
    static int nextOrderId = 1;

    static class ScriptError extends RuntimeException {
        ScriptError(String message) { super(message); }
    }

    static String cents(long n) {
        return String.format("%d.%02d", n / 100, n % 100);
    }

    // Transaction script 1: place an order. Each item is {productId, qty}.
    static int placeOrder(int customerId, int[][] items) {
        if (!customer.containsKey(customerId)) {
            throw new ScriptError("no customer " + customerId);
        }
        // Check everything first, so that a failed script writes nothing.
        for (int[] item : items) {
            if (item[1] <= 0) throw new ScriptError("bad quantity " + item[1]);
            if (!product.containsKey(item[0])) throw new ScriptError("no product " + item[0]);
        }
        int orderId = nextOrderId++;
        orders.put(orderId, customerId);
        for (int[] item : items) orderLine.add(new OrderLine(orderId, item[0], item[1]));
        return orderId;
    }

    // Transaction script 2: show the total of an order. Returns {subtotal, total}.
    static long[] orderTotal(int orderId) {
        Integer customerId = orders.get(orderId);
        if (customerId == null) throw new ScriptError("no order " + orderId);
        String tier = customer.get(customerId).tier();
        long subtotal = 0;
        for (OrderLine line : orderLine) {
            if (line.orderId() == orderId) subtotal += line.qty() * product.get(line.productId()).priceCents();
        }
        long total = subtotal;
        if (tier.equals("gold") && subtotal >= 10000) total = subtotal - subtotal / 10;
        return new long[] {subtotal, total};
    }

    public static void main(String[] args) {
        customer.put(1, new Customer("Ann", "gold"));
        customer.put(2, new Customer("Bob", "regular"));
        product.put(1, new Product("lamp", 2500));
        product.put(2, new Product("desk", 7500));
        product.put(3, new Product("pen", 500));

        int a = placeOrder(1, new int[][] {{1, 2}, {2, 1}});
        System.out.println("placed order " + a + " for " + customer.get(1).name());
        int b = placeOrder(2, new int[][] {{1, 1}, {3, 3}});
        System.out.println("placed order " + b + " for " + customer.get(2).name());
        for (int orderId : new int[] {1, 2}) {
            long[] t = orderTotal(orderId);
            System.out.println("order " + orderId + ": subtotal " + cents(t[0]) + ", total " + cents(t[1]));
        }
        int[][][] bad = {{{9, 1}}, {{1, 0}}};
        int[] who = {1, 2};
        for (int i = 0; i < bad.length; i++) {
            try {
                placeOrder(who[i], bad[i]);
            } catch (ScriptError e) {
                System.out.println("error: " + e.getMessage());
            }
        }
        System.out.println("orders in the database: " + orders.size());
    }
}
Output
placed order 1 for Ann
placed order 2 for Bob
order 1: subtotal 125.00, total 112.50
order 2: subtotal 40.00, total 40.00
error: no product 9
error: bad quantity 0
orders in the database: 2
  • Verdict: idiom. Each script is a static method. In a Java application, a script of this kind is often a method of a class with one method for each request, and the method runs in one JDBC or JPA transaction.
  • ScriptError is unchecked, so the scripts do not declare it, and the caller catches it where it can report the error to the user.
JavaScriptGitHub
// The tables of the database, kept in memory for this example.
const db = {
  customer: new Map([[1, { name: "Ann", tier: "gold" }], [2, { name: "Bob", tier: "regular" }]]),
  product: new Map([[1, { name: "lamp", priceCents: 2500 }], [2, { name: "desk", priceCents: 7500 }], [3, { name: "pen", priceCents: 500 }]]),
  orders: new Map(),
  orderLine: [],
  nextOrderId: 1,
};

class ScriptError extends Error {}

const cents = (n) => `${Math.floor(n / 100)}.${String(n % 100).padStart(2, "0")}`;

// Transaction script 1: place an order.
function placeOrder(customerId, items) {
  const customer = db.customer.get(customerId);
  if (!customer) throw new ScriptError(`no customer ${customerId}`);
  // Check everything first, so that a failed script writes nothing.
  for (const [productId, qty] of items) {
    if (qty <= 0) throw new ScriptError(`bad quantity ${qty}`);
    if (!db.product.has(productId)) throw new ScriptError(`no product ${productId}`);
  }
  const orderId = db.nextOrderId++;
  db.orders.set(orderId, { customerId });
  for (const [productId, qty] of items) db.orderLine.push({ orderId, productId, qty });
  return [orderId, customer.name];
}

// Transaction script 2: show the total of an order.
function orderTotal(orderId) {
  const order = db.orders.get(orderId);
  if (!order) throw new ScriptError(`no order ${orderId}`);
  const tier = db.customer.get(order.customerId).tier;
  let subtotal = 0;
  for (const line of db.orderLine) {
    if (line.orderId === orderId) subtotal += line.qty * db.product.get(line.productId).priceCents;
  }
  let total = subtotal;
  if (tier === "gold" && subtotal >= 10000) total = subtotal - Math.floor(subtotal / 10);
  return [subtotal, total];
}

for (const [customerId, items] of [[1, [[1, 2], [2, 1]]], [2, [[1, 1], [3, 3]]]]) {
  const [orderId, name] = placeOrder(customerId, items);
  console.log(`placed order ${orderId} for ${name}`);
}
for (const orderId of [1, 2]) {
  const [subtotal, total] = orderTotal(orderId);
  console.log(`order ${orderId}: subtotal ${cents(subtotal)}, total ${cents(total)}`);
}
for (const [customerId, items] of [[1, [[9, 1]]], [2, [[1, 0]]]]) {
  try {
    placeOrder(customerId, items);
  } catch (e) {
    if (!(e instanceof ScriptError)) throw e;
    console.log("error:", e.message);
  }
}
console.log("orders in the database:", db.orders.size);
Output
placed order 1 for Ann
placed order 2 for Bob
order 1: subtotal 125.00, total 112.50
order 2: subtotal 40.00, total 40.00
error: no product 9
error: bad quantity 0
orders in the database: 2
  • Verdict: idiom. Each script is a function. The example has no database, so placeOrder checks all the items before it writes, and a failed script leaves the tables as they were. The Python file, with SQLite, gets the same result from a database transaction.
package main

import (
	"errors"
	"fmt"
)

type customer struct{ name, tier string }
type product struct {
	name       string
	priceCents int
}
type orderLine struct{ orderID, productID, qty int }

// The tables of the database, kept in memory for this example.
var (
	customers   = map[int]customer{1: {"Ann", "gold"}, 2: {"Bob", "regular"}}
	products    = map[int]product{1: {"lamp", 2500}, 2: {"desk", 7500}, 3: {"pen", 500}}
	orders      = map[int]int{} // order id to customer id
	orderLines  []orderLine
	nextOrderID = 1
)

// scriptError is the error of a script that the user can correct.
type scriptError struct{ msg string }

func (e *scriptError) Error() string { return e.msg }

func fail(format string, args ...any) error { return &scriptError{fmt.Sprintf(format, args...)} }

func cents(n int) string { return fmt.Sprintf("%d.%02d", n/100, n%100) }

// Transaction script 1: place an order. Each item is {productID, qty}.
func placeOrder(customerID int, items [][2]int) (int, string, error) {
	c, ok := customers[customerID]
	if !ok {
		return 0, "", fail("no customer %d", customerID)
	}
	// Check everything first, so that a failed script writes nothing.
	for _, it := range items {
		if it[1] <= 0 {
			return 0, "", fail("bad quantity %d", it[1])
		}
		if _, ok := products[it[0]]; !ok {
			return 0, "", fail("no product %d", it[0])
		}
	}
	id := nextOrderID
	nextOrderID++
	orders[id] = customerID
	for _, it := range items {
		orderLines = append(orderLines, orderLine{id, it[0], it[1]})
	}
	return id, c.name, nil
}

// Transaction script 2: show the total of an order.
func orderTotal(orderID int) (subtotal, total int, err error) {
	customerID, ok := orders[orderID]
	if !ok {
		return 0, 0, fail("no order %d", orderID)
	}
	tier := customers[customerID].tier
	for _, l := range orderLines {
		if l.orderID == orderID {
			subtotal += l.qty * products[l.productID].priceCents
		}
	}
	total = subtotal
	if tier == "gold" && subtotal >= 10000 {
		total = subtotal - subtotal/10
	}
	return subtotal, total, nil
}

func main() {
	for _, r := range []struct {
		customerID int
		items      [][2]int
	}{{1, [][2]int{{1, 2}, {2, 1}}}, {2, [][2]int{{1, 1}, {3, 3}}}} {
		id, name, _ := placeOrder(r.customerID, r.items)
		fmt.Printf("placed order %d for %s\n", id, name)
	}
	for _, id := range []int{1, 2} {
		s, t, _ := orderTotal(id)
		fmt.Printf("order %d: subtotal %s, total %s\n", id, cents(s), cents(t))
	}
	for _, r := range []struct {
		customerID int
		items      [][2]int
	}{{1, [][2]int{{9, 1}}}, {2, [][2]int{{1, 0}}}} {
		_, _, err := placeOrder(r.customerID, r.items)
		var se *scriptError
		if errors.As(err, &se) {
			fmt.Println("error:", se)
		}
	}
	fmt.Println("orders in the database:", len(orders))
}
Output
placed order 1 for Ann
placed order 2 for Bob
order 1: subtotal 125.00, total 112.50
order 2: subtotal 40.00, total 40.00
error: no product 9
error: bad quantity 0
orders in the database: 2
  • Verdict: idiom. Each script is a function that returns an error. scriptError marks the errors that the user can correct, and the caller finds them with errors.As. In a Go service, each script would take a *sql.Tx and run in one transaction.
RustGitHub
use std::collections::BTreeMap;
use std::fmt;

struct Customer {
    name: &'static str,
    tier: &'static str,
}

struct OrderLine {
    order_id: u32,
    product_id: u32,
    qty: i64,
}

// The tables of the database, kept in memory for this example.
struct Db {
    customer: BTreeMap<u32, Customer>,
    product: BTreeMap<u32, (&'static str, i64)>, // name and price in cents
    orders: BTreeMap<u32, u32>,                  // order id to customer id
    order_line: Vec<OrderLine>,
    next_order_id: u32,
}

#[derive(Debug)]
struct ScriptError(String);

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

fn cents(n: i64) -> String {
    format!("{}.{:02}", n / 100, n % 100)
}

// Transaction script 1: place an order. Each item is (product id, qty).
fn place_order(db: &mut Db, customer_id: u32, items: &[(u32, i64)]) -> Result<(u32, &'static str), ScriptError> {
    let name = match db.customer.get(&customer_id) {
        Some(c) => c.name,
        None => return Err(ScriptError(format!("no customer {}", customer_id))),
    };
    // Check everything first, so that a failed script writes nothing.
    for &(product_id, qty) in items {
        if qty <= 0 {
            return Err(ScriptError(format!("bad quantity {}", qty)));
        }
        if !db.product.contains_key(&product_id) {
            return Err(ScriptError(format!("no product {}", product_id)));
        }
    }
    let order_id = db.next_order_id;
    db.next_order_id += 1;
    db.orders.insert(order_id, customer_id);
    for &(product_id, qty) in items {
        db.order_line.push(OrderLine { order_id, product_id, qty });
    }
    Ok((order_id, name))
}

// Transaction script 2: show the total of an order.
fn order_total(db: &Db, order_id: u32) -> Result<(i64, i64), ScriptError> {
    let customer_id = db
        .orders
        .get(&order_id)
        .ok_or_else(|| ScriptError(format!("no order {}", order_id)))?;
    let tier = db.customer[customer_id].tier;
    let subtotal: i64 = db
        .order_line
        .iter()
        .filter(|l| l.order_id == order_id)
        .map(|l| l.qty * db.product[&l.product_id].1)
        .sum();
    let mut total = subtotal;
    if tier == "gold" && subtotal >= 10000 {
        total = subtotal - subtotal / 10;
    }
    Ok((subtotal, total))
}

fn main() {
    let mut db = Db {
        customer: BTreeMap::from([
            (1, Customer { name: "Ann", tier: "gold" }),
            (2, Customer { name: "Bob", tier: "regular" }),
        ]),
        product: BTreeMap::from([(1, ("lamp", 2500)), (2, ("desk", 7500)), (3, ("pen", 500))]),
        orders: BTreeMap::new(),
        order_line: Vec::new(),
        next_order_id: 1,
    };
    let good: [(u32, &[(u32, i64)]); 2] = [(1, &[(1, 2), (2, 1)]), (2, &[(1, 1), (3, 3)])];
    for (customer_id, items) in good {
        let (order_id, name) = place_order(&mut db, customer_id, items).unwrap();
        println!("placed order {} for {}", order_id, name);
    }
    for order_id in [1, 2] {
        let (subtotal, total) = order_total(&db, order_id).unwrap();
        println!("order {}: subtotal {}, total {}", order_id, cents(subtotal), cents(total));
    }
    let bad: [(u32, &[(u32, i64)]); 2] = [(1, &[(9, 1)]), (2, &[(1, 0)])];
    for (customer_id, items) in bad {
        if let Err(e) = place_order(&mut db, customer_id, items) {
            println!("error: {}", e);
        }
    }
    println!("orders in the database: {}", db.orders.len());
}
Output
placed order 1 for Ann
placed order 2 for Bob
order 1: subtotal 125.00, total 112.50
order 2: subtotal 40.00, total 40.00
error: no product 9
error: bad quantity 0
orders in the database: 2
  • Verdict: idiom. Each script is a function that returns a Result. place_order takes &mut Db, because it writes, and order_total takes &Db, because it only reads. The compiler checks that no script writes the tables while another script reads them.

Consequences

Benefits.

  • Simple. The pattern needs no knowledge of object design. A reader can follow a request from the start of its script to the end.
  • A direct map to the requests. Each script is one request, so it is easy to find the code for a request, and the transaction has clear limits.
  • Little mapping. The scripts work with rows. There is no layer that maps objects to tables, so the Object-relational impedance mismatch does not occur.
  • It works with the tools. Stored procedures are transaction scripts in the database. The PostgreSQL documentation says that PL/pgSQL can "group a block of computation and a series of queries inside the database server", and so saves "client/server communication overhead".3

Liabilities.

Rules are copied, and the copies drift apart. When two scripts need the same rule, the easy step is to copy it. Later, a change goes into one copy only. In the following program, the discount rule changed in the script for the order screen, but the script that prints the invoice still has the old rule, so the two give different totals for one order.

This code runs but gives a wrong answer on purpose.

import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
create table orders (id integer primary key, tier text, subtotal integer);
insert into orders values (1, 'gold', 80);
""")


def order_total(order_id):
    tier, subtotal = db.execute("select tier, subtotal from orders where id = ?", (order_id,)).fetchone()
    # The rule changed: gold customers now get 10% off from 50, not from 100.
    if tier == "gold" and subtotal >= 50:
        return subtotal - subtotal // 10
    return subtotal


def print_invoice(order_id):
    tier, subtotal = db.execute("select tier, subtotal from orders where id = ?", (order_id,)).fetchone()
    # Wrong: a copy of the old rule, which nobody remembered to change.
    total = subtotal - subtotal // 10 if tier == "gold" and subtotal >= 100 else subtotal
    return f"invoice 1: pay {total}"


print("order screen: total", order_total(1))
print(print_invoice(1))
Output
order screen: total 72
invoice 1: pay 80

Move each shared rule into one subprocedure, as the Don't repeat yourself principle asks. When there are many rules of this kind, move to a Domain model.

It does not scale with the complexity of the logic. The scripts are simple while the rules are simple. When the rules interact, each script gets long, and the logic of one concept, such as a customer type, is spread across many scripts.

When not to use it

When the domain logic is complex. Rules that depend on many cases are easier to keep in a Domain model, where polymorphism replaces the conditions. Fowler writes that a design that puts all the behavior into services ends up with transaction scripts, and so loses the advantages that a domain model can bring.4

When the same data has many rules. If many scripts work on the same tables with related rules, a Table module keeps these rules in one class for each table.

Script per command. Each script is a class with one method, which makes it a Command pattern. The presentation can then queue, log or undo the requests.

Several scripts in one class. Related scripts, such as all the scripts for orders, are methods of one class. This is a common form in Java and C#.

Stored procedures. The script runs in the database, in a language such as PL/pgSQL. This removes "Extra round trips between client and server",3 but it ties the logic to one database product.

Related patterns. Domain model and Table module are the other two ways to organize domain logic. A Service layer is often a set of transaction scripts over a domain model. An anemic domain model, with data and no behavior, is in fact a transaction script design.4

Known uses

  • Django view functions. "A view function, or view for short, is a Python function that takes a web request and returns a web response."5 When a view does the checks and the database calls itself, it is a transaction script for that request.
  • Stored procedures in PL/pgSQL, T-SQL and PL/SQL, which put the logic of one business operation in one procedure in the database.3
  • Batch jobs and CGI programs, where each program handles one kind of request from start to end.

References

  1. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Transaction Script, pattern summary
  2. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 9, Domain Logic Patterns, Transaction Script
  3. PostgreSQL 17 documentation, Overview of PL/pgSQL, Advantages of Using PL/pgSQL
  4. Martin Fowler, Anemic Domain Model, 25 November 2003, the whole post
  5. Django 5.2 documentation, Writing views, 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/AS1XQ1/text.yaml