what2watch/src/import_utils.rs

98 lines
2.6 KiB
Rust
Raw Normal View History

use sqlx::{query, query_scalar, SqlitePool};
use crate::{db_id::DbId, Watch};
const USER_EXISTS_QUERY: &str = "select count(*) from witches where id = $1";
const ADD_WATCH_QUERY: &str = "insert into watches (id, title, kind, metadata_url, length, release_date, added_by) values ($1, $2, $3, $4, $5, $6, $7)";
const OMEGA_ID: u128 = u128::MAX;
//-************************************************************************
// utility functions for building CLI tools, currently just for benchmarking
//-************************************************************************
pub async fn add_watch(db_pool: &SqlitePool, watch: &Watch) {
if query(ADD_WATCH_QUERY)
.bind(watch.id)
.bind(&watch.title)
.bind(watch.kind)
.bind(&watch.metadata_url)
.bind(watch.length)
.bind(watch.release_date)
.bind(watch.added_by)
.execute(db_pool)
.await
.is_ok()
{
println!("{}", watch.id);
} else {
eprintln!("failed to add \"{}\"", watch.title);
}
}
pub async fn add_user(
db_pool: &SqlitePool,
username: &str,
displayname: Option<&str>,
email: Option<&str>,
id: Option<DbId>,
) {
let pwhash = "you shall not password";
let id: DbId = id.unwrap_or_else(DbId::new);
if query(crate::signup::CREATE_QUERY)
.bind(id)
.bind(username)
.bind(displayname)
.bind(email)
.bind(pwhash)
.execute(db_pool)
.await
.is_ok()
{
println!("{id}");
} else {
eprintln!("failed to add user \"{username}\"");
}
}
pub async fn ensure_omega(db_pool: &SqlitePool) -> DbId {
if !check_omega_exists(db_pool).await {
add_user(
db_pool,
"The Omega User",
Some("I am the end of all watches."),
None,
Some(OMEGA_ID.into()),
)
.await
}
OMEGA_ID.into()
}
async fn check_omega_exists(db_pool: &SqlitePool) -> bool {
let id: DbId = OMEGA_ID.into();
let count = query_scalar(USER_EXISTS_QUERY)
.bind(id)
.fetch_one(db_pool)
.await
.unwrap_or(0);
dbg!(count);
count > 0
}
//-************************************************************************
//tests
//-************************************************************************
#[cfg(test)]
mod test {
use super::*;
#[tokio::test]
async fn ensure_omega_user() {
let p = crate::db::get_db_pool().await;
assert!(!check_omega_exists(&p).await);
ensure_omega(&p).await;
assert!(check_omega_exists(&p).await);
}
}