SQL databases and Rust

Day 7

Rust for bioinformaticians

What this lecture is

  • Why “a few TSV files” stops working, and a relational database (data organised as tables that reference each other) starts
  • The minimum SQL (Structured Query Language, the standard way to ask a database questions) you will use every working day
  • What SQLite is — an embedded database (lives inside your program, not on a server)
  • Driving SQLite from Rust with the rusqlite crate

The pain that motivates today

You’re managing a microbial strain collection. The lab uses a shared TSV file.

Two team members typing the same strain's name slightly differently, leaving the TSV with inconsistent entries.

Two team members type the same strain’s name slightly differently.

A duplicated row showing the same strain with two strain_id values and contradictory isolation_source entries.

A row gets pasted twice; contradictory values, no way to tell which is right.

Two users opening the same TSV in Excel, with the second save overwriting the first.

Two Excel users save the same TSV; second save silently wins.

A relational database in one picture

A relational database (data organised as tables that reference each other) stores facts as rows in named tables. Each row is a tuple (a single row’s values bundled together).

The strain table drawn as a grid. Header row in light blue lists the five columns (strain_id, strain_name, species, isolation_source, year_isolated) with their types (INTEGER, TEXT, TEXT, TEXT, INTEGER). Four data rows follow; the first row (K-12 MG1655) is highlighted in yellow to make the 'one row equals one record' point visible. An annotation on the left points at the highlighted row and reads 'one row = one record (a tuple)'. A dashed line from the type sub-row points to a label 'each column has a declared type'. A green PRIMARY KEY badge under the strain_id header is connected by a dashed line up to the column. Below the table, three small fact callouts summarise: rows are an unordered set of records; columns have fixed names and types; the primary key is unique across every row.

A table is rows and columns; the primary key names each row.

Tables, rows, columns, types

A table is a named grid.

A row is one record — a tuple of column values.

A column has a name and a declared type. SQLite’s main types:

Declared type Used for
INTEGER counts, IDs, years
REAL floating-point values (OD, fractions)
TEXT strings (names, free text)
INTEGER PRIMARY KEY auto-incrementing row ID

Primary keys — one row, one identity

The primary key uniquely identifies a row. Two rows may agree on every other column, but never on the primary key.

CREATE TABLE strain (
    strain_id        INTEGER PRIMARY KEY,
    strain_name      TEXT    NOT NULL,
    species          TEXT    NOT NULL,
    isolation_source TEXT,
    year_isolated    INTEGER
);

INTEGER PRIMARY KEY auto-assigns the next free integer on INSERT. NOT NULL makes the column mandatory.

Reference: CREATE TABLE, PRIMARY KEY, NOT NULL.

Why tables need to reference each other

If every assay record repeated the full strain metadata:

  1. Storage explodes (same strain, hundreds of assays).
  2. Updates are unsafe — change one row, forget the other 99, the data quietly disagrees with itself.

Normalisation: store each strain once; every assay carries only its strain_id and joins against the strain table when needed.

A wide assay table where strain metadata is repeated on every row, with one row's species edited and the others left stale.

Without references, the same strain is repeated on every assay row; an update misses some copies.

Foreign keys — linking two tables

A second table refers to the first by storing its primary-key value as a foreign key (a column whose value must match a primary key in another table).

This gives referential integrity (the database refuses to insert an assay whose strain doesn’t exist).

Two tables side by side. Left table (strain) has three rows: strain_id 1 K-12 MG1655 in blue, strain_id 2 DH5alpha in magenta, strain_id 3 168 in orange; the strain_id column is highlighted in green with a small PRIMARY KEY badge. Right table (assay) has three rows: assay_id 101 strain_id 1 in blue, 102 strain_id 3 in orange, 103 strain_id 1 in blue; the strain_id column is highlighted in green with a FOREIGN KEY badge in yellow. A large dashed arrow from the assay.strain_id header to the strain.strain_id header reads 'REFERENCES strain(strain_id)'. Coloured connector lines link each assay row to its matching strain row by colour. Caption at bottom explains: one strain can have many assays; every assay belongs to exactly one strain; the database enforces the relationship.

Foreign keys make the relationship explicit and enforced.

INSERT — add rows

INSERT INTO strain (strain_name, species, isolation_source, year_isolated)
VALUES ('K-12 MG1655', 'Escherichia coli', 'human gut', 1922);
  • Strings in single quotes; double quotes mean identifier.
  • We omitted strain_id — INTEGER PRIMARY KEY assigns the next free integer.
Before/after view of the strain table: three rows, then four after the INSERT, with the new row's strain_id auto-assigned.

Before INSERT 3 rows; after, the new row is appended with auto-assigned strain_id.

Reference: INSERT.

SELECT — read rows

SELECT strain_name, species, year_isolated
FROM strain
WHERE species = 'Escherichia coli'
ORDER BY year_isolated DESC
LIMIT 5;
  • FROM picks the table; WHERE filters; ORDER BY sorts; LIMIT cuts.
Output table of the SELECT query, showing only strain_name and species columns for rows where year_isolated exceeds 1980.

Result: only the requested columns, only the matching rows.

SELECT, WHERE, ORDER BY, LIMIT.

Aggregation — GROUP BY + COUNT / AVG

Aggregation collapses many rows into one summary row per group.

-- How many strains per species?
SELECT species, COUNT(*) AS n
FROM strain
GROUP BY species
ORDER BY n DESC;
-- Mean OD per medium, only media measured >= 3 times
SELECT medium, AVG(od600_24h) AS mean_od, COUNT(*) AS n
FROM assay
GROUP BY medium
HAVING COUNT(*) >= 3;

GROUP BY, COUNT, AVG.

Aggregation — visualised

An input assay table with many rows mapped to an output table with one row per medium, showing the AVG(od600_24h) computed per group.

Input: many assay rows. Output: one row per medium with AVG(od600_24h) per group.

SELECT as a pipeline

The clauses don’t run in writing order — they run as a pipeline.

Pipeline stage 1: the FROM clause selects the input table(s).

Stage 1 — FROM: pick the input table(s).

Pipeline stage 2: the WHERE clause filters individual rows.

Stage 2 — WHERE: filter rows.

Pipeline stage 3: the GROUP BY clause buckets rows by a key.

Stage 3 — GROUP BY: bucket rows by a key.

SELECT pipeline (continued)

Pipeline stage 4: the SELECT clause and aggregations compute columns per group.

Stage 4 — SELECT + aggregations: compute columns per group.

Pipeline stage 5: the ORDER BY and LIMIT clauses sort and trim the result.

Stage 5 — ORDER BY + LIMIT: sort and trim.

WHERE filters individual rows before grouping; HAVING filters whole groups after aggregation.

JOIN — combine two tables

A join (stitching two tables together so a single row in the result contains columns from both) is how we follow a foreign key.

SELECT s.strain_name, s.species, a.medium, a.od600_24h
FROM strain AS s
INNER JOIN assay AS a ON a.strain_id = s.strain_id
WHERE s.species = 'Escherichia coli'
ORDER BY a.date_measured;
  • AS s, AS a — table aliases, saves typing
  • ON a.strain_id = s.strain_id — the join condition
  • INNER JOIN (keep only rows that have a match on both sides) is the default and most common shape

INNER JOIN — visualised

The strain and assay tables side by side with no joined output yet.

Start: strain and assay tables, no joined rows yet.

An assay row with strain_id 1 joined to strain row 1, producing one combined output row.

Match #1: assay strain_id = 1 joins to strain row 1.

INNER JOIN — visualised (continued)

A second assay for strain_id 1 joined to the same strain row, illustrating one strain with many assays.

Match #2: a second assay reuses the same strain row (one-to-many).

The complete inner-join output: every assay matched to its strain, one output row per matching pair.

All matching pairs: one output row per (strain, assay) match.

NATURAL JOIN — the shortcut

NATURAL JOIN auto-joins on every column the two tables share by name.

SELECT strain_name, species, medium, od600_24h
FROM strain NATURAL JOIN assay;

Equivalent to JOIN ... ON a.strain_id = s.strain_id because that is the one shared column.

Two table headers side by side with strain_id highlighted as the only shared column name, the implicit NATURAL JOIN key.

strain_id is the only shared column — so it’s the join key.

Convenient on tidy schemas; dangerous when someone later adds a matching-name column. Prefer explicit JOIN ... ON in real code.

NULL is weird — handle with care

NULL is “no value here” — not zero, not empty string. Comparing anything to NULL gives NULL, not true or false.

-- Tiny table: assay_id 101 od=0.42, 102 od=NULL, 103 od=0.61

SELECT * FROM assay WHERE od600_24h = NULL;   -- 0 rows! (NULL = NULL is NULL)
SELECT * FROM assay WHERE od600_24h IS NULL;  -- 1 row   (the right way)

SELECT COUNT(*)          FROM assay;          -- 3 (every row)
SELECT COUNT(od600_24h)  FROM assay;          -- 2 (skips NULL)
  • Use IS NULL / IS NOT NULL, never = NULL.
  • COUNT(*) counts rows; COUNT(column) counts non-NULL values.

LEFT JOIN — keep the unmatched

SELECT s.strain_name, COUNT(a.assay_id) AS n
FROM strain AS s
LEFT JOIN assay AS a ON a.strain_id = s.strain_id
GROUP BY s.strain_name
ORDER BY n;

LEFT JOIN keeps every left-table row, filling NULL on the right when no match exists. A strain with zero assays shows up with n = 0; INNER JOIN would drop it silently.

LEFT JOIN output retaining all left-table rows; rows with no match on the right show NULL values in the right-side columns.

LEFT JOIN keeps unmatched left rows; right-side fields become NULL.

INNER vs LEFT vs NATURAL — when to use which

Want Use
Only rows present in both tables INNER JOIN ... ON ...
Every row from one table, even unmatched LEFT JOIN ... ON ...
Quick prototype on a tidy schema NATURAL JOIN
Real, long-lived code INNER or LEFT with explicit ON

What is SQLite?

A relational database engine packaged as a C library, not a server.

  • One .db file is one entire database (the schema — the table definitions, columns, types, keys — plus every row of data)
  • No daemon, no port, no user accounts, no configuration
  • The most-deployed database in the world — every Android app, every iPhone, every browser, most desktop software, every airliner

SQLite vs. client/server

Two-panel diagram. Left panel headed 'Client / server (PostgreSQL)' in red: a light-blue box labelled 'Process A — your code, cargo run, Postgres client library opens a socket' and a magenta box labelled 'Process B — postgres, postgres -D /var/lib, listens on port 5432, long-running daemon'. A TCP arrow runs between them in both directions. The server connects down to a grey database-file box labelled '/var/lib/postgresql/ — many files, WAL, locks, managed by the server'. Below: cost of admission list — install + configure server daemon, create user, create database set password, open and authenticate a TCP connection, network latency on every query — and a note 'justified at multi-user web scale'. Right panel headed 'Embedded (SQLite)' in green: one large blue process box labelled 'Process — your code, with SQLite linked in, cargo run', containing a smaller green box labelled 'rusqlite + libsqlite3, function calls inside your process (no network)', which connects down to a grey file box labelled 'strains.db — one file, schema + data, opened directly via fs' with a 'read() / write()' label on the arrow. Below: cost of admission list — cargo add rusqlite that is it, no server to start no user to create, no network no socket no auth, one .db file you can email to a colleague — and a note 'justified at one analyst, one pipeline'. Caption at bottom: SQLite is a library, not a server. The most-deployed database in the world.

SQLite is a library, not a server.

Why SQLite fits bioinformatics

  • One file — fits the “one analysis directory” workflow we already use
  • Embedded — no extra service to keep alive on a shared cluster
  • Cross-platform — .db files work unchanged on Linux, macOS, Windows
  • Single writer — fine when one pipeline owns the data

Concretely, where a .sqlite file shows up in practice:

Use case Why a file works
Public annotation dumps (e.g. genome browsers) One download, no server to install
Your lab’s strain or sample collection Email or rsync one .db to a collaborator
Pipeline metadata / per-sample results Embedded next to the output directory
Test fixtures for analysis code Open in-memory, seed, throw away

The sqlite3 CLI

$ sqlite3 strains.db        # opens (creates if missing)
sqlite> SELECT * FROM strain LIMIT 3;     -- runs SQL

Dot-commands are CLI-only features (no trailing ;):

.tables              -- list table names
.schema strain       -- show CREATE TABLE
.headers on          -- show column names in SELECT output
.mode column         -- align rows as a table
.read seed.sql       -- run SQL from a file
.import data.csv t   -- load CSV into table t
.quit

sqlite3 docs.

Talking to SQLite from Rust — rusqlite

[dependencies]
rusqlite = { version = "0.31", features = ["bundled"] }

rusqlite is a thin wrapper (Rust code that calls SQLite’s underlying C functions for you — you write Rust, the C library does the work) around the SQLite C library.

The bundled feature compiles SQLite from source into your binary — no system library required. Costs ~30 s on the first build, then cached.

The rusqlite read pipeline

Four lines of Rust, four conceptual stages:

Step 1: Connection::open opens (or creates) the .db file and returns a Connection handle.

Step 1 — Connection::open(path): open (or create) the .db file.

Step 2: conn.prepare compiles the SQL string into a reusable Statement object.

Step 2 — conn.prepare(...): compile SQL into a reusable prepared statement.

Step 3: stmt.query_map binds parameters, runs the query, and maps each row to a Rust struct via the closure.

Step 3 — stmt.query_map(params, |row| ...): bind, run, map each row.

Step 4: iterate MappedRows with a for loop.

Open and execute one statement

use rusqlite::Connection;

let conn = Connection::open("strains.db")?;

conn.execute(
    "INSERT INTO strain (strain_name, species, year_isolated)
     VALUES (?1, ?2, ?3)",
    rusqlite::params!["K-12 MG1655", "Escherichia coli", 1922],
)?;

Read rows back — the row struct

A plain Rust struct holds one row’s worth of fields:

#[derive(Debug)]
struct Strain {
    strain_id:   i64,
    strain_name: String,
    species:     String,
}

Each column maps to one field. NOT NULL columns map to T; nullable columns map to Option<T> (next slide).

Read rows back — prepare and iterate

let mut stmt = conn.prepare(                            // compile once
    "SELECT strain_id, strain_name, species
     FROM strain
     WHERE species = ?1",
)?;

let rows = stmt.query_map(["Escherichia coli"], |row| { // bind, run, map
    Ok(Strain {
        strain_id:   row.get(0)?,
        strain_name: row.get(1)?,
        species:     row.get(2)?,
    })
})?;

for strain in rows {
    println!("{:?}", strain?);
}

prepare → query_map → loop. Same shape every time.

Nullable columns map to Option

struct Strain {
    strain_id:        i64,
    strain_name:      String,           // NOT NULL  -> T
    species:          String,           // NOT NULL  -> T
    isolation_source: Option<String>,   // nullable  -> Option<T>
    year_isolated:    Option<i64>,      // nullable  -> Option<i64>
}

If a column can be NULL, the Rust field must be Option<T>.

Getting it wrong is one of the few rusqlite errors that bites at runtime — InvalidColumnType on the first NULL.

Parameter binding — never format! into SQL

Parameter binding sends the SQL template and the values separately, instead of pasting values into the SQL string.

// NEVER do this:
let species = user_input;
conn.execute(
    &format!("SELECT * FROM strain WHERE species = '{}'", species),
    [],
)?;

If user_input is "x'; DROP TABLE strain; --", you just deleted the table — a SQL injection.

Parameter binding — the safe form

// ALWAYS do this:
conn.execute(
    "SELECT * FROM strain WHERE species = ?1",
    rusqlite::params![species],
)?;

The ?1 placeholder + params! macro escape the value safely.

Any value not literally typed by you goes through ?1 / params!, never format!. Non-negotiable.

SQL injection in the wild

The “Bobby Tables” comic is a joke, but the bug is real and expensive:

The XKCD 'Exploits of a Mom' comic strip, showing a school calling a parent about their child named 'Robert'); DROP TABLE Students;--' which deleted all student records due to a SQL injection vulnerability.

In 2015 the UK ISP TalkTalk lost ~157,000 customers’ details to SQL injection — total cost ~£77 million.

→ TalkTalk breach, SQL injection incidents

Use parameter binding. Always.

Transactions — atomicity AND performance

A transaction (a group of statements treated as one indivisible unit) gives you two things:

  • Atomicity (all the writes happen together, or none of them do) — if anything fails between BEGIN and COMMIT, the database rolls back to its prior state.
  • Performance — one fsync (force the disk to actually save) at COMMIT, instead of one per row.
Two timelines stacked vertically on the same horizontal time axis. Top timeline headed in red 'Without a transaction — one fsync per INSERT': six small blue INSERT bars, each followed by a tall magenta fsync bar; under the timeline a red bracket spans the full width labelled 'total: ~6 × disk-sync (each fsync ≈ 5–10 ms on an SSD)'. Bottom timeline headed in green 'With a transaction — one fsync at COMMIT': a green BEGIN box, then six small blue INSERT bars back-to-back, then a green COMMIT box, then a single tall magenta fsync bar at the end; under the timeline a green bracket much shorter than the top one labelled 'total: ~1 × disk-sync'. Bottom caption: for a 10 000-row bulk load this is roughly a 1000× speedup; always wrap bulk writes in BEGIN ... COMMIT. In rusqlite use Connection::transaction with tx.commit, and dropping the transaction without commit rolls back.

One fsync per transaction beats one fsync per row.

Transactions in rusqlite

let tx = conn.transaction()?;
{
    let mut stmt = tx.prepare(
        "INSERT INTO strain (strain_name, species, year_isolated)
         VALUES (?1, ?2, ?3)",
    )?;
    for s in strains {
        stmt.execute(rusqlite::params![s.name, s.species, s.year])?;
    }
}
tx.commit()?;

In-memory test databases

#[test]
fn list_strains_returns_all_rows() {
    let conn = Connection::open_in_memory().unwrap();
    conn.execute_batch(SEED_SQL).unwrap();

    let strains = list_strains(&conn).unwrap();

    assert_eq!(strains.len(), 10);
    assert_eq!(strains[0].strain_name, "K-12 MG1655");
}

Connection::open_in_memory gives you a throwaway database that lives in RAM and dies with the test.

#[test] marks a function cargo test will run; open_in_memory() gives each test its own fresh database.

What we deliberately leave out

  • UPDATE, DELETE, ALTER TABLE — same parameter pattern as INSERT
  • Indexes — an index (a pre-sorted lookup the database builds for one column) turns “scan a million rows” into “jump straight to the matches”; matters once a table gets big
  • EXPLAIN QUERY PLAN — see which indexes the engine actually used
  • Window functions, CTEs (WITH ...), recursive queries
  • Migrations (refinery, sqlx-cli) — versioned ALTER TABLE
  • The async ecosystem (sqlx, SeaORM, tokio-postgres)

You will recognise the names. The skills you learn today transfer 1:1 to PostgreSQL, MySQL, and the async stack.

To the exercises

# Exercise What you build
01 sqlite-cli CREATE, INSERT, SELECT, WHERE, GROUP BY
02 natural-join INNER/NATURAL/LEFT JOIN across two tables
03 read-from-rust Connection::open, prepare, query_map
04 write-from-rust transaction, prepared INSERT, Option<T>
05 query-from-rust LEFT JOIN + GROUP BY, from Rust

Reference: day 7 — Concepts. Start: Exercise 1.

cd day7/ex-sqlite-strains
sqlite3 strains.db