Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 31 additions & 0 deletions examples/examples/seed_data.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
use std::{error::Error, ffi::OsStr};

use rusqlite::Connection;

refinery::embed_migrations!("seed_migrations");

fn main() -> Result<(), Box<dyn Error>> {
let usage = "usage: seed_data <database> [--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(())
}
4 changes: 4 additions & 0 deletions examples/seed_migrations/V1__create_demo_projects.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
CREATE TABLE demo_projects (
slug TEXT PRIMARY KEY NOT NULL,
name TEXT NOT NULL
);