From bd59a5128c05dcd550e91bbdd0cd9d5996a65586 Mon Sep 17 00:00:00 2001 From: Joris Date: Sun, 9 Jan 2022 09:43:21 +0100 Subject: Persist events to sqlite db --- src/db/migrations/1-init.sql | 9 +++++++++ src/db/mod.rs | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 src/db/migrations/1-init.sql create mode 100644 src/db/mod.rs (limited to 'src/db') diff --git a/src/db/migrations/1-init.sql b/src/db/migrations/1-init.sql new file mode 100644 index 0000000..72fab80 --- /dev/null +++ b/src/db/migrations/1-init.sql @@ -0,0 +1,9 @@ +CREATE TABLE IF NOT EXISTS "events" ( + "id" INTEGER PRIMARY KEY, + "date" VARCHAR NOT NULL, + "start" VARCHAR NULL, + "end" VARCHAR NULL, + "name" VARCHAR NOT NULL, + "created" TIMESTAMP NOT NULL, + "updated" TIMESTAMP NOT NULL +); diff --git a/src/db/mod.rs b/src/db/mod.rs new file mode 100644 index 0000000..3348673 --- /dev/null +++ b/src/db/mod.rs @@ -0,0 +1,36 @@ +use anyhow::Result; +use rusqlite::{params, Connection}; +use rusqlite_migration::{Migrations, M}; + +use crate::model::event::Event; + +pub fn init() -> Result { + let mut conn = Connection::open("database.db")?; + let migrations = Migrations::new(vec![M::up(include_str!("migrations/1-init.sql"))]); + migrations.to_latest(&mut conn)?; + Ok(conn) +} + +pub fn insert(conn: &Connection, event: &Event) -> Result<()> { + conn.execute( + "INSERT INTO events (date, start, end, name, created, updated) VALUES (?, ?, ?, ?, datetime(), datetime())", + params![event.date, event.start, event.end, event.name] + )?; + + Ok(()) +} + +pub fn list(conn: &Connection) -> Result> { + let mut stmt = conn.prepare("SELECT date, start, end, name FROM events")?; + + let iter = stmt.query_map([], |row| + Ok(Event { + date: row.get(0)?, + start: row.get(1)?, + end: row.get(2)?, + name: row.get(3)?, + }) + )?; + + Ok(iter.map(|r| r.unwrap()).collect()) +} -- cgit v1.2.3