Query CSV files with Zirql
The CSV example reads each file as a table of string fields, taking column names from its first row. You can filter rows, select fields, and combine named files into one report. To build an application like this, follow Build the CSV host.
Run these commands from the root of a Zirql 0.3.0 checkout with Rust 1.88 or
newer. Because csv is a Cargo example executable, installing the library does
not install a standalone CSV command.
Use the tabs to compare a query, its input, and its result, or to copy a shell
command. Each command passes a multiline query as one quoted argument. Results
below are indented for reading; the executable writes compact JSON by default.
Pass --format json or --format markdown after the query to choose the
output format.
The program reader accepts typed param declarations, named functions, and
pattern let bindings followed by one final expression. let and param
statements end with ;, while the final expression has no semicolon. Names
become visible after their declarations, and duplicate or forward bindings
fail. Functions take tables and thresholds as explicit arguments rather than
capturing ambient data. Pass repeated --param name=value arguments to supply
required scalar inputs. report statements are not part of this example.
rows and implicit count select the sole input; when you pass several files,
refer to each table by name. Header declarations apply even when a CSV file has
no data rows.
A typed string function can supply tally keys directly:
cargo run --locked --example csv -- 'fn echo(s:string)->string {s} [echo("ash"),echo("ash")] | tally' examples/csv/people.csvThis writes {"ash":2}, the same JSON object as ["ash","ash"] | tally.
Select rows from one file
Section titled “Select rows from one file”Select active people and keep their names and notes. Switch to CSV input to see the exact source, including CSV quoting and a cell with an embedded newline.
let selected = rows | filter(_.active == "yes");[ {"name": p.name, "note": p.note} for p in selected]id,name,team,active,note2,Grace Hopper,compiler,yes,"Said ""hello"""1,"Ada, Lovelace",compiler,yes,"First linesecond line"3,Barbara Liskov,runtime,yes,4,Edsger Dijkstra,compiler,no,01[ {"name": "Grace Hopper", "note": "Said \"hello\""}, {"name": "Ada, Lovelace", "note": "First line\nsecond line"}, {"name": "Barbara Liskov", "note": ""}]cargo run --locked --example csv -- 'let selected = rows | filter(_.active == "yes");[ {"name": p.name, "note": p.note} for p in selected]' \ examples/csv/people.csvrows names the sole input table, and filtering preserves file order. CSV
quoting preserves the comma in Ada’s name, the quotes in Grace’s note, and the
newline in Ada’s note, which JSON escapes inside its string. Empty cells stay
empty strings. Every cell is a string, including id, yes, no, and 01;
the host never guesses types or trims labels or values.
filter(p => p.active == "yes") names each row, while
filter(_.active == "yes") uses the unnamed row argument; both select the same
rows as [p for p in rows if p.active == "yes"]. Predicates can capture
earlier bindings:
let wanted = "yes";rows | filter(_.active == wanted)To count the rows, pipe the table into count:
cargo run --locked --example csv -- \ 'rows | count' \ examples/csv/people.csvThis prints 4. The shorter count expression uses the same table implicitly.
To count only active people, reuse the saved selection:
cargo run --locked --example csv -- 'let selected = rows | filter(_.active == "yes");selected | count' \ examples/csv/people.csvThis prints 3.
Render a Markdown table
Section titled “Render a Markdown table”Run the same selection with --format markdown to format it as a table:
cargo run --locked --example csv -- 'let selected = rows | filter(_.active == "yes");[{"name": p.name, "note": p.note} for p in selected]' --format markdown examples/csv/people.csv| name | note || --- | --- || Grace Hopper | Said "hello" || Ada, Lovelace | First line<br>second line || Barbara Liskov | |The output has a blank line before and after the table. Columns follow
first-seen field order, rows follow the selected input order, and missing or
absent cells render blank. Pipes and Markdown punctuation are escaped, angle
brackets and ampersands use HTML entities, and newlines become <br>. Nested
cells and structural dictionary keys render as compact JSON with the same
escaping.
A scalar count prints on its own line, scalar collections use a Value column,
and records or dictionaries use Key/Value columns. A keyed map of record
rows adds Key before the field columns. Empty collections and maps print
_No entries._. See Markdown rendering
for the complete shape rules and Rust API.
Parsing, evaluation, and rendering share one budget. Because the renderer
checks the full rectangular table size before expanding it, many sparse
columns can exceed the limit even with few rows. Any failure leaves stdout
empty. --format json selects the default compact JSON output, and positional
and named file arguments work with either format.
Map people within each team
Section titled “Map people within each team”This command visits teams in teams.csv order, filters matching active people,
and maps each person to a report record. Inside the inner pipeline, _ is the
current person while t captures the outer team:
cargo run --locked --example csv -- 'teams | flat_map(t => people | filter(_.team == t.id and _.active == "yes") | map({"team": t.label, "person": _.name}))' \ people=examples/csv/people.csv teams=examples/csv/teams.csvThe exact output is:
[{"team":"Runtime","person":"Barbara Liskov"},{"team":"Compiler","person":"Grace Hopper"},{"team":"Compiler","person":"Ada, Lovelace"}]flat_map concatenates the per-team positional results one level deep.
Operations has no matching people and contributes no rows, and the two Compiler
people keep file order. map alone would produce a nested sequence per team.
Both stages are eager, validate their bodies even on empty input, and share the
request and stream limits. Their inputs and flat_map results must be
positional sequences. The
capacity example uses the same stages
on nested numeric data.
Use your own CSV file
Section titled “Use your own CSV file”Replace the fixture path with your file. Counting rows needs no column names:
cargo run --locked --example csv -- \ 'rows | count' \ './my data.csv'Run rows as the query to inspect the decoded records, then adapt a selection
to match your headers and values. Quote paths that contain spaces; for a named
input, quote the whole argument, such as 'people=./my data.csv'.
The input must be comma-separated UTF-8 with a header row. Headers must be nonempty and unique, and every data row must have the header’s field count. The example caps input at 64 KiB across all files and 1,000 data rows per table. These are application limits; the host tutorial shows where to change them.
Identifier headers support dot access such as p.name. For headers with
spaces, use p["full name"] or lookup(p, "full name"). A column name can
also come from a binding:
cargo run --locked --example csv -- 'let column = "name";[p[column] for p in rows if p.active == "yes"]' \ examples/csv/people.csvThis returns ["Grace Hopper", "Ada, Lovelace", "Barbara Liskov"]. Brackets
evaluate a computed string key, while p.name selects a fixed label. Because
the CSV header declares the available columns, an unknown label fails strict
field access even when a table has no data rows.
Cells are always strings, so sorting an amount column sorts text ("10" comes
before "2"), and an empty cell is "" rather than null. Use explicit
scalar conversions for numeric calculations, and either handle empty cells
explicitly before parsing or let conversion report the malformed value.
Calculate with numeric cells
Section titled “Calculate with numeric cells”examples/csv/orders.csv stores quantities and prices as strings:
item,quantity,priceapples,02,1.25e1pears,10,2.5plums,1,3examples/csv/numeric-orders.zirql declares a minimum quantity and a report
label. Its named function takes the table, threshold, and label explicitly,
parses quantities for filtering and summation, and parses prices for line
totals. An f-string formats prices and totals in each line label to two decimal
places:
param minimum_quantity: int;param report_label: string;fn report_orders( orders: sequence<record {item: string, quantity: string, price: string}>, minimum: int, label: string) -> record {label: string, quantity: int, lines: sequence<record {item: string, total: float, label: string}>} { let selected = orders | filter(parse_int(_.quantity) >= minimum); { "label": label, "quantity": sum([parse_int(row.quantity) for row in selected]), "lines": [{ "item": row.item, "total": parse_float(row.quantity) * parse_float(row.price), "label": f"{row.item}: {parse_int(row.quantity)} × {parse_float(row.price):.2f} = {parse_float(row.quantity) * parse_float(row.price):.2f}" } for row in selected] }}report_orders(rows, minimum_quantity, report_label)Run the sole input through rows with both required parameter values:
cargo run --locked --example csv -- \ "$(cat examples/csv/numeric-orders.zirql)" \ --param minimum_quantity=2 --param report_label=orders \ --format json examples/csv/orders.csvcargo run --locked --example csv -- \ "$(cat examples/csv/numeric-orders.zirql)" \ --param minimum_quantity=2 --param report_label=orders \ --format markdown examples/csv/orders.csvTo call the same function with a named table, change only the final call’s input:
cargo run --locked --example csv -- \ "$(sed 's/report_orders(rows,/report_orders(orders,/' examples/csv/numeric-orders.zirql)" \ --param minimum_quantity=2 --param report_label=orders \ --format json orders=examples/csv/orders.csvcargo run --locked --example csv -- \ "$(sed 's/report_orders(rows,/report_orders(orders,/' examples/csv/numeric-orders.zirql)" \ --param minimum_quantity=2 --param report_label=orders \ --format markdown orders=examples/csv/orders.csvParameter arguments pass values, not query fragments: name=FILE arguments
select files, and --param name=value supplies parameters. Missing, duplicate,
unknown, or mistyped parameters fail before execution.
The report has label "orders" and quantity 12, with line totals 25.0 and
labels "apples: 2 × 12.50 = 25.00" and "pears: 10 × 2.50 = 25.00". The
original "02" and exponent text stay untouched in the CSV cells. The
scalar reference defines both decimal grammars.
Whitespace is not trimmed, so " 2" fails just like malformed or empty text.
Both commands below fail at the conversion and leave stdout empty:
cargo run --locked --example csv -- \ '[parse_int(row.item) for row in rows]' examples/csv/orders.csvcargo run --locked --example csv -- \ '[parse_int(row.note) for row in rows if row.id == "3"]' examples/csv/people.csvReuse selections across named files
Section titled “Reuse selections across named files”Name each input with name=path. Save the active people, build a member list
for each team, then reuse those lists for sorted names and counts.
let selected = people | filter(p => p.active == "yes");let groups = [ { "team": t.label, "members": [p.name for p in selected if p.team == t.id] } for t in teams];[ { "team": g.team, "members": sort(g.members), "count": length(g.members) } for g in groups]people.csv, with its decoded cell values:
| id | name | team | active | note |
|---|---|---|---|---|
| 2 | Grace Hopper | compiler | yes | Said "hello" |
| 1 | Ada, Lovelace | compiler | yes | First line second line |
| 3 | Barbara Liskov | runtime | yes | |
| 4 | Edsger Dijkstra | compiler | no | 01 |
| id | label |
|---|---|
| runtime | Runtime |
| compiler | Compiler |
| operations | Operations |
[ { "team": "Runtime", "members": ["Barbara Liskov"], "count": 1 }, { "team": "Compiler", "members": ["Ada, Lovelace", "Grace Hopper"], "count": 2 }, {"team": "Operations", "members": [], "count": 0}]cargo run --locked --example csv -- 'let selected = people | filter(p => p.active == "yes");let groups = [ { "team": t.label, "members": [p.name for p in selected if p.team == t.id] } for t in teams];[ { "team": g.team, "members": sort(g.members), "count": length(g.members) } for g in groups]' \ people=examples/csv/people.csv \ teams=examples/csv/teams.csvThe outer comprehension follows team-file order, and the inner comprehension
sees both the current team and the saved selected value. sort puts Ada
before Grace in the Compiler list while length counts its original members.
Operations has no active members, so it appears with an empty list. JSON
preserves both array order and the written team, members, count field
order.
A member field can also start a pipeline: g.members | sort gives the same
result as sort(g.members).
Bindings are immutable and visible only after their initializer; a let cannot
replace a table name, rows, or an earlier binding, and comprehension names
stay inside their expression. Through ConstructedProgram, the example accepts
typed parameters, pure named functions, ordered pattern let bindings, and one
final value expression. Functions receive tables and parameters explicitly, as
in the numeric orders report.
Pass either one unnamed file or only named files. Named tables must be unique
ASCII identifiers (a letter or underscore followed by letters, digits, or
underscores). _, rows, input, literals, and control or operator keywords
are reserved, using Zirql’s common keyword classification plus the CSV rows
alias; callable names such as lookup are not reserved and can name a table.
One named table also supplies rows and the implicit current input. With
several tables, refer to them by name; neither rows nor count guesses a
table for you.
Sort rows and reuse the result
Section titled “Sort rows and reuse the result”Constructed sort_by(rows, "name") takes both a collection and a field name.
Its comma belongs to the call, and commas or closing delimiters inside strings
or comments do not affect how the reader classifies it. A saved result accepts
the same constructed suffixes:
cargo run --locked --example csv -- 'let ordered = sort_by(rows, "name");ordered | map(_.name) | count' examples/csv/people.csvThis prints 4. Hosts with native stages also accept selector forms such as
Zirium’s sort_by(names); the shared reader distinguishes those calls before
reading their arguments.
Build a dictionary report
Section titled “Build a dictionary report”When each team needs a single count, use its label as a dictionary key. This
example uses the same people.csv and teams.csv inputs as above.
let selected = people | filter(p => p.active == "yes");sort_by( { t.label: length([p for p in selected if p.team == t.id]) for t in teams }, value, descending=true){ "Compiler": 2, "Runtime": 1, "Operations": 0}cargo run --locked --example csv -- 'let selected = people | filter(p => p.active == "yes");sort_by( { t.label: length([p for p in selected if p.team == t.id]) for t in teams }, value, descending=true)' \ people=examples/csv/people.csv \ teams=examples/csv/teams.csvThe inner comprehension counts selected people in the current team, so every
team gets an entry including Operations with 0. sort_by orders the counts
from largest to smallest while preserving the dictionary kind; equal counts
keep their incoming team order. Duplicate labels fail because a dictionary
requires distinct keys.
Use patterns and other expression forms
Section titled “Use patterns and other expression forms”Patterns extract fields in a predicate or a let binding. Select the first
active person, then extract their name:
cargo run --locked --example csv -- 'let [first, ..] = rows | filter( {active: status, ..} => status == "yes");let {name, ..} = first;name' \ examples/csv/people.csvThis returns "Grace Hopper". The record pattern binds active to status
and .. ignores the remaining fields. The list pattern requires at least one
selected row; if none matches, the let fails at [first, ..] and stdout
stays empty.
Both comprehension spellings use the same reader and evaluator:
cargo run --locked --example csv -- \ '[p.name for p in rows if p.active == "yes"]' \ examples/csv/people.csv
cargo run --locked --example csv -- \ '[name | {name, active, ..} in rows where active == "yes"]' \ examples/csv/people.csvBoth return the three active names in file order, and the same patterns and lexical rules apply to named inputs.
Nested filters can refer to an outer argument. To keep only teams with active people:
cargo run --locked --example csv -- 'teams | filter(t => length(people | filter(_.team == t.id and _.active == "yes")) > 0)' \ people=examples/csv/people.csv \ teams=examples/csv/teams.csv[ {"id": "runtime", "label": "Runtime"}, {"id": "compiler", "label": "Compiler"}]The outer filter binds t to a team. Inside the inner filter, _ is a person
while t stays in scope for the comparison. Operations is omitted because its
selection is empty.
See values and comprehensions for expression syntax and the language reference for collection stages, conditionals, and indexed literals.
Inspect an indexed value
Section titled “Inspect an indexed value”The reader can also build values addressed by integer keys. The
saved indexed example keeps keys
5, 2, 9, with cells at 5 and 2:
cargo run --locked --example csv -- \ "$(cat examples/csv/indexed-arrays.zirql)" \ examples/csv/people.csv{ "keys": [5, 2, 9], "cells": [ {"key": 5, "value": 50}, {"key": 2, "value": 20} ], "second": 20, "has_nine": false}index_set keeps unused keys; entries visits only present cells. You can
also return the keyed value directly:
cargo run --locked --example csv -- \ '[2: 20, 5: 50] axes([5, 2, 9])' \ examples/csv/people.csv{ "kind": "array", "indexing": "explicit", "axes": [[ {"kind": "integer", "value": 5}, {"kind": "integer", "value": 2}, {"kind": "integer", "value": 9} ]], "entries": [ {"key": [{"kind": "integer", "value": 5}], "value": {"kind": "integer", "value": 50}}, {"key": [{"kind": "integer", "value": 2}], "value": {"kind": "integer", "value": 20}} ]}The shared JSON renderer preserves the declared key 9
without inventing a cell for it. See keyed arrays for
row and column domains, typed empties, and sparse cells.
Understand errors
Section titled “Understand errors”A missing column fails at its query range:
cargo run --locked --example csv -- \ 'rows | filter(_.missing == "yes")' \ examples/csv/people.csvSeveral named tables make an implicit request ambiguous:
cargo run --locked --example csv -- \ 'count' \ people=examples/csv/people.csv \ teams=examples/csv/teams.csvA finite range can exceed the request’s result allowance before it is built:
cargo run --locked --example csv -- \ '1..100001' \ examples/csv/people.csvEach command exits unsuccessfully with empty stdout. Query diagnostics report the submitted text, byte range, and available table paths, and malformed query syntax keeps its original byte range. CSV failures identify the table and path along with the decoder’s record, line, and byte position where available. A failed request never prints partial JSON.
How the example evaluates a query
Section titled “How the example evaluates a query”The example loads at most 64 KiB of CSV source bytes across all input files using bounded reads, which also cap the CSV decoder’s temporary buffers. It supplies constructed arrays and records, header types, named-table lookup, and a call to Zirql’s JSON or Markdown renderer. Input loading, decoder admission, copies, parsing, evaluation, and output share one budget: 1,000,000 work units, 100,000 produced or copied results, nesting depth 64, and a 1,000-item stream ceiling. Work includes scanned and copied bytes, field metadata, and output bytes.
ConstructedBinding admits each table against its header-derived declaration,
and ConstructedProgram reads functions, typed parameters, ordered pattern
let bindings, and the final expression before preparing and evaluating them
under the same budget. The example needs no native reader or value-query
traits; it only handles CSV decoding, exact string cells, input-byte limits,
and sole-versus-named table selection.
The shared JSON and Markdown renderers format the
completed value into a buffer. main writes that buffer only after run
succeeds, so any conversion, evaluation, or rendering error leaves stdout
empty.
Build the CSV host walks through loading, declaring, and binding a table, supplying parameters, and returning JSON or Markdown. The minimal embedding starts from values already in memory. Use native integration when your application also needs native handles, source coordinates, or domain calls.
Keep distinct rows and count repeated rows
Section titled “Keep distinct rows and count repeated rows”Rows use structural equality across every field name and value. unique keeps
the first row in each equivalence class at its incoming position, and tally
uses that first row as the dictionary key while counting occurrences. The
resulting dictionary supports the usual selection and ordering operations:
cargo run --locked --example csv -- 'rows | unique | count' examples/csv/people.csvcargo run --locked --example csv -- 'rows | tally | reverse | head(1)' examples/csv/people.csvThe first command returns 4; the second keeps the last distinct row and its
count. Row keys remain records rather than becoming rendered strings.