Rocket/contrib/db_pools
Sergio Benitez 091c6f58f6 Update 'deadpool' and related databases to 0.13. 2024-05-22 19:48:17 -05:00
..
codegen Use workspace lints. Resolve new nightly warnings. 2024-05-20 13:39:14 -05:00
lib Update 'deadpool' and related databases to 0.13. 2024-05-22 19:48:17 -05:00
README.md Update 'SergioBenitez/Rocket' to 'rwf2/Rocket'. 2023-11-21 16:32:25 +01:00

README.md

db_pools ci.svg crates.io docs.svg

Asynchronous database driver integration for Rocket. See the crate docs for full usage details.

Usage

  1. Add rocket_db_pools as a dependency with one or more database driver features enabled:

    [dependencies.rocket_db_pools]
    version = "0.1.0"
    features = ["sqlx_sqlite"]
    
  2. Choose a name for your database, here sqlite_logs. Configure at least a URL for the database:

    [default.databases.sqlite_logs]
    url = "/path/to/database.sqlite"
    
  3. Derive Database for a unit type (Logs here) which wraps the selected driver's Pool type and is decorated with #[database("name")]. Attach Type::init() to your application's Rocket to initialize the database pool:

    use rocket_db_pools::{Database, Connection};
    
    #[derive(Database)]
    #[database("sqlite_logs")]
    struct Logs(sqlx::SqlitePool);
    
    #[launch]
    fn rocket() -> _ {
        rocket::build().attach(Logs::init())
    }
    
  4. Use Connection<Type> as a request guard to retrieve an active database connection:

    #[get("/<id>")]
    async fn read(mut db: Connection<Logs>, id: i64) -> Result<Log> {
        sqlx::query!("SELECT content FROM logs WHERE id = ?", id)
            .fetch_one(&mut *db)
            .map_ok(|r| Log(r.content))
            .await
    }