2022-07-27 13:05:28 +00:00
|
|
|
use crate::cli::CF;
|
2022-07-04 00:01:24 +00:00
|
|
|
use crate::dbs::DB;
|
2022-05-10 07:36:48 +00:00
|
|
|
use crate::err::Error;
|
|
|
|
use crate::net::output;
|
|
|
|
use crate::net::session;
|
|
|
|
use bytes::Bytes;
|
|
|
|
use surrealdb::Session;
|
2020-06-29 15:36:01 +00:00
|
|
|
use warp::http;
|
|
|
|
use warp::Filter;
|
|
|
|
|
2022-05-10 00:07:03 +00:00
|
|
|
const MAX: u64 = 1024 * 1024 * 1024 * 4; // 4 GiB
|
|
|
|
|
2020-06-29 15:36:01 +00:00
|
|
|
pub fn config() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
|
2022-05-10 07:36:48 +00:00
|
|
|
warp::path("import")
|
|
|
|
.and(warp::path::end())
|
2020-06-29 15:36:01 +00:00
|
|
|
.and(warp::post())
|
2022-05-10 07:36:48 +00:00
|
|
|
.and(session::build())
|
|
|
|
.and(warp::header::<String>(http::header::CONTENT_TYPE.as_str()))
|
2022-05-10 00:07:03 +00:00
|
|
|
.and(warp::body::content_length_limit(MAX))
|
2022-05-10 07:36:48 +00:00
|
|
|
.and(warp::body::bytes())
|
|
|
|
.and_then(handler)
|
2020-06-29 15:36:01 +00:00
|
|
|
}
|
|
|
|
|
2022-05-10 07:36:48 +00:00
|
|
|
async fn handler(
|
|
|
|
session: Session,
|
|
|
|
output: String,
|
|
|
|
sql: Bytes,
|
|
|
|
) -> Result<impl warp::Reply, warp::Rejection> {
|
|
|
|
// Check the permissions
|
|
|
|
match session.au.is_db() {
|
|
|
|
true => {
|
|
|
|
// Get the datastore reference
|
|
|
|
let db = DB.get().unwrap();
|
2022-07-27 13:05:28 +00:00
|
|
|
// Get local copy of options
|
|
|
|
let opt = CF.get().unwrap();
|
2022-05-10 07:36:48 +00:00
|
|
|
// Convert the body to a byte slice
|
|
|
|
let sql = std::str::from_utf8(&sql).unwrap();
|
|
|
|
// Execute the sql query in the database
|
2022-07-27 13:05:28 +00:00
|
|
|
match db.execute(sql, &session, None, opt.strict).await {
|
2022-05-10 07:36:48 +00:00
|
|
|
Ok(res) => match output.as_ref() {
|
|
|
|
"application/json" => Ok(output::json(&res)),
|
|
|
|
"application/cbor" => Ok(output::cbor(&res)),
|
|
|
|
"application/msgpack" => Ok(output::pack(&res)),
|
2022-07-04 00:00:39 +00:00
|
|
|
"application/octet-stream" => Ok(output::none()),
|
2022-05-10 07:36:48 +00:00
|
|
|
_ => Err(warp::reject::not_found()),
|
|
|
|
},
|
|
|
|
Err(err) => Err(warp::reject::custom(Error::from(err))),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
_ => Err(warp::reject::custom(Error::InvalidAuth)),
|
|
|
|
}
|
2020-06-29 15:36:01 +00:00
|
|
|
}
|