Use the database url in Rocket.toml to connect to mysql/postgres
This commit is contained in:
parent
dfe26f9b7c
commit
13364ab63c
@ -5,7 +5,9 @@ edition = "2018"
|
||||
publish = false
|
||||
[workspace]
|
||||
[dependencies]
|
||||
rocket = { git = "https://github.com/SergioBenitez/Rocket.git", features = ["json"] }
|
||||
rocket = { git = "https://github.com/SergioBenitez/Rocket.git", features = [
|
||||
"json",
|
||||
] }
|
||||
rocket_db_pools = { git = "https://github.com/SergioBenitez/Rocket.git", features = [] }
|
||||
sea-orm = { path = "../../", features = ["web-api-rocket"] }
|
||||
sea-query = { version = "^0.12.8" }
|
||||
|
@ -1,5 +1,9 @@
|
||||
# [default.databases.sqlx]
|
||||
# url = "sqlite::memory:"
|
||||
[default.databases.rocket_example]
|
||||
|
||||
[global.databases]
|
||||
blog = { url = "sqlite::memory:" }
|
||||
# Mysql
|
||||
# make sure to enable "sqlx-mysql" feature in Cargo.toml, i.e default = ["sqlx-mysql"]
|
||||
# url = "mysql://root:@localhost/rocket_example"
|
||||
|
||||
# Postgres
|
||||
# make sure to enable "sqlx-postgres" feature in Cargo.toml, i.e default = ["sqlx-postgres"]
|
||||
url = "postgres://root:root@localhost/rocket_example"
|
||||
|
@ -4,12 +4,13 @@ use rocket::serde::json::Json;
|
||||
use rocket::{Build, Rocket};
|
||||
use rocket_db_pools::{sqlx, Connection, Database};
|
||||
use sea_orm::entity::*;
|
||||
use sea_orm::RocketDbPool;
|
||||
|
||||
mod setup;
|
||||
|
||||
#[derive(Database, Debug)]
|
||||
#[database("rocket_example")]
|
||||
struct Db(sea_orm::Database);
|
||||
struct Db(RocketDbPool);
|
||||
|
||||
type Result<T, E = rocket::response::Debug<sqlx::Error>> = std::result::Result<T, E>;
|
||||
|
||||
|
@ -1,24 +1,27 @@
|
||||
use async_trait::async_trait;
|
||||
use rocket_db_pools::{rocket::figment::Figment, Config, Error};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct RocketDbPool {
|
||||
db_url: String,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl rocket_db_pools::Pool for crate::Database {
|
||||
impl rocket_db_pools::Pool for RocketDbPool {
|
||||
type Error = crate::DbErr;
|
||||
|
||||
type Connection = crate::DatabaseConnection;
|
||||
|
||||
async fn init(figment: &Figment) -> Result<Self, Self::Error> {
|
||||
Ok(crate::Database {})
|
||||
let config = figment.extract::<Config>().unwrap();
|
||||
let db_url = config.url;
|
||||
|
||||
Ok(RocketDbPool {
|
||||
db_url: db_url.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn get(&self) -> Result<Self::Connection, Self::Error> {
|
||||
#[cfg(feature = "sqlx-mysql")]
|
||||
let db_url = "mysql://root:@localhost/rocket_example";
|
||||
#[cfg(feature = "sqlx-postgres")]
|
||||
let db_url = "postgres://root:root@localhost/rocket_example";
|
||||
|
||||
println!("db_url: {:#?}", db_url);
|
||||
|
||||
Ok(crate::Database::connect(db_url).await.unwrap())
|
||||
Ok(crate::Database::connect(&self.db_url).await.unwrap())
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user