diff options
| author | Fuwn <[email protected]> | 2020-11-18 21:16:45 -0800 |
|---|---|---|
| committer | Fuwn <[email protected]> | 2020-11-18 21:16:45 -0800 |
| commit | d18c1b820448e7b962eff24467d161dd1e1190e6 (patch) | |
| tree | 8fa9038d865b726d1d6b9508acd5cd3ef834b691 /src/db.rs | |
| parent | Create LICENSE.md (diff) | |
| download | chan-d18c1b820448e7b962eff24467d161dd1e1190e6.tar.xz chan-d18c1b820448e7b962eff24467d161dd1e1190e6.zip | |
repo: :star:
Diffstat (limited to 'src/db.rs')
| -rw-r--r-- | src/db.rs | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/src/db.rs b/src/db.rs new file mode 100644 index 0000000..7a5a85d --- /dev/null +++ b/src/db.rs @@ -0,0 +1,43 @@ +use rusqlite::{params, Connection, Result, Error as SQLError}; + +/// The format a valid SQLlite thread entry should have. +#[derive(FromForm, Debug, Serialize, Deserialize)] +pub struct Thread { + pub name: String, + pub comment: String +} + +/// Create a new thread in the SQLite database. +pub fn new_thread(mut thread: Thread) -> Result<()> { + // Open SQLite database file. + let db = Connection::open("chan.db")?; + + // If the name field in the POST request is empty, user should be "anonymous". + if thread.name == "" { + thread.name = "anonymous".to_owned(); + } + + // Add thread entry to database. + db.execute( + "INSERT INTO thread (name, comment) VALUES (?1, ?2)", + params![thread.name, thread.comment] + )?; + + Ok(()) +} + +/// Get all threads from the SQLite databse. +pub fn get_threads() -> Result<Vec<Thread>, SQLError> { + // Open SQLite database file. + let db = Connection::open("chan.db")?; + + // Get all entries from the thread table. + let mut statement = db.prepare("SELECT name, comment FROM thread")?; + let threads = statement.query_map(params![], |row| { + Ok(Thread { + name: row.get(0)?, + comment: row.get(1)? + }) + })?; + threads.collect() +} |