aboutsummaryrefslogtreecommitdiff
path: root/src/db
diff options
context:
space:
mode:
authorJoris2022-01-09 09:43:21 +0100
committerJoris2022-01-09 10:11:29 +0100
commitbd59a5128c05dcd550e91bbdd0cd9d5996a65586 (patch)
tree541f7d49253ad3e7c8dfab480f33a2b10107b0d2 /src/db
parentce978143f1360e16e85587644055a9f83d11c64c (diff)
Persist events to sqlite db
Diffstat (limited to 'src/db')
-rw-r--r--src/db/migrations/1-init.sql9
-rw-r--r--src/db/mod.rs36
2 files changed, 45 insertions, 0 deletions
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<Connection> {
+ 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<Vec<Event>> {
+ 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())
+}