Programming Search⌘K

Patternadvanced

Record set

Also called Record Set, recordset, data set, disconnected row set.

A record set is an in-memory table of rows and named columns that looks like the result of an SQL query, so other code and data-aware UI tools can read and change it.

Family
architectural
Intent
Keep tabular data in memory in the shape of the result of a query.

Intent

A record set is "An in-memory representation of tabular data."1 It has rows and named columns, in the same shape as the result of an SQL query. The program can fill it from a query or make it in code, and can then read it, change it and write the changes back.

Problem

Many tools build user interfaces for relational data with little code. The catalog says that these tools "make display and simple updates ridiculously easy", but that "they have no real facilities in which to place business logic".1 The rules then go into stored procedures or into the code of the UI.

The program needs a structure that the UI tools can use as if it were the result of a query, but that other code can also make, check and change.

Solution

The answer of the catalog is "an in-memory structure that looks exactly like the result of an SQL query but can be generated and manipulated by other parts of the system".1 The parts are:

  • The columns. Each column has a name and usually a type.
  • The rows. Each row has one value for each column. The code reads a value by the row and the name of the column.
  • The state of each row. A row can be unchanged, modified, added or deleted. The code that saves the record set writes only the rows that changed.
  • No open connection. The record set is filled while the connection is open, and is then used without it. It can be passed to the UI, to a Table module, or to another process.
  query --> RecordSet(columns: id, name, balance)
              row 0: 1 | Ann | 12000 | unchanged
              row 1: 2 | Bob |  2550 | modified
              row 2: 3 | Cy  |     0 | added
  UI and table module read and change it; a gateway writes the changed rows back

In the following program, cursor.description "provides the column names of the last query".2 The program keeps the names and the rows after the connection is closed.

import sqlite3

db = sqlite3.connect(":memory:")
db.execute("create table account (id integer, name text)")
db.execute("insert into account values (1, 'Ann'), (2, 'Bob')")
cursor = db.execute("select id, name from account order by id")
columns = [d[0] for d in cursor.description]  # the names of the columns of the result
rows = cursor.fetchall()
db.close()

record_set = [dict(zip(columns, row)) for row in rows]  # still usable with no connection
print(columns)
print(record_set)
Output
['id', 'name']
[{'id': 1, 'name': 'Ann'}, {'id': 2, 'name': 'Bob'}]

Example

Each example has a RecordSet with the columns id, name and balance, and two rows from a query of accounts. The Python example runs the query in an SQLite database in memory. The other examples start from the columns and rows that a database driver would give. The program adds 10.00 to the balance of Bob and adds a row for Cy. It prints each row with its state, finds the names of the rows with a balance over 20.00, and counts the rows that must be saved.

PythonGitHub
import sqlite3


class RecordSet:
    """Rows and named columns in memory, in the shape of the result of a query."""

    def __init__(self, columns, rows):
        self.columns = list(columns)
        self.rows = [list(r) for r in rows]
        self.states = ["unchanged"] * len(self.rows)

    @classmethod
    def from_cursor(cls, cursor):
        return cls([d[0] for d in cursor.description], cursor.fetchall())

    def get(self, i, column):
        return self.rows[i][self.columns.index(column)]

    def set(self, i, column, value):
        self.rows[i][self.columns.index(column)] = value
        if self.states[i] == "unchanged":
            self.states[i] = "modified"

    def add(self, *values):
        self.rows.append(list(values))
        self.states.append("added")

    def where(self, test):
        return [i for i in range(len(self.rows)) if test(lambda c: self.get(i, c))]


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


db = sqlite3.connect(":memory:")
db.execute("create table account (id integer, name text, balance integer)")
db.executemany("insert into account values (?, ?, ?)", [(1, "Ann", 12000), (2, "Bob", 1550)])
rs = RecordSet.from_cursor(db.execute("select id, name, balance from account order by id"))
db.close()  # the record set needs no connection from here on

print("columns:", ", ".join(rs.columns))
rs.set(1, "balance", rs.get(1, "balance") + 1000)
rs.add(3, "Cy", 0)
for i in range(len(rs.rows)):
    print(f"{rs.get(i, 'id')} | {rs.get(i, 'name')} | {money(rs.get(i, 'balance'))} | {rs.states[i]}")
rich = rs.where(lambda col: col("balance") > 2000)
print("balance over 20.00:", ", ".join(rs.get(i, "name") for i in rich))
print("rows to save:", sum(1 for s in rs.states if s != "unchanged"))
Output
columns: id, name, balance
1 | Ann | 120.00 | unchanged
2 | Bob | 25.50 | modified
3 | Cy | 0.00 | added
balance over 20.00: Ann, Bob
rows to save: 2
  • Verdict: stdlib. sqlite3 gives the rows of a query as tuples, and cursor.description gives the names of the columns. The RecordSet class keeps both in memory, so it works after the connection is closed.
  • The class marks each row as unchanged, modified or added, so the code that saves the record set knows which rows to write.
JavaGitHub
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {
    // Rows and named columns in memory, in the shape of the result of a query.
    static class RecordSet {
        final List<String> columns;
        final List<Object[]> rows = new ArrayList<>();
        final List<String> states = new ArrayList<>();

        RecordSet(List<String> columns, List<Object[]> loaded) {
            this.columns = List.copyOf(columns);
            for (Object[] r : loaded) {
                rows.add(r.clone());
                states.add("unchanged");
            }
        }

        Object get(int i, String column) { return rows.get(i)[columns.indexOf(column)]; }

        void set(int i, String column, Object value) {
            rows.get(i)[columns.indexOf(column)] = value;
            if (states.get(i).equals("unchanged")) states.set(i, "modified");
        }

        void add(Object... values) {
            rows.add(values);
            states.add("added");
        }

        List<Integer> where(Predicate<Function<String, Object>> test) {
            return IntStream.range(0, rows.size()).filter(i -> test.test(c -> get(i, c))).boxed().toList();
        }
    }

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

    public static void main(String[] args) {
        // The columns and rows as a JDBC ResultSet gives them for:
        // select id, name, balance from account order by id
        RecordSet rs = new RecordSet(List.of("id", "name", "balance"),
                Arrays.asList(new Object[] {1, "Ann", 12000L}, new Object[] {2, "Bob", 1550L}));

        System.out.println("columns: " + String.join(", ", rs.columns));
        rs.set(1, "balance", (Long) rs.get(1, "balance") + 1000);
        rs.add(3, "Cy", 0L);
        for (int i = 0; i < rs.rows.size(); i++) {
            System.out.println(rs.get(i, "id") + " | " + rs.get(i, "name") + " | "
                    + money((Long) rs.get(i, "balance")) + " | " + rs.states.get(i));
        }
        List<Integer> rich = rs.where(col -> (Long) col.apply("balance") > 2000);
        System.out.println("balance over 20.00: "
                + rich.stream().map(i -> (String) rs.get(i, "name")).collect(Collectors.joining(", ")));
        System.out.println("rows to save: " + rs.states.stream().filter(s -> !s.equals("unchanged")).count());
    }
}
Output
columns: id, name, balance
1 | Ann | 120.00 | unchanged
2 | Bob | 25.50 | modified
3 | Cy | 0.00 | added
balance over 20.00: Ann, Bob
rows to save: 2
  • Verdict: stdlib. javax.sql.rowset.CachedRowSet is a record set of the standard library: it keeps the rows of a ResultSet in memory and can write the changes back. This example writes a small class, because the test image has no database driver.
  • The cells are Object, so the code casts them, as JDBC code does with getObject.
JavaScriptGitHub
// Rows and named columns in memory, in the shape of the result of a query.
class RecordSet {
  constructor(columns, rows) {
    this.columns = [...columns];
    this.rows = rows.map((r) => [...r]);
    this.states = rows.map(() => "unchanged");
  }

  get(i, column) {
    return this.rows[i][this.columns.indexOf(column)];
  }

  set(i, column, value) {
    this.rows[i][this.columns.indexOf(column)] = value;
    if (this.states[i] === "unchanged") this.states[i] = "modified";
  }

  add(...values) {
    this.rows.push(values);
    this.states.push("added");
  }

  where(test) {
    return this.rows.map((_, i) => i).filter((i) => test((c) => this.get(i, c)));
  }
}

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

// The columns and rows as a database driver returns them for:
// select id, name, balance from account order by id
const rs = new RecordSet(["id", "name", "balance"], [
  [1, "Ann", 12000],
  [2, "Bob", 1550],
]);

console.log("columns:", rs.columns.join(", "));
rs.set(1, "balance", rs.get(1, "balance") + 1000);
rs.add(3, "Cy", 0);
rs.rows.forEach((_, i) => {
  console.log(`${rs.get(i, "id")} | ${rs.get(i, "name")} | ${money(rs.get(i, "balance"))} | ${rs.states[i]}`);
});
const rich = rs.where((col) => col("balance") > 2000);
console.log("balance over 20.00:", rich.map((i) => rs.get(i, "name")).join(", "));
console.log("rows to save:", rs.states.filter((s) => s !== "unchanged").length);
Output
columns: id, name, balance
1 | Ann | 120.00 | unchanged
2 | Bob | 25.50 | modified
3 | Cy | 0.00 | added
balance over 20.00: Ann, Bob
rows to save: 2
  • Verdict: idiom. A database driver for JavaScript usually returns the rows of a query as an array of objects or arrays and a list of fields. The RecordSet class keeps the columns and the rows, and the state of each row.
  • where gives the code a function col that reads a column by its name, so the test does not use positions.
package main

import (
	"fmt"
	"strings"
)

// RecordSet keeps rows and named columns in memory, in the shape of the result of a query.
type RecordSet struct {
	Columns []string
	Rows    [][]any
	States  []string
}

func NewRecordSet(columns []string, rows [][]any) *RecordSet {
	rs := &RecordSet{Columns: columns}
	for _, r := range rows {
		rs.Rows = append(rs.Rows, append([]any(nil), r...))
		rs.States = append(rs.States, "unchanged")
	}
	return rs
}

func (rs *RecordSet) index(column string) int {
	for i, c := range rs.Columns {
		if c == column {
			return i
		}
	}
	panic("no column " + column)
}

func (rs *RecordSet) Get(i int, column string) any { return rs.Rows[i][rs.index(column)] }

func (rs *RecordSet) Set(i int, column string, v any) {
	rs.Rows[i][rs.index(column)] = v
	if rs.States[i] == "unchanged" {
		rs.States[i] = "modified"
	}
}

func (rs *RecordSet) Add(values ...any) {
	rs.Rows = append(rs.Rows, values)
	rs.States = append(rs.States, "added")
}

func money(c int64) string { return fmt.Sprintf("%d.%02d", c/100, c%100) }

func main() {
	// The columns and rows as database/sql gives them for:
	// select id, name, balance from account order by id
	rs := NewRecordSet([]string{"id", "name", "balance"}, [][]any{
		{1, "Ann", int64(12000)},
		{2, "Bob", int64(1550)},
	})

	fmt.Println("columns:", strings.Join(rs.Columns, ", "))
	rs.Set(1, "balance", rs.Get(1, "balance").(int64)+1000)
	rs.Add(3, "Cy", int64(0))
	var rich []string
	saves := 0
	for i := range rs.Rows {
		fmt.Printf("%v | %v | %s | %s\n", rs.Get(i, "id"), rs.Get(i, "name"), money(rs.Get(i, "balance").(int64)), rs.States[i])
		if rs.Get(i, "balance").(int64) > 2000 {
			rich = append(rich, rs.Get(i, "name").(string))
		}
		if rs.States[i] != "unchanged" {
			saves++
		}
	}
	fmt.Println("balance over 20.00:", strings.Join(rich, ", "))
	fmt.Println("rows to save:", saves)
}
Output
columns: id, name, balance
1 | Ann | 120.00 | unchanged
2 | Bob | 25.50 | modified
3 | Cy | 0.00 | added
balance over 20.00: Ann, Bob
rows to save: 2
  • Verdict: idiom. database/sql gives the names of the columns with Rows.Columns and the cells with Rows.Scan, but it does not keep the rows in memory. The RecordSet struct does this, with any cells.
  • A type assertion such as .(int64) reads a cell as its type, and panics if the type is wrong.
RustGitHub
use std::fmt;

// A cell of a record set: the types that the columns of this example use.
#[derive(Clone, Debug, PartialEq)]
enum Cell {
    Int(i64),
    Text(String),
}

impl fmt::Display for Cell {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Cell::Int(n) => write!(f, "{}", n),
            Cell::Text(s) => write!(f, "{}", s),
        }
    }
}

// Rows and named columns in memory, in the shape of the result of a query.
struct RecordSet {
    columns: Vec<String>,
    rows: Vec<Vec<Cell>>,
    states: Vec<&'static str>,
}

impl RecordSet {
    fn new(columns: &[&str], rows: Vec<Vec<Cell>>) -> RecordSet {
        let states = vec!["unchanged"; rows.len()];
        RecordSet { columns: columns.iter().map(|c| c.to_string()).collect(), rows, states }
    }

    fn index(&self, column: &str) -> usize {
        self.columns.iter().position(|c| c == column).expect("no such column")
    }

    fn get(&self, i: usize, column: &str) -> &Cell {
        &self.rows[i][self.index(column)]
    }

    fn int(&self, i: usize, column: &str) -> i64 {
        match self.get(i, column) {
            Cell::Int(n) => *n,
            other => panic!("not an integer: {}", other),
        }
    }

    fn set(&mut self, i: usize, column: &str, v: Cell) {
        let k = self.index(column);
        self.rows[i][k] = v;
        if self.states[i] == "unchanged" {
            self.states[i] = "modified";
        }
    }

    fn add(&mut self, values: Vec<Cell>) {
        self.rows.push(values);
        self.states.push("added");
    }
}

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

fn text(s: &str) -> Cell {
    Cell::Text(s.to_string())
}

fn main() {
    // The columns and rows as a database driver returns them for:
    // select id, name, balance from account order by id
    let mut rs = RecordSet::new(
        &["id", "name", "balance"],
        vec![vec![Cell::Int(1), text("Ann"), Cell::Int(12000)], vec![Cell::Int(2), text("Bob"), Cell::Int(1550)]],
    );

    println!("columns: {}", rs.columns.join(", "));
    let b = rs.int(1, "balance");
    rs.set(1, "balance", Cell::Int(b + 1000));
    rs.add(vec![Cell::Int(3), text("Cy"), Cell::Int(0)]);
    for i in 0..rs.rows.len() {
        println!("{} | {} | {} | {}", rs.get(i, "id"), rs.get(i, "name"), money(rs.int(i, "balance")), rs.states[i]);
    }
    let rich: Vec<String> = (0..rs.rows.len()).filter(|&i| rs.int(i, "balance") > 2000).map(|i| rs.get(i, "name").to_string()).collect();
    println!("balance over 20.00: {}", rich.join(", "));
    println!("rows to save: {}", rs.states.iter().filter(|s| **s != "unchanged").count());
}
Output
columns: id, name, balance
1 | Ann | 120.00 | unchanged
2 | Bob | 25.50 | modified
3 | Cy | 0.00 | added
balance over 20.00: Ann, Bob
rows to save: 2
  • Verdict: idiom. The cells are an enum with one variant for each type of column, so a cell can hold an integer or a text. int reads a cell as an integer and panics if it is not one.
  • The standard library has no database access; crates such as rusqlite give rows with named columns.

Consequences

Benefits.

  • Works with data-aware tools. Tables, grids and reports that show query results can show a record set.
  • A place for logic. Code such as a Table module can check and change the rows before the UI shows them or the program saves them.
  • No connection while the user works. The program can read the data, close the connection, and save the changes later.
  • Easy to save changes. The state of each row tells which rows to insert or update.

Liabilities.

Code that reads the values by position breaks when the query changes. In the following program, the rows have no names for the columns. A new version of the query adds a column, and the code that reads the third value now gets an email address.

This code runs but gives a wrong answer on purpose.

rows = [(1, "Ann", 12000), (2, "Bob", 1550)]  # a record set with no names for the columns

# A new version of the query puts the email between the name and the balance.
rows_v2 = [(1, "Ann", "ann@example.org", 12000), (2, "Bob", "bob@example.org", 1550)]


def total_balance(rs):
    return sum(row[2] for row in rs)  # the code finds the balance by its position


print("total:", total_balance(rows))
try:
    print("total:", total_balance(rows_v2))
except TypeError as e:
    print("TypeError:", e)
Output
total: 13550
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Keep the names of the columns in the record set and read each value by its name, for example get(i, "balance").

Weak types. The cells usually have a general type, such as an object. The compiler cannot check the name of a column or the type of a value. Typed data sets, which a tool generates from the schema, solve part of this.

Logic that is spread out. A record set has no behavior of its own. If the rules are not in a Table module or a similar place, they go back into the UI.

Stale data. While the record set is not connected, another user can change the same rows in the database. The save needs a check, such as an Optimistic offline lock.

When not to use it

When the program has a domain model. If the rules are in objects with behavior, the Domain model and a mapper replace the record set, and the UI shows the objects.

When the platform has no tools that use it. The main reason for a record set is the tools that work with it. Without them, a list of data transfer objects or plain records is simpler.

ADO.NET DataSet. "The ADO.NET DataSet is a memory-resident representation of data that provides a consistent relational programming model regardless of the source of the data it contains."3 It can hold several tables with constraints and relations between them.3

Disconnected row sets. In Java, "A CachedRowSet object is a container for rows of data that caches its rows in memory, which makes it possible to operate without always being connected to its data source."4 It connects "while it is reading data to populate itself with rows and again while it is propagating changes back to its underlying data source".4

Related patterns. A Table module puts the business logic for a table next to a record set. A Table Data Gateway can return a record set from a query. The state of each row works like a small Unit of Work. The book pairs Record Set with Table Module.5

Known uses

  • The ADO.NET DataSet and DataTable.3
  • The Java CachedRowSet, a disconnected row set.4

References

  1. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Record Set, pattern summary
  2. Python documentation, sqlite3, DB-API 2.0 interface for SQLite databases, Cursor.description
  3. Microsoft Learn, DataSets, DataTables, and DataViews, ADO.NET, introduction
  4. Java SE 21 API, javax.sql.rowset.CachedRowSet, interface description
  5. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 18, Base Patterns, Record Set

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