2023-04-21 23:39:52 +00:00
|
|
|
use ck::user;
|
|
|
|
use sea_orm::{ColumnTrait, ConnectOptions, DatabaseConnection, EntityTrait, QueryFilter};
|
2023-07-07 19:22:30 +00:00
|
|
|
use thiserror::Error;
|
|
|
|
use tracing::log::LevelFilter;
|
2023-04-21 23:39:52 +00:00
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub struct ConnectorConfig {
|
|
|
|
pub url: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
pub struct CalckeyModel(DatabaseConnection);
|
|
|
|
|
2023-07-07 19:22:30 +00:00
|
|
|
#[derive(Debug, Error)]
|
|
|
|
pub enum CalckeyDbError {
|
|
|
|
#[error("Database error: {0}")]
|
|
|
|
DbError(#[from] sea_orm::DbErr),
|
|
|
|
}
|
|
|
|
|
2023-04-21 23:39:52 +00:00
|
|
|
impl CalckeyModel {
|
2023-07-07 19:22:30 +00:00
|
|
|
pub async fn new(config: ConnectorConfig) -> Result<Self, CalckeyDbError> {
|
2023-04-21 23:39:52 +00:00
|
|
|
let opt = ConnectOptions::new(config.url)
|
|
|
|
.max_connections(64)
|
|
|
|
.min_connections(8)
|
|
|
|
.sqlx_logging(true)
|
|
|
|
.sqlx_logging_level(LevelFilter::Debug)
|
|
|
|
.to_owned();
|
|
|
|
|
|
|
|
Ok(CalckeyModel(sea_orm::Database::connect(opt).await?))
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn get_user_by_tag(
|
|
|
|
&self,
|
|
|
|
name: &str,
|
|
|
|
instance: Option<&str>,
|
2023-07-07 19:22:30 +00:00
|
|
|
) -> Result<Option<user::Model>, CalckeyDbError> {
|
2023-04-21 23:39:52 +00:00
|
|
|
let name = name.to_lowercase();
|
|
|
|
let instance = instance.map(str::to_lowercase);
|
|
|
|
|
|
|
|
let user = if let Some(instance) = instance {
|
|
|
|
user::Entity::find()
|
|
|
|
.filter(user::Column::UsernameLower.eq(name))
|
|
|
|
.filter(user::Column::Host.eq(instance))
|
|
|
|
} else {
|
2023-04-22 00:37:18 +00:00
|
|
|
user::Entity::find().filter(
|
|
|
|
user::Column::UsernameLower
|
|
|
|
.eq(name)
|
|
|
|
.and(user::Column::Host.is_null()),
|
|
|
|
)
|
2023-04-21 23:39:52 +00:00
|
|
|
}
|
|
|
|
.one(&self.0)
|
|
|
|
.await?;
|
|
|
|
|
|
|
|
Ok(user)
|
|
|
|
}
|
|
|
|
|
2023-07-07 19:22:30 +00:00
|
|
|
pub async fn get_user_by_uri(&self, uri: &str) -> Result<Option<user::Model>, CalckeyDbError> {
|
2023-04-21 23:39:52 +00:00
|
|
|
Ok(user::Entity::find()
|
|
|
|
.filter(user::Column::Uri.eq(uri))
|
|
|
|
.one(&self.0)
|
|
|
|
.await?)
|
|
|
|
}
|
|
|
|
}
|