Add raw sqlite example; not in workspace due to sqlite3-sys conflict.

This commit is contained in:
Sergio Benitez 2017-02-02 17:38:16 -08:00
parent 2b65be32e0
commit 7f9ced7db3
4 changed files with 76 additions and 0 deletions

View File

@ -30,4 +30,5 @@ members = [
"examples/pastebin",
"examples/state",
"examples/uuid",
# "examples/raw_sqlite",
]

View File

@ -0,0 +1,12 @@
[package]
name = "raw_sqlite"
version = "0.0.1"
workspace = "../../"
[dependencies]
rocket = { path = "../../lib" }
rocket_codegen = { path = "../../codegen" }
rusqlite = "0.9"
[dev-dependencies]
rocket = { path = "../../lib", features = ["testing"] }

View File

@ -0,0 +1,50 @@
#![feature(plugin)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate rusqlite;
#[cfg(test)] mod tests;
use std::sync::Mutex;
use rocket::{Rocket, State};
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
)", &[])
.expect("create entries table");
conn.execute("INSERT INTO entries (id, name) VALUES ($1, $2)",
&[&0, &"Rocketeer"])
.expect("insert single entry into entries table");
}
#[get("/")]
fn hello(db_conn: State<DbConn>) -> Result<String, Error> {
db_conn.lock()
.expect("db connection lock")
.query_row("SELECT name FROM entries WHERE id = 0",
&[], |row| { row.get(0) })
}
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])
}
fn main() {
rocket().launch();
}

View File

@ -0,0 +1,13 @@
use super::rocket;
use rocket::testing::MockRequest;
use rocket::http::Method::*;
#[test]
fn hello() {
let rocket = rocket();
let mut req = MockRequest::new(Get, "/");
let mut response = req.dispatch_with(&rocket);
let body_str = response.body().and_then(|body| body.into_string());
assert_eq!(body_str, Some("Rocketeer".to_string()));
}