diff --git a/README.md b/README.md index 12cd571..148d64b 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,25 @@ fn main() { ``` For more library examples, refer to the [`examples`](https://github.com/rust-db/refinery/tree/main/examples). + +### Example: Optional development seed data + +Keep data required by every deployment in a versioned migration. For optional +development fixtures, run the same migrations in every environment and load +the fixtures separately when requested. The SQLite +[`seed_data` example](examples/examples/seed_data.rs) runs the schema migration +first and uses `ON CONFLICT (slug) DO NOTHING` so re-running the seed step keeps +existing rows and their edits. + +```sh +db_dir=$(mktemp -d) +cargo run -p refinery-examples --example seed_data -- "$db_dir/demo.db" +cargo run -p refinery-examples --example seed_data -- "$db_dir/demo.db" --seed +cargo run -p refinery-examples --example seed_data -- "$db_dir/demo.db" --seed +``` + +These commands report 0, 1, and 1 rows in the demo table, respectively. + ### Example: CLI ```bash diff --git a/examples/examples/seed_data.rs b/examples/examples/seed_data.rs new file mode 100644 index 0000000..060af73 --- /dev/null +++ b/examples/examples/seed_data.rs @@ -0,0 +1,31 @@ +use std::{error::Error, ffi::OsStr}; + +use rusqlite::Connection; + +refinery::embed_migrations!("seed_migrations"); + +fn main() -> Result<(), Box> { + let usage = "usage: seed_data [--seed]"; + let mut args = std::env::args_os().skip(1); + let path = args.next().ok_or(usage)?; + let seed = match args.next().as_deref() { + None => false, + Some(flag) if flag == OsStr::new("--seed") && args.next().is_none() => true, + Some(_) => return Err(usage.into()), + }; + + let mut conn = Connection::open(path)?; + migrations::runner().run(&mut conn)?; + + if seed { + conn.execute( + "INSERT INTO demo_projects (slug, name) VALUES (?1, ?2) + ON CONFLICT (slug) DO NOTHING", + ("example", "Example project"), + )?; + } + + let count: i64 = conn.query_row("SELECT COUNT(*) FROM demo_projects", [], |row| row.get(0))?; + println!("demo_projects rows: {count}"); + Ok(()) +} diff --git a/examples/seed_migrations/V1__create_demo_projects.sql b/examples/seed_migrations/V1__create_demo_projects.sql new file mode 100644 index 0000000..212286f --- /dev/null +++ b/examples/seed_migrations/V1__create_demo_projects.sql @@ -0,0 +1,4 @@ +CREATE TABLE demo_projects ( + slug TEXT PRIMARY KEY NOT NULL, + name TEXT NOT NULL +);