DEV Community

Cover image for csvq: a CSV command-line toolkit in Rust with Parquet conversion and SQL over files
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

csvq: a CSV command-line toolkit in Rust with Parquet conversion and SQL over files

A CSV file lands on your machine. It might be an export from an accounting tool, a dump from a database, or a log someone turned into columns. Before you do anything with it, you have questions. What are the columns? How many rows? Which values appear in the city column, and how often? Is age really a number everywhere?

There are a few habitual ways to answer. Open it in a spreadsheet, which works until the file has two million rows. Write a short script, which takes ten minutes each time and gets thrown away. Or import it into a database to run one GROUP BY, then forget to drop the table.

csvq is a command-line toolkit for exactly these moments. It is written in Rust and has three parts: xsv-style streaming commands for inspecting and slicing files, conversion between CSV and Parquet, and SQL over files, where the file path goes straight into the FROM clause. The SQL and Parquet parts are powered by Polars.

What it does

Look at a file. headers lists the column names with their 1-based index. count counts data rows. slice prints rows by position, either a range or a single row.

Pick columns and rows. select keeps or reorders columns. It accepts names, 1-based indices and ranges such as 2-4, a-c or 3-. search keeps the rows where a regular expression matches, in all columns or in selected ones, with -i to ignore case and -v to keep the rows that do not match.

Summarize. frequency gives the top values per column, ten by default. stats reports, per column, the type, the nulls, min and max, lengths, mean and standard deviation. With --cardinality it also counts distinct values.

Sort and join. sort orders rows by one or several keys, as text or as numbers (-N), optionally reversed (-R). In numeric mode, values that are not numbers sort last. join is a hash join of two files on key columns, inner by default and left with --left.

Convert. convert goes between CSV/TSV and Parquet, choosing the direction from the file extensions.

Query with SQL. sql runs a query where FROM and JOIN name files. CSV and Parquet can be mixed in one query, and the result is written as CSV to stdout, ready to pipe into another command.

The streaming commands read from a file or from stdin. Two global options apply everywhere: -d sets the delimiter (a single character, or tab), and --no-headers treats the first row as data, in which case columns are named 1, 2, 3 and so on.

How to use it

Install it from GitHub with Cargo:

cargo install --git https://github.com/AbdeldjalilChougui/csvq --locked
Enter fullscreen mode Exit fullscreen mode

Or clone the repository and run cargo install --path . inside it. Then:

csvq headers people.csv
csvq count people.csv
csvq select name,3-4 people.csv            # names, 1-based indices, ranges (a-c, 3-)
csvq search -s city -i '^oran$' people.csv  # regex filter (-v to invert)
csvq slice -s 10 -l 5 people.csv            # rows 10..15  (-i N for one row)
csvq sort -s age -N -R people.csv           # numeric, reversed (multi-key: -s city,name)
csvq frequency -s city -l 5 people.csv      # top values per column
csvq stats --cardinality people.csv         # type, nulls, min/max, lengths, mean, stddev
csvq join city people.csv city cities.csv   # hash join (--left for left join)
csvq convert people.csv people.parquet      # and back: .parquet -> .csv/.tsv
csvq sql "SELECT city, count(*) n, avg(age) FROM people.csv GROUP BY city ORDER BY n DESC"
csvq sql "SELECT p.name, c.code FROM 'data/people.parquet' p JOIN cities.csv c ON p.city = c.city"
cat x.csv | csvq -d ';' select 2            # stdin, custom delimiter (-d tab), --no-headers
Enter fullscreen mode Exit fullscreen mode

The last line shows the Unix side of the tool. Semicolon-separated files are common wherever the comma is the decimal separator, and -d ';' handles them. Because output goes to stdout, commands chain: filter with search, keep three columns with select, then hand the result to frequency.

The sql command deserves a closer look. In the second query above, a Parquet file in a subfolder is joined to a CSV file in the current directory, with aliases, in one line. There is no import step and no schema to declare.

How it works

The streaming commands use the csv crate. select, search, slice, count, stats, frequency and the probe side of join stream row by row in constant memory, apart from per-column counters. That means the size of the file does not decide whether the command can run. sort and the build side of join, which is the second file, are held in memory.

stats infers each column's type with a simple ladder: Integer is a subset of Float, which is a subset of String, and empty cells are ignored. It computes the mean and the population standard deviation in one pass with Welford's algorithm, so it never needs to store the values. Distinct counts are only done on request, because they do use memory.

convert and sql scan files lazily with Polars. For sql, the file paths after FROM and JOIN, bare or quoted, are rewritten to table names taken from the file stem, and those tables are registered in a Polars SQLContext. String literals are left alone, so a path-looking string inside a WHERE clause is not touched.

Things to know

  • sort and join load data into memory. There is no external sort and no index. The index command from xsv is not implemented.
  • Type inference is basic. In stats, each cell is parsed as i64 or f64. Dates are reported as strings.
  • SQL is Polars SQL. sql supports what Polars SQL supports, no more. Only files with .csv, .tsv or .parquet extensions are recognized after FROM and JOIN.
  • The first build is slow. Polars is a large dependency, so expect to wait when you compile from source.

What is tested. cargo test runs unit tests for column selection, for every streaming command and for the SQL rewriter. The CLI tests in tests/cli.rs cover stdin and delimiters, joins, error messages, a CSV to Parquet to CSV round trip that must match byte for byte, SQL aggregation, and a join between a Parquet file and a CSV file.

The README calls the tool fast, but it publishes no benchmark, so I will not quote one here. The claim you can check from the design is narrower and more useful: most commands run in constant memory.

Why I built it

The three jobs, inspect, convert and query, usually mean three different tools with three different sets of flags. xsv showed how pleasant small composable CSV commands can be: one verb per command, stdin in, stdout out. But some questions are just easier to ask in SQL, especially anything with GROUP BY or a join between two files, and more and more data now arrives as Parquet instead of CSV.

Polars already has a lazy scanner for both formats and a SQL context. So the idea was to put the two styles in one binary: streaming commands for the quick look, and csvq sql for the moment a pipeline of small commands would become harder to read than one query. Writing the file path directly in FROM removes the last bit of friction, the step where you would otherwise have to name and register a table before asking your question.

Get the code

The source and the tests are on GitHub: https://github.com/AbdeldjalilChougui/csvq. It is MIT licensed. Issues and pull requests are welcome.


Originally published at abdeldjalilchougui.biz.

Top comments (0)