Add a simple database interaction example #45
mathiversen
started this conversation in
Ideas
Replies: 1 comment 19 replies
-
There are As of todayuse sqlx::sqlite::SqlitePool;
use trillium::{conn_unwrap, Conn, Handler, State, Init};
use trillium_logger::Logger;
use trillium_router::{Router, RouterConnExt};
async fn hello_world(conn: Conn) -> Conn {
conn.ok("hello world!")
}
async fn hello_name(conn: Conn) -> Conn {
let name = conn_unwrap!(conn, conn.param("name"));
let body = format!("hello, {}!", name);
let pool = conn.state::<SqlitePool>().unwrap();
dbg!(&pool);
conn.ok(body)
}
async fn not_found(conn: Conn) -> Conn {
let body = format!("Uh oh, I don't have a route for {}", conn.path());
conn.with_body(body).with_status(404)
}
fn application() -> impl Handler {
(
Logger::new(),
Init::new(|_| async move {
let db = SqlitePool::connect(&std::env::var("DATABASE_URL").unwrap())
.await
.unwrap();
State::new(db)
}),
Router::new()
.get("/", hello_world)
.get("/hello/:name", hello_name),
not_found,
)
}
fn main() {
pretty_env_logger::init();
trillium_smol::run(application())
} Soon but not todayI intend to make a sqlx-specific database handler that also provides per-conn transaction support. When that exists, a rough sketch might look something like: use trillium::{conn_unwrap, Conn, Handler, State};
use trillium_logger::Logger;
use trillium_router::{Router, RouterConnExt};
use trillium_sqlx::{SqlxHandler, SqlxConnExt};
async fn hello_world(conn: Conn) -> Conn {
conn.ok("hello world!")
}
async fn hello_name(conn: Conn) -> Conn {
let name = conn_unwrap!(conn, conn.param("name"));
let user = conn_try!(conn, conn.db().fetch_one("select * from users where name = 'bobby tables'").await);
let body = format!("hello, {}!", name);
conn.ok(body)
}
async fn not_found(conn: Conn) -> Conn {
let body = format!("Uh oh, I don't have a route for {}", conn.path());
conn.with_body(body).with_status(404)
}
fn application() -> impl Handler {
(
Logger::new(),
SqlxHandler::<Sqlite>::from_env(),
Router::new()
.get("/", hello_world)
.get("/hello/:name", hello_name),
not_found,
)
}
fn main() {
pretty_env_logger::init();
trillium_smol::run(application())
} |
Beta Was this translation helpful? Give feedback.
19 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi,
First of all i just want to thank you for making this interesting project public, and for fixing the websocket issue so quickly yesterday!
I've had some more time to play with it but I've run into some issues with how to manage state and share a db connection pool across my handlers/routers. It's probably not so much the framework but rather rust and multi-threading in general, but i think it would help a lot to have such an example somewhere to look at, especially for new rustaceans :)
Beta Was this translation helpful? Give feedback.
All reactions