title: Predicates description: Compose queries with reusable boolean expressions in SQL and at runtime. #
A predicate declares a reusable boolean expression. Embed it in a query's SQL
or pass its generated Go constructor through a predicate parameter at runtime.
The tables in brackets specify which sources the expression requires.
Declare a predicate #
predicate ByTitle[b books](title string) {
b.title = {title}
}
predicate ByAuthor[b books](authorID int64) {
b.author_id = {authorID}
}
Embed a predicate into authored SQL with {ByTitle[b](title)}, or pass its
generated constructor through a predicate parameter:
query FindBooks(filter predicate[books]) {
SELECT b.id, b.title
FROM books AS b
WHERE {filter[b]}
ORDER BY b.id
}
filter := stitchql.And(
store.ByAuthor(authorID),
stitchql.Or(store.ByTitle("Kindred"), store.ByTitle("Parable of the Sower")),
)
books, err := store.FindBooks(filter).Select(ctx, pool)
And, Or, and Not compose authored predicates; True and False provide
explicit constants. A predicate's declared relations determine where it fits.
Each placement binds available aliases by position, and expansions are grouped
to preserve boolean precedence. A zero-valued predicate is invalid.
Relationship filters #
Use SQL subqueries for relationship semantics:
predicate HasBook[a authors](match predicate[books]) {
EXISTS (
SELECT 1
FROM books AS b
WHERE b.author_id = a.id
AND {match[b]}
)
}
The outer predicate requires an author source. Its inner predicate receives the
book source supplied by the subquery. In Go, compose it as
store.HasBook(store.ByTitle("Kindred")) and pass it to a query accepting
predicate[authors].
Aliases inside the subquery remain scoped there. Give fixed inner aliases names that do not shadow the outer source you need to correlate.
Places to use predicates #
Predicates can occupy supported boolean expression positions. These examples
reuse ByTitle from above.
WHERE #
Filter the rows returned by a query:
query BooksByTitle(title string) {
SELECT b.id, b.title
FROM books AS b
WHERE {ByTitle[b](title)}
}
store.BooksByTitle("Kindred").SQL() produces this expanded SQL, formatted here
for readability:
SELECT b.id, b.title
FROM books AS b
WHERE (b.title = $1)
The bound arguments are $1 = "Kindred". The predicate is grouped in parentheses
and its value stays separate from the SQL.
JOIN ON #
Filter which books match each author. Because the condition is in the LEFT JOIN's
ON clause, authors with no matching book still appear:
query AuthorsWithMatchingBooks(title string) {
SELECT a.id AS author_id, b.title
FROM authors AS a
LEFT JOIN books AS b
ON b.author_id = a.id AND {ByTitle[b](title)}
}
HAVING #
Use an aggregate predicate to filter groups:
predicate AtLeastBooks[b books](minimum int64) {
count(b.id) >= {minimum}
}
query ProlificAuthors(minimum int64) {
SELECT b.author_id, count(b.id) AS book_count
FROM books AS b
GROUP BY b.author_id
HAVING {AtLeastBooks[b](minimum)}
}
An aggregate predicate such as AtLeastBooks fits HAVING, but cannot be used
in a row condition such as WHERE or JOIN ON.
CASE WHEN #
Choose a result value without filtering out rows:
query LabelBooks(title string) {
SELECT
b.id,
CASE WHEN {ByTitle[b](title)}
THEN 'matching' ELSE 'other'
END AS match_label
FROM books AS b
}
Each of these positions can also accept a runtime predicate parameter, as in
FindBooks above. The available tables and aggregate rules at each position
determine which predicates fit. The query defines its selected columns, joins,
ordering, and pagination.
Reuse across packages #
Export a predicate by starting its name with an uppercase letter:
package store
predicate ByTitle[b books](title string) {
b.title = {title}
}
For compile-time embedding, import its package in the consuming .stitchql file:
package reports
import catalog "example.com/app/store"
query BooksByTitle(title string) {
SELECT b.id, b.title
FROM books AS b
WHERE {catalog.ByTitle[b](title)}
}
For runtime composition, declare a predicate parameter in the consuming query:
package reports
query FindBooks(filter predicate[books]) {
SELECT b.id, b.title
FROM books AS b
WHERE {filter[b]}
}
Import both generated packages in Go and pass the predicate constructor to the
query. No StitchQL import is required in reports/search.stitchql:
import (
"example.com/app/reports"
catalog "example.com/app/store"
)
// Inside your calling function:
books, err := reports.FindBooks(catalog.ByTitle("Kindred")).Select(ctx, pool)
Both packages must resolve books to the same database table. Generate both
packages before compiling the Go application.
See Querying for composing filters in Go and inspecting the resulting SQL before execution.