aboutsummaryrefslogtreecommitdiff
path: root/src/db
diff options
context:
space:
mode:
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())
+}