Patterncore
Query Object
Also called query object pattern, criteria object, criteria API, query builder.
Query Object represents a database query as a structure of objects that name classes and fields, and the structure writes itself as SQL with the columns from the mapping metadata.
- Family
- architectural
- Intent
- An object that represents a database query.
Intent
Query Object is "An object that represents a database query."1 The program builds the query from objects that name classes and fields. The query object then writes itself as SQL, with the tables and columns that the mapping gives.
Problem
Fowler states the problem in two parts. First, "SQL can be an involved language, and many developers aren't particularly familiar with it. Furthermore, you need to know what the database schema looks like to form queries."1 Second, the usual cure, a finder method for each query with the SQL inside, does not help with queries that the program builds at run time, such as a search form with optional fields, and it repeats the column names in each finder.1 When a column changes its name, each finder that names it must change, and a finder that is missed fails at run time.
The same problem appears outside SQL. Microsoft describes it for C#: "Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support."2
Solution
"A Query Object is an interpreter, that is, a structure of objects that can form itself into a SQL query. You can create this query by referring to classes and fields rather than tables and columns."1
The participants are:
- Criterion. One condition on one field, such as
country = 'NZ'orgoals > 10. It holds the field name, the operator and the value. - Group. A node that joins other conditions with
andoror. Because a group holds conditions, and is a condition itself, the query is a tree. - Query object. The class of the objects that the query finds, the list of criteria, and the order. It has the method that writes the SQL.
- Data map. The Metadata Mapping that turns each field into its column. The query object reads it when it writes the SQL, and only there.
Fowler connects the pattern to the rest of the mapping layer: it pays off mainly with a domain model and a Data Mapper, and serious use of it needs Metadata Mapping.3
Query(Player) to_sql(data map)
and select ... from player
+-- country = 'NZ' ------> where nation = ?
+-- goals > 10 and goals_scored > ?
order by name order by name
params: ['NZ', 10]
The following program turns a list of criteria on the fields of a player into SQL on the columns of the table.
class Criterion:
def __init__(self, op, field, value):
self.op, self.field, self.value = op, field, value
# The query names fields of the class. The data map turns them into columns.
COLUMNS = {"name": "name", "country": "nation", "goals": "goals_scored"}
def to_sql(table, criteria):
where = " and ".join(f"{COLUMNS[c.field]} {c.op} ?" for c in criteria)
return f"select * from {table} where {where}", [c.value for c in criteria]
query = [Criterion("=", "country", "NZ"), Criterion(">", "goals", 10)]
print(to_sql("player", query))
('select * from player where nation = ? and goals_scored > ?', ['NZ', 10])
Example
Each example file has a Player class and a data map in which the field country maps to the column nation, and the field goals maps to the column goals_scored. The query object is a tree of criteria and or groups, with an order. Each node has two methods: one writes the node as SQL and collects the parameter values, and one tests an object in memory. The program builds two queries, prints the SQL and the parameters of each, and prints the players found. Then the column nation is renamed: only the data map changes, and the first query, not changed, gives the new SQL and the same players. The Python file runs the SQL in SQLite and also tests the objects in memory; the other files have no database, so they print the same SQL and find the rows with the in-memory method.
import sqlite3
class Player:
def __init__(self, id, name, country, goals):
self.id, self.name, self.country, self.goals = id, name, country, goals
# The metadata: each field of Player and its column in the player table.
PLAYER_MAP = {"table": "player",
"columns": {"id": "id", "name": "name", "country": "nation", "goals": "goals_scored"}}
class Criterion:
# One condition on a field. The query object is a tree of these.
def __init__(self, op, field, value):
self.op, self.field, self.value = op, field, value
def sql(self, cols, params):
col = cols[self.field]
if self.op == "starts":
params.append(self.value + "%")
return f"{col} like ?"
params.append(self.value)
return f"{col} {self.op} ?"
def matches(self, obj):
v = getattr(obj, self.field)
if self.op == "=":
return v == self.value
if self.op == ">":
return v > self.value
return v.startswith(self.value)
class AnyOf:
# A group of conditions joined with "or".
def __init__(self, *parts):
self.parts = parts
def sql(self, cols, params):
return "(" + " or ".join(p.sql(cols, params) for p in self.parts) + ")"
def matches(self, obj):
return any(p.matches(obj) for p in self.parts)
def eq(field, value):
return Criterion("=", field, value)
def gt(field, value):
return Criterion(">", field, value)
def starts(field, value):
return Criterion("starts", field, value)
class Query:
# A query on fields of a class. It knows nothing of tables and columns
# until to_sql reads the data map.
def __init__(self):
self.criteria, self.order = [], None
def where(self, c):
self.criteria.append(c)
return self
def order_by(self, field):
self.order = field
return self
def to_sql(self, data_map):
cols, params = data_map["columns"], []
sql = f"select {', '.join(cols.values())} from {data_map['table']}"
if self.criteria:
sql += " where " + " and ".join(c.sql(cols, params) for c in self.criteria)
if self.order:
sql += f" order by {cols[self.order]}"
return sql, params
def matches(self, obj):
return all(c.matches(obj) for c in self.criteria)
PLAYERS = [Player(1, "Ann", "NZ", 14), Player(2, "Bo", "NZ", 3), Player(3, "Cy", "NZ", 21),
Player(4, "Dee", "AU", 9), Player(5, "Eli", "GB", 12)]
def make_db(data_map):
cols = data_map["columns"]
db = sqlite3.connect(":memory:")
db.execute(f"create table player (id integer primary key, name text, {cols['country']} text, goals_scored integer)")
db.executemany("insert into player values (?, ?, ?, ?)",
[(p.id, p.name, p.country, p.goals) for p in PLAYERS])
return db
def run(title, query, data_map):
sql, params = query.to_sql(data_map)
print("query:", title)
print("sql:", sql)
print("params:", params)
rows = make_db(data_map).execute(sql, params).fetchall()
print("rows:", " | ".join(f"{r[1]} ({r[2]}, {r[3]})" for r in rows))
found = sorted((p for p in PLAYERS if query.matches(p)), key=lambda p: getattr(p, query.order))
print("in memory:", " | ".join(p.name for p in found))
q1 = Query().where(eq("country", "NZ")).where(gt("goals", 10)).order_by("name")
q2 = Query().where(AnyOf(starts("name", "B"), eq("country", "AU"))).order_by("name")
run("from NZ and more than 10 goals", q1, PLAYER_MAP)
run("name starts with B or from AU", q2, PLAYER_MAP)
# The column nation is renamed. Only the data map changes; the query does not.
NEW_MAP = {"table": "player", "columns": dict(PLAYER_MAP["columns"], country="country_code")}
run("from NZ and more than 10 goals, after the rename", q1, NEW_MAP)
query: from NZ and more than 10 goals
sql: select id, name, nation, goals_scored from player where nation = ? and goals_scored > ? order by name
params: ['NZ', 10]
rows: Ann (NZ, 14) | Cy (NZ, 21)
in memory: Ann | Cy
query: name starts with B or from AU
sql: select id, name, nation, goals_scored from player where (name like ? or nation = ?) order by name
params: ['B%', 'AU']
rows: Bo (NZ, 3) | Dee (AU, 9)
in memory: Bo | Dee
query: from NZ and more than 10 goals, after the rename
sql: select id, name, country_code, goals_scored from player where country_code = ? and goals_scored > ? order by name
params: ['NZ', 10]
rows: Ann (NZ, 14) | Cy (NZ, 21)
in memory: Ann | Cy
- Verdict: idiom. The criteria are small classes with a
sqlmethod and amatchesmethod, so one tree has two interpreters.to_sqlreads the data map, so the query names only the fields ofPlayer. - The values go into the parameter list and never into the SQL text, so
sqlite3binds them. - In real code, SQLAlchemy
select()and the DjangoQuerySetare query objects of this kind.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
record Player(int id, String name, String country, int goals) {
Object get(String field) {
return switch (field) {
case "id" -> id;
case "name" -> name;
case "country" -> country;
case "goals" -> goals;
default -> throw new IllegalArgumentException(field);
};
}
}
// The metadata: the table and, for each field of Player, its column.
record DataMap(String table, Map<String, String> columns) {}
// A node of the query object: it can write itself as SQL or test an object.
interface Condition {
String sql(Map<String, String> cols, List<Object> params);
boolean matches(Player p);
}
record Criterion(String op, String field, Object value) implements Condition {
public String sql(Map<String, String> cols, List<Object> params) {
String col = cols.get(field);
if (op.equals("starts")) {
params.add(value + "%");
return col + " like ?";
}
params.add(value);
return col + " " + op + " ?";
}
public boolean matches(Player p) {
Object v = p.get(field);
return switch (op) {
case "=" -> v.equals(value);
case ">" -> (Integer) v > (Integer) value;
default -> ((String) v).startsWith((String) value);
};
}
}
// A group of conditions joined with "or".
record AnyOf(List<Condition> parts) implements Condition {
public String sql(Map<String, String> cols, List<Object> params) {
List<String> s = new ArrayList<>();
for (Condition c : parts) s.add(c.sql(cols, params));
return "(" + String.join(" or ", s) + ")";
}
public boolean matches(Player p) {
return parts.stream().anyMatch(c -> c.matches(p));
}
}
// A query on fields of a class. It knows nothing of tables and columns
// until toSql reads the data map.
static class Query {
final List<Condition> criteria = new ArrayList<>();
String order;
Query where(Condition c) {
criteria.add(c);
return this;
}
Query orderBy(String field) {
order = field;
return this;
}
String toSql(DataMap map, List<Object> params) {
Map<String, String> cols = map.columns();
String sql = "select " + String.join(", ", cols.values()) + " from " + map.table();
if (!criteria.isEmpty()) {
List<String> s = new ArrayList<>();
for (Condition c : criteria) s.add(c.sql(cols, params));
sql += " where " + String.join(" and ", s);
}
if (order != null) sql += " order by " + cols.get(order);
return sql;
}
boolean matches(Player p) {
return criteria.stream().allMatch(c -> c.matches(p));
}
}
static final List<Player> PLAYERS = List.of(
new Player(1, "Ann", "NZ", 14), new Player(2, "Bo", "NZ", 3), new Player(3, "Cy", "NZ", 21),
new Player(4, "Dee", "AU", 9), new Player(5, "Eli", "GB", 12));
static void run(String title, Query q, DataMap map) {
List<Object> params = new ArrayList<>();
String sql = q.toSql(map, params);
System.out.println("query: " + title);
System.out.println("sql: " + sql);
String shown = params.stream()
.map(p -> p instanceof String ? "'" + p + "'" : String.valueOf(p))
.collect(Collectors.joining(", "));
System.out.println("params: [" + shown + "]");
// No database here: the same query object is run on the objects in memory.
List<Player> found = PLAYERS.stream().filter(q::matches)
.sorted(Comparator.comparing(p -> (String) p.get(q.order))).toList();
System.out.println("rows: " + found.stream()
.map(p -> p.name() + " (" + p.country() + ", " + p.goals() + ")")
.collect(Collectors.joining(" | ")));
System.out.println("in memory: " + found.stream().map(Player::name).collect(Collectors.joining(" | ")));
}
static Criterion eq(String f, Object v) { return new Criterion("=", f, v); }
static Criterion gt(String f, Object v) { return new Criterion(">", f, v); }
static Criterion starts(String f, String v) { return new Criterion("starts", f, v); }
public static void main(String[] args) {
Map<String, String> cols = new LinkedHashMap<>();
cols.put("id", "id");
cols.put("name", "name");
cols.put("country", "nation");
cols.put("goals", "goals_scored");
DataMap playerMap = new DataMap("player", cols);
Query q1 = new Query().where(eq("country", "NZ")).where(gt("goals", 10)).orderBy("name");
Query q2 = new Query().where(new AnyOf(List.of(starts("name", "B"), eq("country", "AU")))).orderBy("name");
run("from NZ and more than 10 goals", q1, playerMap);
run("name starts with B or from AU", q2, playerMap);
// The column nation is renamed. Only the data map changes; the query does not.
Map<String, String> newCols = new LinkedHashMap<>(cols);
newCols.put("country", "country_code");
run("from NZ and more than 10 goals, after the rename", q1, new DataMap("player", newCols));
}
}
query: from NZ and more than 10 goals
sql: select id, name, nation, goals_scored from player where nation = ? and goals_scored > ? order by name
params: ['NZ', 10]
rows: Ann (NZ, 14) | Cy (NZ, 21)
in memory: Ann | Cy
query: name starts with B or from AU
sql: select id, name, nation, goals_scored from player where (name like ? or nation = ?) order by name
params: ['B%', 'AU']
rows: Bo (NZ, 3) | Dee (AU, 9)
in memory: Bo | Dee
query: from NZ and more than 10 goals, after the rename
sql: select id, name, country_code, goals_scored from player where country_code = ? and goals_scored > ? order by name
params: ['NZ', 10]
rows: Ann (NZ, 14) | Cy (NZ, 21)
in memory: Ann | Cy
- Verdict: idiom.
Conditionis an interface with two records that implement it, soAnyOfcan hold criteria and other groups. - The example has no database, so the rows come from the same query object run on the objects in memory.
- The Jakarta Persistence Criteria API is the standard query object of Java. It names attributes through a metamodel, so the compiler checks the field names, which the strings here do not.
class Player {
constructor(id, name, country, goals) {
Object.assign(this, { id, name, country, goals });
}
}
// The metadata: each field of Player and its column in the player table.
const PLAYER_MAP = {
table: "player",
columns: { id: "id", name: "name", country: "nation", goals: "goals_scored" },
};
// One condition on a field. The query object is a tree of these.
class Criterion {
constructor(op, field, value) {
Object.assign(this, { op, field, value });
}
sql(cols, params) {
const col = cols[this.field];
if (this.op === "starts") {
params.push(this.value + "%");
return `${col} like ?`;
}
params.push(this.value);
return `${col} ${this.op} ?`;
}
matches(obj) {
const v = obj[this.field];
if (this.op === "=") return v === this.value;
if (this.op === ">") return v > this.value;
return v.startsWith(this.value);
}
}
// A group of conditions joined with "or".
class AnyOf {
constructor(...parts) {
this.parts = parts;
}
sql(cols, params) {
return "(" + this.parts.map((p) => p.sql(cols, params)).join(" or ") + ")";
}
matches(obj) {
return this.parts.some((p) => p.matches(obj));
}
}
const eq = (f, v) => new Criterion("=", f, v);
const gt = (f, v) => new Criterion(">", f, v);
const starts = (f, v) => new Criterion("starts", f, v);
// A query on fields of a class. It knows nothing of tables and columns
// until toSql reads the data map.
class Query {
constructor() {
this.criteria = [];
this.order = null;
}
where(c) {
this.criteria.push(c);
return this;
}
orderBy(field) {
this.order = field;
return this;
}
toSql(map) {
const cols = map.columns;
const params = [];
let sql = `select ${Object.values(cols).join(", ")} from ${map.table}`;
if (this.criteria.length > 0) {
sql += " where " + this.criteria.map((c) => c.sql(cols, params)).join(" and ");
}
if (this.order) sql += ` order by ${cols[this.order]}`;
return [sql, params];
}
matches(obj) {
return this.criteria.every((c) => c.matches(obj));
}
}
const PLAYERS = [
new Player(1, "Ann", "NZ", 14), new Player(2, "Bo", "NZ", 3), new Player(3, "Cy", "NZ", 21),
new Player(4, "Dee", "AU", 9), new Player(5, "Eli", "GB", 12),
];
function run(title, query, map) {
const [sql, params] = query.toSql(map);
console.log("query:", title);
console.log("sql:", sql);
const shown = params.map((p) => (typeof p === "string" ? `'${p}'` : String(p)));
console.log(`params: [${shown.join(", ")}]`);
// No database here: the same query object is run on the objects in memory.
const found = PLAYERS.filter((p) => query.matches(p))
.sort((a, b) => (a[query.order] < b[query.order] ? -1 : 1));
console.log("rows:", found.map((p) => `${p.name} (${p.country}, ${p.goals})`).join(" | "));
console.log("in memory:", found.map((p) => p.name).join(" | "));
}
const q1 = new Query().where(eq("country", "NZ")).where(gt("goals", 10)).orderBy("name");
const q2 = new Query().where(new AnyOf(starts("name", "B"), eq("country", "AU"))).orderBy("name");
run("from NZ and more than 10 goals", q1, PLAYER_MAP);
run("name starts with B or from AU", q2, PLAYER_MAP);
// The column nation is renamed. Only the data map changes; the query does not.
const NEW_MAP = { table: "player", columns: { ...PLAYER_MAP.columns, country: "country_code" } };
run("from NZ and more than 10 goals, after the rename", q1, NEW_MAP);
query: from NZ and more than 10 goals
sql: select id, name, nation, goals_scored from player where nation = ? and goals_scored > ? order by name
params: ['NZ', 10]
rows: Ann (NZ, 14) | Cy (NZ, 21)
in memory: Ann | Cy
query: name starts with B or from AU
sql: select id, name, nation, goals_scored from player where (name like ? or nation = ?) order by name
params: ['B%', 'AU']
rows: Bo (NZ, 3) | Dee (AU, 9)
in memory: Bo | Dee
query: from NZ and more than 10 goals, after the rename
sql: select id, name, country_code, goals_scored from player where country_code = ? and goals_scored > ? order by name
params: ['NZ', 10]
rows: Ann (NZ, 14) | Cy (NZ, 21)
in memory: Ann | Cy
- Verdict: idiom. Each criterion is a class with
sqlandmatches, andwherereturnsthisso that the calls chain. - The example has no database, so the rows come from the same query object run on the objects in memory. The SQL and the parameters are the same as in the Python file.
- Query builders for JavaScript, such as Knex, have this design.
package main
import (
"fmt"
"sort"
"strings"
)
type Player struct {
ID int
Name string
Country string
Goals int
}
func (p Player) get(field string) any {
switch field {
case "id":
return p.ID
case "name":
return p.Name
case "country":
return p.Country
}
return p.Goals
}
// DataMap is the metadata: the table and, for each field, its column.
type DataMap struct {
Table string
Fields []string
Columns map[string]string
}
// Condition is a node of the query object: it can write itself as SQL or test an object.
type Condition interface {
SQL(cols map[string]string, params *[]any) string
Matches(p Player) bool
}
type Criterion struct {
Op, Field string
Value any
}
func (c Criterion) SQL(cols map[string]string, params *[]any) string {
col := cols[c.Field]
if c.Op == "starts" {
*params = append(*params, c.Value.(string)+"%")
return col + " like ?"
}
*params = append(*params, c.Value)
return col + " " + c.Op + " ?"
}
func (c Criterion) Matches(p Player) bool {
v := p.get(c.Field)
switch c.Op {
case "=":
return v == c.Value
case ">":
return v.(int) > c.Value.(int)
}
return strings.HasPrefix(v.(string), c.Value.(string))
}
// AnyOf is a group of conditions joined with "or".
type AnyOf []Condition
func (a AnyOf) SQL(cols map[string]string, params *[]any) string {
var s []string
for _, c := range a {
s = append(s, c.SQL(cols, params))
}
return "(" + strings.Join(s, " or ") + ")"
}
func (a AnyOf) Matches(p Player) bool {
for _, c := range a {
if c.Matches(p) {
return true
}
}
return false
}
// Query is a query on fields. It knows nothing of tables and columns
// until ToSQL reads the data map.
type Query struct {
criteria []Condition
order string
}
func (q *Query) Where(c Condition) *Query {
q.criteria = append(q.criteria, c)
return q
}
func (q *Query) OrderBy(f string) *Query {
q.order = f
return q
}
func (q *Query) ToSQL(m DataMap) (string, []any) {
var cols []string
for _, f := range m.Fields {
cols = append(cols, m.Columns[f])
}
params := []any{}
sql := "select " + strings.Join(cols, ", ") + " from " + m.Table
if len(q.criteria) > 0 {
var s []string
for _, c := range q.criteria {
s = append(s, c.SQL(m.Columns, ¶ms))
}
sql += " where " + strings.Join(s, " and ")
}
if q.order != "" {
sql += " order by " + m.Columns[q.order]
}
return sql, params
}
func (q *Query) Matches(p Player) bool {
for _, c := range q.criteria {
if !c.Matches(p) {
return false
}
}
return true
}
var players = []Player{{1, "Ann", "NZ", 14}, {2, "Bo", "NZ", 3}, {3, "Cy", "NZ", 21}, {4, "Dee", "AU", 9}, {5, "Eli", "GB", 12}}
func run(title string, q *Query, m DataMap) {
sql, params := q.ToSQL(m)
fmt.Println("query:", title)
fmt.Println("sql:", sql)
var shown []string
for _, p := range params {
if s, ok := p.(string); ok {
shown = append(shown, "'"+s+"'")
} else {
shown = append(shown, fmt.Sprint(p))
}
}
fmt.Printf("params: [%s]\n", strings.Join(shown, ", "))
// No database here: the same query object is run on the objects in memory.
var found []Player
for _, p := range players {
if q.Matches(p) {
found = append(found, p)
}
}
sort.Slice(found, func(i, j int) bool { return found[i].get(q.order).(string) < found[j].get(q.order).(string) })
var rows, names []string
for _, p := range found {
rows = append(rows, fmt.Sprintf("%s (%s, %d)", p.Name, p.Country, p.Goals))
names = append(names, p.Name)
}
fmt.Println("rows:", strings.Join(rows, " | "))
fmt.Println("in memory:", strings.Join(names, " | "))
}
func main() {
fields := []string{"id", "name", "country", "goals"}
playerMap := DataMap{"player", fields, map[string]string{"id": "id", "name": "name", "country": "nation", "goals": "goals_scored"}}
q1 := (&Query{}).Where(Criterion{"=", "country", "NZ"}).Where(Criterion{">", "goals", 10}).OrderBy("name")
q2 := (&Query{}).Where(AnyOf{Criterion{"starts", "name", "B"}, Criterion{"=", "country", "AU"}}).OrderBy("name")
run("from NZ and more than 10 goals", q1, playerMap)
run("name starts with B or from AU", q2, playerMap)
// The column nation is renamed. Only the data map changes; the query does not.
newCols := map[string]string{}
for k, v := range playerMap.Columns {
newCols[k] = v
}
newCols["country"] = "country_code"
run("from NZ and more than 10 goals, after the rename", q1, DataMap{"player", fields, newCols})
}
query: from NZ and more than 10 goals
sql: select id, name, nation, goals_scored from player where nation = ? and goals_scored > ? order by name
params: ['NZ', 10]
rows: Ann (NZ, 14) | Cy (NZ, 21)
in memory: Ann | Cy
query: name starts with B or from AU
sql: select id, name, nation, goals_scored from player where (name like ? or nation = ?) order by name
params: ['B%', 'AU']
rows: Bo (NZ, 3) | Dee (AU, 9)
in memory: Bo | Dee
query: from NZ and more than 10 goals, after the rename
sql: select id, name, country_code, goals_scored from player where country_code = ? and goals_scored > ? order by name
params: ['NZ', 10]
rows: Ann (NZ, 14) | Cy (NZ, 21)
in memory: Ann | Cy
- Verdict: idiom.
Conditionis an interface, andAnyOfis a slice of conditions with its own methods. The parameters are collected through a pointer to a slice. - The
DataMapkeeps the fields in a slice because the order of a Go map is not fixed, and the column list must have a fixed order. - The example has no database, so the rows come from the same query object run on the objects in memory.
struct Player {
name: &'static str,
country: &'static str,
goals: i64,
}
#[derive(Clone, PartialEq)]
enum Value {
Int(i64),
Text(String),
}
impl Player {
fn get(&self, field: &str) -> Value {
match field {
"name" => Value::Text(self.name.to_string()),
"country" => Value::Text(self.country.to_string()),
_ => Value::Int(self.goals),
}
}
}
// The metadata: the table and, for each field, its column, in order.
struct DataMap {
table: &'static str,
columns: Vec<(&'static str, &'static str)>,
}
impl DataMap {
fn column(&self, field: &str) -> &'static str {
self.columns.iter().find(|(f, _)| *f == field).unwrap().1
}
}
// A node of the query object: it can write itself as SQL or test an object.
enum Condition {
Eq(&'static str, Value),
Gt(&'static str, i64),
Starts(&'static str, &'static str),
AnyOf(Vec<Condition>),
}
impl Condition {
fn sql(&self, map: &DataMap, params: &mut Vec<Value>) -> String {
match self {
Condition::Eq(f, v) => {
params.push(v.clone());
format!("{} = ?", map.column(f))
}
Condition::Gt(f, v) => {
params.push(Value::Int(*v));
format!("{} > ?", map.column(f))
}
Condition::Starts(f, v) => {
params.push(Value::Text(format!("{}%", v)));
format!("{} like ?", map.column(f))
}
Condition::AnyOf(parts) => {
let s: Vec<String> = parts.iter().map(|c| c.sql(map, params)).collect();
format!("({})", s.join(" or "))
}
}
}
fn matches(&self, p: &Player) -> bool {
match self {
Condition::Eq(f, v) => p.get(f) == *v,
Condition::Gt(f, v) => matches!(p.get(f), Value::Int(x) if x > *v),
Condition::Starts(f, v) => matches!(p.get(f), Value::Text(s) if s.starts_with(v)),
Condition::AnyOf(parts) => parts.iter().any(|c| c.matches(p)),
}
}
}
// A query on fields. It knows nothing of tables and columns
// until to_sql reads the data map.
struct Query {
criteria: Vec<Condition>,
order: &'static str,
}
impl Query {
fn to_sql(&self, map: &DataMap) -> (String, Vec<Value>) {
let cols: Vec<&str> = map.columns.iter().map(|(_, c)| *c).collect();
let mut params = Vec::new();
let mut sql = format!("select {} from {}", cols.join(", "), map.table);
if !self.criteria.is_empty() {
let s: Vec<String> = self.criteria.iter().map(|c| c.sql(map, &mut params)).collect();
sql += &format!(" where {}", s.join(" and "));
}
sql += &format!(" order by {}", map.column(self.order));
(sql, params)
}
fn matches(&self, p: &Player) -> bool {
self.criteria.iter().all(|c| c.matches(p))
}
}
fn run(title: &str, q: &Query, map: &DataMap, players: &[Player]) {
let (sql, params) = q.to_sql(map);
println!("query: {}", title);
println!("sql: {}", sql);
let shown: Vec<String> = params
.iter()
.map(|p| match p {
Value::Text(s) => format!("'{}'", s),
Value::Int(i) => i.to_string(),
})
.collect();
println!("params: [{}]", shown.join(", "));
// No database here: the same query object is run on the objects in memory.
let mut found: Vec<&Player> = players.iter().filter(|p| q.matches(p)).collect();
found.sort_by_key(|p| p.name);
let rows: Vec<String> = found.iter().map(|p| format!("{} ({}, {})", p.name, p.country, p.goals)).collect();
let names: Vec<&str> = found.iter().map(|p| p.name).collect();
println!("rows: {}", rows.join(" | "));
println!("in memory: {}", names.join(" | "));
}
fn main() {
let players = [
Player { name: "Ann", country: "NZ", goals: 14 },
Player { name: "Bo", country: "NZ", goals: 3 },
Player { name: "Cy", country: "NZ", goals: 21 },
Player { name: "Dee", country: "AU", goals: 9 },
Player { name: "Eli", country: "GB", goals: 12 },
];
let mut columns = vec![("id", "id"), ("name", "name"), ("country", "nation"), ("goals", "goals_scored")];
let player_map = DataMap { table: "player", columns: columns.clone() };
let q1 = Query {
criteria: vec![Condition::Eq("country", Value::Text("NZ".to_string())), Condition::Gt("goals", 10)],
order: "name",
};
let q2 = Query {
criteria: vec![Condition::AnyOf(vec![Condition::Starts("name", "B"), Condition::Eq("country", Value::Text("AU".to_string()))])],
order: "name",
};
run("from NZ and more than 10 goals", &q1, &player_map, &players);
run("name starts with B or from AU", &q2, &player_map, &players);
// The column nation is renamed. Only the data map changes; the query does not.
columns[2] = ("country", "country_code");
let new_map = DataMap { table: "player", columns };
run("from NZ and more than 10 goals, after the rename", &q1, &new_map, &players);
}
query: from NZ and more than 10 goals
sql: select id, name, nation, goals_scored from player where nation = ? and goals_scored > ? order by name
params: ['NZ', 10]
rows: Ann (NZ, 14) | Cy (NZ, 21)
in memory: Ann | Cy
query: name starts with B or from AU
sql: select id, name, nation, goals_scored from player where (name like ? or nation = ?) order by name
params: ['B%', 'AU']
rows: Bo (NZ, 3) | Dee (AU, 9)
in memory: Bo | Dee
query: from NZ and more than 10 goals, after the rename
sql: select id, name, country_code, goals_scored from player where country_code = ? and goals_scored > ? order by name
params: ['NZ', 10]
rows: Ann (NZ, 14) | Cy (NZ, 21)
in memory: Ann | Cy
- Verdict: idiom.
Conditionis an enum, andsqlandmatchesare twomatchexpressions over it, so the compiler checks that each kind of node is handled. - The data map is a vector of pairs, which keeps the column order fixed.
- The example has no database, so the rows come from the same query object run on the objects in memory. Diesel and SeaORM are Rust query builders with this design.
Consequences
Benefits.
- The query uses the names of the domain. The code that asks for players from NZ names the field
country, not the columnnation. - A change to the schema is a change in one place. The data map holds the column names, so a rename does not touch the queries.
- Queries can be built at run time. A search form can add one criterion for each field that the user filled in, with no string building.
- The values are always parameters. The query object puts each value in the parameter list and never in the SQL text, so a value cannot change the SQL. This is the main defence against SQL injection.
- The same query can run in two places. Because the query is data, a second interpreter can test objects in memory, for example objects that the session holds and has not yet written.
Liabilities.
Finder methods with their own SQL repeat the column names. This is the problem that the pattern solves. In the following program, the column nation was renamed to country_code. One finder was changed and the other was not, and the error shows only when that finder runs.
This code runs but gives a wrong answer on purpose.
import sqlite3
db = sqlite3.connect(":memory:")
# The column nation was renamed to country_code in the last migration.
db.execute("create table player (id integer primary key, name text, country_code text, goals_scored integer)")
db.execute("insert into player values (1, 'Ann', 'NZ', 14)")
# Wrong: each finder method holds its own SQL with the column names in it.
# The rename was made in one finder and not in the other.
def find_by_country(country):
return db.execute("select name from player where country_code = ?", (country,)).fetchall()
def find_scorers(country, goals):
sql = "select name from player where nation = ? and goals_scored > ?"
return db.execute(sql, (country, goals)).fetchall()
print(find_by_country("NZ"))
try:
print(find_scorers("NZ", 10))
except sqlite3.OperationalError as e:
print("error:", e)
[('Ann',)]
error: no such column: nation
A home-made query object covers only part of SQL. Joins, grouping, subqueries and window functions each need new kinds of nodes. Most projects with a query object of their own also keep a way to send plain SQL.
The SQL is out of sight. The statement that runs is not in the source, so a slow query is harder to find, and the program must log the SQL to show it.
Two interpreters can give different answers. In the examples, starts becomes like 'B%' in SQL and a prefix test in memory. These are not the same test. In SQLite, in a LIKE pattern, "Any other character matches itself or its lower/upper case equivalent (i.e. case-insensitive matching)", and the percent sign and the underscore are wildcards.4 So the name bo matches like 'B%' and fails the prefix test, and a value with % or _ in it needs an escape character in SQL.
When not to use it
When the queries are few and fixed. A small number of finder methods, or a Table Data Gateway with named queries, is shorter and shows the SQL.
When the ORM already has one. SQLAlchemy, Django, Jakarta Persistence and LINQ each give a query object that covers much more of SQL than a home-made one. Write the query in their form.
For reports and heavy SQL. A report with many joins and aggregates is often clearer as SQL that a person can read and tune.
Variants and related patterns
Criteria APIs. The query is a tree of objects that the program builds with method calls, as in the Jakarta Persistence Criteria API.5
Query builders. The objects mirror SQL itself, with select, where and join, and not the domain. SQLAlchemy Core is a query builder, and the ORM adds the mapped classes to it.6
Language-integrated queries. LINQ puts the query in the syntax of C#, as a query expression that the compiler checks.2 A LINQ provider for a database turns the query expression into SQL.
Query by example. The program fills some fields of an object, and the query finds the objects whose fields have the same values.
Related patterns. A query object is an Interpreter pattern whose nodes are a Composite pattern. The chain of where calls is a form of Builder pattern. A Specification is a predicate object of the domain, which a query object can turn into SQL. A Repository pattern often takes a query object or a specification as the argument of its find method. Django and SQLAlchemy build the query first and run it later, which is lazy evaluation of the query.
Known uses
- SQLAlchemy: "SELECT statements are produced by the select() function which returns a Select object."6 Select.where in selectable.py at 2.0.57 adds each criterion to the tuple
_where_criteria, and the docstring says that the new criterion is "joined to the existing clause via AND, if any."7 - Django: a
QuerySetis a query object, and aQobject is a criterion that can be combined with others. "When an operator is used on two Q objects, it yields a new Q object."8 class Q in query_utils.py at 5.2.8 is a tree node with the connectorsAND,ORandXOR.9 - Jakarta Persistence: "The Jakarta Persistence Criteria API is used to define queries through the construction of object-based query definition objects, rather than use of the string-based approach of the Jakarta Persistence query language".5 Hibernate and EclipseLink implement it.
- C# and .NET: "The variables in a query expression are all strongly typed."2 Entity Framework Core is a LINQ provider that turns a query expression over a
DbSetinto SQL.
References
- Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Query Object, pattern summary
- Microsoft Learn, Language Integrated Query (LINQ), introduction; Query expression overview
- Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 13, Object-Relational Metadata Mapping Patterns, Query Object
- SQLite documentation, SQL Language Expressions, 5. The LIKE, GLOB, REGEXP, MATCH, and extract operators
- Jakarta Persistence 3.2 specification, 6. Criteria API; 6.1. Overview
- SQLAlchemy 2.0 documentation, Writing SELECT statements for ORM Mapped Classes, introduction
- SQLAlchemy 2.0.57 source, lib/sqlalchemy/sql/selectable.py, Select.where, lines 6238 to 6253
- Django 5.2 documentation, Making queries, Complex lookups with Q objects
- Django 5.2.8 source, django/db/models/query_utils.py, class Q, lines 39 to 80
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 0HFN1F Edit this page History Report an error Markdown