Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
RUST / THE COOKBOOK/ DATA & TOOLS
RECIPE 04 / 8

A tiny durable task tool.

A Clap CLI backed by SQLite, parameterized statements, and tests.

BY NAVAN SAMI~25 MIN BUILDLOCAL PROJECT
Download this project ↓
Clap 4rusqlite 0.41SQLite

01 The shape of the build

This tool gives tasks persistence beyond one process. Clap parses a clear command interface, and rusqlite wraps SQLite with bound parameters. The schema is created on startup for this first version; schema evolution would need numbered migrations. The database path is explicit, and tests use in-memory databases so they do not touch a learner’s real task file. SQL operations return affected-row counts, allowing the CLI to distinguish successful completion from an unknown ID.

  1. 1

    Open an explicit database file and create the initial table.

  2. 2

    Trim and validate task titles before binding them to an INSERT.

  3. 3

    List rows in ID order and update completion by a bound ID.

  4. 4

    Use in-memory databases to test persistence operations without global fixtures.

02 Get it running

Install Rust stable and extract this project’s ZIP. Run these commands from the extracted sqlite-tool folder. The full workbench keeps it under cookbook/sqlite-tool.

terminal
cargo test
cargo run -- --db practice.sqlite add "Learn Rust"
cargo run -- --db practice.sqlite list
cargo run -- --db practice.sqlite done 1
cargo run -- --db practice.sqlite list
WHAT YOU SHOULD SEE

The first list shows 1 | [ ] Learn Rust. After done 1, it shows 1 | [x] Learn Rust. The SQLite file keeps the data between commands.

First builds download dependencies. The included Cargo.lock files record the versions resolved during authoring. Use --locked with Cargo commands when you want to enforce those resolutions.

03 The complete source

Every source file below is also in the download. Start with the manifest, then follow the Rust entry point and any UI or test files.

Cargo.toml10 lines +
Cargo.toml
[package]
name = "sqlite-tool"
version = "0.1.0"
edition = "2024"

[dependencies]
clap = { version = "4", features = ["derive"] }
rusqlite = { version = "0.41", features = ["bundled"] }

[workspace]
src/lib.rs31 lines +
src/lib.rs
use rusqlite::{Connection, Result, params};
pub fn initialize(db: &Connection) -> Result<()> {
    db.execute_batch("CREATE TABLE IF NOT EXISTS tasks(id INTEGER PRIMARY KEY, title TEXT NOT NULL, complete INTEGER NOT NULL DEFAULT 0)")
}
pub fn add(db: &Connection, title: &str) -> Result<i64> {
    db.execute("INSERT INTO tasks(title) VALUES (?1)", params![title])?;
    Ok(db.last_insert_rowid())
}
pub fn done(db: &Connection, id: i64) -> Result<bool> {
    Ok(db.execute("UPDATE tasks SET complete=1 WHERE id=?1", params![id])? > 0)
}
pub fn list(db: &Connection) -> Result<Vec<(i64, String, bool)>> {
    let mut statement = db.prepare("SELECT id,title,complete FROM tasks ORDER BY id")?;
    statement
        .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))?
        .collect()
}
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn round_trip() -> Result<()> {
        let db = Connection::open_in_memory()?;
        initialize(&db)?;
        let id = add(&db, "Navan's task")?;
        assert!(done(&db, id)?);
        assert!(!done(&db, 999)?);
        assert_eq!(list(&db)?, vec![(id, "Navan's task".into(), true)]);
        Ok(())
    }
}
src/main.rs42 lines +
src/main.rs
use clap::{Parser, Subcommand};
use rusqlite::Connection;
use std::path::PathBuf;
#[derive(Parser)]
#[command(about = "A small local SQLite task tool")]
struct Args {
    #[arg(long, default_value = "practice.sqlite")]
    db: PathBuf,
    #[command(subcommand)]
    command: Command,
}
#[derive(Subcommand)]
enum Command {
    Add { title: String },
    List,
    Done { id: i64 },
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args = Args::parse();
    let db = Connection::open(args.db)?;
    sqlite_tool::initialize(&db)?;
    match args.command {
        Command::Add { title } => {
            let title = title.trim();
            if title.is_empty() || title.chars().count() > 80 {
                return Err("title must contain 1–80 characters".into());
            }
            println!("created {}", sqlite_tool::add(&db, title)?);
        }
        Command::List => {
            for (id, title, complete) in sqlite_tool::list(&db)? {
                println!("{id} | [{}] {title}", if complete { "x" } else { " " });
            }
        }
        Command::Done { id } => {
            if !sqlite_tool::done(&db, id)? {
                return Err("task not found".into());
            }
        }
    }
    Ok(())
}

04 Check the behavior

  • □cargo test verifies insertion, completion, and missing-ID handling.
  • □An apostrophe in a title is stored as text through SQL parameters.
  • □Opening the same --db path in a new process preserves tasks.

05 Know what you are building on

The practice database is created at the path you choose.

CREATE TABLE IF NOT EXISTS is initial setup, not a full migration system.

The tool has one local user and no synchronization or encrypted storage.

MAKE IT YOUR OWN

Choose one boundary to improve. Write down the new behavior, add a test that demonstrates it, then change the implementation. Keep the original working path intact.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.