2019-08-20 23:53:00 +00:00
|
|
|
#![feature(proc_macro_hygiene)]
|
2017-02-03 01:38:16 +00:00
|
|
|
|
2018-06-28 15:55:15 +00:00
|
|
|
#[macro_use] extern crate rocket;
|
2019-06-13 02:41:29 +00:00
|
|
|
|
2019-01-27 15:52:03 +00:00
|
|
|
use rusqlite::types::ToSql;
|
2017-02-03 01:38:16 +00:00
|
|
|
|
|
|
|
#[cfg(test)] mod tests;
|
|
|
|
|
|
|
|
use std::sync::Mutex;
|
2019-09-10 04:54:41 +00:00
|
|
|
|
|
|
|
use rocket::{Rocket, State, response::Debug};
|
|
|
|
|
2017-02-03 01:38:16 +00:00
|
|
|
use rusqlite::{Connection, Error};
|
|
|
|
|
|
|
|
type DbConn = Mutex<Connection>;
|
|
|
|
|
|
|
|
fn init_database(conn: &Connection) {
|
|
|
|
conn.execute("CREATE TABLE entries (
|
|
|
|
id INTEGER PRIMARY KEY,
|
|
|
|
name TEXT NOT NULL
|
2019-01-27 15:52:03 +00:00
|
|
|
)", &[] as &[&dyn ToSql])
|
2017-02-03 01:38:16 +00:00
|
|
|
.expect("create entries table");
|
|
|
|
|
|
|
|
conn.execute("INSERT INTO entries (id, name) VALUES ($1, $2)",
|
2019-01-27 15:52:03 +00:00
|
|
|
&[&0 as &dyn ToSql, &"Rocketeer"])
|
2017-02-03 01:38:16 +00:00
|
|
|
.expect("insert single entry into entries table");
|
|
|
|
}
|
|
|
|
|
|
|
|
#[get("/")]
|
2019-09-10 04:54:41 +00:00
|
|
|
fn hello(db_conn: State<'_, DbConn>) -> Result<String, Debug<Error>> {
|
2017-02-03 01:38:16 +00:00
|
|
|
db_conn.lock()
|
|
|
|
.expect("db connection lock")
|
|
|
|
.query_row("SELECT name FROM entries WHERE id = 0",
|
2019-01-27 15:52:03 +00:00
|
|
|
&[] as &[&dyn ToSql], |row| { row.get(0) })
|
2019-09-10 04:54:41 +00:00
|
|
|
.map_err(Debug)
|
2017-02-03 01:38:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn rocket() -> Rocket {
|
|
|
|
// Open a new in-memory SQLite database.
|
|
|
|
let conn = Connection::open_in_memory().expect("in memory db");
|
|
|
|
|
|
|
|
// Initialize the `entries` table in the in-memory database.
|
|
|
|
init_database(&conn);
|
|
|
|
|
|
|
|
// Have Rocket manage the database pool.
|
|
|
|
rocket::ignite()
|
|
|
|
.manage(Mutex::new(conn))
|
|
|
|
.mount("/", routes![hello])
|
|
|
|
}
|
|
|
|
|
2020-06-14 15:57:55 +00:00
|
|
|
#[rocket::main]
|
|
|
|
async fn main() {
|
|
|
|
let _ = rocket().launch().await;
|
2017-02-03 01:38:16 +00:00
|
|
|
}
|