Introducing Zirql, an embeddable query languageDRAFT
When implementing Zincite1, I wanted a query language similar to the one I had built for Zirium.
As with Zirium, I took inspiration from tools such as awk and jq, whose operations suit the data they work on: text records and fields for awk, JSON values for jq.
In Zincite, I was particularly interested in writing checkers and transformations for MiniZinc data files: checking assumptions about an instance, changing its parameters, or shrinking an instance to investigate a problem.
It soon looked more fun to unify the two query languages than to maintain a second implementation. Selecting MiniZinc declarations and following MLIR operands need different host operations, but filtering collections, naming intermediate results, and combining conditions share the same language machinery, and I wanted improvements to those parts to land in both tools at once.
The result is Zirql, a Rust library that both tools use to parse and evaluate queries. Each application, which I will call the host, supplies its own data and domain operations, while Zirql handles the language around them. The examples below use Zirql 0.3.0, with Zirium 0.7.0 and Zincite 0.3.0 for the host-specific queries.
We will start with the documentation’s word example, since a plain list of strings needs almost no setup, then move to CSV tables, look at what embedding Zirql in Rust looks like, and finish with real queries from Zirium and Zincite.
Start with four words
Our input file, words.txt, contains:
ash apple birch appleThe host splits the file on whitespace and exposes the resulting array as words, leaving case, punctuation, and duplicates intact:
["ash", "apple", "birch", "apple"]To find the words beginning with a, filter the array:
words | filter(w => starts_with(w, "a"))The result is:
["ash", "apple", "apple"]The predicate is a lambda where w names the current word, and filter keeps an entry whenever the lambda returns true, preserving both input order and duplicates.
For a short predicate, _ can stand in for the current argument:
words | filter(starts_with(_, "a"))Because starts_with is built into Zirql, the same operation works on filenames or identifiers read from source code.
It compares strings as written, so starts_with("Apple", "a") is false.
Instead of a pipeline, you can also build a list with a comprehension. Here is the same example using MiniZinc’s comprehension style:2
[w | w in words where starts_with(w, "a")]I prefer filter when selecting entries unchanged, and reach for a comprehension when constructing a new value for each entry or combining several generators.
To put the selected words in alphabetical order, add sort:
words | filter(starts_with(_, "a")) | sortThat gives ["apple", "apple", "ash"].
Adding unique removes duplicate spellings:
words | filter(starts_with(_, "a")) | sort | unique["apple", "ash"]Without the preceding sort, unique keeps the first occurrence of each word in input order.
For counts instead of a deduplicated list, tally produces a dictionary of occurrence counts, ordered by first appearance in the input (ash before apple):
words | filter(starts_with(_, "a")) | tally{"ash": 1, "apple": 2}All of these stages come from Zirql itself; the word host only supplies the input array.
Find neighbouring words
Because the array preserves order, we can also ask which words appear next to each other. Suppose we want to count neighbouring pairs regardless of which word comes first. We can build a set for each adjacent pair and tally those sets:
[ {words[i], words[i + 1]} | i in index_set(words) where i < length(words)] | tallyThe result is a dictionary mapping sets to counts, shown here in Zirql notation:
{ {"ash", "apple"}: 1, {"apple", "birch"}: 2}Array positions start at one, so index_set(words) gives the valid indices and i < length(words) stops before the last element so words[i + 1] stays in bounds.
Indexing is what keeps the pairs adjacent; two independent generators over words would visit every combination, including words that never appeared side by side.
For each index, the comprehension builds a set of the two neighbouring words, so the second and third pairs (apple, birch and birch, apple) compare equal by membership and tally counts them together.
As before, dictionary entries follow first occurrence, and looking up neighbours[{"birch", "apple"}] returns 2 regardless of element order.
Because sets discard duplicates, two adjacent occurrences of apple would produce the singleton set {"apple"}, while an empty file or a single word produces {}.
Tuples, arrays, and dictionaries can also serve as dictionary keys in Zirql; since JSON objects only allow string keys, a host that emits JSON has to decide how to encode non-string keys.
The same calculation can also be written with overlapping windows:
words | windows(2) | map([first, second] => {first, second}) | tallywindows(2) produces each adjacent pair, and the lambda destructures it into first and second to build the same set keys and counts as above.
From words to CSV tables
The same filters can work on records with named fields. The CSV example loads each row as a record, using the header names as fields, and writes query results as JSON. We can use it to make a packing list from a couple of files.
Suppose we are bringing games to a friend’s house.
games.csv records who owns each game, whether we are bringing it and whether it is packed.
Kingdomino is already in the bag; Patchwork and NMBR 9 still need packing.
Everdell and Cottage Garden are staying home (bring is "no"), although both are unpacked.
The columns are title, owner, bring and packed.
Select the games still to pack
With one input file, rows names its array of records.
To find the games still to pack, select rows where bring is "yes" and packed is "no".
Step through the filters to see which cells they check and which rows they return:
Choose a step to follow the underlined query text.
rows | filter(_.bring == "yes")
| filter(_.packed == "no")The header supplies the field names. All five games are available, including Everdell and Cottage Garden, which are staying home.
| Row | title | owner | bring | packed |
|---|---|---|---|---|
| 1 | Kingdomino | mira | yes | yes |
| 2 | Patchwork | leo | yes | no |
| 3 | NMBR 9 | mira | yes | no |
| 4 | Everdell | mira | no | no |
| 5 | Cottage Garden | leo | no | no |
Choose “Return rows” to see the first result.
The first filter selects the games to bring; the second selects those still unpacked.
_.bring and _.packed read fields on the current row.
Checking only packed would also select Everdell and Cottage Garden.
The result contains the whole Patchwork and NMBR 9 records, in file order.
The CSV host keeps cells as strings.
It neither turns "01" into a number nor interprets "yes" as a Boolean.
To run this example, use Rust 1.88 or newer, clone the release and save the linked games.csv file in the checkout:
git clone --branch v0.3.0 --depth 1 https://github.com/zayenz/zirql.gitcd zirqlcargo run --locked --example csv -- 'rows | filter(_.bring == "yes") | filter(_.packed == "no")' games.csvLook up the owners in another file
The game file identifies owners by ID.
A second file, people.csv, maps these to names: mira is Mira and leo is Leo.
Save it beside games.csv.
Pass the files as games=games.csv and people=people.csv, and those names become bindings in the query.
Choose a step to follow the underlined query text.
let pending = games
| filter(_.bring == "yes")
| filter(_.packed == "no");
[
{
"game": g.title,
"owner": p.name
}
| g in pending,
p in people
where p.id == g.owner
]Save the games we are bringing but have not packed as pending. Everdell and Cottage Garden are excluded before matching owners.
| Row | title | owner | bring | packed |
|---|---|---|---|---|
| 1 | Kingdomino | mira | yes | yes |
| 2, selected | Patchwork | leo | yes | no |
| 3, selected | NMBR 9 | mira | yes | no |
| 4 | Everdell | mira | no | no |
| 5 | Cottage Garden | leo | no | no |
| Row | id | name |
|---|---|---|
| 1 | mira | Mira |
| 2 | leo | Leo |
Choose “Return pairs” to see the first result.
let names the filtered array pending.
For each game, p in people visits the owner rows, and where p.id == g.owner selects the matching row.
The comprehension builds a record with the game’s title and the owner’s name.
Run the complete query with both named files:
cargo run --locked --example csv -- 'let pending = games | filter(_.bring == "yes") | filter(_.packed == "no");[ { "game": g.title, "owner": p.name } | g in pending, p in people where p.id == g.owner]' games=games.csv people=people.csvThe result names Leo for Patchwork, then Mira for NMBR 9.
Each owner ID occurs once in this file.
A missing ID would omit the game; repeated IDs would produce multiple matches.
With several files, the query must use the table names rather than rows.
To turn these records into reminders, replace the record expression with p.name ++ ": bring " ++ g.title.
++ concatenates strings, giving ["Leo: bring Patchwork", "Mira: bring NMBR 9"].
Rewrite the records for a checklist
The same file can supply a checklist for all three games we are bringing. Kingdomino needs to appear too, with its box already checked. Step through the construction to see how the source fields become checklist records:
Choose a step to follow the underlined query text.
[
{
"label": g.title,
"checked": g.packed == "yes"
}
| g in rows
where g.bring == "yes"
]The checklist includes all three games we are bringing, including the packed Kingdomino. The two games staying home are excluded.
| Row | title | owner | bring | packed |
|---|---|---|---|---|
| 1, selected | Kingdomino | mira | yes (selected cell) | yes |
| 2, selected | Patchwork | leo | yes (selected cell) | no |
| 3, selected | NMBR 9 | mira | yes (selected cell) | no |
| 4 | Everdell | mira | no | no |
| 5 | Cottage Garden | leo | no | no |
Choose “Compare text” to see the first result.
The where condition selects the games to bring.
Each record uses the title as its label and the comparison g.packed == "yes" as its Boolean checked value.
This gives true for Kingdomino and false for Patchwork and NMBR 9.
The host writes the new records as JSON for the checklist’s presentation code.
Run it with games.csv as the only input again:
cargo run --locked --example csv -- '[ { "label": g.title, "checked": g.packed == "yes" } | g in rows where g.bring == "yes"]' games.csvThe CSV host
The Build the CSV host guide walks through the complete implementation.
The host loads the files, declares row fields from their headers, and hands the query to Zirql to evaluate and render as JSON or Markdown (pass --format markdown after the query and before the file arguments to print a table).
The example also supports typed parameters via --param name=value, named functions, and destructuring bindings.
Cells stay as strings throughout, so numeric calculations use explicit conversions such as parse_int and parse_float.
Putting Zirql in a Rust application
For the Rust integration, I will return to the smaller word host.
The complete example for this post reads a text file and evaluates an expression against its words.
Save it as src/main.rs in a new Rust project with this Cargo.toml:
[package]name = "word-query"version = "0.1.0"edition = "2024"
[dependencies]zirql = "0.3.0"With Rust 1.88 or newer, this builds the word-query command.
Zirql is still early, so I expect the API to evolve as more applications use it.
With words.txt beside Cargo.toml, run:
cargo run -- words.txt 'words | filter(w => starts_with(w, "a"))'cargo run -- words.txt 'length(words)'cargo run -- words.txtThe first command selects ash, apple, apple; the second returns 4; without an expression, the command runs the neighbouring-word tally from earlier.
The host prints Rust’s Debug format, such as Integer(4) for a count, whereas the earlier examples use JSON or Zirql notation so they are easier to read.
To pass host data into Zirql, the host builds a ConstructedValue (which can hold strings, numbers, arrays, tuples, sets, and dictionaries, including records with named fields) and wraps it in a ConstructedBinding alongside its declared type:
let words = ConstructedBinding::new( words, DeclaredType::Sequence(Box::new(DeclaredType::String)), &mut budget, location,)?;Declaring the type separately matters when an input is empty: even for an empty file, Zirql still knows that words is a sequence of strings.
Admission validates the values against that declaration once and keeps them behind an immutable shared owner, so reusing the binding across queries does not copy the array.
The CSV host uses the same API, building a record declaration from each file’s headers.
Next, ConstructedProgram parses and prepares the query with words in scope, then evaluates it against the bound data:
let program = ConstructedProgram::read(&query, &["words"], &mut budget, 64)?;let result = program.evaluate( &[("words", &words)], Some(&words), ParameterInputs::Cli(&[]), FunctionLimits { active_depth: 32 }, &mut budget,)?;println!("{result:#?}");Passing Some(&words) as the current input lets short pipelines start directly on the word list, so a bare count counts its entries.
During read, Zirql rejects trailing input and checks names, declarations, and functions before evaluation produces a Rust value.
This small host accepts bindings and named functions followed by a final expression, and passes no external parameter values, so a query declaring a required parameter fails with a missing-value error.
Notice that the same budget runs through loading, admission, reading, preparation, and evaluation.
The host chooses limits on work, produced values, and nesting, and Zirql enforces them across parsing and evaluation, including nested and recursive calls.
The budget tracks query work rather than wall-clock time or memory, so a host still needs to account for its own loading work and cap file sizes separately.
The embedding guide covers native adapters and other entry points, including constructing Zirql’s expression types directly if a host already has its own parser.
Build a tool around the result
An editor tool could use the word host to find where repeated words appear, and we can produce that report just by changing the query without rebuilding the Rust program. Build a record for each occurrence, then group by spelling:
group_by( [ {"word": words[i], "position": i} | i in index_set(words) ], "word")Each group has a key and an items array; for apple, that gives both occurrences:
{ "key": "apple", "items": [ {"word": "apple", "position": 2}, {"word": "apple", "position": 4} ]}Groups appear in the order their keys first occurred, with their members kept in input order, so the editor can inspect the returned Rust values directly and flag any group with more than one item.
Turning this into a real editor tool quickly raises host-policy questions.
Should Apple and apple count as the same word?
Should apple, keep its comma or drop it?
A host can normalise text in its loader, or expose operations that let each query decide.
There is also a deeper limit to passing plain strings: the positions above count words, whereas highlighting text in an editor needs character offsets in the source file. Rather than flattening everything up front, a host can expose native handles (references into its own data model) along with operations to read their text or follow relations between them. The documentation sketches these extensions; the runnable example above sticks to plain strings.
That handle model is how Zirium and Zincite work.
Two MLIR operations called arith.addi can be distinct operations, and two MiniZinc declarations called capacity can live in different scopes.
Queries keep hold of the actual objects until a final projection asks for names or report fields, which can then be grouped just like words.
Find repeated operands in Zirium
Zirium queries MLIR, an intermediate representation used by compilers.
Suppose we want to find additions of the form x + x.
Both operands have to refer to the same SSA value, not merely share a printed name across different scopes.
In Zirium’s query language, that looks like this:
let matches = match { from add in (input | filter(op("arith.addi"))); bind lhs = operand(add, 0); bind rhs = operand(add, 1); where same_value(lhs, rhs);};let rows = matches | project(m, { "function": m.add | root(op("func.func")) | attr("sym_name") | one, "operation": m.add | names | one});report {"matches": rows, "count": length(rows)};The from clause visits each addition, the two bind clauses capture its operands, and same_value checks whether they point to the same SSA value.
The projection then reports the containing function’s name and the addition’s operation name.
On Zirium’s function example, this finds the addition in double and reports a count of 1.
Note that operand uses zero-based positions to match MLIR, whereas ordinary Zirql value arrays are one-based.
Here Zirql handles the bindings and scoping, while Zirium supplies operand, same_value, and navigation up to the containing function.
Compute over a tree
Queries can also define recursive functions. Zirium’s subtree-cost example has a root with no cost annotation and two children with costs 3 and 4:
fn subtree_cost(op: Operation) -> int { (cost_annotation(op) default 1) + sum([subtree_cost(child) | child in direct_children(op)])}let selected = filter(op("example.root"));report subtree_cost(selected) | jsonThe answer is 8: one for the unannotated root plus the two child costs.
default 1 supplies 1 when the annotation is missing, while a malformed annotation still fails as an error.
This recursion follows the containment tree through direct_children; walking operand dependencies instead would traverse a graph where operations could be revisited or form cycles.
Recursive calls draw from the same query budget as everything else.
Use Zincite as a Bash checker
Checking data files was one of my main reasons for adding queries to Zincite. In How I write MiniZinc, assertions sit next to the data declarations inside the model; a query lets me run checks directly against an instance file on its own. For example, having enough total capacity does not guarantee enough capacity at every position.
Save this as capacity.dzn:
demand = [2, 3, 4];capacity = [6, 8, 5];Suppose we want to double demand and fail the command if any position exceeds its capacity.
Zirql’s require turns a failed condition into a query error.
Save this query as capacity.zq:
let demand = items | filter(name("demand")) | values | one;let capacity = items | filter(name("capacity")) | values | one;let aligned_capacity = require( index_set(demand) = index_set(capacity), capacity, % Return this array when the indices match. "demand and capacity must have the same index set");let scaled = [2 * d | d in demand];require( forall( [scaled[i] <= aligned_capacity[i] | i in index_set(demand)] ), true, % Return true when every position fits. "Doubled demand exceeds capacity at one or more positions")The comprehension checks each scaled demand against the capacity at the same index, and forall returns true only when every position fits.
Here total scaled demand is 18 and total capacity is 19, yet the third position needs 8 and only has 5.
Running zincite query --program-file capacity.zq capacity.dzn fails with the message above and exits with a nonzero status.
That distinction matters for shell scripts: a query that merely evaluates to false still succeeds, whereas require triggers an evaluation error and a nonzero exit code, so Bash can branch on it without parsing stdout:
if zincite query --program-file capacity.zq capacity.dzn >/dev/null; then printf '%s\n' 'Capacity check passed'else printf '%s\n' 'Capacity check failed' >&2 exit 1fiRedirecting stdout suppresses the normal output while error diagnostics still go to stderr. With the data above, the script takes the failure branch; changing the third capacity from 5 to 8 makes it pass, while a parse error or exhausted query budget also exits nonzero.
The first require checks that the index sets match before comparing elements, so two arrays of equal length with different index ranges cannot be paired by mistake.
Zincite supplies the literal data and Zirql evaluates both checks without running a MiniZinc solver.
Zincite’s query guide extends this capacity example with input validation and detailed reports.
Conclusion
Extracting Zirql lets me improve filtering, comprehensions, and checks once and get the updates in both Zirium and Zincite, while the CSV host gives me a smaller testbed for trying ideas on plain tabular files. Next changes will keep coming from what those hosts actually run into in practice.
Footnotes
-
In How I write MiniZinc, I introduced Zincite’s formatting and linting tools and briefly covered its query language. The query guide has more detail. ↩
-
Zirql also accepts comprehensions with
forandif, as in Python:[w for w in words if starts_with(w, "a")]has the same meaning as the example above. ↩