mirror of https://github.com/rwf2/Rocket.git
1.7 KiB
1.7 KiB
db_pools
This crate provides traits, utilities, and a procedural macro for configuring and accessing database connection pools in Rocket.
Usage
First, enable the feature corresponding to your database type:
[dependencies.rocket_db_pools]
version = "0.1.0-dev"
features = ["sqlx_sqlite"]
A full list of supported databases and their associated feature names is
available in the crate docs. In whichever configuration source you choose,
configure a databases
dictionary with a key for each database, here
sqlite_logs
in a TOML source:
[default.databases]
sqlite_logs = { url = "/path/to/database.sqlite" }
In your application's source code:
#[macro_use] extern crate rocket;
use rocket::serde::json::Json;
use rocket_db_pools::{Database, sqlx};
#[derive(Database)]
#[database("sqlite_logs")]
struct LogsDb(sqlx::SqlitePool);
type LogsDbConn = <LogsDb as Database>::Connection;
#[get("/logs/<id>")]
async fn get_logs(mut db: LogsDbConn, id: usize) -> Result<Json<Vec<String>>> {
let logs = sqlx::query!("SELECT text FROM logs;").execute(&mut *db).await?;
Ok(Json(logs))
}
#[launch]
fn rocket() -> _ {
rocket::build().attach(LogsDb::fairing())
}
See the crate docs for full details.