Commonize and distinguish a lot of struct names in labrinth::database::models (#3691)

This commit is contained in:
Josiah Glosson
2025-05-24 04:38:43 -05:00
committed by GitHub
parent 9c1bdf16e4
commit 4e4a7be7ef
78 changed files with 1075 additions and 1009 deletions

View File

@@ -1,9 +1,9 @@
use crate::database; use crate::database;
use crate::database::models::Collection; use crate::database::models::DBCollection;
use crate::database::models::project_item::QueryProject; use crate::database::models::project_item::ProjectQueryResult;
use crate::database::models::version_item::QueryVersion; use crate::database::models::version_item::VersionQueryResult;
use crate::database::redis::RedisPool; use crate::database::redis::RedisPool;
use crate::database::{Project, Version, models}; use crate::database::{DBProject, DBVersion, models};
use crate::models::users::User; use crate::models::users::User;
use crate::routes::ApiError; use crate::routes::ApiError;
use itertools::Itertools; use itertools::Itertools;
@@ -38,7 +38,7 @@ where
} }
pub async fn is_visible_project( pub async fn is_visible_project(
project_data: &Project, project_data: &DBProject,
user_option: &Option<User>, user_option: &Option<User>,
pool: &PgPool, pool: &PgPool,
hide_unlisted: bool, hide_unlisted: bool,
@@ -54,7 +54,7 @@ pub async fn is_visible_project(
} }
pub async fn is_team_member_project( pub async fn is_team_member_project(
project_data: &Project, project_data: &DBProject,
user_option: &Option<User>, user_option: &Option<User>,
pool: &PgPool, pool: &PgPool,
) -> Result<bool, ApiError> { ) -> Result<bool, ApiError> {
@@ -64,7 +64,7 @@ pub async fn is_team_member_project(
} }
pub async fn filter_visible_projects( pub async fn filter_visible_projects(
mut projects: Vec<QueryProject>, mut projects: Vec<ProjectQueryResult>,
user_option: &Option<User>, user_option: &Option<User>,
pool: &PgPool, pool: &PgPool,
hide_unlisted: bool, hide_unlisted: bool,
@@ -86,7 +86,7 @@ pub async fn filter_visible_projects(
// - the user is a mod // - the user is a mod
// This is essentially whether you can know of the project's existence // This is essentially whether you can know of the project's existence
pub async fn filter_visible_project_ids( pub async fn filter_visible_project_ids(
projects: Vec<&Project>, projects: Vec<&DBProject>,
user_option: &Option<User>, user_option: &Option<User>,
pool: &PgPool, pool: &PgPool,
hide_unlisted: bool, hide_unlisted: bool,
@@ -126,7 +126,7 @@ pub async fn filter_visible_project_ids(
// These are projects we have internal access to and can potentially see even if they are hidden // These are projects we have internal access to and can potentially see even if they are hidden
// This is useful for getting visibility of versions, or seeing analytics or sensitive team-restricted data of a project // This is useful for getting visibility of versions, or seeing analytics or sensitive team-restricted data of a project
pub async fn filter_enlisted_projects_ids( pub async fn filter_enlisted_projects_ids(
projects: Vec<&Project>, projects: Vec<&DBProject>,
user_option: &Option<User>, user_option: &Option<User>,
pool: &PgPool, pool: &PgPool,
) -> Result<Vec<crate::database::models::DBProjectId>, ApiError> { ) -> Result<Vec<crate::database::models::DBProjectId>, ApiError> {
@@ -173,7 +173,7 @@ pub async fn filter_enlisted_projects_ids(
} }
pub async fn is_visible_version( pub async fn is_visible_version(
version_data: &Version, version_data: &DBVersion,
user_option: &Option<User>, user_option: &Option<User>,
pool: &PgPool, pool: &PgPool,
redis: &RedisPool, redis: &RedisPool,
@@ -184,7 +184,7 @@ pub async fn is_visible_version(
} }
pub async fn is_team_member_version( pub async fn is_team_member_version(
version_data: &Version, version_data: &DBVersion,
user_option: &Option<User>, user_option: &Option<User>,
pool: &PgPool, pool: &PgPool,
redis: &RedisPool, redis: &RedisPool,
@@ -195,7 +195,7 @@ pub async fn is_team_member_version(
} }
pub async fn filter_visible_versions( pub async fn filter_visible_versions(
mut versions: Vec<QueryVersion>, mut versions: Vec<VersionQueryResult>,
user_option: &Option<User>, user_option: &Option<User>,
pool: &PgPool, pool: &PgPool,
redis: &RedisPool, redis: &RedisPool,
@@ -211,7 +211,7 @@ pub async fn filter_visible_versions(
Ok(versions.into_iter().map(|x| x.into()).collect()) Ok(versions.into_iter().map(|x| x.into()).collect())
} }
impl ValidateAuthorized for models::OAuthClient { impl ValidateAuthorized for models::DBOAuthClient {
fn validate_authorized( fn validate_authorized(
&self, &self,
user_option: Option<&User>, user_option: Option<&User>,
@@ -232,7 +232,7 @@ impl ValidateAuthorized for models::OAuthClient {
} }
pub async fn filter_visible_version_ids( pub async fn filter_visible_version_ids(
versions: Vec<&Version>, versions: Vec<&DBVersion>,
user_option: &Option<User>, user_option: &Option<User>,
pool: &PgPool, pool: &PgPool,
redis: &RedisPool, redis: &RedisPool,
@@ -247,7 +247,7 @@ pub async fn filter_visible_version_ids(
// Get visible projects- ones we are allowed to see public versions for. // Get visible projects- ones we are allowed to see public versions for.
let visible_project_ids = filter_visible_project_ids( let visible_project_ids = filter_visible_project_ids(
Project::get_many_ids(&project_ids, pool, redis) DBProject::get_many_ids(&project_ids, pool, redis)
.await? .await?
.iter() .iter()
.map(|x| &x.inner) .map(|x| &x.inner)
@@ -287,7 +287,7 @@ pub async fn filter_visible_version_ids(
} }
pub async fn filter_enlisted_version_ids( pub async fn filter_enlisted_version_ids(
versions: Vec<&Version>, versions: Vec<&DBVersion>,
user_option: &Option<User>, user_option: &Option<User>,
pool: &PgPool, pool: &PgPool,
redis: &RedisPool, redis: &RedisPool,
@@ -299,7 +299,7 @@ pub async fn filter_enlisted_version_ids(
// Get enlisted projects- ones we are allowed to see hidden versions for. // Get enlisted projects- ones we are allowed to see hidden versions for.
let authorized_project_ids = filter_enlisted_projects_ids( let authorized_project_ids = filter_enlisted_projects_ids(
Project::get_many_ids(&project_ids, pool, redis) DBProject::get_many_ids(&project_ids, pool, redis)
.await? .await?
.iter() .iter()
.map(|x| &x.inner) .map(|x| &x.inner)
@@ -325,7 +325,7 @@ pub async fn filter_enlisted_version_ids(
} }
pub async fn is_visible_collection( pub async fn is_visible_collection(
collection_data: &Collection, collection_data: &DBCollection,
user_option: &Option<User>, user_option: &Option<User>,
) -> Result<bool, ApiError> { ) -> Result<bool, ApiError> {
let mut authorized = !collection_data.status.is_hidden() let mut authorized = !collection_data.status.is_hidden()
@@ -341,7 +341,7 @@ pub async fn is_visible_collection(
} }
pub async fn filter_visible_collections( pub async fn filter_visible_collections(
collections: Vec<Collection>, collections: Vec<DBCollection>,
user_option: &Option<User>, user_option: &Option<User>,
) -> Result<Vec<crate::models::collections::Collection>, ApiError> { ) -> Result<Vec<crate::models::collections::Collection>, ApiError> {
let mut return_collections = Vec::new(); let mut return_collections = Vec::new();

View File

@@ -1,10 +1,10 @@
use crate::auth::get_user_from_headers; use crate::auth::get_user_from_headers;
use crate::auth::oauth::uris::{OAuthRedirectUris, ValidatedRedirectUri}; use crate::auth::oauth::uris::{OAuthRedirectUris, ValidatedRedirectUri};
use crate::auth::validate::extract_authorization_header; use crate::auth::validate::extract_authorization_header;
use crate::database::models::flow_item::Flow; use crate::database::models::flow_item::DBFlow;
use crate::database::models::oauth_client_authorization_item::OAuthClientAuthorization; use crate::database::models::oauth_client_authorization_item::DBOAuthClientAuthorization;
use crate::database::models::oauth_client_item::OAuthClient as DBOAuthClient; use crate::database::models::oauth_client_item::DBOAuthClient;
use crate::database::models::oauth_token_item::OAuthAccessToken; use crate::database::models::oauth_token_item::DBOAuthAccessToken;
use crate::database::models::{ use crate::database::models::{
DBOAuthClientAuthorizationId, generate_oauth_access_token_id, DBOAuthClientAuthorizationId, generate_oauth_access_token_id,
generate_oauth_client_authorization_id, generate_oauth_client_authorization_id,
@@ -106,7 +106,7 @@ pub async fn init_oauth(
} }
let existing_authorization = let existing_authorization =
OAuthClientAuthorization::get(client.id, user.id.into(), &**pool) DBOAuthClientAuthorization::get(client.id, user.id.into(), &**pool)
.await .await
.map_err(|e| { .map_err(|e| {
OAuthError::redirect(e, &oauth_info.state, &redirect_uri) OAuthError::redirect(e, &oauth_info.state, &redirect_uri)
@@ -131,7 +131,7 @@ pub async fn init_oauth(
.await .await
} }
_ => { _ => {
let flow_id = Flow::InitOAuthAppApproval { let flow_id = DBFlow::InitOAuthAppApproval {
user_id: user.id.into(), user_id: user.id.into(),
client_id: client.id, client_id: client.id,
existing_authorization_id: existing_authorization existing_authorization_id: existing_authorization
@@ -231,13 +231,13 @@ pub async fn request_token(
// Ensure auth code is single use // Ensure auth code is single use
// per IETF RFC6749 Section 10.5 (https://datatracker.ietf.org/doc/html/rfc6749#section-10.5) // per IETF RFC6749 Section 10.5 (https://datatracker.ietf.org/doc/html/rfc6749#section-10.5)
let flow = Flow::take_if( let flow = DBFlow::take_if(
&req_params.code, &req_params.code,
|f| matches!(f, Flow::OAuthAuthorizationCodeSupplied { .. }), |f| matches!(f, DBFlow::OAuthAuthorizationCodeSupplied { .. }),
&redis, &redis,
) )
.await?; .await?;
if let Some(Flow::OAuthAuthorizationCodeSupplied { if let Some(DBFlow::OAuthAuthorizationCodeSupplied {
user_id, user_id,
client_id, client_id,
authorization_id, authorization_id,
@@ -274,8 +274,8 @@ pub async fn request_token(
let token_id = let token_id =
generate_oauth_access_token_id(&mut transaction).await?; generate_oauth_access_token_id(&mut transaction).await?;
let token = generate_access_token(); let token = generate_access_token();
let token_hash = OAuthAccessToken::hash_token(&token); let token_hash = DBOAuthAccessToken::hash_token(&token);
let time_until_expiration = OAuthAccessToken { let time_until_expiration = DBOAuthAccessToken {
id: token_id, id: token_id,
authorization_id, authorization_id,
token_hash, token_hash,
@@ -328,13 +328,13 @@ pub async fn accept_or_reject_client_scopes(
.await? .await?
.1; .1;
let flow = Flow::take_if( let flow = DBFlow::take_if(
&body.flow, &body.flow,
|f| matches!(f, Flow::InitOAuthAppApproval { .. }), |f| matches!(f, DBFlow::InitOAuthAppApproval { .. }),
&redis, &redis,
) )
.await?; .await?;
if let Some(Flow::InitOAuthAppApproval { if let Some(DBFlow::InitOAuthAppApproval {
user_id, user_id,
client_id, client_id,
existing_authorization_id, existing_authorization_id,
@@ -359,7 +359,7 @@ pub async fn accept_or_reject_client_scopes(
.await? .await?
} }
}; };
OAuthClientAuthorization::upsert( DBOAuthClientAuthorization::upsert(
auth_id, auth_id,
client_id, client_id,
user_id, user_id,
@@ -425,7 +425,7 @@ async fn init_oauth_code_flow(
state: Option<String>, state: Option<String>,
redis: &RedisPool, redis: &RedisPool,
) -> Result<HttpResponse, OAuthError> { ) -> Result<HttpResponse, OAuthError> {
let code = Flow::OAuthAuthorizationCodeSupplied { let code = DBFlow::OAuthAuthorizationCodeSupplied {
user_id, user_id,
client_id: client_id.into(), client_id: client_id.into(),
authorization_id, authorization_id,

View File

@@ -50,7 +50,7 @@ pub async fn get_user_record_from_bearer_token<'a, 'b, E>(
executor: E, executor: E,
redis: &RedisPool, redis: &RedisPool,
session_queue: &AuthQueue, session_queue: &AuthQueue,
) -> Result<Option<(Scopes, user_item::User)>, AuthenticationError> ) -> Result<Option<(Scopes, user_item::DBUser)>, AuthenticationError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy, E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy,
{ {
@@ -63,7 +63,7 @@ where
let possible_user = match token.split_once('_') { let possible_user = match token.split_once('_') {
Some(("mrp", _)) => { Some(("mrp", _)) => {
let pat = let pat =
crate::database::models::pat_item::PersonalAccessToken::get( crate::database::models::pat_item::DBPersonalAccessToken::get(
token, executor, redis, token, executor, redis,
) )
.await? .await?
@@ -74,25 +74,26 @@ where
} }
let user = let user =
user_item::User::get_id(pat.user_id, executor, redis).await?; user_item::DBUser::get_id(pat.user_id, executor, redis).await?;
session_queue.add_pat(pat.id).await; session_queue.add_pat(pat.id).await;
user.map(|x| (pat.scopes, x)) user.map(|x| (pat.scopes, x))
} }
Some(("mra", _)) => { Some(("mra", _)) => {
let session = crate::database::models::session_item::Session::get( let session =
token, executor, redis, crate::database::models::session_item::DBSession::get(
) token, executor, redis,
.await? )
.ok_or_else(|| AuthenticationError::InvalidCredentials)?; .await?
.ok_or_else(|| AuthenticationError::InvalidCredentials)?;
if session.expires < Utc::now() { if session.expires < Utc::now() {
return Err(AuthenticationError::InvalidCredentials); return Err(AuthenticationError::InvalidCredentials);
} }
let user = let user =
user_item::User::get_id(session.user_id, executor, redis) user_item::DBUser::get_id(session.user_id, executor, redis)
.await?; .await?;
let rate_limit_ignore = dotenvy::var("RATE_LIMIT_IGNORE_KEY")?; let rate_limit_ignore = dotenvy::var("RATE_LIMIT_IGNORE_KEY")?;
@@ -110,11 +111,11 @@ where
user.map(|x| (Scopes::all(), x)) user.map(|x| (Scopes::all(), x))
} }
Some(("mro", _)) => { Some(("mro", _)) => {
use crate::database::models::oauth_token_item::OAuthAccessToken; use crate::database::models::oauth_token_item::DBOAuthAccessToken;
let hash = OAuthAccessToken::hash_token(token); let hash = DBOAuthAccessToken::hash_token(token);
let access_token = let access_token =
crate::database::models::oauth_token_item::OAuthAccessToken::get(hash, executor) crate::database::models::oauth_token_item::DBOAuthAccessToken::get(hash, executor)
.await? .await?
.ok_or(AuthenticationError::InvalidCredentials)?; .ok_or(AuthenticationError::InvalidCredentials)?;
@@ -122,9 +123,12 @@ where
return Err(AuthenticationError::InvalidCredentials); return Err(AuthenticationError::InvalidCredentials);
} }
let user = let user = user_item::DBUser::get_id(
user_item::User::get_id(access_token.user_id, executor, redis) access_token.user_id,
.await?; executor,
redis,
)
.await?;
session_queue.add_oauth_access_token(access_token.id).await; session_queue.add_oauth_access_token(access_token.id).await;
@@ -135,7 +139,7 @@ where
let id = let id =
AuthProvider::GitHub.get_user_id(&user.id, executor).await?; AuthProvider::GitHub.get_user_id(&user.id, executor).await?;
let user = user_item::User::get_id( let user = user_item::DBUser::get_id(
id.ok_or_else(|| AuthenticationError::InvalidCredentials)?, id.ok_or_else(|| AuthenticationError::InvalidCredentials)?,
executor, executor,
redis, redis,

View File

@@ -1,9 +1,9 @@
pub mod models; pub mod models;
mod postgres_database; mod postgres_database;
pub mod redis; pub mod redis;
pub use models::Image; pub use models::DBImage;
pub use models::Project; pub use models::DBProject;
pub use models::Version; pub use models::DBVersion;
pub use postgres_database::check_for_migrations; pub use postgres_database::check_for_migrations;
pub use postgres_database::connect; pub use postgres_database::connect;
pub use postgres_database::register_and_set_metrics; pub use postgres_database::register_and_set_metrics;

View File

@@ -7,7 +7,7 @@ use crate::models::billing::{
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use std::convert::{TryFrom, TryInto}; use std::convert::{TryFrom, TryInto};
pub struct ChargeItem { pub struct DBCharge {
pub id: DBChargeId, pub id: DBChargeId,
pub user_id: DBUserId, pub user_id: DBUserId,
pub price_id: DBProductPriceId, pub price_id: DBProductPriceId,
@@ -30,7 +30,7 @@ pub struct ChargeItem {
pub net: Option<i64>, pub net: Option<i64>,
} }
struct ChargeResult { struct ChargeQueryResult {
id: i64, id: i64,
user_id: i64, user_id: i64,
price_id: i64, price_id: i64,
@@ -48,11 +48,11 @@ struct ChargeResult {
net: Option<i64>, net: Option<i64>,
} }
impl TryFrom<ChargeResult> for ChargeItem { impl TryFrom<ChargeQueryResult> for DBCharge {
type Error = serde_json::Error; type Error = serde_json::Error;
fn try_from(r: ChargeResult) -> Result<Self, Self::Error> { fn try_from(r: ChargeQueryResult) -> Result<Self, Self::Error> {
Ok(ChargeItem { Ok(DBCharge {
id: DBChargeId(r.id), id: DBChargeId(r.id),
user_id: DBUserId(r.user_id), user_id: DBUserId(r.user_id),
price_id: DBProductPriceId(r.price_id), price_id: DBProductPriceId(r.price_id),
@@ -77,7 +77,7 @@ impl TryFrom<ChargeResult> for ChargeItem {
macro_rules! select_charges_with_predicate { macro_rules! select_charges_with_predicate {
($predicate:tt, $param:ident) => { ($predicate:tt, $param:ident) => {
sqlx::query_as!( sqlx::query_as!(
ChargeResult, ChargeQueryResult,
r#" r#"
SELECT SELECT
id, user_id, price_id, amount, currency_code, status, due, last_attempt, id, user_id, price_id, amount, currency_code, status, due, last_attempt,
@@ -96,7 +96,7 @@ macro_rules! select_charges_with_predicate {
}; };
} }
impl ChargeItem { impl DBCharge {
pub async fn upsert( pub async fn upsert(
&self, &self,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>, transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
@@ -146,7 +146,7 @@ impl ChargeItem {
pub async fn get( pub async fn get(
id: DBChargeId, id: DBChargeId,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Option<ChargeItem>, DatabaseError> { ) -> Result<Option<DBCharge>, DatabaseError> {
let id = id.0; let id = id.0;
let res = select_charges_with_predicate!("WHERE id = $1", id) let res = select_charges_with_predicate!("WHERE id = $1", id)
.fetch_optional(exec) .fetch_optional(exec)
@@ -158,7 +158,7 @@ impl ChargeItem {
pub async fn get_from_user( pub async fn get_from_user(
user_id: DBUserId, user_id: DBUserId,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Vec<ChargeItem>, DatabaseError> { ) -> Result<Vec<DBCharge>, DatabaseError> {
let user_id = user_id.0; let user_id = user_id.0;
let res = select_charges_with_predicate!( let res = select_charges_with_predicate!(
"WHERE user_id = $1 ORDER BY due DESC", "WHERE user_id = $1 ORDER BY due DESC",
@@ -176,7 +176,7 @@ impl ChargeItem {
pub async fn get_children( pub async fn get_children(
charge_id: DBChargeId, charge_id: DBChargeId,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Vec<ChargeItem>, DatabaseError> { ) -> Result<Vec<DBCharge>, DatabaseError> {
let charge_id = charge_id.0; let charge_id = charge_id.0;
let res = select_charges_with_predicate!( let res = select_charges_with_predicate!(
"WHERE parent_charge_id = $1", "WHERE parent_charge_id = $1",
@@ -194,7 +194,7 @@ impl ChargeItem {
pub async fn get_open_subscription( pub async fn get_open_subscription(
user_subscription_id: DBUserSubscriptionId, user_subscription_id: DBUserSubscriptionId,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Option<ChargeItem>, DatabaseError> { ) -> Result<Option<DBCharge>, DatabaseError> {
let user_subscription_id = user_subscription_id.0; let user_subscription_id = user_subscription_id.0;
let res = select_charges_with_predicate!( let res = select_charges_with_predicate!(
"WHERE subscription_id = $1 AND (status = 'open' OR status = 'cancelled')", "WHERE subscription_id = $1 AND (status = 'open' OR status = 'cancelled')",
@@ -208,7 +208,7 @@ impl ChargeItem {
pub async fn get_chargeable( pub async fn get_chargeable(
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Vec<ChargeItem>, DatabaseError> { ) -> Result<Vec<DBCharge>, DatabaseError> {
let charge_type = ChargeType::Subscription.as_str(); let charge_type = ChargeType::Subscription.as_str();
let res = select_charges_with_predicate!( let res = select_charges_with_predicate!(
r#" r#"
@@ -232,7 +232,7 @@ impl ChargeItem {
pub async fn get_unprovision( pub async fn get_unprovision(
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Vec<ChargeItem>, DatabaseError> { ) -> Result<Vec<DBCharge>, DatabaseError> {
let charge_type = ChargeType::Subscription.as_str(); let charge_type = ChargeType::Subscription.as_str();
let res = select_charges_with_predicate!( let res = select_charges_with_predicate!(
r#" r#"

View File

@@ -25,7 +25,7 @@ impl CollectionBuilder {
self, self,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>, transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
) -> Result<DBCollectionId, DatabaseError> { ) -> Result<DBCollectionId, DatabaseError> {
let collection_struct = Collection { let collection_struct = DBCollection {
id: self.collection_id, id: self.collection_id,
name: self.name, name: self.name,
user_id: self.user_id, user_id: self.user_id,
@@ -44,7 +44,7 @@ impl CollectionBuilder {
} }
} }
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Collection { pub struct DBCollection {
pub id: DBCollectionId, pub id: DBCollectionId,
pub user_id: DBUserId, pub user_id: DBUserId,
pub name: String, pub name: String,
@@ -58,7 +58,7 @@ pub struct Collection {
pub projects: Vec<DBProjectId>, pub projects: Vec<DBProjectId>,
} }
impl Collection { impl DBCollection {
pub async fn insert( pub async fn insert(
&self, &self,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>, transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
@@ -131,7 +131,7 @@ impl Collection {
.execute(&mut **transaction) .execute(&mut **transaction)
.await?; .await?;
models::Collection::clear_cache(collection.id, redis).await?; models::DBCollection::clear_cache(collection.id, redis).await?;
Ok(Some(())) Ok(Some(()))
} else { } else {
@@ -143,11 +143,11 @@ impl Collection {
id: DBCollectionId, id: DBCollectionId,
executor: E, executor: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Option<Collection>, DatabaseError> ) -> Result<Option<DBCollection>, DatabaseError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres>, E: sqlx::Executor<'a, Database = sqlx::Postgres>,
{ {
Collection::get_many(&[id], executor, redis) DBCollection::get_many(&[id], executor, redis)
.await .await
.map(|x| x.into_iter().next()) .map(|x| x.into_iter().next())
} }
@@ -156,7 +156,7 @@ impl Collection {
collection_ids: &[DBCollectionId], collection_ids: &[DBCollectionId],
exec: E, exec: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Vec<Collection>, DatabaseError> ) -> Result<Vec<DBCollection>, DatabaseError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres>, E: sqlx::Executor<'a, Database = sqlx::Postgres>,
{ {
@@ -180,7 +180,7 @@ impl Collection {
) )
.fetch(exec) .fetch(exec)
.try_fold(DashMap::new(), |acc, m| { .try_fold(DashMap::new(), |acc, m| {
let collection = Collection { let collection = DBCollection {
id: DBCollectionId(m.id), id: DBCollectionId(m.id),
user_id: DBUserId(m.user_id), user_id: DBUserId(m.user_id),
name: m.name.clone(), name: m.name.clone(),

View File

@@ -15,7 +15,7 @@ const FLOWS_NAMESPACE: &str = "flows";
#[derive(Deserialize, Serialize)] #[derive(Deserialize, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")] #[serde(tag = "type", rename_all = "snake_case")]
pub enum Flow { pub enum DBFlow {
OAuth { OAuth {
user_id: Option<DBUserId>, user_id: Option<DBUserId>,
url: String, url: String,
@@ -53,7 +53,7 @@ pub enum Flow {
}, },
} }
impl Flow { impl DBFlow {
pub async fn insert( pub async fn insert(
&self, &self,
expires: Duration, expires: Duration,
@@ -81,7 +81,7 @@ impl Flow {
pub async fn get( pub async fn get(
id: &str, id: &str,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Option<Flow>, DatabaseError> { ) -> Result<Option<DBFlow>, DatabaseError> {
let mut redis = redis.connect().await?; let mut redis = redis.connect().await?;
redis.get_deserialized_from_json(FLOWS_NAMESPACE, id).await redis.get_deserialized_from_json(FLOWS_NAMESPACE, id).await
@@ -91,9 +91,9 @@ impl Flow {
/// The predicate should validate that the flow being removed is the correct one, as a security measure /// The predicate should validate that the flow being removed is the correct one, as a security measure
pub async fn take_if( pub async fn take_if(
id: &str, id: &str,
predicate: impl FnOnce(&Flow) -> bool, predicate: impl FnOnce(&DBFlow) -> bool,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Option<Flow>, DatabaseError> { ) -> Result<Option<DBFlow>, DatabaseError> {
let flow = Self::get(id, redis).await?; let flow = Self::get(id, redis).await?;
if let Some(flow) = flow.as_ref() { if let Some(flow) = flow.as_ref() {
if predicate(flow) { if predicate(flow) {

View File

@@ -1,14 +1,14 @@
use crate::database::models::DBUserId; use crate::database::models::DBUserId;
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
pub struct FriendItem { pub struct DBFriend {
pub user_id: DBUserId, pub user_id: DBUserId,
pub friend_id: DBUserId, pub friend_id: DBUserId,
pub created: DateTime<Utc>, pub created: DateTime<Utc>,
pub accepted: bool, pub accepted: bool,
} }
impl FriendItem { impl DBFriend {
pub async fn insert( pub async fn insert(
&self, &self,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>, transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
@@ -33,7 +33,7 @@ impl FriendItem {
user_id: DBUserId, user_id: DBUserId,
friend_id: DBUserId, friend_id: DBUserId,
exec: E, exec: E,
) -> Result<Option<FriendItem>, sqlx::Error> ) -> Result<Option<DBFriend>, sqlx::Error>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres>, E: sqlx::Executor<'a, Database = sqlx::Postgres>,
{ {
@@ -48,7 +48,7 @@ impl FriendItem {
) )
.fetch_optional(exec) .fetch_optional(exec)
.await? .await?
.map(|row| FriendItem { .map(|row| DBFriend {
user_id: DBUserId(row.user_id), user_id: DBUserId(row.user_id),
friend_id: DBUserId(row.friend_id), friend_id: DBUserId(row.friend_id),
created: row.created, created: row.created,
@@ -84,7 +84,7 @@ impl FriendItem {
user_id: DBUserId, user_id: DBUserId,
accepted: Option<bool>, accepted: Option<bool>,
exec: E, exec: E,
) -> Result<Vec<FriendItem>, sqlx::Error> ) -> Result<Vec<DBFriend>, sqlx::Error>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres>, E: sqlx::Executor<'a, Database = sqlx::Postgres>,
{ {
@@ -99,7 +99,7 @@ impl FriendItem {
.fetch_all(exec) .fetch_all(exec)
.await? .await?
.into_iter() .into_iter()
.map(|row| FriendItem { .map(|row| DBFriend {
user_id: DBUserId(row.user_id), user_id: DBUserId(row.user_id),
friend_id: DBUserId(row.friend_id), friend_id: DBUserId(row.friend_id),
created: row.created, created: row.created,

View File

@@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize};
const IMAGES_NAMESPACE: &str = "images"; const IMAGES_NAMESPACE: &str = "images";
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Image { pub struct DBImage {
pub id: DBImageId, pub id: DBImageId,
pub url: String, pub url: String,
pub raw_url: String, pub raw_url: String,
@@ -25,7 +25,7 @@ pub struct Image {
pub report_id: Option<DBReportId>, pub report_id: Option<DBReportId>,
} }
impl Image { impl DBImage {
pub async fn insert( pub async fn insert(
&self, &self,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>, transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
@@ -75,7 +75,7 @@ impl Image {
.execute(&mut **transaction) .execute(&mut **transaction)
.await?; .await?;
Image::clear_cache(image.id, redis).await?; DBImage::clear_cache(image.id, redis).await?;
Ok(Some(())) Ok(Some(()))
} else { } else {
@@ -86,7 +86,7 @@ impl Image {
pub async fn get_many_contexted( pub async fn get_many_contexted(
context: ImageContext, context: ImageContext,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>, transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
) -> Result<Vec<Image>, sqlx::Error> { ) -> Result<Vec<DBImage>, sqlx::Error> {
// Set all of project_id, version_id, thread_message_id, report_id to None // Set all of project_id, version_id, thread_message_id, report_id to None
// Then set the one that is relevant to Some // Then set the one that is relevant to Some
@@ -141,7 +141,7 @@ impl Image {
.map_ok(|row| { .map_ok(|row| {
let id = DBImageId(row.id); let id = DBImageId(row.id);
Image { DBImage {
id, id,
url: row.url, url: row.url,
raw_url: row.raw_url, raw_url: row.raw_url,
@@ -155,7 +155,7 @@ impl Image {
report_id: row.report_id.map(DBReportId), report_id: row.report_id.map(DBReportId),
} }
}) })
.try_collect::<Vec<Image>>() .try_collect::<Vec<DBImage>>()
.await .await
} }
@@ -163,11 +163,11 @@ impl Image {
id: DBImageId, id: DBImageId,
executor: E, executor: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Option<Image>, DatabaseError> ) -> Result<Option<DBImage>, DatabaseError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres>, E: sqlx::Executor<'a, Database = sqlx::Postgres>,
{ {
Image::get_many(&[id], executor, redis) DBImage::get_many(&[id], executor, redis)
.await .await
.map(|x| x.into_iter().next()) .map(|x| x.into_iter().next())
} }
@@ -176,7 +176,7 @@ impl Image {
image_ids: &[DBImageId], image_ids: &[DBImageId],
exec: E, exec: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Vec<Image>, DatabaseError> ) -> Result<Vec<DBImage>, DatabaseError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres>, E: sqlx::Executor<'a, Database = sqlx::Postgres>,
{ {
@@ -197,7 +197,7 @@ impl Image {
) )
.fetch(exec) .fetch(exec)
.try_fold(DashMap::new(), |acc, i| { .try_fold(DashMap::new(), |acc, i| {
let img = Image { let img = DBImage {
id: DBImageId(i.id), id: DBImageId(i.id),
url: i.url, url: i.url,
raw_url: i.raw_url, raw_url: i.raw_url,

View File

@@ -26,17 +26,17 @@ pub mod user_item;
pub mod user_subscription_item; pub mod user_subscription_item;
pub mod version_item; pub mod version_item;
pub use collection_item::Collection; pub use collection_item::DBCollection;
pub use ids::*; pub use ids::*;
pub use image_item::Image; pub use image_item::DBImage;
pub use oauth_client_item::OAuthClient; pub use oauth_client_item::DBOAuthClient;
pub use organization_item::Organization; pub use organization_item::DBOrganization;
pub use project_item::Project; pub use project_item::DBProject;
pub use team_item::Team; pub use team_item::DBTeam;
pub use team_item::TeamMember; pub use team_item::DBTeamMember;
pub use thread_item::{Thread, ThreadMessage}; pub use thread_item::{DBThread, DBThreadMessage};
pub use user_item::User; pub use user_item::DBUser;
pub use version_item::Version; pub use version_item::DBVersion;
#[derive(Error, Debug)] #[derive(Error, Debug)]
pub enum DatabaseError { pub enum DatabaseError {

View File

@@ -12,7 +12,7 @@ pub struct NotificationBuilder {
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub struct Notification { pub struct DBNotification {
pub id: DBNotificationId, pub id: DBNotificationId,
pub user_id: DBUserId, pub user_id: DBUserId,
pub body: NotificationBody, pub body: NotificationBody,
@@ -21,7 +21,7 @@ pub struct Notification {
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub struct NotificationAction { pub struct DBNotificationAction {
pub id: NotificationActionId, pub id: NotificationActionId,
pub notification_id: DBNotificationId, pub notification_id: DBNotificationId,
pub name: String, pub name: String,
@@ -72,13 +72,13 @@ impl NotificationBuilder {
.execute(&mut **transaction) .execute(&mut **transaction)
.await?; .await?;
Notification::clear_user_notifications_cache(&users, redis).await?; DBNotification::clear_user_notifications_cache(&users, redis).await?;
Ok(()) Ok(())
} }
} }
impl Notification { impl DBNotification {
pub async fn get<'a, 'b, E>( pub async fn get<'a, 'b, E>(
id: DBNotificationId, id: DBNotificationId,
executor: E, executor: E,
@@ -94,7 +94,7 @@ impl Notification {
pub async fn get_many<'a, E>( pub async fn get_many<'a, E>(
notification_ids: &[DBNotificationId], notification_ids: &[DBNotificationId],
exec: E, exec: E,
) -> Result<Vec<Notification>, sqlx::Error> ) -> Result<Vec<DBNotification>, sqlx::Error>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy, E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy,
{ {
@@ -116,7 +116,7 @@ impl Notification {
.map_ok(|row| { .map_ok(|row| {
let id = DBNotificationId(row.id); let id = DBNotificationId(row.id);
Notification { DBNotification {
id, id,
user_id: DBUserId(row.user_id), user_id: DBUserId(row.user_id),
read: row.read, read: row.read,
@@ -140,7 +140,7 @@ impl Notification {
}), }),
} }
}) })
.try_collect::<Vec<Notification>>() .try_collect::<Vec<DBNotification>>()
.await .await
} }
@@ -148,13 +148,13 @@ impl Notification {
user_id: DBUserId, user_id: DBUserId,
exec: E, exec: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Vec<Notification>, DatabaseError> ) -> Result<Vec<DBNotification>, DatabaseError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy, E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy,
{ {
let mut redis = redis.connect().await?; let mut redis = redis.connect().await?;
let cached_notifications: Option<Vec<Notification>> = redis let cached_notifications: Option<Vec<DBNotification>> = redis
.get_deserialized_from_json( .get_deserialized_from_json(
USER_NOTIFICATIONS_NAMESPACE, USER_NOTIFICATIONS_NAMESPACE,
&user_id.0.to_string(), &user_id.0.to_string(),
@@ -180,7 +180,7 @@ impl Notification {
.map_ok(|row| { .map_ok(|row| {
let id = DBNotificationId(row.id); let id = DBNotificationId(row.id);
Notification { DBNotification {
id, id,
user_id: DBUserId(row.user_id), user_id: DBUserId(row.user_id),
read: row.read, read: row.read,
@@ -204,7 +204,7 @@ impl Notification {
}), }),
} }
}) })
.try_collect::<Vec<Notification>>() .try_collect::<Vec<DBNotification>>()
.await?; .await?;
redis redis
@@ -249,7 +249,7 @@ impl Notification {
.try_collect::<Vec<_>>() .try_collect::<Vec<_>>()
.await?; .await?;
Notification::clear_user_notifications_cache( DBNotification::clear_user_notifications_cache(
affected_users.iter(), affected_users.iter(),
redis, redis,
) )
@@ -297,7 +297,7 @@ impl Notification {
.try_collect::<Vec<_>>() .try_collect::<Vec<_>>()
.await?; .await?;
Notification::clear_user_notifications_cache( DBNotification::clear_user_notifications_cache(
affected_users.iter(), affected_users.iter(),
redis, redis,
) )

View File

@@ -9,7 +9,7 @@ use super::{
}; };
#[derive(Deserialize, Serialize, Clone, Debug)] #[derive(Deserialize, Serialize, Clone, Debug)]
pub struct OAuthClientAuthorization { pub struct DBOAuthClientAuthorization {
pub id: DBOAuthClientAuthorizationId, pub id: DBOAuthClientAuthorizationId,
pub client_id: DBOAuthClientId, pub client_id: DBOAuthClientId,
pub user_id: DBUserId, pub user_id: DBUserId,
@@ -17,7 +17,7 @@ pub struct OAuthClientAuthorization {
pub created: DateTime<Utc>, pub created: DateTime<Utc>,
} }
struct AuthorizationQueryResult { struct DBAuthClientAuthorizationQueryResult {
id: i64, id: i64,
client_id: i64, client_id: i64,
user_id: i64, user_id: i64,
@@ -25,9 +25,9 @@ struct AuthorizationQueryResult {
created: DateTime<Utc>, created: DateTime<Utc>,
} }
impl From<AuthorizationQueryResult> for OAuthClientAuthorization { impl From<DBAuthClientAuthorizationQueryResult> for DBOAuthClientAuthorization {
fn from(value: AuthorizationQueryResult) -> Self { fn from(value: DBAuthClientAuthorizationQueryResult) -> Self {
OAuthClientAuthorization { DBOAuthClientAuthorization {
id: DBOAuthClientAuthorizationId(value.id), id: DBOAuthClientAuthorizationId(value.id),
client_id: DBOAuthClientId(value.client_id), client_id: DBOAuthClientId(value.client_id),
user_id: DBUserId(value.user_id), user_id: DBUserId(value.user_id),
@@ -37,14 +37,14 @@ impl From<AuthorizationQueryResult> for OAuthClientAuthorization {
} }
} }
impl OAuthClientAuthorization { impl DBOAuthClientAuthorization {
pub async fn get( pub async fn get(
client_id: DBOAuthClientId, client_id: DBOAuthClientId,
user_id: DBUserId, user_id: DBUserId,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Option<OAuthClientAuthorization>, DatabaseError> { ) -> Result<Option<DBOAuthClientAuthorization>, DatabaseError> {
let value = sqlx::query_as!( let value = sqlx::query_as!(
AuthorizationQueryResult, DBAuthClientAuthorizationQueryResult,
" "
SELECT id, client_id, user_id, scopes, created SELECT id, client_id, user_id, scopes, created
FROM oauth_client_authorizations FROM oauth_client_authorizations
@@ -62,9 +62,9 @@ impl OAuthClientAuthorization {
pub async fn get_all_for_user( pub async fn get_all_for_user(
user_id: DBUserId, user_id: DBUserId,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Vec<OAuthClientAuthorization>, DatabaseError> { ) -> Result<Vec<DBOAuthClientAuthorization>, DatabaseError> {
let results = sqlx::query_as!( let results = sqlx::query_as!(
AuthorizationQueryResult, DBAuthClientAuthorizationQueryResult,
" "
SELECT id, client_id, user_id, scopes, created SELECT id, client_id, user_id, scopes, created
FROM oauth_client_authorizations FROM oauth_client_authorizations

View File

@@ -7,28 +7,28 @@ use super::{DBOAuthClientId, DBOAuthRedirectUriId, DBUserId, DatabaseError};
use crate::models::pats::Scopes; use crate::models::pats::Scopes;
#[derive(Deserialize, Serialize, Clone, Debug)] #[derive(Deserialize, Serialize, Clone, Debug)]
pub struct OAuthRedirectUri { pub struct DBOAuthRedirectUri {
pub id: DBOAuthRedirectUriId, pub id: DBOAuthRedirectUriId,
pub client_id: DBOAuthClientId, pub client_id: DBOAuthClientId,
pub uri: String, pub uri: String,
} }
#[derive(Deserialize, Serialize, Clone, Debug)] #[derive(Deserialize, Serialize, Clone, Debug)]
pub struct OAuthClient { pub struct DBOAuthClient {
pub id: DBOAuthClientId, pub id: DBOAuthClientId,
pub name: String, pub name: String,
pub icon_url: Option<String>, pub icon_url: Option<String>,
pub raw_icon_url: Option<String>, pub raw_icon_url: Option<String>,
pub max_scopes: Scopes, pub max_scopes: Scopes,
pub secret_hash: String, pub secret_hash: String,
pub redirect_uris: Vec<OAuthRedirectUri>, pub redirect_uris: Vec<DBOAuthRedirectUri>,
pub created: DateTime<Utc>, pub created: DateTime<Utc>,
pub created_by: DBUserId, pub created_by: DBUserId,
pub url: Option<String>, pub url: Option<String>,
pub description: Option<String>, pub description: Option<String>,
} }
struct ClientQueryResult { struct OAuthClientQueryResult {
id: i64, id: i64,
name: String, name: String,
icon_url: Option<String>, icon_url: Option<String>,
@@ -49,7 +49,7 @@ macro_rules! select_clients_with_predicate {
// the combination of the JOIN and filter using ANY makes sqlx think all columns are nullable // the combination of the JOIN and filter using ANY makes sqlx think all columns are nullable
// https://docs.rs/sqlx/latest/sqlx/macro.query.html#force-nullable // https://docs.rs/sqlx/latest/sqlx/macro.query.html#force-nullable
sqlx::query_as!( sqlx::query_as!(
ClientQueryResult, OAuthClientQueryResult,
r#" r#"
SELECT SELECT
clients.id as "id!", clients.id as "id!",
@@ -77,18 +77,18 @@ macro_rules! select_clients_with_predicate {
}; };
} }
impl OAuthClient { impl DBOAuthClient {
pub async fn get( pub async fn get(
id: DBOAuthClientId, id: DBOAuthClientId,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Option<OAuthClient>, DatabaseError> { ) -> Result<Option<DBOAuthClient>, DatabaseError> {
Ok(Self::get_many(&[id], exec).await?.into_iter().next()) Ok(Self::get_many(&[id], exec).await?.into_iter().next())
} }
pub async fn get_many( pub async fn get_many(
ids: &[DBOAuthClientId], ids: &[DBOAuthClientId],
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Vec<OAuthClient>, DatabaseError> { ) -> Result<Vec<DBOAuthClient>, DatabaseError> {
let ids = ids.iter().map(|id| id.0).collect_vec(); let ids = ids.iter().map(|id| id.0).collect_vec();
let ids_ref: &[i64] = &ids; let ids_ref: &[i64] = &ids;
let results = select_clients_with_predicate!( let results = select_clients_with_predicate!(
@@ -104,7 +104,7 @@ impl OAuthClient {
pub async fn get_all_user_clients( pub async fn get_all_user_clients(
user_id: DBUserId, user_id: DBUserId,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Vec<OAuthClient>, DatabaseError> { ) -> Result<Vec<DBOAuthClient>, DatabaseError> {
let user_id_param = user_id.0; let user_id_param = user_id.0;
let clients = select_clients_with_predicate!( let clients = select_clients_with_predicate!(
"WHERE created_by = $1", "WHERE created_by = $1",
@@ -208,7 +208,7 @@ impl OAuthClient {
} }
pub async fn insert_redirect_uris( pub async fn insert_redirect_uris(
uris: &[OAuthRedirectUri], uris: &[DBOAuthRedirectUri],
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<(), DatabaseError> { ) -> Result<(), DatabaseError> {
let (ids, client_ids, uris): (Vec<_>, Vec<_>, Vec<_>) = uris let (ids, client_ids, uris): (Vec<_>, Vec<_>, Vec<_>) = uris
@@ -235,14 +235,14 @@ impl OAuthClient {
} }
} }
impl From<ClientQueryResult> for OAuthClient { impl From<OAuthClientQueryResult> for DBOAuthClient {
fn from(r: ClientQueryResult) -> Self { fn from(r: OAuthClientQueryResult) -> Self {
let redirects = if let (Some(ids), Some(uris)) = let redirects = if let (Some(ids), Some(uris)) =
(r.uri_ids.as_ref(), r.uri_vals.as_ref()) (r.uri_ids.as_ref(), r.uri_vals.as_ref())
{ {
ids.iter() ids.iter()
.zip(uris.iter()) .zip(uris.iter())
.map(|(id, uri)| OAuthRedirectUri { .map(|(id, uri)| DBOAuthRedirectUri {
id: DBOAuthRedirectUriId(*id), id: DBOAuthRedirectUriId(*id),
client_id: DBOAuthClientId(r.id), client_id: DBOAuthClientId(r.id),
uri: uri.to_string(), uri: uri.to_string(),
@@ -252,7 +252,7 @@ impl From<ClientQueryResult> for OAuthClient {
vec![] vec![]
}; };
OAuthClient { DBOAuthClient {
id: DBOAuthClientId(r.id), id: DBOAuthClientId(r.id),
name: r.name, name: r.name,
icon_url: r.icon_url, icon_url: r.icon_url,

View File

@@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize};
use sha2::Digest; use sha2::Digest;
#[derive(Deserialize, Serialize, Clone, Debug)] #[derive(Deserialize, Serialize, Clone, Debug)]
pub struct OAuthAccessToken { pub struct DBOAuthAccessToken {
pub id: DBOAuthAccessTokenId, pub id: DBOAuthAccessTokenId,
pub authorization_id: DBOAuthClientAuthorizationId, pub authorization_id: DBOAuthClientAuthorizationId,
pub token_hash: String, pub token_hash: String,
@@ -22,11 +22,11 @@ pub struct OAuthAccessToken {
pub user_id: DBUserId, pub user_id: DBUserId,
} }
impl OAuthAccessToken { impl DBOAuthAccessToken {
pub async fn get( pub async fn get(
token_hash: String, token_hash: String,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Option<OAuthAccessToken>, DatabaseError> { ) -> Result<Option<DBOAuthAccessToken>, DatabaseError> {
let value = sqlx::query!( let value = sqlx::query!(
" "
SELECT SELECT
@@ -49,7 +49,7 @@ impl OAuthAccessToken {
.fetch_optional(exec) .fetch_optional(exec)
.await?; .await?;
Ok(value.map(|r| OAuthAccessToken { Ok(value.map(|r| DBOAuthAccessToken {
id: DBOAuthAccessTokenId(r.id), id: DBOAuthAccessTokenId(r.id),
authorization_id: DBOAuthClientAuthorizationId(r.authorization_id), authorization_id: DBOAuthClientAuthorizationId(r.authorization_id),
token_hash: r.token_hash, token_hash: r.token_hash,

View File

@@ -5,7 +5,7 @@ use futures::TryStreamExt;
use std::fmt::{Debug, Display}; use std::fmt::{Debug, Display};
use std::hash::Hash; use std::hash::Hash;
use super::{TeamMember, ids::*}; use super::{DBTeamMember, ids::*};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
const ORGANIZATIONS_NAMESPACE: &str = "organizations"; const ORGANIZATIONS_NAMESPACE: &str = "organizations";
@@ -13,7 +13,7 @@ const ORGANIZATIONS_TITLES_NAMESPACE: &str = "organizations_titles";
#[derive(Deserialize, Serialize, Clone, Debug)] #[derive(Deserialize, Serialize, Clone, Debug)]
/// An organization of users who together control one or more projects and organizations. /// An organization of users who together control one or more projects and organizations.
pub struct Organization { pub struct DBOrganization {
/// The id of the organization /// The id of the organization
pub id: DBOrganizationId, pub id: DBOrganizationId,
@@ -35,7 +35,7 @@ pub struct Organization {
pub color: Option<u32>, pub color: Option<u32>,
} }
impl Organization { impl DBOrganization {
pub async fn insert( pub async fn insert(
self, self,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>, transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
@@ -142,7 +142,7 @@ impl Organization {
) )
.fetch(exec) .fetch(exec)
.try_fold(DashMap::new(), |acc, m| { .try_fold(DashMap::new(), |acc, m| {
let org = Organization { let org = DBOrganization {
id: DBOrganizationId(m.id), id: DBOrganizationId(m.id),
slug: m.slug.clone(), slug: m.slug.clone(),
name: m.name, name: m.name,
@@ -188,7 +188,7 @@ impl Organization {
.await?; .await?;
if let Some(result) = result { if let Some(result) = result {
Ok(Some(Organization { Ok(Some(DBOrganization {
id: DBOrganizationId(result.id), id: DBOrganizationId(result.id),
slug: result.slug, slug: result.slug,
name: result.name, name: result.name,
@@ -221,7 +221,7 @@ impl Organization {
.execute(&mut **transaction) .execute(&mut **transaction)
.await?; .await?;
TeamMember::clear_cache(organization.team_id, redis).await?; DBTeamMember::clear_cache(organization.team_id, redis).await?;
sqlx::query!( sqlx::query!(
" "

View File

@@ -15,7 +15,7 @@ const PATS_TOKENS_NAMESPACE: &str = "pats_tokens";
const PATS_USERS_NAMESPACE: &str = "pats_users"; const PATS_USERS_NAMESPACE: &str = "pats_users";
#[derive(Deserialize, Serialize, Clone, Debug)] #[derive(Deserialize, Serialize, Clone, Debug)]
pub struct PersonalAccessToken { pub struct DBPersonalAccessToken {
pub id: DBPatId, pub id: DBPatId,
pub name: String, pub name: String,
pub access_token: String, pub access_token: String,
@@ -26,7 +26,7 @@ pub struct PersonalAccessToken {
pub last_used: Option<DateTime<Utc>>, pub last_used: Option<DateTime<Utc>>,
} }
impl PersonalAccessToken { impl DBPersonalAccessToken {
pub async fn insert( pub async fn insert(
&self, &self,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>, transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
@@ -63,7 +63,7 @@ impl PersonalAccessToken {
id: T, id: T,
exec: E, exec: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Option<PersonalAccessToken>, DatabaseError> ) -> Result<Option<DBPersonalAccessToken>, DatabaseError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres>, E: sqlx::Executor<'a, Database = sqlx::Postgres>,
{ {
@@ -76,7 +76,7 @@ impl PersonalAccessToken {
pat_ids: &[DBPatId], pat_ids: &[DBPatId],
exec: E, exec: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Vec<PersonalAccessToken>, DatabaseError> ) -> Result<Vec<DBPersonalAccessToken>, DatabaseError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres>, E: sqlx::Executor<'a, Database = sqlx::Postgres>,
{ {
@@ -84,7 +84,7 @@ impl PersonalAccessToken {
.iter() .iter()
.map(|x| crate::models::ids::PatId::from(*x)) .map(|x| crate::models::ids::PatId::from(*x))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
PersonalAccessToken::get_many(&ids, exec, redis).await DBPersonalAccessToken::get_many(&ids, exec, redis).await
} }
pub async fn get_many< pub async fn get_many<
@@ -95,7 +95,7 @@ impl PersonalAccessToken {
pat_strings: &[T], pat_strings: &[T],
exec: E, exec: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Vec<PersonalAccessToken>, DatabaseError> ) -> Result<Vec<DBPersonalAccessToken>, DatabaseError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres>, E: sqlx::Executor<'a, Database = sqlx::Postgres>,
{ {
@@ -125,7 +125,7 @@ impl PersonalAccessToken {
) )
.fetch(exec) .fetch(exec)
.try_fold(DashMap::new(), |acc, x| { .try_fold(DashMap::new(), |acc, x| {
let pat = PersonalAccessToken { let pat = DBPersonalAccessToken {
id: DBPatId(x.id), id: DBPatId(x.id),
name: x.name, name: x.name,
access_token: x.access_token.clone(), access_token: x.access_token.clone(),

View File

@@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
use super::{DBPayoutId, DBUserId, DatabaseError}; use super::{DBPayoutId, DBUserId, DatabaseError};
#[derive(Deserialize, Serialize, Clone, Debug)] #[derive(Deserialize, Serialize, Clone, Debug)]
pub struct Payout { pub struct DBPayout {
pub id: DBPayoutId, pub id: DBPayoutId,
pub user_id: DBUserId, pub user_id: DBUserId,
pub created: DateTime<Utc>, pub created: DateTime<Utc>,
@@ -19,7 +19,7 @@ pub struct Payout {
pub platform_id: Option<String>, pub platform_id: Option<String>,
} }
impl Payout { impl DBPayout {
pub async fn insert( pub async fn insert(
&self, &self,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>, transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
@@ -51,11 +51,11 @@ impl Payout {
pub async fn get<'a, 'b, E>( pub async fn get<'a, 'b, E>(
id: DBPayoutId, id: DBPayoutId,
executor: E, executor: E,
) -> Result<Option<Payout>, DatabaseError> ) -> Result<Option<DBPayout>, DatabaseError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres>, E: sqlx::Executor<'a, Database = sqlx::Postgres>,
{ {
Payout::get_many(&[id], executor) DBPayout::get_many(&[id], executor)
.await .await
.map(|x| x.into_iter().next()) .map(|x| x.into_iter().next())
} }
@@ -63,7 +63,7 @@ impl Payout {
pub async fn get_many<'a, E>( pub async fn get_many<'a, E>(
payout_ids: &[DBPayoutId], payout_ids: &[DBPayoutId],
exec: E, exec: E,
) -> Result<Vec<Payout>, DatabaseError> ) -> Result<Vec<DBPayout>, DatabaseError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres>, E: sqlx::Executor<'a, Database = sqlx::Postgres>,
{ {
@@ -78,7 +78,7 @@ impl Payout {
&payout_ids.into_iter().map(|x| x.0).collect::<Vec<_>>() &payout_ids.into_iter().map(|x| x.0).collect::<Vec<_>>()
) )
.fetch(exec) .fetch(exec)
.map_ok(|r| Payout { .map_ok(|r| DBPayout {
id: DBPayoutId(r.id), id: DBPayoutId(r.id),
user_id: DBUserId(r.user_id), user_id: DBUserId(r.user_id),
created: r.created, created: r.created,
@@ -89,7 +89,7 @@ impl Payout {
platform_id: r.platform_id, platform_id: r.platform_id,
fee: r.fee, fee: r.fee,
}) })
.try_collect::<Vec<Payout>>() .try_collect::<Vec<DBPayout>>()
.await?; .await?;
Ok(results) Ok(results)

View File

@@ -11,13 +11,13 @@ use std::convert::TryInto;
const PRODUCTS_NAMESPACE: &str = "products"; const PRODUCTS_NAMESPACE: &str = "products";
pub struct ProductItem { pub struct DBProduct {
pub id: DBProductId, pub id: DBProductId,
pub metadata: ProductMetadata, pub metadata: ProductMetadata,
pub unitary: bool, pub unitary: bool,
} }
struct ProductResult { struct ProductQueryResult {
id: i64, id: i64,
metadata: serde_json::Value, metadata: serde_json::Value,
unitary: bool, unitary: bool,
@@ -26,7 +26,7 @@ struct ProductResult {
macro_rules! select_products_with_predicate { macro_rules! select_products_with_predicate {
($predicate:tt, $param:ident) => { ($predicate:tt, $param:ident) => {
sqlx::query_as!( sqlx::query_as!(
ProductResult, ProductQueryResult,
r#" r#"
SELECT id, metadata, unitary SELECT id, metadata, unitary
FROM products FROM products
@@ -37,11 +37,11 @@ macro_rules! select_products_with_predicate {
}; };
} }
impl TryFrom<ProductResult> for ProductItem { impl TryFrom<ProductQueryResult> for DBProduct {
type Error = serde_json::Error; type Error = serde_json::Error;
fn try_from(r: ProductResult) -> Result<Self, Self::Error> { fn try_from(r: ProductQueryResult) -> Result<Self, Self::Error> {
Ok(ProductItem { Ok(DBProduct {
id: DBProductId(r.id), id: DBProductId(r.id),
metadata: serde_json::from_value(r.metadata)?, metadata: serde_json::from_value(r.metadata)?,
unitary: r.unitary, unitary: r.unitary,
@@ -49,18 +49,18 @@ impl TryFrom<ProductResult> for ProductItem {
} }
} }
impl ProductItem { impl DBProduct {
pub async fn get( pub async fn get(
id: DBProductId, id: DBProductId,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Option<ProductItem>, DatabaseError> { ) -> Result<Option<DBProduct>, DatabaseError> {
Ok(Self::get_many(&[id], exec).await?.into_iter().next()) Ok(Self::get_many(&[id], exec).await?.into_iter().next())
} }
pub async fn get_many( pub async fn get_many(
ids: &[DBProductId], ids: &[DBProductId],
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Vec<ProductItem>, DatabaseError> { ) -> Result<Vec<DBProduct>, DatabaseError> {
let ids = ids.iter().map(|id| id.0).collect_vec(); let ids = ids.iter().map(|id| id.0).collect_vec();
let ids_ref: &[i64] = &ids; let ids_ref: &[i64] = &ids;
let results = select_products_with_predicate!( let results = select_products_with_predicate!(
@@ -78,7 +78,7 @@ impl ProductItem {
pub async fn get_all( pub async fn get_all(
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Vec<ProductItem>, DatabaseError> { ) -> Result<Vec<DBProduct>, DatabaseError> {
let one = 1; let one = 1;
let results = select_products_with_predicate!("WHERE 1 = $1", one) let results = select_products_with_predicate!("WHERE 1 = $1", one)
.fetch_all(exec) .fetch_all(exec)
@@ -92,24 +92,24 @@ impl ProductItem {
} }
#[derive(Deserialize, Serialize)] #[derive(Deserialize, Serialize)]
pub struct QueryProduct { pub struct QueryProductWithPrices {
pub id: DBProductId, pub id: DBProductId,
pub metadata: ProductMetadata, pub metadata: ProductMetadata,
pub unitary: bool, pub unitary: bool,
pub prices: Vec<ProductPriceItem>, pub prices: Vec<DBProductPrice>,
} }
impl QueryProduct { impl QueryProductWithPrices {
pub async fn list<'a, E>( pub async fn list<'a, E>(
exec: E, exec: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Vec<QueryProduct>, DatabaseError> ) -> Result<Vec<QueryProductWithPrices>, DatabaseError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy, E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy,
{ {
let mut redis = redis.connect().await?; let mut redis = redis.connect().await?;
let res: Option<Vec<QueryProduct>> = redis let res: Option<Vec<QueryProductWithPrices>> = redis
.get_deserialized_from_json(PRODUCTS_NAMESPACE, "all") .get_deserialized_from_json(PRODUCTS_NAMESPACE, "all")
.await?; .await?;
@@ -117,8 +117,8 @@ impl QueryProduct {
return Ok(res); return Ok(res);
} }
let all_products = product_item::ProductItem::get_all(exec).await?; let all_products = product_item::DBProduct::get_all(exec).await?;
let prices = product_item::ProductPriceItem::get_all_products_prices( let prices = product_item::DBProductPrice::get_all_products_prices(
&all_products.iter().map(|x| x.id).collect::<Vec<_>>(), &all_products.iter().map(|x| x.id).collect::<Vec<_>>(),
exec, exec,
) )
@@ -126,7 +126,7 @@ impl QueryProduct {
let products = all_products let products = all_products
.into_iter() .into_iter()
.map(|x| QueryProduct { .map(|x| QueryProductWithPrices {
id: x.id, id: x.id,
metadata: x.metadata, metadata: x.metadata,
prices: prices prices: prices
@@ -134,7 +134,7 @@ impl QueryProduct {
.map(|x| x.1) .map(|x| x.1)
.unwrap_or_default() .unwrap_or_default()
.into_iter() .into_iter()
.map(|x| ProductPriceItem { .map(|x| DBProductPrice {
id: x.id, id: x.id,
product_id: x.product_id, product_id: x.product_id,
prices: x.prices, prices: x.prices,
@@ -154,14 +154,14 @@ impl QueryProduct {
} }
#[derive(Deserialize, Serialize)] #[derive(Deserialize, Serialize)]
pub struct ProductPriceItem { pub struct DBProductPrice {
pub id: DBProductPriceId, pub id: DBProductPriceId,
pub product_id: DBProductId, pub product_id: DBProductId,
pub prices: Price, pub prices: Price,
pub currency_code: String, pub currency_code: String,
} }
struct ProductPriceResult { struct ProductPriceQueryResult {
id: i64, id: i64,
product_id: i64, product_id: i64,
prices: serde_json::Value, prices: serde_json::Value,
@@ -171,7 +171,7 @@ struct ProductPriceResult {
macro_rules! select_prices_with_predicate { macro_rules! select_prices_with_predicate {
($predicate:tt, $param:ident) => { ($predicate:tt, $param:ident) => {
sqlx::query_as!( sqlx::query_as!(
ProductPriceResult, ProductPriceQueryResult,
r#" r#"
SELECT id, product_id, prices, currency_code SELECT id, product_id, prices, currency_code
FROM products_prices FROM products_prices
@@ -182,11 +182,11 @@ macro_rules! select_prices_with_predicate {
}; };
} }
impl TryFrom<ProductPriceResult> for ProductPriceItem { impl TryFrom<ProductPriceQueryResult> for DBProductPrice {
type Error = serde_json::Error; type Error = serde_json::Error;
fn try_from(r: ProductPriceResult) -> Result<Self, Self::Error> { fn try_from(r: ProductPriceQueryResult) -> Result<Self, Self::Error> {
Ok(ProductPriceItem { Ok(DBProductPrice {
id: DBProductPriceId(r.id), id: DBProductPriceId(r.id),
product_id: DBProductId(r.product_id), product_id: DBProductId(r.product_id),
prices: serde_json::from_value(r.prices)?, prices: serde_json::from_value(r.prices)?,
@@ -195,18 +195,18 @@ impl TryFrom<ProductPriceResult> for ProductPriceItem {
} }
} }
impl ProductPriceItem { impl DBProductPrice {
pub async fn get( pub async fn get(
id: DBProductPriceId, id: DBProductPriceId,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Option<ProductPriceItem>, DatabaseError> { ) -> Result<Option<DBProductPrice>, DatabaseError> {
Ok(Self::get_many(&[id], exec).await?.into_iter().next()) Ok(Self::get_many(&[id], exec).await?.into_iter().next())
} }
pub async fn get_many( pub async fn get_many(
ids: &[DBProductPriceId], ids: &[DBProductPriceId],
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Vec<ProductPriceItem>, DatabaseError> { ) -> Result<Vec<DBProductPrice>, DatabaseError> {
let ids = ids.iter().map(|id| id.0).collect_vec(); let ids = ids.iter().map(|id| id.0).collect_vec();
let ids_ref: &[i64] = &ids; let ids_ref: &[i64] = &ids;
let results = select_prices_with_predicate!( let results = select_prices_with_predicate!(
@@ -225,7 +225,7 @@ impl ProductPriceItem {
pub async fn get_all_product_prices( pub async fn get_all_product_prices(
product_id: DBProductId, product_id: DBProductId,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Vec<ProductPriceItem>, DatabaseError> { ) -> Result<Vec<DBProductPrice>, DatabaseError> {
let res = Self::get_all_products_prices(&[product_id], exec).await?; let res = Self::get_all_products_prices(&[product_id], exec).await?;
Ok(res.remove(&product_id).map(|x| x.1).unwrap_or_default()) Ok(res.remove(&product_id).map(|x| x.1).unwrap_or_default())
@@ -234,8 +234,7 @@ impl ProductPriceItem {
pub async fn get_all_products_prices( pub async fn get_all_products_prices(
product_ids: &[DBProductId], product_ids: &[DBProductId],
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<DashMap<DBProductId, Vec<ProductPriceItem>>, DatabaseError> ) -> Result<DashMap<DBProductId, Vec<DBProductPrice>>, DatabaseError> {
{
let ids = product_ids.iter().map(|id| id.0).collect_vec(); let ids = product_ids.iter().map(|id| id.0).collect_vec();
let ids_ref: &[i64] = &ids; let ids_ref: &[i64] = &ids;
@@ -247,9 +246,9 @@ impl ProductPriceItem {
.fetch(exec) .fetch(exec)
.try_fold( .try_fold(
DashMap::new(), DashMap::new(),
|acc: DashMap<DBProductId, Vec<ProductPriceItem>>, x| { |acc: DashMap<DBProductId, Vec<DBProductPrice>>, x| {
if let Ok(item) = <ProductPriceResult as TryInto< if let Ok(item) = <ProductPriceQueryResult as TryInto<
ProductPriceItem, DBProductPrice,
>>::try_into(x) >>::try_into(x)
{ {
acc.entry(item.product_id).or_default().push(item); acc.entry(item.product_id).or_default().push(item);

View File

@@ -2,7 +2,7 @@ use super::loader_fields::{
QueryLoaderField, QueryLoaderFieldEnumValue, QueryVersionField, QueryLoaderField, QueryLoaderFieldEnumValue, QueryVersionField,
VersionField, VersionField,
}; };
use super::{User, ids::*}; use super::{DBUser, ids::*};
use crate::database::models; use crate::database::models;
use crate::database::models::DatabaseError; use crate::database::models::DatabaseError;
use crate::database::redis::RedisPool; use crate::database::redis::RedisPool;
@@ -57,7 +57,7 @@ impl LinkUrl {
} }
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GalleryItem { pub struct DBGalleryItem {
pub image_url: String, pub image_url: String,
pub raw_image_url: String, pub raw_image_url: String,
pub featured: bool, pub featured: bool,
@@ -67,7 +67,7 @@ pub struct GalleryItem {
pub ordering: i64, pub ordering: i64,
} }
impl GalleryItem { impl DBGalleryItem {
pub async fn insert_many( pub async fn insert_many(
items: Vec<Self>, items: Vec<Self>,
project_id: DBProjectId, project_id: DBProjectId,
@@ -117,13 +117,13 @@ impl GalleryItem {
} }
} }
pub struct ModCategory { pub struct DBModCategory {
pub project_id: DBProjectId, pub project_id: DBProjectId,
pub category_id: CategoryId, pub category_id: CategoryId,
pub is_additional: bool, pub is_additional: bool,
} }
impl ModCategory { impl DBModCategory {
pub async fn insert_many( pub async fn insert_many(
items: Vec<Self>, items: Vec<Self>,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>, transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
@@ -171,7 +171,7 @@ pub struct ProjectBuilder {
pub license: String, pub license: String,
pub slug: Option<String>, pub slug: Option<String>,
pub link_urls: Vec<LinkUrl>, pub link_urls: Vec<LinkUrl>,
pub gallery_items: Vec<GalleryItem>, pub gallery_items: Vec<DBGalleryItem>,
pub color: Option<u32>, pub color: Option<u32>,
pub monetization_status: MonetizationStatus, pub monetization_status: MonetizationStatus,
} }
@@ -181,7 +181,7 @@ impl ProjectBuilder {
self, self,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>, transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
) -> Result<DBProjectId, DatabaseError> { ) -> Result<DBProjectId, DatabaseError> {
let project_struct = Project { let project_struct = DBProject {
id: self.project_id, id: self.project_id,
team_id: self.team_id, team_id: self.team_id,
organization_id: self.organization_id, organization_id: self.organization_id,
@@ -234,7 +234,7 @@ impl ProjectBuilder {
) )
.await?; .await?;
GalleryItem::insert_many( DBGalleryItem::insert_many(
gallery_items, gallery_items,
self.project_id, self.project_id,
&mut *transaction, &mut *transaction,
@@ -244,26 +244,26 @@ impl ProjectBuilder {
let project_id = self.project_id; let project_id = self.project_id;
let mod_categories = categories let mod_categories = categories
.into_iter() .into_iter()
.map(|category_id| ModCategory { .map(|category_id| DBModCategory {
project_id, project_id,
category_id, category_id,
is_additional: false, is_additional: false,
}) })
.chain(additional_categories.into_iter().map(|category_id| { .chain(additional_categories.into_iter().map(|category_id| {
ModCategory { DBModCategory {
project_id, project_id,
category_id, category_id,
is_additional: true, is_additional: true,
} }
})) }))
.collect_vec(); .collect_vec();
ModCategory::insert_many(mod_categories, &mut *transaction).await?; DBModCategory::insert_many(mod_categories, &mut *transaction).await?;
Ok(self.project_id) Ok(self.project_id)
} }
} }
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Project { pub struct DBProject {
pub id: DBProjectId, pub id: DBProjectId,
pub team_id: DBTeamId, pub team_id: DBTeamId,
pub organization_id: Option<DBOrganizationId>, pub organization_id: Option<DBOrganizationId>,
@@ -291,7 +291,7 @@ pub struct Project {
pub loaders: Vec<String>, pub loaders: Vec<String>,
} }
impl Project { impl DBProject {
pub async fn insert( pub async fn insert(
&self, &self,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>, transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
@@ -343,7 +343,7 @@ impl Project {
let project = Self::get_id(id, &mut **transaction, redis).await?; let project = Self::get_id(id, &mut **transaction, redis).await?;
if let Some(project) = project { if let Some(project) = project {
Project::clear_cache(id, project.inner.slug, Some(true), redis) DBProject::clear_cache(id, project.inner.slug, Some(true), redis)
.await?; .await?;
sqlx::query!( sqlx::query!(
@@ -376,7 +376,8 @@ impl Project {
.execute(&mut **transaction) .execute(&mut **transaction)
.await?; .await?;
models::Thread::remove_full(project.thread_id, transaction).await?; models::DBThread::remove_full(project.thread_id, transaction)
.await?;
sqlx::query!( sqlx::query!(
" "
@@ -410,7 +411,7 @@ impl Project {
.await?; .await?;
for version in project.versions { for version in project.versions {
super::Version::remove_full(version, redis, transaction) super::DBVersion::remove_full(version, redis, transaction)
.await?; .await?;
} }
@@ -444,7 +445,7 @@ impl Project {
.execute(&mut **transaction) .execute(&mut **transaction)
.await?; .await?;
models::TeamMember::clear_cache(project.inner.team_id, redis) models::DBTeamMember::clear_cache(project.inner.team_id, redis)
.await?; .await?;
let affected_user_ids = sqlx::query!( let affected_user_ids = sqlx::query!(
@@ -460,7 +461,7 @@ impl Project {
.try_collect::<Vec<_>>() .try_collect::<Vec<_>>()
.await?; .await?;
User::clear_project_cache(&affected_user_ids, redis).await?; DBUser::clear_project_cache(&affected_user_ids, redis).await?;
sqlx::query!( sqlx::query!(
" "
@@ -482,11 +483,11 @@ impl Project {
string: &str, string: &str,
executor: E, executor: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Option<QueryProject>, DatabaseError> ) -> Result<Option<ProjectQueryResult>, DatabaseError>
where where
E: sqlx::Acquire<'a, Database = sqlx::Postgres>, E: sqlx::Acquire<'a, Database = sqlx::Postgres>,
{ {
Project::get_many(&[string], executor, redis) DBProject::get_many(&[string], executor, redis)
.await .await
.map(|x| x.into_iter().next()) .map(|x| x.into_iter().next())
} }
@@ -495,11 +496,11 @@ impl Project {
id: DBProjectId, id: DBProjectId,
executor: E, executor: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Option<QueryProject>, DatabaseError> ) -> Result<Option<ProjectQueryResult>, DatabaseError>
where where
E: sqlx::Acquire<'a, Database = sqlx::Postgres>, E: sqlx::Acquire<'a, Database = sqlx::Postgres>,
{ {
Project::get_many( DBProject::get_many(
&[crate::models::ids::ProjectId::from(id)], &[crate::models::ids::ProjectId::from(id)],
executor, executor,
redis, redis,
@@ -512,7 +513,7 @@ impl Project {
project_ids: &[DBProjectId], project_ids: &[DBProjectId],
exec: E, exec: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Vec<QueryProject>, DatabaseError> ) -> Result<Vec<ProjectQueryResult>, DatabaseError>
where where
E: sqlx::Acquire<'a, Database = sqlx::Postgres>, E: sqlx::Acquire<'a, Database = sqlx::Postgres>,
{ {
@@ -520,7 +521,7 @@ impl Project {
.iter() .iter()
.map(|x| crate::models::ids::ProjectId::from(*x)) .map(|x| crate::models::ids::ProjectId::from(*x))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
Project::get_many(&ids, exec, redis).await DBProject::get_many(&ids, exec, redis).await
} }
pub async fn get_many< pub async fn get_many<
@@ -531,7 +532,7 @@ impl Project {
project_strings: &[T], project_strings: &[T],
exec: E, exec: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Vec<QueryProject>, DatabaseError> ) -> Result<Vec<ProjectQueryResult>, DatabaseError>
where where
E: sqlx::Acquire<'a, Database = sqlx::Postgres>, E: sqlx::Acquire<'a, Database = sqlx::Postgres>,
{ {
@@ -638,7 +639,7 @@ impl Project {
.try_collect() .try_collect()
.await?; .await?;
let mods_gallery: DashMap<DBProjectId, Vec<GalleryItem>> = sqlx::query!( let mods_gallery: DashMap<DBProjectId, Vec<DBGalleryItem>> = sqlx::query!(
" "
SELECT DISTINCT mod_id, mg.image_url, mg.raw_image_url, mg.featured, mg.name, mg.description, mg.created, mg.ordering SELECT DISTINCT mod_id, mg.image_url, mg.raw_image_url, mg.featured, mg.name, mg.description, mg.created, mg.ordering
FROM mods_gallery mg FROM mods_gallery mg
@@ -648,10 +649,10 @@ impl Project {
&project_ids_parsed, &project_ids_parsed,
&slugs &slugs
).fetch(&mut *exec) ).fetch(&mut *exec)
.try_fold(DashMap::new(), |acc : DashMap<DBProjectId, Vec<GalleryItem>>, m| { .try_fold(DashMap::new(), |acc : DashMap<DBProjectId, Vec<DBGalleryItem>>, m| {
acc.entry(DBProjectId(m.mod_id)) acc.entry(DBProjectId(m.mod_id))
.or_default() .or_default()
.push(GalleryItem { .push(DBGalleryItem {
image_url: m.image_url, image_url: m.image_url,
raw_image_url: m.raw_image_url, raw_image_url: m.raw_image_url,
featured: m.featured.unwrap_or(false), featured: m.featured.unwrap_or(false),
@@ -802,8 +803,8 @@ impl Project {
.filter(|x| loader_loader_field_ids.contains(&x.id)) .filter(|x| loader_loader_field_ids.contains(&x.id))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let project = QueryProject { let project = ProjectQueryResult {
inner: Project { inner: DBProject {
id: DBProjectId(id), id: DBProjectId(id),
team_id: DBTeamId(m.team_id), team_id: DBTeamId(m.team_id),
organization_id: m.organization_id.map(DBOrganizationId), organization_id: m.organization_id.map(DBOrganizationId),
@@ -958,15 +959,15 @@ impl Project {
} }
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
pub struct QueryProject { pub struct ProjectQueryResult {
pub inner: Project, pub inner: DBProject,
pub categories: Vec<String>, pub categories: Vec<String>,
pub additional_categories: Vec<String>, pub additional_categories: Vec<String>,
pub versions: Vec<DBVersionId>, pub versions: Vec<DBVersionId>,
pub project_types: Vec<String>, pub project_types: Vec<String>,
pub games: Vec<String>, pub games: Vec<String>,
pub urls: Vec<LinkUrl>, pub urls: Vec<LinkUrl>,
pub gallery_items: Vec<GalleryItem>, pub gallery_items: Vec<DBGalleryItem>,
pub thread_id: DBThreadId, pub thread_id: DBThreadId,
pub aggregate_version_fields: Vec<VersionField>, pub aggregate_version_fields: Vec<VersionField>,
} }

View File

@@ -1,7 +1,7 @@
use super::ids::*; use super::ids::*;
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
pub struct Report { pub struct DBReport {
pub id: DBReportId, pub id: DBReportId,
pub report_type_id: ReportTypeId, pub report_type_id: ReportTypeId,
pub project_id: Option<DBProjectId>, pub project_id: Option<DBProjectId>,
@@ -13,7 +13,7 @@ pub struct Report {
pub closed: bool, pub closed: bool,
} }
pub struct QueryReport { pub struct ReportQueryResult {
pub id: DBReportId, pub id: DBReportId,
pub report_type: String, pub report_type: String,
pub project_id: Option<DBProjectId>, pub project_id: Option<DBProjectId>,
@@ -26,7 +26,7 @@ pub struct QueryReport {
pub thread_id: DBThreadId, pub thread_id: DBThreadId,
} }
impl Report { impl DBReport {
pub async fn insert( pub async fn insert(
&self, &self,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>, transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
@@ -59,7 +59,7 @@ impl Report {
pub async fn get<'a, E>( pub async fn get<'a, E>(
id: DBReportId, id: DBReportId,
exec: E, exec: E,
) -> Result<Option<QueryReport>, sqlx::Error> ) -> Result<Option<ReportQueryResult>, sqlx::Error>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres>, E: sqlx::Executor<'a, Database = sqlx::Postgres>,
{ {
@@ -71,7 +71,7 @@ impl Report {
pub async fn get_many<'a, E>( pub async fn get_many<'a, E>(
report_ids: &[DBReportId], report_ids: &[DBReportId],
exec: E, exec: E,
) -> Result<Vec<QueryReport>, sqlx::Error> ) -> Result<Vec<ReportQueryResult>, sqlx::Error>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres>, E: sqlx::Executor<'a, Database = sqlx::Postgres>,
{ {
@@ -91,7 +91,7 @@ impl Report {
&report_ids_parsed &report_ids_parsed
) )
.fetch(exec) .fetch(exec)
.map_ok(|x| QueryReport { .map_ok(|x| ReportQueryResult {
id: DBReportId(x.id), id: DBReportId(x.id),
report_type: x.name, report_type: x.name,
project_id: x.mod_id.map(DBProjectId), project_id: x.mod_id.map(DBProjectId),
@@ -103,7 +103,7 @@ impl Report {
closed: x.closed, closed: x.closed,
thread_id: DBThreadId(x.thread_id) thread_id: DBThreadId(x.thread_id)
}) })
.try_collect::<Vec<QueryReport>>() .try_collect::<Vec<ReportQueryResult>>()
.await?; .await?;
Ok(reports) Ok(reports)
@@ -137,7 +137,7 @@ impl Report {
.await?; .await?;
if let Some(thread_id) = thread_id { if let Some(thread_id) = thread_id {
crate::database::models::Thread::remove_full( crate::database::models::DBThread::remove_full(
DBThreadId(thread_id.id), DBThreadId(thread_id.id),
transaction, transaction,
) )

View File

@@ -62,7 +62,7 @@ impl SessionBuilder {
} }
#[derive(Deserialize, Serialize)] #[derive(Deserialize, Serialize)]
pub struct Session { pub struct DBSession {
pub id: DBSessionId, pub id: DBSessionId,
pub session: String, pub session: String,
pub user_id: DBUserId, pub user_id: DBUserId,
@@ -81,7 +81,7 @@ pub struct Session {
pub ip: String, pub ip: String,
} }
impl Session { impl DBSession {
pub async fn get< pub async fn get<
'a, 'a,
E, E,
@@ -90,7 +90,7 @@ impl Session {
id: T, id: T,
exec: E, exec: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Option<Session>, DatabaseError> ) -> Result<Option<DBSession>, DatabaseError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres>, E: sqlx::Executor<'a, Database = sqlx::Postgres>,
{ {
@@ -103,11 +103,11 @@ impl Session {
id: DBSessionId, id: DBSessionId,
executor: E, executor: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Option<Session>, DatabaseError> ) -> Result<Option<DBSession>, DatabaseError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres>, E: sqlx::Executor<'a, Database = sqlx::Postgres>,
{ {
Session::get_many( DBSession::get_many(
&[crate::models::ids::SessionId::from(id)], &[crate::models::ids::SessionId::from(id)],
executor, executor,
redis, redis,
@@ -120,7 +120,7 @@ impl Session {
session_ids: &[DBSessionId], session_ids: &[DBSessionId],
exec: E, exec: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Vec<Session>, DatabaseError> ) -> Result<Vec<DBSession>, DatabaseError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres>, E: sqlx::Executor<'a, Database = sqlx::Postgres>,
{ {
@@ -128,7 +128,7 @@ impl Session {
.iter() .iter()
.map(|x| crate::models::ids::SessionId::from(*x)) .map(|x| crate::models::ids::SessionId::from(*x))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
Session::get_many(&ids, exec, redis).await DBSession::get_many(&ids, exec, redis).await
} }
pub async fn get_many< pub async fn get_many<
@@ -139,7 +139,7 @@ impl Session {
session_strings: &[T], session_strings: &[T],
exec: E, exec: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Vec<Session>, DatabaseError> ) -> Result<Vec<DBSession>, DatabaseError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres>, E: sqlx::Executor<'a, Database = sqlx::Postgres>,
{ {
@@ -173,7 +173,7 @@ impl Session {
) )
.fetch(exec) .fetch(exec)
.try_fold(DashMap::new(), |acc, x| { .try_fold(DashMap::new(), |acc, x| {
let session = Session { let session = DBSession {
id: DBSessionId(x.id), id: DBSessionId(x.id),
session: x.session.clone(), session: x.session.clone(),
user_id: DBUserId(x.user_id), user_id: DBUserId(x.user_id),

View File

@@ -1,4 +1,4 @@
use super::{Organization, Project, ids::*}; use super::{DBOrganization, DBProject, ids::*};
use crate::{ use crate::{
database::redis::RedisPool, database::redis::RedisPool,
models::teams::{OrganizationPermissions, ProjectPermissions}, models::teams::{OrganizationPermissions, ProjectPermissions},
@@ -32,7 +32,7 @@ impl TeamBuilder {
) -> Result<DBTeamId, super::DatabaseError> { ) -> Result<DBTeamId, super::DatabaseError> {
let team_id = generate_team_id(transaction).await?; let team_id = generate_team_id(transaction).await?;
let team = Team { id: team_id }; let team = DBTeam { id: team_id };
sqlx::query!( sqlx::query!(
" "
@@ -109,7 +109,7 @@ impl TeamBuilder {
} }
/// A team of users who control a project /// A team of users who control a project
pub struct Team { pub struct DBTeam {
/// The id of the team /// The id of the team
pub id: DBTeamId, pub id: DBTeamId,
} }
@@ -120,7 +120,7 @@ pub enum TeamAssociationId {
Organization(DBOrganizationId), Organization(DBOrganizationId),
} }
impl Team { impl DBTeam {
pub async fn get_association<'a, 'b, E>( pub async fn get_association<'a, 'b, E>(
id: DBTeamId, id: DBTeamId,
executor: E, executor: E,
@@ -165,7 +165,7 @@ impl Team {
/// A member of a team /// A member of a team
#[derive(Deserialize, Serialize, Clone, Debug)] #[derive(Deserialize, Serialize, Clone, Debug)]
pub struct TeamMember { pub struct DBTeamMember {
pub id: DBTeamMemberId, pub id: DBTeamMemberId,
pub team_id: DBTeamId, pub team_id: DBTeamId,
@@ -187,13 +187,13 @@ pub struct TeamMember {
pub ordering: i64, pub ordering: i64,
} }
impl TeamMember { impl DBTeamMember {
// Lists the full members of a team // Lists the full members of a team
pub async fn get_from_team_full<'a, 'b, E>( pub async fn get_from_team_full<'a, 'b, E>(
id: DBTeamId, id: DBTeamId,
executor: E, executor: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Vec<TeamMember>, super::DatabaseError> ) -> Result<Vec<DBTeamMember>, super::DatabaseError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy, E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy,
{ {
@@ -204,7 +204,7 @@ impl TeamMember {
team_ids: &[DBTeamId], team_ids: &[DBTeamId],
exec: E, exec: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Vec<TeamMember>, super::DatabaseError> ) -> Result<Vec<DBTeamMember>, super::DatabaseError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy, E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy,
{ {
@@ -228,8 +228,8 @@ impl TeamMember {
&team_ids &team_ids
) )
.fetch(exec) .fetch(exec)
.try_fold(DashMap::new(), |acc: DashMap<i64, Vec<TeamMember>>, m| { .try_fold(DashMap::new(), |acc: DashMap<i64, Vec<DBTeamMember>>, m| {
let member = TeamMember { let member = DBTeamMember {
id: DBTeamMemberId(m.id), id: DBTeamMemberId(m.id),
team_id: DBTeamId(m.team_id), team_id: DBTeamId(m.team_id),
role: m.member_role, role: m.member_role,
@@ -307,7 +307,7 @@ impl TeamMember {
user_id as DBUserId user_id as DBUserId
) )
.fetch(executor) .fetch(executor)
.map_ok(|m| TeamMember { .map_ok(|m| DBTeamMember {
id: DBTeamMemberId(m.id), id: DBTeamMemberId(m.id),
team_id: DBTeamId(m.team_id), team_id: DBTeamId(m.team_id),
user_id, user_id,
@@ -322,7 +322,7 @@ impl TeamMember {
payouts_split: m.payouts_split, payouts_split: m.payouts_split,
ordering: m.ordering, ordering: m.ordering,
}) })
.try_collect::<Vec<TeamMember>>() .try_collect::<Vec<DBTeamMember>>()
.await?; .await?;
Ok(team_members) Ok(team_members)
@@ -354,7 +354,7 @@ impl TeamMember {
.await?; .await?;
if let Some(m) = result { if let Some(m) = result {
Ok(Some(TeamMember { Ok(Some(DBTeamMember {
id: DBTeamMemberId(m.id), id: DBTeamMemberId(m.id),
team_id: id, team_id: id,
user_id, user_id,
@@ -577,7 +577,7 @@ impl TeamMember {
.await?; .await?;
if let Some(m) = result { if let Some(m) = result {
Ok(Some(TeamMember { Ok(Some(DBTeamMember {
id: DBTeamMemberId(m.id), id: DBTeamMemberId(m.id),
team_id: DBTeamId(m.team_id), team_id: DBTeamId(m.team_id),
user_id, user_id,
@@ -629,7 +629,7 @@ impl TeamMember {
.await?; .await?;
if let Some(m) = result { if let Some(m) = result {
Ok(Some(TeamMember { Ok(Some(DBTeamMember {
id: DBTeamMemberId(m.id), id: DBTeamMemberId(m.id),
team_id: DBTeamId(m.team_id), team_id: DBTeamId(m.team_id),
user_id, user_id,
@@ -675,7 +675,7 @@ impl TeamMember {
.await?; .await?;
if let Some(m) = result { if let Some(m) = result {
Ok(Some(TeamMember { Ok(Some(DBTeamMember {
id: DBTeamMemberId(m.id), id: DBTeamMemberId(m.id),
team_id: DBTeamId(m.team_id), team_id: DBTeamId(m.team_id),
user_id, user_id,
@@ -702,7 +702,7 @@ impl TeamMember {
// - project team member (a user's membership to a given project) // - project team member (a user's membership to a given project)
// - organization team member (a user's membership to a given organization that owns a given project) // - organization team member (a user's membership to a given organization that owns a given project)
pub async fn get_for_project_permissions<'a, 'b, E>( pub async fn get_for_project_permissions<'a, 'b, E>(
project: &Project, project: &DBProject,
user_id: DBUserId, user_id: DBUserId,
executor: E, executor: E,
) -> Result<(Option<Self>, Option<Self>), super::DatabaseError> ) -> Result<(Option<Self>, Option<Self>), super::DatabaseError>
@@ -713,7 +713,7 @@ impl TeamMember {
Self::get_from_user_id(project.team_id, user_id, executor).await?; Self::get_from_user_id(project.team_id, user_id, executor).await?;
let organization = let organization =
Organization::get_associated_organization_project_id( DBOrganization::get_associated_organization_project_id(
project.id, executor, project.id, executor,
) )
.await?; .await?;

View File

@@ -12,14 +12,14 @@ pub struct ThreadBuilder {
} }
#[derive(Clone, Serialize)] #[derive(Clone, Serialize)]
pub struct Thread { pub struct DBThread {
pub id: DBThreadId, pub id: DBThreadId,
pub project_id: Option<DBProjectId>, pub project_id: Option<DBProjectId>,
pub report_id: Option<DBReportId>, pub report_id: Option<DBReportId>,
pub type_: ThreadType, pub type_: ThreadType,
pub messages: Vec<ThreadMessage>, pub messages: Vec<DBThreadMessage>,
pub members: Vec<DBUserId>, pub members: Vec<DBUserId>,
} }
@@ -31,7 +31,7 @@ pub struct ThreadMessageBuilder {
} }
#[derive(Serialize, Deserialize, Clone)] #[derive(Serialize, Deserialize, Clone)]
pub struct ThreadMessage { pub struct DBThreadMessage {
pub id: DBThreadMessageId, pub id: DBThreadMessageId,
pub thread_id: DBThreadId, pub thread_id: DBThreadId,
pub author_id: Option<DBUserId>, pub author_id: Option<DBUserId>,
@@ -111,11 +111,11 @@ impl ThreadBuilder {
} }
} }
impl Thread { impl DBThread {
pub async fn get<'a, E>( pub async fn get<'a, E>(
id: DBThreadId, id: DBThreadId,
exec: E, exec: E,
) -> Result<Option<Thread>, sqlx::Error> ) -> Result<Option<DBThread>, sqlx::Error>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy, E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy,
{ {
@@ -127,7 +127,7 @@ impl Thread {
pub async fn get_many<'a, E>( pub async fn get_many<'a, E>(
thread_ids: &[DBThreadId], thread_ids: &[DBThreadId],
exec: E, exec: E,
) -> Result<Vec<Thread>, sqlx::Error> ) -> Result<Vec<DBThread>, sqlx::Error>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy, E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy,
{ {
@@ -149,13 +149,13 @@ impl Thread {
&thread_ids_parsed &thread_ids_parsed
) )
.fetch(exec) .fetch(exec)
.map_ok(|x| Thread { .map_ok(|x| DBThread {
id: DBThreadId(x.id), id: DBThreadId(x.id),
project_id: x.mod_id.map(DBProjectId), project_id: x.mod_id.map(DBProjectId),
report_id: x.report_id.map(DBReportId), report_id: x.report_id.map(DBReportId),
type_: ThreadType::from_string(&x.thread_type), type_: ThreadType::from_string(&x.thread_type),
messages: { messages: {
let mut messages: Vec<ThreadMessage> = serde_json::from_value( let mut messages: Vec<DBThreadMessage> = serde_json::from_value(
x.messages.unwrap_or_default(), x.messages.unwrap_or_default(),
) )
.ok() .ok()
@@ -165,7 +165,7 @@ impl Thread {
}, },
members: x.members.unwrap_or_default().into_iter().map(DBUserId).collect(), members: x.members.unwrap_or_default().into_iter().map(DBUserId).collect(),
}) })
.try_collect::<Vec<Thread>>() .try_collect::<Vec<DBThread>>()
.await?; .await?;
Ok(threads) Ok(threads)
@@ -207,11 +207,11 @@ impl Thread {
} }
} }
impl ThreadMessage { impl DBThreadMessage {
pub async fn get<'a, E>( pub async fn get<'a, E>(
id: DBThreadMessageId, id: DBThreadMessageId,
exec: E, exec: E,
) -> Result<Option<ThreadMessage>, sqlx::Error> ) -> Result<Option<DBThreadMessage>, sqlx::Error>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres>, E: sqlx::Executor<'a, Database = sqlx::Postgres>,
{ {
@@ -223,7 +223,7 @@ impl ThreadMessage {
pub async fn get_many<'a, E>( pub async fn get_many<'a, E>(
message_ids: &[DBThreadMessageId], message_ids: &[DBThreadMessageId],
exec: E, exec: E,
) -> Result<Vec<ThreadMessage>, sqlx::Error> ) -> Result<Vec<DBThreadMessage>, sqlx::Error>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres>, E: sqlx::Executor<'a, Database = sqlx::Postgres>,
{ {
@@ -240,7 +240,7 @@ impl ThreadMessage {
&message_ids_parsed &message_ids_parsed
) )
.fetch(exec) .fetch(exec)
.map_ok(|x| ThreadMessage { .map_ok(|x| DBThreadMessage {
id: DBThreadMessageId(x.id), id: DBThreadMessageId(x.id),
thread_id: DBThreadId(x.thread_id), thread_id: DBThreadId(x.thread_id),
author_id: x.author_id.map(DBUserId), author_id: x.author_id.map(DBUserId),
@@ -248,7 +248,7 @@ impl ThreadMessage {
created: x.created, created: x.created,
hide_identity: x.hide_identity, hide_identity: x.hide_identity,
}) })
.try_collect::<Vec<ThreadMessage>>() .try_collect::<Vec<DBThreadMessage>>()
.await?; .await?;
Ok(messages) Ok(messages)

View File

@@ -1,8 +1,8 @@
use super::ids::{DBProjectId, DBUserId}; use super::ids::{DBProjectId, DBUserId};
use super::{DBCollectionId, DBReportId, DBThreadId}; use super::{DBCollectionId, DBReportId, DBThreadId};
use crate::database::models; use crate::database::models;
use crate::database::models::charge_item::ChargeItem; use crate::database::models::charge_item::DBCharge;
use crate::database::models::user_subscription_item::UserSubscriptionItem; use crate::database::models::user_subscription_item::DBUserSubscription;
use crate::database::models::{DBOrganizationId, DatabaseError}; use crate::database::models::{DBOrganizationId, DatabaseError};
use crate::database::redis::RedisPool; use crate::database::redis::RedisPool;
use crate::models::billing::ChargeStatus; use crate::models::billing::ChargeStatus;
@@ -19,7 +19,7 @@ const USER_USERNAMES_NAMESPACE: &str = "users_usernames";
const USERS_PROJECTS_NAMESPACE: &str = "users_projects"; const USERS_PROJECTS_NAMESPACE: &str = "users_projects";
#[derive(Deserialize, Serialize, Clone, Debug)] #[derive(Deserialize, Serialize, Clone, Debug)]
pub struct User { pub struct DBUser {
pub id: DBUserId, pub id: DBUserId,
pub github_id: Option<i64>, pub github_id: Option<i64>,
@@ -51,7 +51,7 @@ pub struct User {
pub allow_friend_requests: bool, pub allow_friend_requests: bool,
} }
impl User { impl DBUser {
pub async fn insert( pub async fn insert(
&self, &self,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>, transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
@@ -104,11 +104,11 @@ impl User {
string: &str, string: &str,
executor: E, executor: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Option<User>, DatabaseError> ) -> Result<Option<DBUser>, DatabaseError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres>, E: sqlx::Executor<'a, Database = sqlx::Postgres>,
{ {
User::get_many(&[string], executor, redis) DBUser::get_many(&[string], executor, redis)
.await .await
.map(|x| x.into_iter().next()) .map(|x| x.into_iter().next())
} }
@@ -117,11 +117,11 @@ impl User {
id: DBUserId, id: DBUserId,
executor: E, executor: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Option<User>, DatabaseError> ) -> Result<Option<DBUser>, DatabaseError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres>, E: sqlx::Executor<'a, Database = sqlx::Postgres>,
{ {
User::get_many(&[ariadne::ids::UserId::from(id)], executor, redis) DBUser::get_many(&[ariadne::ids::UserId::from(id)], executor, redis)
.await .await
.map(|x| x.into_iter().next()) .map(|x| x.into_iter().next())
} }
@@ -130,7 +130,7 @@ impl User {
user_ids: &[DBUserId], user_ids: &[DBUserId],
exec: E, exec: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Vec<User>, DatabaseError> ) -> Result<Vec<DBUser>, DatabaseError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres>, E: sqlx::Executor<'a, Database = sqlx::Postgres>,
{ {
@@ -138,7 +138,7 @@ impl User {
.iter() .iter()
.map(|x| ariadne::ids::UserId::from(*x)) .map(|x| ariadne::ids::UserId::from(*x))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
User::get_many(&ids, exec, redis).await DBUser::get_many(&ids, exec, redis).await
} }
pub async fn get_many< pub async fn get_many<
@@ -149,7 +149,7 @@ impl User {
users_strings: &[T], users_strings: &[T],
exec: E, exec: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Vec<User>, DatabaseError> ) -> Result<Vec<DBUser>, DatabaseError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres>, E: sqlx::Executor<'a, Database = sqlx::Postgres>,
{ {
@@ -187,7 +187,7 @@ impl User {
) )
.fetch(exec) .fetch(exec)
.try_fold(DashMap::new(), |acc, u| { .try_fold(DashMap::new(), |acc, u| {
let user = User { let user = DBUser {
id: DBUserId(u.id), id: DBUserId(u.id),
github_id: u.github_id, github_id: u.github_id,
discord_id: u.discord_id, discord_id: u.discord_id,
@@ -459,7 +459,7 @@ impl User {
let user = Self::get_id(id, &mut **transaction, redis).await?; let user = Self::get_id(id, &mut **transaction, redis).await?;
if let Some(delete_user) = user { if let Some(delete_user) = user {
User::clear_caches(&[(id, Some(delete_user.username))], redis) DBUser::clear_caches(&[(id, Some(delete_user.username))], redis)
.await?; .await?;
let deleted_user: DBUserId = let deleted_user: DBUserId =
@@ -536,7 +536,7 @@ impl User {
.await?; .await?;
for collection_id in user_collections { for collection_id in user_collections {
models::Collection::remove(collection_id, transaction, redis) models::DBCollection::remove(collection_id, transaction, redis)
.await?; .await?;
} }
@@ -555,7 +555,7 @@ impl User {
.await?; .await?;
for thread_id in report_threads { for thread_id in report_threads {
models::Thread::remove_full(thread_id, transaction).await?; models::DBThread::remove_full(thread_id, transaction).await?;
} }
sqlx::query!( sqlx::query!(
@@ -661,12 +661,12 @@ impl User {
.await?; .await?;
let open_subscriptions = let open_subscriptions =
UserSubscriptionItem::get_all_user(id, &mut **transaction) DBUserSubscription::get_all_user(id, &mut **transaction)
.await?; .await?;
for x in open_subscriptions { for x in open_subscriptions {
let charge = let charge =
ChargeItem::get_open_subscription(x.id, &mut **transaction) DBCharge::get_open_subscription(x.id, &mut **transaction)
.await?; .await?;
if let Some(mut charge) = charge { if let Some(mut charge) = charge {
charge.status = ChargeStatus::Cancelled; charge.status = ChargeStatus::Cancelled;

View File

@@ -8,7 +8,7 @@ use chrono::{DateTime, Utc};
use itertools::Itertools; use itertools::Itertools;
use std::convert::{TryFrom, TryInto}; use std::convert::{TryFrom, TryInto};
pub struct UserSubscriptionItem { pub struct DBUserSubscription {
pub id: DBUserSubscriptionId, pub id: DBUserSubscriptionId,
pub user_id: DBUserId, pub user_id: DBUserId,
pub price_id: DBProductPriceId, pub price_id: DBProductPriceId,
@@ -18,7 +18,7 @@ pub struct UserSubscriptionItem {
pub metadata: Option<SubscriptionMetadata>, pub metadata: Option<SubscriptionMetadata>,
} }
struct UserSubscriptionResult { struct UserSubscriptionQueryResult {
id: i64, id: i64,
user_id: i64, user_id: i64,
price_id: i64, price_id: i64,
@@ -31,7 +31,7 @@ struct UserSubscriptionResult {
macro_rules! select_user_subscriptions_with_predicate { macro_rules! select_user_subscriptions_with_predicate {
($predicate:tt, $param:ident) => { ($predicate:tt, $param:ident) => {
sqlx::query_as!( sqlx::query_as!(
UserSubscriptionResult, UserSubscriptionQueryResult,
r#" r#"
SELECT SELECT
us.id, us.user_id, us.price_id, us.interval, us.created, us.status, us.metadata us.id, us.user_id, us.price_id, us.interval, us.created, us.status, us.metadata
@@ -43,11 +43,11 @@ macro_rules! select_user_subscriptions_with_predicate {
}; };
} }
impl TryFrom<UserSubscriptionResult> for UserSubscriptionItem { impl TryFrom<UserSubscriptionQueryResult> for DBUserSubscription {
type Error = serde_json::Error; type Error = serde_json::Error;
fn try_from(r: UserSubscriptionResult) -> Result<Self, Self::Error> { fn try_from(r: UserSubscriptionQueryResult) -> Result<Self, Self::Error> {
Ok(UserSubscriptionItem { Ok(DBUserSubscription {
id: DBUserSubscriptionId(r.id), id: DBUserSubscriptionId(r.id),
user_id: DBUserId(r.user_id), user_id: DBUserId(r.user_id),
price_id: DBProductPriceId(r.price_id), price_id: DBProductPriceId(r.price_id),
@@ -59,18 +59,18 @@ impl TryFrom<UserSubscriptionResult> for UserSubscriptionItem {
} }
} }
impl UserSubscriptionItem { impl DBUserSubscription {
pub async fn get( pub async fn get(
id: DBUserSubscriptionId, id: DBUserSubscriptionId,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Option<UserSubscriptionItem>, DatabaseError> { ) -> Result<Option<DBUserSubscription>, DatabaseError> {
Ok(Self::get_many(&[id], exec).await?.into_iter().next()) Ok(Self::get_many(&[id], exec).await?.into_iter().next())
} }
pub async fn get_many( pub async fn get_many(
ids: &[DBUserSubscriptionId], ids: &[DBUserSubscriptionId],
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Vec<UserSubscriptionItem>, DatabaseError> { ) -> Result<Vec<DBUserSubscription>, DatabaseError> {
let ids = ids.iter().map(|id| id.0).collect_vec(); let ids = ids.iter().map(|id| id.0).collect_vec();
let ids_ref: &[i64] = &ids; let ids_ref: &[i64] = &ids;
let results = select_user_subscriptions_with_predicate!( let results = select_user_subscriptions_with_predicate!(
@@ -89,7 +89,7 @@ impl UserSubscriptionItem {
pub async fn get_all_user( pub async fn get_all_user(
user_id: DBUserId, user_id: DBUserId,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Vec<UserSubscriptionItem>, DatabaseError> { ) -> Result<Vec<DBUserSubscription>, DatabaseError> {
let user_id = user_id.0; let user_id = user_id.0;
let results = select_user_subscriptions_with_predicate!( let results = select_user_subscriptions_with_predicate!(
"WHERE us.user_id = $1", "WHERE us.user_id = $1",
@@ -107,7 +107,7 @@ impl UserSubscriptionItem {
pub async fn get_all_servers( pub async fn get_all_servers(
status: Option<SubscriptionStatus>, status: Option<SubscriptionStatus>,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>, exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Vec<UserSubscriptionItem>, DatabaseError> { ) -> Result<Vec<DBUserSubscription>, DatabaseError> {
let status = status.map(|x| x.as_str()); let status = status.map(|x| x.as_str());
let results = select_user_subscriptions_with_predicate!( let results = select_user_subscriptions_with_predicate!(

View File

@@ -179,7 +179,7 @@ impl VersionBuilder {
self, self,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>, transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
) -> Result<DBVersionId, DatabaseError> { ) -> Result<DBVersionId, DatabaseError> {
let version = Version { let version = DBVersion {
id: self.version_id, id: self.version_id,
project_id: self.project_id, project_id: self.project_id,
author_id: self.author_id, author_id: self.author_id,
@@ -229,12 +229,12 @@ impl VersionBuilder {
let loader_versions = loaders let loader_versions = loaders
.iter() .iter()
.map(|&loader_id| LoaderVersion { .map(|&loader_id| DBLoaderVersion {
loader_id, loader_id,
version_id, version_id,
}) })
.collect_vec(); .collect_vec();
LoaderVersion::insert_many(loader_versions, transaction).await?; DBLoaderVersion::insert_many(loader_versions, transaction).await?;
VersionField::insert_many(self.version_fields, transaction).await?; VersionField::insert_many(self.version_fields, transaction).await?;
@@ -243,12 +243,12 @@ impl VersionBuilder {
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub struct LoaderVersion { pub struct DBLoaderVersion {
pub loader_id: LoaderId, pub loader_id: LoaderId,
pub version_id: DBVersionId, pub version_id: DBVersionId,
} }
impl LoaderVersion { impl DBLoaderVersion {
pub async fn insert_many( pub async fn insert_many(
items: Vec<Self>, items: Vec<Self>,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>, transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
@@ -273,7 +273,7 @@ impl LoaderVersion {
} }
#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)] #[derive(Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct Version { pub struct DBVersion {
pub id: DBVersionId, pub id: DBVersionId,
pub project_id: DBProjectId, pub project_id: DBProjectId,
pub author_id: DBUserId, pub author_id: DBUserId,
@@ -289,7 +289,7 @@ pub struct Version {
pub ordering: Option<i32>, pub ordering: Option<i32>,
} }
impl Version { impl DBVersion {
pub async fn insert( pub async fn insert(
&self, &self,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>, transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
@@ -339,7 +339,7 @@ impl Version {
return Ok(None); return Ok(None);
}; };
Version::clear_cache(&result, redis).await?; DBVersion::clear_cache(&result, redis).await?;
sqlx::query!( sqlx::query!(
" "
@@ -447,7 +447,7 @@ impl Version {
.execute(&mut **transaction) .execute(&mut **transaction)
.await?; .await?;
crate::database::models::Project::clear_cache( crate::database::models::DBProject::clear_cache(
DBProjectId(project_id.mod_id), DBProjectId(project_id.mod_id),
None, None,
None, None,
@@ -462,7 +462,7 @@ impl Version {
id: DBVersionId, id: DBVersionId,
executor: E, executor: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Option<QueryVersion>, DatabaseError> ) -> Result<Option<VersionQueryResult>, DatabaseError>
where where
E: sqlx::Acquire<'a, Database = sqlx::Postgres>, E: sqlx::Acquire<'a, Database = sqlx::Postgres>,
{ {
@@ -475,7 +475,7 @@ impl Version {
version_ids: &[DBVersionId], version_ids: &[DBVersionId],
exec: E, exec: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Vec<QueryVersion>, DatabaseError> ) -> Result<Vec<VersionQueryResult>, DatabaseError>
where where
E: sqlx::Acquire<'a, Database = sqlx::Postgres>, E: sqlx::Acquire<'a, Database = sqlx::Postgres>,
{ {
@@ -684,7 +684,7 @@ impl Version {
}) })
.await?; .await?;
let dependencies : DashMap<DBVersionId, Vec<QueryDependency>> = sqlx::query!( let dependencies : DashMap<DBVersionId, Vec<DependencyQueryResult>> = sqlx::query!(
" "
SELECT DISTINCT dependent_id as version_id, d.mod_dependency_id as dependency_project_id, d.dependency_id as dependency_version_id, d.dependency_file_name as file_name, d.dependency_type as dependency_type SELECT DISTINCT dependent_id as version_id, d.mod_dependency_id as dependency_project_id, d.dependency_id as dependency_version_id, d.dependency_file_name as file_name, d.dependency_type as dependency_type
FROM dependencies d FROM dependencies d
@@ -692,8 +692,8 @@ impl Version {
", ",
&version_ids &version_ids
).fetch(&mut *exec) ).fetch(&mut *exec)
.try_fold(DashMap::new(), |acc : DashMap<_,Vec<QueryDependency>>, m| { .try_fold(DashMap::new(), |acc : DashMap<_,Vec<DependencyQueryResult>>, m| {
let dependency = QueryDependency { let dependency = DependencyQueryResult {
project_id: m.dependency_project_id.map(DBProjectId), project_id: m.dependency_project_id.map(DBProjectId),
version_id: m.dependency_version_id.map(DBVersionId), version_id: m.dependency_version_id.map(DBVersionId),
file_name: m.file_name, file_name: m.file_name,
@@ -735,8 +735,8 @@ impl Version {
.filter(|x| loader_loader_field_ids.contains(&x.id)) .filter(|x| loader_loader_field_ids.contains(&x.id))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let query_version = QueryVersion { let query_version = VersionQueryResult {
inner: Version { inner: DBVersion {
id: DBVersionId(v.id), id: DBVersionId(v.id),
project_id: DBProjectId(v.mod_id), project_id: DBProjectId(v.mod_id),
author_id: DBUserId(v.author_id), author_id: DBUserId(v.author_id),
@@ -765,7 +765,7 @@ impl Version {
} }
} }
QueryFile { FileQueryResult {
id: x.id, id: x.id,
url: x.url.clone(), url: x.url.clone(),
filename: x.filename.clone(), filename: x.filename.clone(),
@@ -815,7 +815,7 @@ impl Version {
version_id: Option<DBVersionId>, version_id: Option<DBVersionId>,
executor: E, executor: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Option<SingleFile>, DatabaseError> ) -> Result<Option<DBFile>, DatabaseError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy, E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy,
{ {
@@ -832,7 +832,7 @@ impl Version {
hashes: &[String], hashes: &[String],
executor: E, executor: E,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Vec<SingleFile>, DatabaseError> ) -> Result<Vec<DBFile>, DatabaseError>
where where
E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy, E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy,
{ {
@@ -872,7 +872,7 @@ impl Version {
if let Some(hash) = hashes.get(&algorithm) { if let Some(hash) = hashes.get(&algorithm) {
let key = format!("{algorithm}_{hash}"); let key = format!("{algorithm}_{hash}");
let file = SingleFile { let file = DBFile {
id: DBFileId(f.id), id: DBFileId(f.id),
version_id: DBVersionId(f.version_id), version_id: DBVersionId(f.version_id),
project_id: DBProjectId(f.mod_id), project_id: DBProjectId(f.mod_id),
@@ -899,7 +899,7 @@ impl Version {
} }
pub async fn clear_cache( pub async fn clear_cache(
version: &QueryVersion, version: &VersionQueryResult,
redis: &RedisPool, redis: &RedisPool,
) -> Result<(), DatabaseError> { ) -> Result<(), DatabaseError> {
let mut redis = redis.connect().await?; let mut redis = redis.connect().await?;
@@ -927,19 +927,19 @@ impl Version {
} }
#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)] #[derive(Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct QueryVersion { pub struct VersionQueryResult {
pub inner: Version, pub inner: DBVersion,
pub files: Vec<QueryFile>, pub files: Vec<FileQueryResult>,
pub version_fields: Vec<VersionField>, pub version_fields: Vec<VersionField>,
pub loaders: Vec<String>, pub loaders: Vec<String>,
pub project_types: Vec<String>, pub project_types: Vec<String>,
pub games: Vec<String>, pub games: Vec<String>,
pub dependencies: Vec<QueryDependency>, pub dependencies: Vec<DependencyQueryResult>,
} }
#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)] #[derive(Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct QueryDependency { pub struct DependencyQueryResult {
pub project_id: Option<DBProjectId>, pub project_id: Option<DBProjectId>,
pub version_id: Option<DBVersionId>, pub version_id: Option<DBVersionId>,
pub file_name: Option<String>, pub file_name: Option<String>,
@@ -947,7 +947,7 @@ pub struct QueryDependency {
} }
#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)] #[derive(Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct QueryFile { pub struct FileQueryResult {
pub id: DBFileId, pub id: DBFileId,
pub url: String, pub url: String,
pub filename: String, pub filename: String,
@@ -958,7 +958,7 @@ pub struct QueryFile {
} }
#[derive(Clone, Deserialize, Serialize)] #[derive(Clone, Deserialize, Serialize)]
pub struct SingleFile { pub struct DBFile {
pub id: DBFileId, pub id: DBFileId,
pub version_id: DBVersionId, pub version_id: DBVersionId,
pub project_id: DBProjectId, pub project_id: DBProjectId,
@@ -970,19 +970,19 @@ pub struct SingleFile {
pub file_type: Option<FileType>, pub file_type: Option<FileType>,
} }
impl std::cmp::Ord for QueryVersion { impl std::cmp::Ord for VersionQueryResult {
fn cmp(&self, other: &Self) -> std::cmp::Ordering { fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.inner.cmp(&other.inner) self.inner.cmp(&other.inner)
} }
} }
impl std::cmp::PartialOrd for QueryVersion { impl std::cmp::PartialOrd for VersionQueryResult {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other)) Some(self.cmp(other))
} }
} }
impl std::cmp::Ord for Version { impl std::cmp::Ord for DBVersion {
fn cmp(&self, other: &Self) -> Ordering { fn cmp(&self, other: &Self) -> Ordering {
let ordering_order = match (self.ordering, other.ordering) { let ordering_order = match (self.ordering, other.ordering) {
(None, None) => Ordering::Equal, (None, None) => Ordering::Equal,
@@ -998,7 +998,7 @@ impl std::cmp::Ord for Version {
} }
} }
impl std::cmp::PartialOrd for Version { impl std::cmp::PartialOrd for DBVersion {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other)) Some(self.cmp(other))
} }
@@ -1035,8 +1035,8 @@ mod tests {
id: i64, id: i64,
ordering: Option<i32>, ordering: Option<i32>,
date_published: DateTime<Utc>, date_published: DateTime<Utc>,
) -> Version { ) -> DBVersion {
Version { DBVersion {
id: DBVersionId(id), id: DBVersionId(id),
ordering, ordering,
date_published, date_published,

View File

@@ -103,7 +103,7 @@ impl LegacyProject {
// It's safe to use a db version_item for this as the only info is side types, game versions, and loader fields (for loaders), which used to be public on project anyway. // It's safe to use a db version_item for this as the only info is side types, game versions, and loader fields (for loaders), which used to be public on project anyway.
pub fn from( pub fn from(
data: Project, data: Project,
versions_item: Option<version_item::QueryVersion>, versions_item: Option<version_item::VersionQueryResult>,
) -> Self { ) -> Self {
let mut client_side = LegacySideType::Unknown; let mut client_side = LegacySideType::Unknown;
let mut server_side = LegacySideType::Unknown; let mut server_side = LegacySideType::Unknown;
@@ -237,7 +237,8 @@ impl LegacyProject {
.filter_map(|p| p.versions.first().map(|i| (*i).into())) .filter_map(|p| p.versions.first().map(|i| (*i).into()))
.collect(); .collect();
let example_versions = let example_versions =
version_item::Version::get_many(&version_ids, exec, redis).await?; version_item::DBVersion::get_many(&version_ids, exec, redis)
.await?;
let mut legacy_projects = Vec::new(); let mut legacy_projects = Vec::new();
for project in data { for project in data {
let version_item = example_versions let version_item = example_versions

View File

@@ -90,11 +90,11 @@ pub struct UserSubscription {
pub metadata: Option<SubscriptionMetadata>, pub metadata: Option<SubscriptionMetadata>,
} }
impl From<crate::database::models::user_subscription_item::UserSubscriptionItem> impl From<crate::database::models::user_subscription_item::DBUserSubscription>
for UserSubscription for UserSubscription
{ {
fn from( fn from(
x: crate::database::models::user_subscription_item::UserSubscriptionItem, x: crate::database::models::user_subscription_item::DBUserSubscription,
) -> Self { ) -> Self {
Self { Self {
id: x.id.into(), id: x.id.into(),

View File

@@ -35,8 +35,8 @@ pub struct Collection {
pub projects: Vec<ProjectId>, pub projects: Vec<ProjectId>,
} }
impl From<database::models::Collection> for Collection { impl From<database::models::DBCollection> for Collection {
fn from(c: database::models::Collection) -> Self { fn from(c: database::models::DBCollection) -> Self {
Self { Self {
id: c.id.into(), id: c.id.into(),
user: c.user_id.into(), user: c.user_id.into(),

View File

@@ -2,7 +2,7 @@ use super::{
ids::{ProjectId, ThreadMessageId, VersionId}, ids::{ProjectId, ThreadMessageId, VersionId},
pats::Scopes, pats::Scopes,
}; };
use crate::database::models::image_item::Image as DBImage; use crate::database::models::image_item::DBImage;
use crate::models::ids::{ImageId, ReportId}; use crate::models::ids::{ImageId, ReportId};
use ariadne::ids::UserId; use ariadne::ids::UserId;
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};

View File

@@ -1,6 +1,6 @@
use super::ids::OrganizationId; use super::ids::OrganizationId;
use crate::database::models::notification_item::Notification as DBNotification; use crate::database::models::notification_item::DBNotification;
use crate::database::models::notification_item::NotificationAction as DBNotificationAction; use crate::database::models::notification_item::DBNotificationAction;
use crate::models::ids::{ use crate::models::ids::{
NotificationId, ProjectId, ReportId, TeamId, ThreadId, ThreadMessageId, NotificationId, ProjectId, ReportId, TeamId, ThreadId, ThreadMessageId,
VersionId, VersionId,

View File

@@ -1,7 +1,7 @@
use super::pats::Scopes; use super::pats::Scopes;
use crate::database::models::oauth_client_authorization_item::OAuthClientAuthorization as DBOAuthClientAuthorization; use crate::database::models::oauth_client_authorization_item::DBOAuthClientAuthorization;
use crate::database::models::oauth_client_item::OAuthClient as DBOAuthClient; use crate::database::models::oauth_client_item::DBOAuthClient;
use crate::database::models::oauth_client_item::OAuthRedirectUri as DBOAuthRedirectUri; use crate::database::models::oauth_client_item::DBOAuthRedirectUri;
use crate::models::ids::{ use crate::models::ids::{
OAuthClientAuthorizationId, OAuthClientId, OAuthRedirectUriId, OAuthClientAuthorizationId, OAuthClientId, OAuthRedirectUriId,
}; };

View File

@@ -27,7 +27,7 @@ pub struct Organization {
impl Organization { impl Organization {
pub fn from( pub fn from(
data: crate::database::models::organization_item::Organization, data: crate::database::models::organization_item::DBOrganization,
team_members: Vec<TeamMember>, team_members: Vec<TeamMember>,
) -> Self { ) -> Self {
Self { Self {

View File

@@ -155,7 +155,7 @@ pub struct PersonalAccessToken {
impl PersonalAccessToken { impl PersonalAccessToken {
pub fn from( pub fn from(
data: crate::database::models::pat_item::PersonalAccessToken, data: crate::database::models::pat_item::DBPersonalAccessToken,
include_token: bool, include_token: bool,
) -> Self { ) -> Self {
Self { Self {

View File

@@ -22,7 +22,7 @@ pub struct Payout {
} }
impl Payout { impl Payout {
pub fn from(data: crate::database::models::payout_item::Payout) -> Self { pub fn from(data: crate::database::models::payout_item::DBPayout) -> Self {
Self { Self {
id: data.id.into(), id: data.id.into(),
user_id: data.user_id.into(), user_id: data.user_id.into(),

View File

@@ -1,8 +1,8 @@
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use crate::database::models::loader_fields::VersionField; use crate::database::models::loader_fields::VersionField;
use crate::database::models::project_item::{LinkUrl, QueryProject}; use crate::database::models::project_item::{LinkUrl, ProjectQueryResult};
use crate::database::models::version_item::QueryVersion; use crate::database::models::version_item::VersionQueryResult;
use crate::models::ids::{ use crate::models::ids::{
OrganizationId, ProjectId, TeamId, ThreadId, VersionId, OrganizationId, ProjectId, TeamId, ThreadId, VersionId,
}; };
@@ -139,8 +139,8 @@ pub fn from_duplicate_version_fields(
fields fields
} }
impl From<QueryProject> for Project { impl From<ProjectQueryResult> for Project {
fn from(data: QueryProject) -> Self { fn from(data: ProjectQueryResult) -> Self {
let fields = let fields =
from_duplicate_version_fields(data.aggregate_version_fields); from_duplicate_version_fields(data.aggregate_version_fields);
let m = data.inner; let m = data.inner;
@@ -657,8 +657,8 @@ where
Ok(map) Ok(map)
} }
impl From<QueryVersion> for Version { impl From<VersionQueryResult> for Version {
fn from(data: QueryVersion) -> Version { fn from(data: VersionQueryResult) -> Version {
let v = data.inner; let v = data.inner;
Version { Version {
id: v.id.into(), id: v.id.into(),

View File

@@ -1,4 +1,4 @@
use crate::database::models::report_item::QueryReport as DBReport; use crate::database::models::report_item::ReportQueryResult as DBReport;
use crate::models::ids::{ProjectId, ReportId, ThreadId, VersionId}; use crate::models::ids::{ProjectId, ReportId, ThreadId, VersionId};
use ariadne::ids::UserId; use ariadne::ids::UserId;
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};

View File

@@ -27,7 +27,7 @@ pub struct Session {
impl Session { impl Session {
pub fn from( pub fn from(
data: crate::database::models::session_item::Session, data: crate::database::models::session_item::DBSession,
include_session: bool, include_session: bool,
current_session: Option<&str>, current_session: Option<&str>,
) -> Self { ) -> Self {

View File

@@ -42,8 +42,10 @@ impl Default for ProjectPermissions {
impl ProjectPermissions { impl ProjectPermissions {
pub fn get_permissions_by_role( pub fn get_permissions_by_role(
role: &crate::models::users::Role, role: &crate::models::users::Role,
project_team_member: &Option<crate::database::models::TeamMember>, // team member of the user in the project project_team_member: &Option<crate::database::models::DBTeamMember>, // team member of the user in the project
organization_team_member: &Option<crate::database::models::TeamMember>, // team member of the user in the organization organization_team_member: &Option<
crate::database::models::DBTeamMember,
>, // team member of the user in the organization
) -> Option<Self> { ) -> Option<Self> {
if role.is_admin() { if role.is_admin() {
return Some(ProjectPermissions::all()); return Some(ProjectPermissions::all());
@@ -99,7 +101,7 @@ impl Default for OrganizationPermissions {
impl OrganizationPermissions { impl OrganizationPermissions {
pub fn get_permissions_by_role( pub fn get_permissions_by_role(
role: &crate::models::users::Role, role: &crate::models::users::Role,
team_member: &Option<crate::database::models::TeamMember>, team_member: &Option<crate::database::models::DBTeamMember>,
) -> Option<Self> { ) -> Option<Self> {
if role.is_admin() { if role.is_admin() {
return Some(OrganizationPermissions::all()); return Some(OrganizationPermissions::all());
@@ -154,8 +156,8 @@ pub struct TeamMember {
impl TeamMember { impl TeamMember {
pub fn from( pub fn from(
data: crate::database::models::team_item::TeamMember, data: crate::database::models::team_item::DBTeamMember,
user: crate::database::models::User, user: crate::database::models::DBUser,
override_permissions: bool, override_permissions: bool,
) -> Self { ) -> Self {
let user: User = user.into(); let user: User = user.into();
@@ -166,7 +168,7 @@ impl TeamMember {
// if already available. // if already available.
// (Avoids a db query in some cases) // (Avoids a db query in some cases)
pub fn from_model( pub fn from_model(
data: crate::database::models::team_item::TeamMember, data: crate::database::models::team_item::DBTeamMember,
user: crate::models::users::User, user: crate::models::users::User,
override_permissions: bool, override_permissions: bool,
) -> Self { ) -> Self {

View File

@@ -86,7 +86,7 @@ impl ThreadType {
impl Thread { impl Thread {
pub fn from( pub fn from(
data: crate::database::models::Thread, data: crate::database::models::DBThread,
users: Vec<User>, users: Vec<User>,
user: &User, user: &User,
) -> Self { ) -> Self {
@@ -119,7 +119,7 @@ impl Thread {
impl ThreadMessage { impl ThreadMessage {
pub fn from( pub fn from(
data: crate::database::models::ThreadMessage, data: crate::database::models::DBThreadMessage,
user: &User, user: &User,
) -> Self { ) -> Self {
Self { Self {

View File

@@ -63,7 +63,7 @@ pub struct UserPayoutData {
pub balance: Decimal, pub balance: Decimal,
} }
use crate::database::models::user_item::User as DBUser; use crate::database::models::user_item::DBUser;
impl From<DBUser> for User { impl From<DBUser> for User {
fn from(data: DBUser) -> Self { fn from(data: DBUser) -> Self {
Self { Self {
@@ -196,9 +196,7 @@ pub struct UserFriend {
} }
impl UserFriend { impl UserFriend {
pub fn from( pub fn from(data: crate::database::models::friend_item::DBFriend) -> Self {
data: crate::database::models::friend_item::FriendItem,
) -> Self {
Self { Self {
id: data.friend_id.into(), id: data.friend_id.into(),
friend_id: data.user_id.into(), friend_id: data.user_id.into(),

View File

@@ -233,7 +233,7 @@ impl AutomatedModerationQueue {
for project in projects { for project in projects {
async { async {
let project = let project =
database::Project::get_id((project).into(), &pool, &redis).await?; database::DBProject::get_id((project).into(), &pool, &redis).await?;
if let Some(project) = project { if let Some(project) = project {
let res = async { let res = async {
@@ -261,7 +261,7 @@ impl AutomatedModerationQueue {
} }
let versions = let versions =
database::Version::get_many(&project.versions, &pool, &redis) database::DBVersion::get_many(&project.versions, &pool, &redis)
.await? .await?
.into_iter() .into_iter()
// we only support modpacks at this time // we only support modpacks at this time
@@ -343,7 +343,7 @@ impl AutomatedModerationQueue {
} }
} }
let files = database::models::Version::get_files_from_hash( let files = database::models::DBVersion::get_files_from_hash(
"sha1".to_string(), "sha1".to_string(),
&hashes.iter().map(|x| x.0.clone()).collect::<Vec<_>>(), &hashes.iter().map(|x| x.0.clone()).collect::<Vec<_>>(),
&pool, &pool,
@@ -354,7 +354,7 @@ impl AutomatedModerationQueue {
let version_ids = let version_ids =
files.iter().map(|x| x.version_id).collect::<Vec<_>>(); files.iter().map(|x| x.version_id).collect::<Vec<_>>();
let versions_data = filter_visible_versions( let versions_data = filter_visible_versions(
database::models::Version::get_many( database::models::DBVersion::get_many(
&version_ids, &version_ids,
&pool, &pool,
&redis, &redis,
@@ -621,7 +621,7 @@ impl AutomatedModerationQueue {
} }
if !mod_messages.is_empty() { if !mod_messages.is_empty() {
let first_time = database::models::Thread::get(project.thread_id, &pool).await? let first_time = database::models::DBThread::get(project.thread_id, &pool).await?
.map(|x| x.messages.iter().all(|x| x.author_id == Some(database::models::DBUserId(AUTOMOD_ID)) || x.hide_identity)) .map(|x| x.messages.iter().all(|x| x.author_id == Some(database::models::DBUserId(AUTOMOD_ID)) || x.hide_identity))
.unwrap_or(true); .unwrap_or(true);
@@ -640,7 +640,7 @@ impl AutomatedModerationQueue {
.insert(&mut transaction) .insert(&mut transaction)
.await?; .await?;
let members = database::models::TeamMember::get_from_team_full( let members = database::models::DBTeamMember::get_from_team_full(
project.inner.team_id, project.inner.team_id,
&pool, &pool,
&redis, &redis,
@@ -700,7 +700,7 @@ impl AutomatedModerationQueue {
.execute(&pool) .execute(&pool)
.await?; .await?;
database::models::Project::clear_cache( database::models::DBProject::clear_cache(
project.inner.id, project.inner.id,
project.inner.slug.clone(), project.inner.slug.clone(),
None, None,

View File

@@ -1,5 +1,5 @@
use crate::database::models::pat_item::PersonalAccessToken; use crate::database::models::pat_item::DBPersonalAccessToken;
use crate::database::models::session_item::Session; use crate::database::models::session_item::DBSession;
use crate::database::models::{ use crate::database::models::{
DBOAuthAccessTokenId, DBPatId, DBSessionId, DBUserId, DatabaseError, DBOAuthAccessTokenId, DBPatId, DBSessionId, DBUserId, DatabaseError,
}; };
@@ -123,10 +123,10 @@ impl AuthQueue {
Some(session), Some(session),
Some(user_id), Some(user_id),
)); ));
Session::remove(id, &mut transaction).await?; DBSession::remove(id, &mut transaction).await?;
} }
Session::clear_cache(clear_cache_sessions, redis).await?; DBSession::clear_cache(clear_cache_sessions, redis).await?;
let ids = pat_queue.iter().map(|id| id.0).collect_vec(); let ids = pat_queue.iter().map(|id| id.0).collect_vec();
let clear_cache_pats = pat_queue let clear_cache_pats = pat_queue
@@ -153,7 +153,7 @@ impl AuthQueue {
.await?; .await?;
transaction.commit().await?; transaction.commit().await?;
PersonalAccessToken::clear_cache(clear_cache_pats, redis).await?; DBPersonalAccessToken::clear_cache(clear_cache_pats, redis).await?;
} }
Ok(()) Ok(())

View File

@@ -130,7 +130,7 @@ pub async fn page_view_ingest(
]; ];
if PROJECT_TYPES.contains(&segments_vec[0]) { if PROJECT_TYPES.contains(&segments_vec[0]) {
let project = crate::database::models::Project::get( let project = crate::database::models::DBProject::get(
segments_vec[1], segments_vec[1],
&**pool, &**pool,
&redis, &redis,
@@ -189,7 +189,7 @@ pub async fn playtime_ingest(
)); ));
} }
let versions = crate::database::models::Version::get_many( let versions = crate::database::models::DBVersion::get_many(
&playtimes.iter().map(|x| (*x.0).into()).collect::<Vec<_>>(), &playtimes.iter().map(|x| (*x.0).into()).collect::<Vec<_>>(),
&**pool, &**pool,
&redis, &redis,

View File

@@ -204,7 +204,7 @@ pub async fn delphi_result_ingest(
let webhook_url = dotenvy::var("DELPHI_SLACK_WEBHOOK")?; let webhook_url = dotenvy::var("DELPHI_SLACK_WEBHOOK")?;
let project = crate::database::models::Project::get_id( let project = crate::database::models::DBProject::get_id(
body.project_id.into(), body.project_id.into(),
&**pool, &**pool,
&redis, &redis,

View File

@@ -1,5 +1,5 @@
use crate::auth::{get_user_from_headers, send_email}; use crate::auth::{get_user_from_headers, send_email};
use crate::database::models::charge_item::ChargeItem; use crate::database::models::charge_item::DBCharge;
use crate::database::models::{ use crate::database::models::{
generate_charge_id, generate_user_subscription_id, product_item, generate_charge_id, generate_user_subscription_id, product_item,
user_subscription_item, user_subscription_item,
@@ -59,7 +59,8 @@ pub async fn products(
pool: web::Data<PgPool>, pool: web::Data<PgPool>,
redis: web::Data<RedisPool>, redis: web::Data<RedisPool>,
) -> Result<HttpResponse, ApiError> { ) -> Result<HttpResponse, ApiError> {
let products = product_item::QueryProduct::list(&**pool, &redis).await?; let products =
product_item::QueryProductWithPrices::list(&**pool, &redis).await?;
let products = products let products = products
.into_iter() .into_iter()
@@ -107,7 +108,7 @@ pub async fn subscriptions(
.1; .1;
let subscriptions = let subscriptions =
user_subscription_item::UserSubscriptionItem::get_all_user( user_subscription_item::DBUserSubscription::get_all_user(
if let Some(user_id) = query.user_id { if let Some(user_id) = query.user_id {
if user.role.is_admin() { if user.role.is_admin() {
user_id.into() user_id.into()
@@ -173,8 +174,8 @@ pub async fn refund_charge(
)); ));
} }
if let Some(charge) = ChargeItem::get(id.into(), &**pool).await? { if let Some(charge) = DBCharge::get(id.into(), &**pool).await? {
let refunds = ChargeItem::get_children(id.into(), &**pool).await?; let refunds = DBCharge::get_children(id.into(), &**pool).await?;
let refunds = -refunds let refunds = -refunds
.into_iter() .into_iter()
.filter_map(|x| match x.status { .filter_map(|x| match x.status {
@@ -261,7 +262,7 @@ pub async fn refund_charge(
let mut transaction = pool.begin().await?; let mut transaction = pool.begin().await?;
let charge_id = generate_charge_id(&mut transaction).await?; let charge_id = generate_charge_id(&mut transaction).await?;
ChargeItem { DBCharge {
id: charge_id, id: charge_id,
user_id: charge.user_id, user_id: charge.user_id,
price_id: charge.price_id, price_id: charge.price_id,
@@ -284,7 +285,7 @@ pub async fn refund_charge(
if body.0.unprovision.unwrap_or(false) { if body.0.unprovision.unwrap_or(false) {
if let Some(subscription_id) = charge.subscription_id { if let Some(subscription_id) = charge.subscription_id {
let open_charge = let open_charge =
ChargeItem::get_open_subscription(subscription_id, &**pool) DBCharge::get_open_subscription(subscription_id, &**pool)
.await?; .await?;
if let Some(mut open_charge) = open_charge { if let Some(mut open_charge) = open_charge {
open_charge.status = ChargeStatus::Cancelled; open_charge.status = ChargeStatus::Cancelled;
@@ -332,7 +333,7 @@ pub async fn edit_subscription(
let (id,) = info.into_inner(); let (id,) = info.into_inner();
if let Some(subscription) = if let Some(subscription) =
user_subscription_item::UserSubscriptionItem::get(id.into(), &**pool) user_subscription_item::DBUserSubscription::get(id.into(), &**pool)
.await? .await?
{ {
if subscription.user_id != user.id.into() && !user.role.is_admin() { if subscription.user_id != user.id.into() && !user.role.is_admin() {
@@ -342,7 +343,7 @@ pub async fn edit_subscription(
let mut transaction = pool.begin().await?; let mut transaction = pool.begin().await?;
let mut open_charge = let mut open_charge =
crate::database::models::charge_item::ChargeItem::get_open_subscription( crate::database::models::charge_item::DBCharge::get_open_subscription(
subscription.id, subscription.id,
&mut *transaction, &mut *transaction,
) )
@@ -353,7 +354,7 @@ pub async fn edit_subscription(
) )
})?; })?;
let current_price = product_item::ProductPriceItem::get( let current_price = product_item::DBProductPrice::get(
subscription.price_id, subscription.price_id,
&mut *transaction, &mut *transaction,
) )
@@ -397,7 +398,7 @@ pub async fn edit_subscription(
let intent = if let Some(product_id) = &edit_subscription.product { let intent = if let Some(product_id) = &edit_subscription.product {
let product_price = let product_price =
product_item::ProductPriceItem::get_all_product_prices( product_item::DBProductPrice::get_all_product_prices(
(*product_id).into(), (*product_id).into(),
&mut *transaction, &mut *transaction,
) )
@@ -622,7 +623,7 @@ pub async fn charges(
.1; .1;
let charges = let charges =
crate::database::models::charge_item::ChargeItem::get_from_user( crate::database::models::charge_item::DBCharge::get_from_user(
if let Some(user_id) = query.user_id { if let Some(user_id) = query.user_id {
if user.role.is_admin() { if user.role.is_admin() {
user_id.into() user_id.into()
@@ -829,7 +830,7 @@ pub async fn remove_payment_method(
.await?; .await?;
let user_subscriptions = let user_subscriptions =
user_subscription_item::UserSubscriptionItem::get_all_user( user_subscription_item::DBUserSubscription::get_all_user(
user.id.into(), user.id.into(),
&**pool, &**pool,
) )
@@ -935,12 +936,11 @@ pub async fn active_servers(
)); ));
} }
let servers = let servers = user_subscription_item::DBUserSubscription::get_all_servers(
user_subscription_item::UserSubscriptionItem::get_all_servers( query.subscription_status,
query.subscription_status, &**pool,
&**pool, )
) .await?;
.await?;
#[derive(Serialize)] #[derive(Serialize)]
struct ActiveServer { struct ActiveServer {
@@ -1153,7 +1153,7 @@ pub async fn initiate_payment(
match payment_request.charge { match payment_request.charge {
ChargeRequestType::Existing { id } => { ChargeRequestType::Existing { id } => {
let charge = let charge =
crate::database::models::charge_item::ChargeItem::get( crate::database::models::charge_item::DBCharge::get(
id.into(), id.into(),
&**pool, &**pool,
) )
@@ -1178,7 +1178,7 @@ pub async fn initiate_payment(
interval, interval,
} => { } => {
let product = let product =
product_item::ProductItem::get(product_id.into(), &**pool) product_item::DBProduct::get(product_id.into(), &**pool)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
@@ -1188,7 +1188,7 @@ pub async fn initiate_payment(
})?; })?;
let mut product_prices = let mut product_prices =
product_item::ProductPriceItem::get_all_product_prices( product_item::DBProductPrice::get_all_product_prices(
product.id, &**pool, product.id, &**pool,
) )
.await?; .await?;
@@ -1229,14 +1229,14 @@ pub async fn initiate_payment(
if let Price::Recurring { .. } = price_item.prices { if let Price::Recurring { .. } = price_item.prices {
if product.unitary { if product.unitary {
let user_subscriptions = let user_subscriptions =
user_subscription_item::UserSubscriptionItem::get_all_user( user_subscription_item::DBUserSubscription::get_all_user(
user.id.into(), user.id.into(),
&**pool, &**pool,
) )
.await?; .await?;
let user_products = let user_products =
product_item::ProductPriceItem::get_many( product_item::DBProductPrice::get_many(
&user_subscriptions &user_subscriptions
.iter() .iter()
.filter(|x| { .filter(|x| {
@@ -1413,12 +1413,12 @@ pub async fn stripe_webhook(
&dotenvy::var("STRIPE_WEBHOOK_SECRET")?, &dotenvy::var("STRIPE_WEBHOOK_SECRET")?,
) { ) {
struct PaymentIntentMetadata { struct PaymentIntentMetadata {
pub user_item: crate::database::models::user_item::User, pub user_item: crate::database::models::user_item::DBUser,
pub product_price_item: product_item::ProductPriceItem, pub product_price_item: product_item::DBProductPrice,
pub product_item: product_item::ProductItem, pub product_item: product_item::DBProduct,
pub charge_item: crate::database::models::charge_item::ChargeItem, pub charge_item: crate::database::models::charge_item::DBCharge,
pub user_subscription_item: pub user_subscription_item:
Option<user_subscription_item::UserSubscriptionItem>, Option<user_subscription_item::DBUserSubscription>,
pub payment_metadata: Option<PaymentRequestMetadata>, pub payment_metadata: Option<PaymentRequestMetadata>,
#[allow(dead_code)] #[allow(dead_code)]
pub charge_type: ChargeType, pub charge_type: ChargeType,
@@ -1447,7 +1447,7 @@ pub async fn stripe_webhook(
}; };
let user = if let Some(user) = let user = if let Some(user) =
crate::database::models::user_item::User::get_id( crate::database::models::user_item::DBUser::get_id(
user_id, pool, redis, user_id, pool, redis,
) )
.await? .await?
@@ -1483,17 +1483,14 @@ pub async fn stripe_webhook(
let (charge, price, product, subscription) = if let Some( let (charge, price, product, subscription) = if let Some(
mut charge, mut charge,
) = ) =
crate::database::models::charge_item::ChargeItem::get( crate::database::models::charge_item::DBCharge::get(
charge_id, pool, charge_id, pool,
) )
.await? .await?
{ {
let price = if let Some(price) = let price = if let Some(price) =
product_item::ProductPriceItem::get( product_item::DBProductPrice::get(charge.price_id, pool)
charge.price_id, .await?
pool,
)
.await?
{ {
price price
} else { } else {
@@ -1501,7 +1498,7 @@ pub async fn stripe_webhook(
}; };
let product = if let Some(product) = let product = if let Some(product) =
product_item::ProductItem::get(price.product_id, pool) product_item::DBProduct::get(price.product_id, pool)
.await? .await?
{ {
product product
@@ -1517,7 +1514,7 @@ pub async fn stripe_webhook(
if let Some(subscription_id) = charge.subscription_id { if let Some(subscription_id) = charge.subscription_id {
let mut subscription = if let Some(subscription) = let mut subscription = if let Some(subscription) =
user_subscription_item::UserSubscriptionItem::get( user_subscription_item::DBUserSubscription::get(
subscription_id, subscription_id,
pool, pool,
) )
@@ -1567,7 +1564,7 @@ pub async fn stripe_webhook(
}; };
let price = if let Some(price) = let price = if let Some(price) =
product_item::ProductPriceItem::get(price_id, pool) product_item::DBProductPrice::get(price_id, pool)
.await? .await?
{ {
price price
@@ -1576,7 +1573,7 @@ pub async fn stripe_webhook(
}; };
let product = if let Some(product) = let product = if let Some(product) =
product_item::ProductItem::get(price.product_id, pool) product_item::DBProduct::get(price.product_id, pool)
.await? .await?
{ {
product product
@@ -1608,14 +1605,14 @@ pub async fn stripe_webhook(
break 'metadata; break 'metadata;
}; };
let subscription = if let Some(mut subscription) = user_subscription_item::UserSubscriptionItem::get(subscription_id, pool).await? { let subscription = if let Some(mut subscription) = user_subscription_item::DBUserSubscription::get(subscription_id, pool).await? {
subscription.status = SubscriptionStatus::Unprovisioned; subscription.status = SubscriptionStatus::Unprovisioned;
subscription.price_id = price_id; subscription.price_id = price_id;
subscription.interval = interval; subscription.interval = interval;
subscription subscription
} else { } else {
user_subscription_item::UserSubscriptionItem { user_subscription_item::DBUserSubscription {
id: subscription_id, id: subscription_id,
user_id, user_id,
price_id, price_id,
@@ -1637,7 +1634,7 @@ pub async fn stripe_webhook(
} }
}; };
let charge = ChargeItem { let charge = DBCharge {
id: charge_id, id: charge_id,
user_id, user_id,
price_id, price_id,
@@ -1870,7 +1867,7 @@ pub async fn stripe_webhook(
if let Some(mut subscription) = if let Some(mut subscription) =
metadata.user_subscription_item metadata.user_subscription_item
{ {
let open_charge = ChargeItem::get_open_subscription( let open_charge = DBCharge::get_open_subscription(
subscription.id, subscription.id,
&mut *transaction, &mut *transaction,
) )
@@ -1898,7 +1895,7 @@ pub async fn stripe_webhook(
{ {
let charge_id = let charge_id =
generate_charge_id(&mut transaction).await?; generate_charge_id(&mut transaction).await?;
ChargeItem { DBCharge {
id: charge_id, id: charge_id,
user_id: metadata.user_item.id, user_id: metadata.user_item.id,
price_id: metadata.product_price_item.id, price_id: metadata.product_price_item.id,
@@ -1936,7 +1933,7 @@ pub async fn stripe_webhook(
} }
transaction.commit().await?; transaction.commit().await?;
crate::database::models::user_item::User::clear_caches( crate::database::models::user_item::DBUser::clear_caches(
&[(metadata.user_item.id, None)], &[(metadata.user_item.id, None)],
&redis, &redis,
) )
@@ -2098,7 +2095,7 @@ async fn get_or_create_customer(
.execute(pool) .execute(pool)
.await?; .await?;
crate::database::models::user_item::User::clear_caches( crate::database::models::user_item::DBUser::clear_caches(
&[(user_id.into(), None)], &[(user_id.into(), None)],
redis, redis,
) )
@@ -2116,10 +2113,10 @@ pub async fn index_subscriptions(pool: PgPool, redis: RedisPool) {
let mut clear_cache_users = Vec::new(); let mut clear_cache_users = Vec::new();
// If an active subscription has a canceled charge OR a failed charge more than two days ago, it should be cancelled // If an active subscription has a canceled charge OR a failed charge more than two days ago, it should be cancelled
let all_charges = ChargeItem::get_unprovision(&pool).await?; let all_charges = DBCharge::get_unprovision(&pool).await?;
let mut all_subscriptions = let mut all_subscriptions =
user_subscription_item::UserSubscriptionItem::get_many( user_subscription_item::DBUserSubscription::get_many(
&all_charges &all_charges
.iter() .iter()
.filter_map(|x| x.subscription_id) .filter_map(|x| x.subscription_id)
@@ -2129,7 +2126,7 @@ pub async fn index_subscriptions(pool: PgPool, redis: RedisPool) {
&pool, &pool,
) )
.await?; .await?;
let subscription_prices = product_item::ProductPriceItem::get_many( let subscription_prices = product_item::DBProductPrice::get_many(
&all_subscriptions &all_subscriptions
.iter() .iter()
.map(|x| x.price_id) .map(|x| x.price_id)
@@ -2139,7 +2136,7 @@ pub async fn index_subscriptions(pool: PgPool, redis: RedisPool) {
&pool, &pool,
) )
.await?; .await?;
let subscription_products = product_item::ProductItem::get_many( let subscription_products = product_item::DBProduct::get_many(
&subscription_prices &subscription_prices
.iter() .iter()
.map(|x| x.product_id) .map(|x| x.product_id)
@@ -2149,7 +2146,7 @@ pub async fn index_subscriptions(pool: PgPool, redis: RedisPool) {
&pool, &pool,
) )
.await?; .await?;
let users = crate::database::models::User::get_many_ids( let users = crate::database::models::DBUser::get_many_ids(
&all_subscriptions &all_subscriptions
.iter() .iter()
.map(|x| x.user_id) .map(|x| x.user_id)
@@ -2260,7 +2257,7 @@ pub async fn index_subscriptions(pool: PgPool, redis: RedisPool) {
clear_cache_users.push(user.id); clear_cache_users.push(user.id);
} }
crate::database::models::User::clear_caches( crate::database::models::DBUser::clear_caches(
&clear_cache_users &clear_cache_users
.into_iter() .into_iter()
.map(|x| (x, None)) .map(|x| (x, None))
@@ -2289,12 +2286,12 @@ pub async fn index_billing(
let res = async { let res = async {
// If a charge is open and due or has been attempted more than two days ago, it should be processed // If a charge is open and due or has been attempted more than two days ago, it should be processed
let charges_to_do = let charges_to_do =
crate::database::models::charge_item::ChargeItem::get_chargeable( crate::database::models::charge_item::DBCharge::get_chargeable(
&pool, &pool,
) )
.await?; .await?;
let prices = product_item::ProductPriceItem::get_many( let prices = product_item::DBProductPrice::get_many(
&charges_to_do &charges_to_do
.iter() .iter()
.map(|x| x.price_id) .map(|x| x.price_id)
@@ -2305,7 +2302,7 @@ pub async fn index_billing(
) )
.await?; .await?;
let users = crate::database::models::User::get_many_ids( let users = crate::database::models::DBUser::get_many_ids(
&charges_to_do &charges_to_do
.iter() .iter()
.map(|x| x.user_id) .map(|x| x.user_id)

View File

@@ -1,7 +1,7 @@
use crate::auth::email::send_email; use crate::auth::email::send_email;
use crate::auth::validate::get_user_record_from_bearer_token; use crate::auth::validate::get_user_record_from_bearer_token;
use crate::auth::{AuthProvider, AuthenticationError, get_user_from_headers}; use crate::auth::{AuthProvider, AuthenticationError, get_user_from_headers};
use crate::database::models::flow_item::Flow; use crate::database::models::flow_item::DBFlow;
use crate::database::redis::RedisPool; use crate::database::redis::RedisPool;
use crate::file_hosting::FileHost; use crate::file_hosting::FileHost;
use crate::models::pats::Scopes; use crate::models::pats::Scopes;
@@ -76,7 +76,7 @@ impl TempUser {
redis: &RedisPool, redis: &RedisPool,
) -> Result<crate::database::models::DBUserId, AuthenticationError> { ) -> Result<crate::database::models::DBUserId, AuthenticationError> {
if let Some(email) = &self.email { if let Some(email) = &self.email {
if crate::database::models::User::get_email(email, client) if crate::database::models::DBUser::get_email(email, client)
.await? .await?
.is_some() .is_some()
{ {
@@ -101,7 +101,7 @@ impl TempUser {
} }
); );
let new_id = crate::database::models::User::get( let new_id = crate::database::models::DBUser::get(
&test_username, &test_username,
client, client,
redis, redis,
@@ -156,7 +156,7 @@ impl TempUser {
}; };
if let Some(username) = username { if let Some(username) = username {
crate::database::models::User { crate::database::models::DBUser {
id: user_id, id: user_id,
github_id: if provider == AuthProvider::GitHub { github_id: if provider == AuthProvider::GitHub {
Some( Some(
@@ -1083,7 +1083,7 @@ pub async fn init(
None None
}; };
let state = Flow::OAuth { let state = DBFlow::OAuth {
user_id, user_id,
url: info.url, url: info.url,
provider: info.provider, provider: info.provider,
@@ -1112,16 +1112,16 @@ pub async fn auth_callback(
let state = state_string.clone(); let state = state_string.clone();
let res: Result<HttpResponse, AuthenticationError> = async move { let res: Result<HttpResponse, AuthenticationError> = async move {
let flow = Flow::get(&state, &redis).await?; let flow = DBFlow::get(&state, &redis).await?;
// Extract cookie header from request // Extract cookie header from request
if let Some(Flow::OAuth { if let Some(DBFlow::OAuth {
user_id, user_id,
provider, provider,
url, url,
}) = flow }) = flow
{ {
Flow::remove(&state, &redis).await?; DBFlow::remove(&state, &redis).await?;
let token = provider.get_token(query).await?; let token = provider.get_token(query).await?;
let oauth_user = provider.get_user(&token).await?; let oauth_user = provider.get_user(&token).await?;
@@ -1138,7 +1138,7 @@ pub async fn auth_callback(
.update_user_id(id, Some(&oauth_user.id), &mut transaction) .update_user_id(id, Some(&oauth_user.id), &mut transaction)
.await?; .await?;
let user = crate::database::models::User::get_id(id, &**client, &redis).await?; let user = crate::database::models::DBUser::get_id(id, &**client, &redis).await?;
if provider == AuthProvider::PayPal { if provider == AuthProvider::PayPal {
sqlx::query!( sqlx::query!(
@@ -1165,19 +1165,19 @@ pub async fn auth_callback(
} }
transaction.commit().await?; transaction.commit().await?;
crate::database::models::User::clear_caches(&[(id, None)], &redis).await?; crate::database::models::DBUser::clear_caches(&[(id, None)], &redis).await?;
Ok(HttpResponse::TemporaryRedirect() Ok(HttpResponse::TemporaryRedirect()
.append_header(("Location", &*url)) .append_header(("Location", &*url))
.json(serde_json::json!({ "url": url }))) .json(serde_json::json!({ "url": url })))
} else { } else {
let user_id = if let Some(user_id) = user_id_opt { let user_id = if let Some(user_id) = user_id_opt {
let user = crate::database::models::User::get_id(user_id, &**client, &redis) let user = crate::database::models::DBUser::get_id(user_id, &**client, &redis)
.await? .await?
.ok_or_else(|| AuthenticationError::InvalidCredentials)?; .ok_or_else(|| AuthenticationError::InvalidCredentials)?;
if user.totp_secret.is_some() { if user.totp_secret.is_some() {
let flow = Flow::Login2FA { user_id: user.id } let flow = DBFlow::Login2FA { user_id: user.id }
.insert(Duration::minutes(30), &redis) .insert(Duration::minutes(30), &redis)
.await?; .await?;
@@ -1279,7 +1279,7 @@ pub async fn delete_auth_provider(
} }
transaction.commit().await?; transaction.commit().await?;
crate::database::models::User::clear_caches( crate::database::models::DBUser::clear_caches(
&[(user.id.into(), None)], &[(user.id.into(), None)],
&redis, &redis,
) )
@@ -1346,7 +1346,7 @@ pub async fn create_account_with_password(
return Err(ApiError::Turnstile); return Err(ApiError::Turnstile);
} }
if crate::database::models::User::get( if crate::database::models::DBUser::get(
&new_account.username, &new_account.username,
&**pool, &**pool,
&redis, &redis,
@@ -1385,7 +1385,7 @@ pub async fn create_account_with_password(
.hash_password(new_account.password.as_bytes(), &salt)? .hash_password(new_account.password.as_bytes(), &salt)?
.to_string(); .to_string();
if crate::database::models::User::get_email(&new_account.email, &**pool) if crate::database::models::DBUser::get_email(&new_account.email, &**pool)
.await? .await?
.is_some() .is_some()
{ {
@@ -1394,7 +1394,7 @@ pub async fn create_account_with_password(
)); ));
} }
crate::database::models::User { crate::database::models::DBUser {
id: user_id, id: user_id,
github_id: None, github_id: None,
discord_id: None, discord_id: None,
@@ -1426,7 +1426,7 @@ pub async fn create_account_with_password(
let session = issue_session(req, user_id, &mut transaction, &redis).await?; let session = issue_session(req, user_id, &mut transaction, &redis).await?;
let res = crate::models::sessions::Session::from(session, true, None); let res = crate::models::sessions::Session::from(session, true, None);
let flow = Flow::ConfirmEmail { let flow = DBFlow::ConfirmEmail {
user_id, user_id,
confirm_email: new_account.email.clone(), confirm_email: new_account.email.clone(),
} }
@@ -1467,17 +1467,19 @@ pub async fn login_password(
} }
let user = if let Some(user) = let user = if let Some(user) =
crate::database::models::User::get(&login.username, &**pool, &redis) crate::database::models::DBUser::get(&login.username, &**pool, &redis)
.await? .await?
{ {
user user
} else { } else {
let user = let user = crate::database::models::DBUser::get_email(
crate::database::models::User::get_email(&login.username, &**pool) &login.username,
.await? &**pool,
.ok_or_else(|| AuthenticationError::InvalidCredentials)?; )
.await?
.ok_or_else(|| AuthenticationError::InvalidCredentials)?;
crate::database::models::User::get_id(user, &**pool, &redis) crate::database::models::DBUser::get_id(user, &**pool, &redis)
.await? .await?
.ok_or_else(|| AuthenticationError::InvalidCredentials)? .ok_or_else(|| AuthenticationError::InvalidCredentials)?
}; };
@@ -1495,7 +1497,7 @@ pub async fn login_password(
.map_err(|_| AuthenticationError::InvalidCredentials)?; .map_err(|_| AuthenticationError::InvalidCredentials)?;
if user.totp_secret.is_some() { if user.totp_secret.is_some() {
let flow = Flow::Login2FA { user_id: user.id } let flow = DBFlow::Login2FA { user_id: user.id }
.insert(Duration::minutes(30), &redis) .insert(Duration::minutes(30), &redis)
.await?; .await?;
@@ -1568,7 +1570,7 @@ async fn validate_2fa_code(
Ok(true) Ok(true)
} else if allow_backup { } else if allow_backup {
let backup_codes = let backup_codes =
crate::database::models::User::get_backup_codes(user_id, pool) crate::database::models::DBUser::get_backup_codes(user_id, pool)
.await?; .await?;
if !backup_codes.contains(&input) { if !backup_codes.contains(&input) {
@@ -1587,7 +1589,7 @@ async fn validate_2fa_code(
.execute(&mut **transaction) .execute(&mut **transaction)
.await?; .await?;
crate::database::models::User::clear_caches( crate::database::models::DBUser::clear_caches(
&[(user_id, None)], &[(user_id, None)],
redis, redis,
) )
@@ -1607,13 +1609,13 @@ pub async fn login_2fa(
redis: Data<RedisPool>, redis: Data<RedisPool>,
login: web::Json<Login2FA>, login: web::Json<Login2FA>,
) -> Result<HttpResponse, ApiError> { ) -> Result<HttpResponse, ApiError> {
let flow = Flow::get(&login.flow, &redis) let flow = DBFlow::get(&login.flow, &redis)
.await? .await?
.ok_or_else(|| AuthenticationError::InvalidCredentials)?; .ok_or_else(|| AuthenticationError::InvalidCredentials)?;
if let Flow::Login2FA { user_id } = flow { if let DBFlow::Login2FA { user_id } = flow {
let user = let user =
crate::database::models::User::get_id(user_id, &**pool, &redis) crate::database::models::DBUser::get_id(user_id, &**pool, &redis)
.await? .await?
.ok_or_else(|| AuthenticationError::InvalidCredentials)?; .ok_or_else(|| AuthenticationError::InvalidCredentials)?;
@@ -1634,7 +1636,7 @@ pub async fn login_2fa(
AuthenticationError::InvalidCredentials, AuthenticationError::InvalidCredentials,
)); ));
} }
Flow::remove(&login.flow, &redis).await?; DBFlow::remove(&login.flow, &redis).await?;
let session = let session =
issue_session(req, user_id, &mut transaction, &redis).await?; issue_session(req, user_id, &mut transaction, &redis).await?;
@@ -1670,7 +1672,7 @@ pub async fn begin_2fa_flow(
let string = totp_rs::Secret::generate_secret(); let string = totp_rs::Secret::generate_secret();
let encoded = string.to_encoded(); let encoded = string.to_encoded();
let flow = Flow::Initialize2FA { let flow = DBFlow::Initialize2FA {
user_id: user.id.into(), user_id: user.id.into(),
secret: encoded.to_string(), secret: encoded.to_string(),
} }
@@ -1696,11 +1698,11 @@ pub async fn finish_2fa_flow(
login: web::Json<Login2FA>, login: web::Json<Login2FA>,
session_queue: Data<AuthQueue>, session_queue: Data<AuthQueue>,
) -> Result<HttpResponse, ApiError> { ) -> Result<HttpResponse, ApiError> {
let flow = Flow::get(&login.flow, &redis) let flow = DBFlow::get(&login.flow, &redis)
.await? .await?
.ok_or_else(|| AuthenticationError::InvalidCredentials)?; .ok_or_else(|| AuthenticationError::InvalidCredentials)?;
if let Flow::Initialize2FA { user_id, secret } = flow { if let DBFlow::Initialize2FA { user_id, secret } = flow {
let user = get_user_from_headers( let user = get_user_from_headers(
&req, &req,
&**pool, &**pool,
@@ -1735,7 +1737,7 @@ pub async fn finish_2fa_flow(
)); ));
} }
Flow::remove(&login.flow, &redis).await?; DBFlow::remove(&login.flow, &redis).await?;
sqlx::query!( sqlx::query!(
" "
@@ -1794,7 +1796,7 @@ pub async fn finish_2fa_flow(
} }
transaction.commit().await?; transaction.commit().await?;
crate::database::models::User::clear_caches( crate::database::models::DBUser::clear_caches(
&[(user.id.into(), None)], &[(user.id.into(), None)],
&redis, &redis,
) )
@@ -1893,7 +1895,7 @@ pub async fn remove_2fa(
} }
transaction.commit().await?; transaction.commit().await?;
crate::database::models::User::clear_caches(&[(user.id, None)], &redis) crate::database::models::DBUser::clear_caches(&[(user.id, None)], &redis)
.await?; .await?;
Ok(HttpResponse::NoContent().finish()) Ok(HttpResponse::NoContent().finish())
@@ -1916,15 +1918,17 @@ pub async fn reset_password_begin(
return Err(ApiError::Turnstile); return Err(ApiError::Turnstile);
} }
let user = if let Some(user_id) = crate::database::models::User::get_email( let user = if let Some(user_id) =
&reset_password.username, crate::database::models::DBUser::get_email(
&**pool, &reset_password.username,
) &**pool,
.await? )
.await?
{ {
crate::database::models::User::get_id(user_id, &**pool, &redis).await? crate::database::models::DBUser::get_id(user_id, &**pool, &redis)
.await?
} else { } else {
crate::database::models::User::get( crate::database::models::DBUser::get(
&reset_password.username, &reset_password.username,
&**pool, &**pool,
&redis, &redis,
@@ -1933,7 +1937,7 @@ pub async fn reset_password_begin(
}; };
if let Some(user) = user { if let Some(user) = user {
let flow = Flow::ForgotPassword { user_id: user.id } let flow = DBFlow::ForgotPassword { user_id: user.id }
.insert(Duration::hours(24), &redis) .insert(Duration::hours(24), &redis)
.await?; .await?;
@@ -1975,13 +1979,14 @@ pub async fn change_password(
session_queue: Data<AuthQueue>, session_queue: Data<AuthQueue>,
) -> Result<HttpResponse, ApiError> { ) -> Result<HttpResponse, ApiError> {
let user = if let Some(flow) = &change_password.flow { let user = if let Some(flow) = &change_password.flow {
let flow = Flow::get(flow, &redis).await?; let flow = DBFlow::get(flow, &redis).await?;
if let Some(Flow::ForgotPassword { user_id }) = flow { if let Some(DBFlow::ForgotPassword { user_id }) = flow {
let user = let user = crate::database::models::DBUser::get_id(
crate::database::models::User::get_id(user_id, &**pool, &redis) user_id, &**pool, &redis,
.await? )
.ok_or_else(|| AuthenticationError::InvalidCredentials)?; .await?
.ok_or_else(|| AuthenticationError::InvalidCredentials)?;
Some(user) Some(user)
} else { } else {
@@ -2085,7 +2090,7 @@ pub async fn change_password(
.await?; .await?;
if let Some(flow) = &change_password.flow { if let Some(flow) = &change_password.flow {
Flow::remove(flow, &redis).await?; DBFlow::remove(flow, &redis).await?;
} }
if let Some(email) = user.email { if let Some(email) = user.email {
@@ -2105,7 +2110,7 @@ pub async fn change_password(
} }
transaction.commit().await?; transaction.commit().await?;
crate::database::models::User::clear_caches(&[(user.id, None)], &redis) crate::database::models::DBUser::clear_caches(&[(user.id, None)], &redis)
.await?; .await?;
Ok(HttpResponse::Ok().finish()) Ok(HttpResponse::Ok().finish())
@@ -2183,7 +2188,7 @@ pub async fn set_email(
.await?; .await?;
} }
let flow = Flow::ConfirmEmail { let flow = DBFlow::ConfirmEmail {
user_id: user.id.into(), user_id: user.id.into(),
confirm_email: email.email.clone(), confirm_email: email.email.clone(),
} }
@@ -2197,7 +2202,7 @@ pub async fn set_email(
)?; )?;
transaction.commit().await?; transaction.commit().await?;
crate::database::models::User::clear_caches( crate::database::models::DBUser::clear_caches(
&[(user.id.into(), None)], &[(user.id.into(), None)],
&redis, &redis,
) )
@@ -2230,7 +2235,7 @@ pub async fn resend_verify_email(
)); ));
} }
let flow = Flow::ConfirmEmail { let flow = DBFlow::ConfirmEmail {
user_id: user.id.into(), user_id: user.id.into(),
confirm_email: email.clone(), confirm_email: email.clone(),
} }
@@ -2262,15 +2267,15 @@ pub async fn verify_email(
redis: Data<RedisPool>, redis: Data<RedisPool>,
email: web::Json<VerifyEmail>, email: web::Json<VerifyEmail>,
) -> Result<HttpResponse, ApiError> { ) -> Result<HttpResponse, ApiError> {
let flow = Flow::get(&email.flow, &redis).await?; let flow = DBFlow::get(&email.flow, &redis).await?;
if let Some(Flow::ConfirmEmail { if let Some(DBFlow::ConfirmEmail {
user_id, user_id,
confirm_email, confirm_email,
}) = flow }) = flow
{ {
let user = let user =
crate::database::models::User::get_id(user_id, &**pool, &redis) crate::database::models::DBUser::get_id(user_id, &**pool, &redis)
.await? .await?
.ok_or_else(|| AuthenticationError::InvalidCredentials)?; .ok_or_else(|| AuthenticationError::InvalidCredentials)?;
@@ -2294,10 +2299,13 @@ pub async fn verify_email(
.execute(&mut *transaction) .execute(&mut *transaction)
.await?; .await?;
Flow::remove(&email.flow, &redis).await?; DBFlow::remove(&email.flow, &redis).await?;
transaction.commit().await?; transaction.commit().await?;
crate::database::models::User::clear_caches(&[(user.id, None)], &redis) crate::database::models::DBUser::clear_caches(
.await?; &[(user.id, None)],
&redis,
)
.await?;
Ok(HttpResponse::NoContent().finish()) Ok(HttpResponse::NoContent().finish())
} else { } else {

View File

@@ -30,9 +30,9 @@ pub async fn export(
let user_id = user.id.into(); let user_id = user.id.into();
let collection_ids = let collection_ids =
crate::database::models::User::get_collections(user_id, &**pool) crate::database::models::DBUser::get_collections(user_id, &**pool)
.await?; .await?;
let collections = crate::database::models::Collection::get_many( let collections = crate::database::models::DBCollection::get_many(
&collection_ids, &collection_ids,
&**pool, &**pool,
&redis, &redis,
@@ -42,24 +42,25 @@ pub async fn export(
.map(crate::models::collections::Collection::from) .map(crate::models::collections::Collection::from)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let follows = crate::database::models::User::get_follows(user_id, &**pool) let follows =
.await? crate::database::models::DBUser::get_follows(user_id, &**pool)
.into_iter() .await?
.map(crate::models::ids::ProjectId::from) .into_iter()
.collect::<Vec<_>>(); .map(crate::models::ids::ProjectId::from)
.collect::<Vec<_>>();
let projects = let projects =
crate::database::models::User::get_projects(user_id, &**pool, &redis) crate::database::models::DBUser::get_projects(user_id, &**pool, &redis)
.await? .await?
.into_iter() .into_iter()
.map(crate::models::ids::ProjectId::from) .map(crate::models::ids::ProjectId::from)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let org_ids = let org_ids =
crate::database::models::User::get_organizations(user_id, &**pool) crate::database::models::DBUser::get_organizations(user_id, &**pool)
.await?; .await?;
let orgs = let orgs =
crate::database::models::organization_item::Organization::get_many_ids( crate::database::models::organization_item::DBOrganization::get_many_ids(
&org_ids, &**pool, &redis, &org_ids, &**pool, &redis,
) )
.await? .await?
@@ -68,7 +69,7 @@ pub async fn export(
.map(|x| crate::models::organizations::Organization::from(x, vec![])) .map(|x| crate::models::organizations::Organization::from(x, vec![]))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let notifs = crate::database::models::notification_item::Notification::get_many_user( let notifs = crate::database::models::notification_item::DBNotification::get_many_user(
user_id, &**pool, &redis, user_id, &**pool, &redis,
) )
.await? .await?
@@ -77,7 +78,7 @@ pub async fn export(
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let oauth_clients = let oauth_clients =
crate::database::models::oauth_client_item::OAuthClient::get_all_user_clients( crate::database::models::oauth_client_item::DBOAuthClient::get_all_user_clients(
user_id, &**pool, user_id, &**pool,
) )
.await? .await?
@@ -85,7 +86,7 @@ pub async fn export(
.map(crate::models::oauth_clients::OAuthClient::from) .map(crate::models::oauth_clients::OAuthClient::from)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let oauth_authorizations = crate::database::models::oauth_client_authorization_item::OAuthClientAuthorization::get_all_for_user( let oauth_authorizations = crate::database::models::oauth_client_authorization_item::DBOAuthClientAuthorization::get_all_for_user(
user_id, &**pool, user_id, &**pool,
) )
.await? .await?
@@ -94,12 +95,12 @@ pub async fn export(
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let pat_ids = let pat_ids =
crate::database::models::pat_item::PersonalAccessToken::get_user_pats( crate::database::models::pat_item::DBPersonalAccessToken::get_user_pats(
user_id, &**pool, &redis, user_id, &**pool, &redis,
) )
.await?; .await?;
let pats = let pats =
crate::database::models::pat_item::PersonalAccessToken::get_many_ids( crate::database::models::pat_item::DBPersonalAccessToken::get_many_ids(
&pat_ids, &**pool, &redis, &pat_ids, &**pool, &redis,
) )
.await? .await?
@@ -108,12 +109,12 @@ pub async fn export(
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let payout_ids = let payout_ids =
crate::database::models::payout_item::Payout::get_all_for_user( crate::database::models::payout_item::DBPayout::get_all_for_user(
user_id, &**pool, user_id, &**pool,
) )
.await?; .await?;
let payouts = crate::database::models::payout_item::Payout::get_many( let payouts = crate::database::models::payout_item::DBPayout::get_many(
&payout_ids, &payout_ids,
&**pool, &**pool,
) )
@@ -122,10 +123,11 @@ pub async fn export(
.map(crate::models::payouts::Payout::from) .map(crate::models::payouts::Payout::from)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let report_ids = let report_ids = crate::database::models::user_item::DBUser::get_reports(
crate::database::models::user_item::User::get_reports(user_id, &**pool) user_id, &**pool,
.await?; )
let reports = crate::database::models::report_item::Report::get_many( .await?;
let reports = crate::database::models::report_item::DBReport::get_many(
&report_ids, &report_ids,
&**pool, &**pool,
) )
@@ -147,7 +149,7 @@ pub async fn export(
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let messages = let messages =
crate::database::models::thread_item::ThreadMessage::get_many( crate::database::models::thread_item::DBThreadMessage::get_many(
&message_ids, &message_ids,
&**pool, &**pool,
) )
@@ -166,18 +168,19 @@ pub async fn export(
.map(|x| crate::database::models::ids::DBImageId(x.id)) .map(|x| crate::database::models::ids::DBImageId(x.id))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let uploaded_images = crate::database::models::image_item::Image::get_many( let uploaded_images =
&uploaded_images_ids, crate::database::models::image_item::DBImage::get_many(
&**pool, &uploaded_images_ids,
&redis, &**pool,
) &redis,
.await? )
.into_iter() .await?
.map(crate::models::images::Image::from) .into_iter()
.collect::<Vec<_>>(); .map(crate::models::images::Image::from)
.collect::<Vec<_>>();
let subscriptions = let subscriptions =
crate::database::models::user_subscription_item::UserSubscriptionItem::get_all_user( crate::database::models::user_subscription_item::DBUserSubscription::get_all_user(
user_id, &**pool, user_id, &**pool,
) )
.await? .await?

View File

@@ -61,7 +61,7 @@ pub async fn get_projects(
.await?; .await?;
let projects: Vec<_> = let projects: Vec<_> =
database::Project::get_many_ids(&project_ids, &**pool, &redis) database::DBProject::get_many_ids(&project_ids, &**pool, &redis)
.await? .await?
.into_iter() .into_iter()
.map(crate::models::projects::Project::from) .map(crate::models::projects::Project::from)
@@ -88,7 +88,7 @@ pub async fn get_project_meta(
let project_id = info.into_inner().0; let project_id = info.into_inner().0;
let project = let project =
database::models::Project::get(&project_id, &**pool, &redis).await?; database::models::DBProject::get(&project_id, &**pool, &redis).await?;
if let Some(project) = project { if let Some(project) = project {
let rows = sqlx::query!( let rows = sqlx::query!(

View File

@@ -45,13 +45,13 @@ pub async fn get_pats(
.1; .1;
let pat_ids = let pat_ids =
database::models::pat_item::PersonalAccessToken::get_user_pats( database::models::pat_item::DBPersonalAccessToken::get_user_pats(
user.id.into(), user.id.into(),
&**pool, &**pool,
&redis, &redis,
) )
.await?; .await?;
let pats = database::models::pat_item::PersonalAccessToken::get_many_ids( let pats = database::models::pat_item::DBPersonalAccessToken::get_many_ids(
&pat_ids, &**pool, &redis, &pat_ids, &**pool, &redis,
) )
.await?; .await?;
@@ -116,7 +116,7 @@ pub async fn create_pat(
let token = format!("mrp_{token}"); let token = format!("mrp_{token}");
let name = info.name.clone(); let name = info.name.clone();
database::models::pat_item::PersonalAccessToken { database::models::pat_item::DBPersonalAccessToken {
id, id,
name: name.clone(), name: name.clone(),
access_token: token.clone(), access_token: token.clone(),
@@ -130,7 +130,7 @@ pub async fn create_pat(
.await?; .await?;
transaction.commit().await?; transaction.commit().await?;
database::models::pat_item::PersonalAccessToken::clear_cache( database::models::pat_item::DBPersonalAccessToken::clear_cache(
vec![(None, None, Some(user.id.into()))], vec![(None, None, Some(user.id.into()))],
&redis, &redis,
) )
@@ -180,7 +180,7 @@ pub async fn edit_pat(
.1; .1;
let id = id.into_inner().0; let id = id.into_inner().0;
let pat = database::models::pat_item::PersonalAccessToken::get( let pat = database::models::pat_item::DBPersonalAccessToken::get(
&id, &**pool, &redis, &id, &**pool, &redis,
) )
.await?; .await?;
@@ -242,7 +242,7 @@ pub async fn edit_pat(
} }
transaction.commit().await?; transaction.commit().await?;
database::models::pat_item::PersonalAccessToken::clear_cache( database::models::pat_item::DBPersonalAccessToken::clear_cache(
vec![(Some(pat.id), Some(pat.access_token), Some(pat.user_id))], vec![(Some(pat.id), Some(pat.access_token), Some(pat.user_id))],
&redis, &redis,
) )
@@ -271,7 +271,7 @@ pub async fn delete_pat(
.await? .await?
.1; .1;
let id = id.into_inner().0; let id = id.into_inner().0;
let pat = database::models::pat_item::PersonalAccessToken::get( let pat = database::models::pat_item::DBPersonalAccessToken::get(
&id, &**pool, &redis, &id, &**pool, &redis,
) )
.await?; .await?;
@@ -279,13 +279,13 @@ pub async fn delete_pat(
if let Some(pat) = pat { if let Some(pat) = pat {
if pat.user_id == user.id.into() { if pat.user_id == user.id.into() {
let mut transaction = pool.begin().await?; let mut transaction = pool.begin().await?;
database::models::pat_item::PersonalAccessToken::remove( database::models::pat_item::DBPersonalAccessToken::remove(
pat.id, pat.id,
&mut transaction, &mut transaction,
) )
.await?; .await?;
transaction.commit().await?; transaction.commit().await?;
database::models::pat_item::PersonalAccessToken::clear_cache( database::models::pat_item::DBPersonalAccessToken::clear_cache(
vec![(Some(pat.id), Some(pat.access_token), Some(pat.user_id))], vec![(Some(pat.id), Some(pat.access_token), Some(pat.user_id))],
&redis, &redis,
) )

View File

@@ -1,6 +1,6 @@
use crate::auth::{AuthenticationError, get_user_from_headers}; use crate::auth::{AuthenticationError, get_user_from_headers};
use crate::database::models::DBUserId; use crate::database::models::DBUserId;
use crate::database::models::session_item::Session as DBSession; use crate::database::models::session_item::DBSession;
use crate::database::models::session_item::SessionBuilder; use crate::database::models::session_item::SessionBuilder;
use crate::database::redis::RedisPool; use crate::database::redis::RedisPool;
use crate::models::pats::Scopes; use crate::models::pats::Scopes;

View File

@@ -1,6 +1,6 @@
use crate::auth::AuthenticationError; use crate::auth::AuthenticationError;
use crate::auth::validate::get_user_record_from_bearer_token; use crate::auth::validate::get_user_record_from_bearer_token;
use crate::database::models::friend_item::FriendItem; use crate::database::models::friend_item::DBFriend;
use crate::database::redis::RedisPool; use crate::database::redis::RedisPool;
use crate::models::pats::Scopes; use crate::models::pats::Scopes;
use crate::models::users::User; use crate::models::users::User;
@@ -85,8 +85,7 @@ pub async fn ws_init(
}; };
let friends = let friends =
FriendItem::get_user_friends(user.id.into(), Some(true), &**pool) DBFriend::get_user_friends(user.id.into(), Some(true), &**pool).await?;
.await?;
let friend_statuses = if !friends.is_empty() { let friend_statuses = if !friends.is_empty() {
let db = db.clone(); let db = db.clone();
@@ -383,7 +382,7 @@ pub async fn broadcast_to_local_friends(
user_id, user_id,
message, message,
sockets, sockets,
FriendItem::get_user_friends(user_id.into(), Some(true), pool).await?, DBFriend::get_user_friends(user_id.into(), Some(true), pool).await?,
) )
.await .await
} }
@@ -392,7 +391,7 @@ async fn broadcast_to_known_local_friends(
user_id: UserId, user_id: UserId,
message: ServerToClientMessage, message: ServerToClientMessage,
sockets: &ActiveSockets, sockets: &ActiveSockets,
friends: Vec<FriendItem>, friends: Vec<DBFriend>,
) -> Result<(), crate::database::models::DatabaseError> { ) -> Result<(), crate::database::models::DatabaseError> {
// FIXME Probably shouldn't be using database errors for this. Maybe ApiError? // FIXME Probably shouldn't be using database errors for this. Maybe ApiError?

View File

@@ -1,8 +1,10 @@
use crate::auth::checks::{is_visible_project, is_visible_version}; use crate::auth::checks::{is_visible_project, is_visible_version};
use crate::database::models::legacy_loader_fields::MinecraftGameVersion; use crate::database::models::legacy_loader_fields::MinecraftGameVersion;
use crate::database::models::loader_fields::Loader; use crate::database::models::loader_fields::Loader;
use crate::database::models::project_item::QueryProject; use crate::database::models::project_item::ProjectQueryResult;
use crate::database::models::version_item::{QueryFile, QueryVersion}; use crate::database::models::version_item::{
FileQueryResult, VersionQueryResult,
};
use crate::database::redis::RedisPool; use crate::database::redis::RedisPool;
use crate::models::ids::{ProjectId, VersionId}; use crate::models::ids::{ProjectId, VersionId};
use crate::models::pats::Scopes; use crate::models::pats::Scopes;
@@ -76,7 +78,7 @@ pub async fn maven_metadata(
) -> Result<HttpResponse, ApiError> { ) -> Result<HttpResponse, ApiError> {
let project_id = params.into_inner().0; let project_id = params.into_inner().0;
let Some(project) = let Some(project) =
database::models::Project::get(&project_id, &**pool, &redis).await? database::models::DBProject::get(&project_id, &**pool, &redis).await?
else { else {
return Err(ApiError::NotFound); return Err(ApiError::NotFound);
}; };
@@ -159,17 +161,17 @@ pub async fn maven_metadata(
} }
async fn find_version( async fn find_version(
project: &QueryProject, project: &ProjectQueryResult,
vcoords: &String, vcoords: &String,
pool: &PgPool, pool: &PgPool,
redis: &RedisPool, redis: &RedisPool,
) -> Result<Option<QueryVersion>, ApiError> { ) -> Result<Option<VersionQueryResult>, ApiError> {
let id_option = ariadne::ids::base62_impl::parse_base62(vcoords) let id_option = ariadne::ids::base62_impl::parse_base62(vcoords)
.ok() .ok()
.map(|x| x as i64); .map(|x| x as i64);
let all_versions = let all_versions =
database::models::Version::get_many(&project.versions, pool, redis) database::models::DBVersion::get_many(&project.versions, pool, redis)
.await?; .await?;
let exact_matches = all_versions let exact_matches = all_versions
@@ -236,9 +238,9 @@ async fn find_version(
fn find_file<'a>( fn find_file<'a>(
project_id: &str, project_id: &str,
vcoords: &str, vcoords: &str,
version: &'a QueryVersion, version: &'a VersionQueryResult,
file: &str, file: &str,
) -> Option<&'a QueryFile> { ) -> Option<&'a FileQueryResult> {
if let Some(selected_file) = if let Some(selected_file) =
version.files.iter().find(|x| x.filename == file) version.files.iter().find(|x| x.filename == file)
{ {
@@ -282,7 +284,7 @@ pub async fn version_file(
) -> Result<HttpResponse, ApiError> { ) -> Result<HttpResponse, ApiError> {
let (project_id, vnum, file) = params.into_inner(); let (project_id, vnum, file) = params.into_inner();
let Some(project) = let Some(project) =
database::models::Project::get(&project_id, &**pool, &redis).await? database::models::DBProject::get(&project_id, &**pool, &redis).await?
else { else {
return Err(ApiError::NotFound); return Err(ApiError::NotFound);
}; };
@@ -348,7 +350,7 @@ pub async fn version_file_sha1(
) -> Result<HttpResponse, ApiError> { ) -> Result<HttpResponse, ApiError> {
let (project_id, vnum, file) = params.into_inner(); let (project_id, vnum, file) = params.into_inner();
let Some(project) = let Some(project) =
database::models::Project::get(&project_id, &**pool, &redis).await? database::models::DBProject::get(&project_id, &**pool, &redis).await?
else { else {
return Err(ApiError::NotFound); return Err(ApiError::NotFound);
}; };
@@ -393,7 +395,7 @@ pub async fn version_file_sha512(
) -> Result<HttpResponse, ApiError> { ) -> Result<HttpResponse, ApiError> {
let (project_id, vnum, file) = params.into_inner(); let (project_id, vnum, file) = params.into_inner();
let Some(project) = let Some(project) =
database::models::Project::get(&project_id, &**pool, &redis).await? database::models::DBProject::get(&project_id, &**pool, &redis).await?
else { else {
return Err(ApiError::NotFound); return Err(ApiError::NotFound);
}; };

View File

@@ -42,7 +42,7 @@ pub async fn forge_updates(
let (id,) = info.into_inner(); let (id,) = info.into_inner();
let project = database::models::Project::get(&id, &**pool, &redis) let project = database::models::DBProject::get(&id, &**pool, &redis)
.await? .await?
.ok_or_else(|| ApiError::InvalidInput(ERROR.to_string()))?; .ok_or_else(|| ApiError::InvalidInput(ERROR.to_string()))?;
@@ -61,9 +61,12 @@ pub async fn forge_updates(
return Err(ApiError::InvalidInput(ERROR.to_string())); return Err(ApiError::InvalidInput(ERROR.to_string()));
} }
let versions = let versions = database::models::DBVersion::get_many(
database::models::Version::get_many(&project.versions, &**pool, &redis) &project.versions,
.await?; &**pool,
&redis,
)
.await?;
let loaders = match &*neo.neoforge { let loaders = match &*neo.neoforge {
"only" => |x: &String| *x == "neoforge", "only" => |x: &String| *x == "neoforge",

View File

@@ -258,8 +258,12 @@ pub async fn project_create(
Ok(project) => { Ok(project) => {
let version_item = match project.versions.first() { let version_item = match project.versions.first() {
Some(vid) => { Some(vid) => {
version_item::Version::get((*vid).into(), &**client, &redis) version_item::DBVersion::get(
.await? (*vid).into(),
&**client,
&redis,
)
.await?
} }
None => None, None => None,
}; };

View File

@@ -229,7 +229,7 @@ pub async fn project_get(
Ok(project) => { Ok(project) => {
let version_item = match project.versions.first() { let version_item = match project.versions.first() {
Some(vid) => { Some(vid) => {
version_item::Version::get((*vid).into(), &**pool, &redis) version_item::DBVersion::get((*vid).into(), &**pool, &redis)
.await? .await?
} }
None => None, None => None,
@@ -469,7 +469,7 @@ pub async fn project_edit(
if let Some(donation_urls) = v2_new_project.donation_urls { if let Some(donation_urls) = v2_new_project.donation_urls {
// Fetch current donation links from project so we know what to delete // Fetch current donation links from project so we know what to delete
let fetched_example_project = let fetched_example_project =
project_item::Project::get(&info.0, &**pool, &redis).await?; project_item::DBProject::get(&info.0, &**pool, &redis).await?;
let donation_links = fetched_example_project let donation_links = fetched_example_project
.map(|x| { .map(|x| {
x.urls x.urls
@@ -533,7 +533,7 @@ pub async fn project_edit(
if response.status().is_success() if response.status().is_success()
&& (client_side.is_some() || server_side.is_some()) && (client_side.is_some() || server_side.is_some())
{ {
let project_item = project_item::Project::get( let project_item = project_item::DBProject::get(
&new_slug.unwrap_or(project_id), &new_slug.unwrap_or(project_id),
&**pool, &**pool,
&redis, &redis,
@@ -541,7 +541,7 @@ pub async fn project_edit(
.await?; .await?;
let version_ids = project_item.map(|x| x.versions).unwrap_or_default(); let version_ids = project_item.map(|x| x.versions).unwrap_or_default();
let versions = let versions =
version_item::Version::get_many(&version_ids, &**pool, &redis) version_item::DBVersion::get_many(&version_ids, &**pool, &redis)
.await?; .await?;
for version in versions { for version in versions {
let version = Version::from(version); let version = Version::from(version);

View File

@@ -288,17 +288,20 @@ async fn get_example_version_fields(
None => return Ok(None), None => return Ok(None),
}; };
let vid = let vid = match project_item::DBProject::get_id(
match project_item::Project::get_id(project_id.into(), &**pool, redis) project_id.into(),
.await? &**pool,
.and_then(|p| p.versions.first().cloned()) redis,
{ )
Some(vid) => vid, .await?
None => return Ok(None), .and_then(|p| p.versions.first().cloned())
}; {
Some(vid) => vid,
None => return Ok(None),
};
let example_version = let example_version =
match version_item::Version::get(vid, &**pool, redis).await? { match version_item::DBVersion::get(vid, &**pool, redis).await? {
Some(version) => version, Some(version) => version,
None => return Ok(None), None => return Ok(None),
}; };

View File

@@ -578,7 +578,7 @@ async fn filter_allowed_ids(
// If no project_ids or version_ids are provided, we default to all projects the user has *public* access to // If no project_ids or version_ids are provided, we default to all projects the user has *public* access to
if project_ids.is_none() && !remove_defaults.unwrap_or(false) { if project_ids.is_none() && !remove_defaults.unwrap_or(false) {
project_ids = Some( project_ids = Some(
user_item::User::get_projects(user.id.into(), &***pool, redis) user_item::DBUser::get_projects(user.id.into(), &***pool, redis)
.await? .await?
.into_iter() .into_iter()
.map(|x| ProjectId::from(x).to_string()) .map(|x| ProjectId::from(x).to_string())
@@ -589,7 +589,7 @@ async fn filter_allowed_ids(
// Convert String list to list of ProjectIds or VersionIds // Convert String list to list of ProjectIds or VersionIds
// - Filter out unauthorized projects/versions // - Filter out unauthorized projects/versions
let project_ids = if let Some(project_strings) = project_ids { let project_ids = if let Some(project_strings) = project_ids {
let projects_data = database::models::Project::get_many( let projects_data = database::models::DBProject::get_many(
&project_strings, &project_strings,
&***pool, &***pool,
redis, redis,
@@ -601,7 +601,7 @@ async fn filter_allowed_ids(
.map(|x| x.inner.team_id) .map(|x| x.inner.team_id)
.collect::<Vec<database::models::DBTeamId>>(); .collect::<Vec<database::models::DBTeamId>>();
let team_members = let team_members =
database::models::TeamMember::get_from_team_full_many( database::models::DBTeamMember::get_from_team_full_many(
&team_ids, &***pool, redis, &team_ids, &***pool, redis,
) )
.await?; .await?;
@@ -610,7 +610,7 @@ async fn filter_allowed_ids(
.iter() .iter()
.filter_map(|x| x.inner.organization_id) .filter_map(|x| x.inner.organization_id)
.collect::<Vec<database::models::DBOrganizationId>>(); .collect::<Vec<database::models::DBOrganizationId>>();
let organizations = database::models::Organization::get_many_ids( let organizations = database::models::DBOrganization::get_many_ids(
&organization_ids, &organization_ids,
&***pool, &***pool,
redis, redis,
@@ -622,7 +622,7 @@ async fn filter_allowed_ids(
.map(|x| x.team_id) .map(|x| x.team_id)
.collect::<Vec<database::models::DBTeamId>>(); .collect::<Vec<database::models::DBTeamId>>();
let organization_team_members = let organization_team_members =
database::models::TeamMember::get_from_team_full_many( database::models::DBTeamMember::get_from_team_full_many(
&organization_team_ids, &organization_team_ids,
&***pool, &***pool,
redis, redis,

View File

@@ -85,7 +85,7 @@ pub async fn collection_create(
let collection_id: CollectionId = let collection_id: CollectionId =
generate_collection_id(&mut transaction).await?.into(); generate_collection_id(&mut transaction).await?.into();
let initial_project_ids = project_item::Project::get_many( let initial_project_ids = project_item::DBProject::get_many(
&collection_create_data.projects, &collection_create_data.projects,
&mut *transaction, &mut *transaction,
&redis, &redis,
@@ -149,7 +149,7 @@ pub async fn collections_get(
.collect::<Result<Vec<_>, _>>()?; .collect::<Result<Vec<_>, _>>()?;
let collections_data = let collections_data =
database::models::Collection::get_many(&ids, &**pool, &redis).await?; database::models::DBCollection::get_many(&ids, &**pool, &redis).await?;
let user_option = get_user_from_headers( let user_option = get_user_from_headers(
&req, &req,
@@ -179,7 +179,7 @@ pub async fn collection_get(
let id = database::models::DBCollectionId(parse_base62(&string)? as i64); let id = database::models::DBCollectionId(parse_base62(&string)? as i64);
let collection_data = let collection_data =
database::models::Collection::get(id, &**pool, &redis).await?; database::models::DBCollection::get(id, &**pool, &redis).await?;
let user_option = get_user_from_headers( let user_option = get_user_from_headers(
&req, &req,
&**pool, &**pool,
@@ -242,7 +242,8 @@ pub async fn collection_edit(
let string = info.into_inner().0; let string = info.into_inner().0;
let id = database::models::DBCollectionId(parse_base62(&string)? as i64); let id = database::models::DBCollectionId(parse_base62(&string)? as i64);
let result = database::models::Collection::get(id, &**pool, &redis).await?; let result =
database::models::DBCollection::get(id, &**pool, &redis).await?;
if let Some(collection_item) = result { if let Some(collection_item) = result {
if !can_modify_collection(&collection_item, &user) { if !can_modify_collection(&collection_item, &user) {
@@ -322,7 +323,7 @@ pub async fn collection_edit(
.collect_vec(); .collect_vec();
let mut validated_project_ids = Vec::new(); let mut validated_project_ids = Vec::new();
for project_id in new_project_ids { for project_id in new_project_ids {
let project = database::models::Project::get( let project = database::models::DBProject::get(
project_id, &**pool, &redis, project_id, &**pool, &redis,
) )
.await? .await?
@@ -359,7 +360,7 @@ pub async fn collection_edit(
} }
transaction.commit().await?; transaction.commit().await?;
database::models::Collection::clear_cache(collection_item.id, &redis) database::models::DBCollection::clear_cache(collection_item.id, &redis)
.await?; .await?;
Ok(HttpResponse::NoContent().body("")) Ok(HttpResponse::NoContent().body(""))
@@ -397,7 +398,7 @@ pub async fn collection_icon_edit(
let string = info.into_inner().0; let string = info.into_inner().0;
let id = database::models::DBCollectionId(parse_base62(&string)? as i64); let id = database::models::DBCollectionId(parse_base62(&string)? as i64);
let collection_item = let collection_item =
database::models::Collection::get(id, &**pool, &redis) database::models::DBCollection::get(id, &**pool, &redis)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
@@ -451,7 +452,7 @@ pub async fn collection_icon_edit(
.await?; .await?;
transaction.commit().await?; transaction.commit().await?;
database::models::Collection::clear_cache(collection_item.id, &redis) database::models::DBCollection::clear_cache(collection_item.id, &redis)
.await?; .await?;
Ok(HttpResponse::NoContent().body("")) Ok(HttpResponse::NoContent().body(""))
@@ -478,7 +479,7 @@ pub async fn delete_collection_icon(
let string = info.into_inner().0; let string = info.into_inner().0;
let id = database::models::DBCollectionId(parse_base62(&string)? as i64); let id = database::models::DBCollectionId(parse_base62(&string)? as i64);
let collection_item = let collection_item =
database::models::Collection::get(id, &**pool, &redis) database::models::DBCollection::get(id, &**pool, &redis)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
@@ -509,7 +510,7 @@ pub async fn delete_collection_icon(
.await?; .await?;
transaction.commit().await?; transaction.commit().await?;
database::models::Collection::clear_cache(collection_item.id, &redis) database::models::DBCollection::clear_cache(collection_item.id, &redis)
.await?; .await?;
Ok(HttpResponse::NoContent().body("")) Ok(HttpResponse::NoContent().body(""))
@@ -534,7 +535,7 @@ pub async fn collection_delete(
let string = info.into_inner().0; let string = info.into_inner().0;
let id = database::models::DBCollectionId(parse_base62(&string)? as i64); let id = database::models::DBCollectionId(parse_base62(&string)? as i64);
let collection = database::models::Collection::get(id, &**pool, &redis) let collection = database::models::DBCollection::get(id, &**pool, &redis)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
@@ -546,7 +547,7 @@ pub async fn collection_delete(
} }
let mut transaction = pool.begin().await?; let mut transaction = pool.begin().await?;
let result = database::models::Collection::remove( let result = database::models::DBCollection::remove(
collection.id, collection.id,
&mut transaction, &mut transaction,
&redis, &redis,
@@ -554,7 +555,7 @@ pub async fn collection_delete(
.await?; .await?;
transaction.commit().await?; transaction.commit().await?;
database::models::Collection::clear_cache(collection.id, &redis).await?; database::models::DBCollection::clear_cache(collection.id, &redis).await?;
if result.is_some() { if result.is_some() {
Ok(HttpResponse::NoContent().body("")) Ok(HttpResponse::NoContent().body(""))
@@ -564,7 +565,7 @@ pub async fn collection_delete(
} }
fn can_modify_collection( fn can_modify_collection(
collection: &database::models::Collection, collection: &database::models::DBCollection,
user: &models::users::User, user: &models::users::User,
) -> bool { ) -> bool {
collection.user_id == user.id.into() || user.role.is_mod() collection.user_id == user.id.into() || user.role.is_mod()

View File

@@ -43,13 +43,13 @@ pub async fn add_friend(
let string = info.into_inner().0; let string = info.into_inner().0;
let friend = let friend =
crate::database::models::User::get(&string, &**pool, &redis).await?; crate::database::models::DBUser::get(&string, &**pool, &redis).await?;
if let Some(friend) = friend { if let Some(friend) = friend {
let mut transaction = pool.begin().await?; let mut transaction = pool.begin().await?;
if let Some(friend) = if let Some(friend) =
crate::database::models::friend_item::FriendItem::get_friend( crate::database::models::friend_item::DBFriend::get_friend(
user.id.into(), user.id.into(),
friend.id, friend.id,
&**pool, &**pool,
@@ -68,7 +68,7 @@ pub async fn add_friend(
)); ));
} }
crate::database::models::friend_item::FriendItem::update_friend( crate::database::models::friend_item::DBFriend::update_friend(
friend.user_id, friend.user_id,
friend.friend_id, friend.friend_id,
true, true,
@@ -115,7 +115,7 @@ pub async fn add_friend(
)); ));
} }
crate::database::models::friend_item::FriendItem { crate::database::models::friend_item::DBFriend {
user_id: user.id.into(), user_id: user.id.into(),
friend_id: friend.id, friend_id: friend.id,
created: Utc::now(), created: Utc::now(),
@@ -161,12 +161,12 @@ pub async fn remove_friend(
let string = info.into_inner().0; let string = info.into_inner().0;
let friend = let friend =
crate::database::models::User::get(&string, &**pool, &redis).await?; crate::database::models::DBUser::get(&string, &**pool, &redis).await?;
if let Some(friend) = friend { if let Some(friend) = friend {
let mut transaction = pool.begin().await?; let mut transaction = pool.begin().await?;
crate::database::models::friend_item::FriendItem::remove( crate::database::models::friend_item::DBFriend::remove(
user.id.into(), user.id.into(),
friend.id, friend.id,
&mut transaction, &mut transaction,
@@ -206,7 +206,7 @@ pub async fn friends(
.1; .1;
let friends = let friends =
crate::database::models::friend_item::FriendItem::get_user_friends( crate::database::models::friend_item::DBFriend::get_user_friends(
user.id.into(), user.id.into(),
None, None,
&**pool, &**pool,

View File

@@ -67,7 +67,7 @@ pub async fn images_add(
ImageContext::Project { project_id } => { ImageContext::Project { project_id } => {
if let Some(id) = data.project_id { if let Some(id) = data.project_id {
let project = let project =
project_item::Project::get(&id, &**pool, &redis).await?; project_item::DBProject::get(&id, &**pool, &redis).await?;
if let Some(project) = project { if let Some(project) = project {
if is_team_member_project( if is_team_member_project(
&project.inner, &project.inner,
@@ -92,7 +92,7 @@ pub async fn images_add(
ImageContext::Version { version_id } => { ImageContext::Version { version_id } => {
if let Some(id) = data.version_id { if let Some(id) = data.version_id {
let version = let version =
version_item::Version::get(id.into(), &**pool, &redis) version_item::DBVersion::get(id.into(), &**pool, &redis)
.await?; .await?;
if let Some(version) = version { if let Some(version) = version {
if is_team_member_version( if is_team_member_version(
@@ -119,7 +119,7 @@ pub async fn images_add(
ImageContext::ThreadMessage { thread_message_id } => { ImageContext::ThreadMessage { thread_message_id } => {
if let Some(id) = data.thread_message_id { if let Some(id) = data.thread_message_id {
let thread_message = let thread_message =
thread_item::ThreadMessage::get(id.into(), &**pool) thread_item::DBThreadMessage::get(id.into(), &**pool)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
@@ -127,7 +127,7 @@ pub async fn images_add(
.to_string(), .to_string(),
) )
})?; })?;
let thread = thread_item::Thread::get(thread_message.thread_id, &**pool) let thread = thread_item::DBThread::get(thread_message.thread_id, &**pool)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
@@ -147,14 +147,14 @@ pub async fn images_add(
} }
ImageContext::Report { report_id } => { ImageContext::Report { report_id } => {
if let Some(id) = data.report_id { if let Some(id) = data.report_id {
let report = report_item::Report::get(id.into(), &**pool) let report = report_item::DBReport::get(id.into(), &**pool)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
"The report could not be found.".to_string(), "The report could not be found.".to_string(),
) )
})?; })?;
let thread = thread_item::Thread::get(report.thread_id, &**pool) let thread = thread_item::DBThread::get(report.thread_id, &**pool)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
@@ -198,7 +198,7 @@ pub async fn images_add(
let mut transaction = pool.begin().await?; let mut transaction = pool.begin().await?;
let db_image: database::models::Image = database::models::Image { let db_image: database::models::DBImage = database::models::DBImage {
id: database::models::generate_image_id(&mut transaction).await?, id: database::models::generate_image_id(&mut transaction).await?,
url: upload_result.url, url: upload_result.url,
raw_url: upload_result.raw_url, raw_url: upload_result.raw_url,

View File

@@ -46,7 +46,7 @@ pub async fn notifications_get(
.1; .1;
use database::models::DBNotificationId; use database::models::DBNotificationId;
use database::models::notification_item::Notification as DBNotification; use database::models::notification_item::DBNotification;
let notification_ids: Vec<DBNotificationId> = let notification_ids: Vec<DBNotificationId> =
serde_json::from_str::<Vec<NotificationId>>(ids.ids.as_str())? serde_json::from_str::<Vec<NotificationId>>(ids.ids.as_str())?
@@ -55,7 +55,7 @@ pub async fn notifications_get(
.collect(); .collect();
let notifications_data: Vec<DBNotification> = let notifications_data: Vec<DBNotification> =
database::models::notification_item::Notification::get_many( database::models::notification_item::DBNotification::get_many(
&notification_ids, &notification_ids,
&**pool, &**pool,
) )
@@ -90,7 +90,7 @@ pub async fn notification_get(
let id = info.into_inner().0; let id = info.into_inner().0;
let notification_data = let notification_data =
database::models::notification_item::Notification::get( database::models::notification_item::DBNotification::get(
id.into(), id.into(),
&**pool, &**pool,
) )
@@ -127,7 +127,7 @@ pub async fn notification_read(
let id = info.into_inner().0; let id = info.into_inner().0;
let notification_data = let notification_data =
database::models::notification_item::Notification::get( database::models::notification_item::DBNotification::get(
id.into(), id.into(),
&**pool, &**pool,
) )
@@ -137,7 +137,7 @@ pub async fn notification_read(
if data.user_id == user.id.into() || user.role.is_admin() { if data.user_id == user.id.into() || user.role.is_admin() {
let mut transaction = pool.begin().await?; let mut transaction = pool.begin().await?;
database::models::notification_item::Notification::read( database::models::notification_item::DBNotification::read(
id.into(), id.into(),
&mut transaction, &mut transaction,
&redis, &redis,
@@ -177,7 +177,7 @@ pub async fn notification_delete(
let id = info.into_inner().0; let id = info.into_inner().0;
let notification_data = let notification_data =
database::models::notification_item::Notification::get( database::models::notification_item::DBNotification::get(
id.into(), id.into(),
&**pool, &**pool,
) )
@@ -187,7 +187,7 @@ pub async fn notification_delete(
if data.user_id == user.id.into() || user.role.is_admin() { if data.user_id == user.id.into() || user.role.is_admin() {
let mut transaction = pool.begin().await?; let mut transaction = pool.begin().await?;
database::models::notification_item::Notification::remove( database::models::notification_item::DBNotification::remove(
id.into(), id.into(),
&mut transaction, &mut transaction,
&redis, &redis,
@@ -234,7 +234,7 @@ pub async fn notifications_read(
let mut transaction = pool.begin().await?; let mut transaction = pool.begin().await?;
let notifications_data = let notifications_data =
database::models::notification_item::Notification::get_many( database::models::notification_item::DBNotification::get_many(
&notification_ids, &notification_ids,
&**pool, &**pool,
) )
@@ -249,7 +249,7 @@ pub async fn notifications_read(
} }
} }
database::models::notification_item::Notification::read_many( database::models::notification_item::DBNotification::read_many(
&notifications, &notifications,
&mut transaction, &mut transaction,
&redis, &redis,
@@ -287,7 +287,7 @@ pub async fn notifications_delete(
let mut transaction = pool.begin().await?; let mut transaction = pool.begin().await?;
let notifications_data = let notifications_data =
database::models::notification_item::Notification::get_many( database::models::notification_item::DBNotification::get_many(
&notification_ids, &notification_ids,
&**pool, &**pool,
) )
@@ -302,7 +302,7 @@ pub async fn notifications_delete(
} }
} }
database::models::notification_item::Notification::remove_many( database::models::notification_item::DBNotification::remove_many(
&notifications, &notifications,
&mut transaction, &mut transaction,
&redis, &redis,

View File

@@ -5,10 +5,10 @@ use crate::{
auth::{checks::ValidateAuthorized, get_user_from_headers}, auth::{checks::ValidateAuthorized, get_user_from_headers},
database::{ database::{
models::{ models::{
DBOAuthClientId, DatabaseError, User, generate_oauth_client_id, DBOAuthClientId, DBUser, DatabaseError, generate_oauth_client_id,
generate_oauth_redirect_id, generate_oauth_redirect_id,
oauth_client_authorization_item::OAuthClientAuthorization, oauth_client_authorization_item::DBOAuthClientAuthorization,
oauth_client_item::{OAuthClient, OAuthRedirectUri}, oauth_client_item::{DBOAuthClient, DBOAuthRedirectUri},
}, },
redis::RedisPool, redis::RedisPool,
}, },
@@ -38,7 +38,6 @@ use serde::{Deserialize, Serialize};
use sqlx::PgPool; use sqlx::PgPool;
use validator::Validate; use validator::Validate;
use crate::database::models::oauth_client_item::OAuthClient as DBOAuthClient;
use crate::models::ids::OAuthClientId; use crate::models::ids::OAuthClientId;
use crate::util::img::{delete_old_images, upload_image_optimized}; use crate::util::img::{delete_old_images, upload_image_optimized};
@@ -75,7 +74,7 @@ pub async fn get_user_clients(
.await? .await?
.1; .1;
let target_user = User::get(&info.into_inner(), &**pool, &redis).await?; let target_user = DBUser::get(&info.into_inner(), &**pool, &redis).await?;
if let Some(target_user) = target_user { if let Some(target_user) = target_user {
if target_user.id != current_user.id.into() if target_user.id != current_user.id.into()
@@ -87,7 +86,8 @@ pub async fn get_user_clients(
} }
let clients = let clients =
OAuthClient::get_all_user_clients(target_user.id, &**pool).await?; DBOAuthClient::get_all_user_clients(target_user.id, &**pool)
.await?;
let response = clients let response = clients
.into_iter() .into_iter()
@@ -190,7 +190,7 @@ pub async fn oauth_client_create(
) )
.await?; .await?;
let client = OAuthClient { let client = DBOAuthClient {
id: client_id, id: client_id,
icon_url: None, icon_url: None,
raw_icon_url: None, raw_icon_url: None,
@@ -234,10 +234,10 @@ pub async fn oauth_client_delete(
.1; .1;
let client = let client =
OAuthClient::get(client_id.into_inner().into(), &**pool).await?; DBOAuthClient::get(client_id.into_inner().into(), &**pool).await?;
if let Some(client) = client { if let Some(client) = client {
client.validate_authorized(Some(&current_user))?; client.validate_authorized(Some(&current_user))?;
OAuthClient::remove(client.id, &**pool).await?; DBOAuthClient::remove(client.id, &**pool).await?;
Ok(HttpResponse::NoContent().body("")) Ok(HttpResponse::NoContent().body(""))
} else { } else {
@@ -295,7 +295,7 @@ pub async fn oauth_client_edit(
})?; })?;
if let Some(existing_client) = if let Some(existing_client) =
OAuthClient::get(client_id.into_inner().into(), &**pool).await? DBOAuthClient::get(client_id.into_inner().into(), &**pool).await?
{ {
existing_client.validate_authorized(Some(&current_user))?; existing_client.validate_authorized(Some(&current_user))?;
@@ -368,7 +368,7 @@ pub async fn oauth_client_icon_edit(
.await? .await?
.1; .1;
let client = OAuthClient::get((*client_id).into(), &**pool) let client = DBOAuthClient::get((*client_id).into(), &**pool)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
@@ -435,7 +435,7 @@ pub async fn oauth_client_icon_delete(
.await? .await?
.1; .1;
let client = OAuthClient::get((*client_id).into(), &**pool) let client = DBOAuthClient::get((*client_id).into(), &**pool)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
@@ -482,7 +482,7 @@ pub async fn get_user_oauth_authorizations(
.await? .await?
.1; .1;
let authorizations = OAuthClientAuthorization::get_all_for_user( let authorizations = DBOAuthClientAuthorization::get_all_for_user(
current_user.id.into(), current_user.id.into(),
&**pool, &**pool,
) )
@@ -512,7 +512,7 @@ pub async fn revoke_oauth_authorization(
.await? .await?
.1; .1;
OAuthClientAuthorization::remove( DBOAuthClientAuthorization::remove(
info.client_id.into(), info.client_id.into(),
current_user.id.into(), current_user.id.into(),
&**pool, &**pool,
@@ -534,11 +534,11 @@ async fn create_redirect_uris(
uri_strings: impl IntoIterator<Item = impl Display>, uri_strings: impl IntoIterator<Item = impl Display>,
client_id: DBOAuthClientId, client_id: DBOAuthClientId,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>, transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
) -> Result<Vec<OAuthRedirectUri>, DatabaseError> { ) -> Result<Vec<DBOAuthRedirectUri>, DatabaseError> {
let mut redirect_uris = vec![]; let mut redirect_uris = vec![];
for uri in uri_strings.into_iter() { for uri in uri_strings.into_iter() {
let id = generate_oauth_redirect_id(transaction).await?; let id = generate_oauth_redirect_id(transaction).await?;
redirect_uris.push(OAuthRedirectUri { redirect_uris.push(DBOAuthRedirectUri {
id, id,
client_id, client_id,
uri: uri.to_string(), uri: uri.to_string(),
@@ -550,7 +550,7 @@ async fn create_redirect_uris(
async fn edit_redirects( async fn edit_redirects(
redirects: Vec<String>, redirects: Vec<String>,
existing_client: &OAuthClient, existing_client: &DBOAuthClient,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>, transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
) -> Result<(), DatabaseError> { ) -> Result<(), DatabaseError> {
let updated_redirects: HashSet<String> = redirects.into_iter().collect(); let updated_redirects: HashSet<String> = redirects.into_iter().collect();
@@ -566,12 +566,12 @@ async fn edit_redirects(
&mut *transaction, &mut *transaction,
) )
.await?; .await?;
OAuthClient::insert_redirect_uris(&redirects_to_add, &mut **transaction) DBOAuthClient::insert_redirect_uris(&redirects_to_add, &mut **transaction)
.await?; .await?;
let mut redirects_to_remove = existing_client.redirect_uris.clone(); let mut redirects_to_remove = existing_client.redirect_uris.clone();
redirects_to_remove.retain(|r| !updated_redirects.contains(&r.uri)); redirects_to_remove.retain(|r| !updated_redirects.contains(&r.uri));
OAuthClient::remove_redirect_uris( DBOAuthClient::remove_redirect_uris(
redirects_to_remove.iter().map(|r| r.id), redirects_to_remove.iter().map(|r| r.id),
&mut **transaction, &mut **transaction,
) )
@@ -585,7 +585,7 @@ pub async fn get_clients_inner(
pool: web::Data<PgPool>, pool: web::Data<PgPool>,
) -> Result<Vec<models::oauth_clients::OAuthClient>, ApiError> { ) -> Result<Vec<models::oauth_clients::OAuthClient>, ApiError> {
let ids: Vec<DBOAuthClientId> = ids.iter().map(|i| (*i).into()).collect(); let ids: Vec<DBOAuthClientId> = ids.iter().map(|i| (*i).into()).collect();
let clients = OAuthClient::get_many(&ids, &**pool).await?; let clients = DBOAuthClient::get_many(&ids, &**pool).await?;
Ok(clients.into_iter().map(|c| c.into()).collect_vec()) Ok(clients.into_iter().map(|c| c.into()).collect_vec())
} }

View File

@@ -3,9 +3,9 @@ use std::sync::Arc;
use super::ApiError; use super::ApiError;
use crate::auth::{filter_visible_projects, get_user_from_headers}; use crate::auth::{filter_visible_projects, get_user_from_headers};
use crate::database::models::team_item::TeamMember; use crate::database::models::team_item::DBTeamMember;
use crate::database::models::{ use crate::database::models::{
Organization, generate_organization_id, team_item, DBOrganization, generate_organization_id, team_item,
}; };
use crate::database::redis::RedisPool; use crate::database::redis::RedisPool;
use crate::file_hosting::FileHost; use crate::file_hosting::FileHost;
@@ -69,7 +69,7 @@ pub async fn organization_projects_get(
.map(|x| x.1) .map(|x| x.1)
.ok(); .ok();
let organization_data = Organization::get(&id, &**pool, &redis).await?; let organization_data = DBOrganization::get(&id, &**pool, &redis).await?;
if let Some(organization) = organization_data { if let Some(organization) = organization_data {
let project_ids = sqlx::query!( let project_ids = sqlx::query!(
" "
@@ -84,7 +84,7 @@ pub async fn organization_projects_get(
.try_collect::<Vec<_>>() .try_collect::<Vec<_>>()
.await?; .await?;
let projects_data = crate::database::models::Project::get_many_ids( let projects_data = crate::database::models::DBProject::get_many_ids(
&project_ids, &project_ids,
&**pool, &**pool,
&redis, &redis,
@@ -146,7 +146,7 @@ pub async fn organization_create(
organization_strings.push(name_organization_id.to_string()); organization_strings.push(name_organization_id.to_string());
} }
organization_strings.push(new_organization.slug.clone()); organization_strings.push(new_organization.slug.clone());
let results = Organization::get_many( let results = DBOrganization::get_many(
&organization_strings, &organization_strings,
&mut *transaction, &mut *transaction,
&redis, &redis,
@@ -174,7 +174,7 @@ pub async fn organization_create(
let team_id = team.insert(&mut transaction).await?; let team_id = team.insert(&mut transaction).await?;
// Create organization // Create organization
let organization = Organization { let organization = DBOrganization {
id: organization_id, id: organization_id,
slug: new_organization.slug.clone(), slug: new_organization.slug.clone(),
name: new_organization.name.clone(), name: new_organization.name.clone(),
@@ -188,10 +188,11 @@ pub async fn organization_create(
transaction.commit().await?; transaction.commit().await?;
// Only member is the owner, the logged in one // Only member is the owner, the logged in one
let member_data = TeamMember::get_from_team_full(team_id, &**pool, &redis) let member_data =
.await? DBTeamMember::get_from_team_full(team_id, &**pool, &redis)
.into_iter() .await?
.next(); .into_iter()
.next();
let members_data = if let Some(member_data) = member_data { let members_data = if let Some(member_data) = member_data {
vec![crate::models::teams::TeamMember::from_model( vec![crate::models::teams::TeamMember::from_model(
member_data, member_data,
@@ -230,13 +231,13 @@ pub async fn organization_get(
.ok(); .ok();
let user_id = current_user.as_ref().map(|x| x.id.into()); let user_id = current_user.as_ref().map(|x| x.id.into());
let organization_data = Organization::get(&id, &**pool, &redis).await?; let organization_data = DBOrganization::get(&id, &**pool, &redis).await?;
if let Some(data) = organization_data { if let Some(data) = organization_data {
let members_data = let members_data =
TeamMember::get_from_team_full(data.team_id, &**pool, &redis) DBTeamMember::get_from_team_full(data.team_id, &**pool, &redis)
.await?; .await?;
let users = crate::database::models::User::get_many_ids( let users = crate::database::models::DBUser::get_many_ids(
&members_data.iter().map(|x| x.user_id).collect::<Vec<_>>(), &members_data.iter().map(|x| x.user_id).collect::<Vec<_>>(),
&**pool, &**pool,
&redis, &redis,
@@ -293,15 +294,16 @@ pub async fn organizations_get(
) -> Result<HttpResponse, ApiError> { ) -> Result<HttpResponse, ApiError> {
let ids = serde_json::from_str::<Vec<&str>>(&ids.ids)?; let ids = serde_json::from_str::<Vec<&str>>(&ids.ids)?;
let organizations_data = let organizations_data =
Organization::get_many(&ids, &**pool, &redis).await?; DBOrganization::get_many(&ids, &**pool, &redis).await?;
let team_ids = organizations_data let team_ids = organizations_data
.iter() .iter()
.map(|x| x.team_id) .map(|x| x.team_id)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let teams_data = let teams_data =
TeamMember::get_from_team_full_many(&team_ids, &**pool, &redis).await?; DBTeamMember::get_from_team_full_many(&team_ids, &**pool, &redis)
let users = crate::database::models::User::get_many_ids( .await?;
let users = crate::database::models::DBUser::get_many_ids(
&teams_data.iter().map(|x| x.user_id).collect::<Vec<_>>(), &teams_data.iter().map(|x| x.user_id).collect::<Vec<_>>(),
&**pool, &**pool,
&redis, &redis,
@@ -405,11 +407,11 @@ pub async fn organizations_edit(
let string = info.into_inner().0; let string = info.into_inner().0;
let result = let result =
database::models::Organization::get(&string, &**pool, &redis).await?; database::models::DBOrganization::get(&string, &**pool, &redis).await?;
if let Some(organization_item) = result { if let Some(organization_item) = result {
let id = organization_item.id; let id = organization_item.id;
let team_member = database::models::TeamMember::get_from_user_id( let team_member = database::models::DBTeamMember::get_from_user_id(
organization_item.team_id, organization_item.team_id,
user.id.into(), user.id.into(),
&**pool, &**pool,
@@ -526,7 +528,7 @@ pub async fn organizations_edit(
} }
transaction.commit().await?; transaction.commit().await?;
database::models::Organization::clear_cache( database::models::DBOrganization::clear_cache(
organization_item.id, organization_item.id,
Some(organization_item.slug), Some(organization_item.slug),
&redis, &redis,
@@ -564,7 +566,7 @@ pub async fn organization_delete(
let string = info.into_inner().0; let string = info.into_inner().0;
let organization = let organization =
database::models::Organization::get(&string, &**pool, &redis) database::models::DBOrganization::get(&string, &**pool, &redis)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
@@ -574,7 +576,7 @@ pub async fn organization_delete(
if !user.role.is_admin() { if !user.role.is_admin() {
let team_member = let team_member =
database::models::TeamMember::get_from_user_id_organization( database::models::DBTeamMember::get_from_user_id_organization(
organization.id, organization.id,
user.id.into(), user.id.into(),
false, false,
@@ -638,7 +640,7 @@ pub async fn organization_delete(
&mut transaction, &mut transaction,
) )
.await?; .await?;
let member = TeamMember { let member = DBTeamMember {
id: new_id, id: new_id,
team_id: *organization_project_team, team_id: *organization_project_team,
user_id: owner_id, user_id: owner_id,
@@ -653,7 +655,7 @@ pub async fn organization_delete(
member.insert(&mut transaction).await?; member.insert(&mut transaction).await?;
} }
// Safely remove the organization // Safely remove the organization
let result = database::models::Organization::remove( let result = database::models::DBOrganization::remove(
organization.id, organization.id,
&mut transaction, &mut transaction,
&redis, &redis,
@@ -662,7 +664,7 @@ pub async fn organization_delete(
transaction.commit().await?; transaction.commit().await?;
database::models::Organization::clear_cache( database::models::DBOrganization::clear_cache(
organization.id, organization.id,
Some(organization.slug), Some(organization.slug),
&redis, &redis,
@@ -670,7 +672,7 @@ pub async fn organization_delete(
.await?; .await?;
for team_id in organization_project_teams { for team_id in organization_project_teams {
database::models::TeamMember::clear_cache(team_id, &redis).await?; database::models::DBTeamMember::clear_cache(team_id, &redis).await?;
} }
if result.is_some() { if result.is_some() {
@@ -704,7 +706,7 @@ pub async fn organization_projects_add(
.1; .1;
let organization = let organization =
database::models::Organization::get(&info, &**pool, &redis) database::models::DBOrganization::get(&info, &**pool, &redis)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
@@ -712,7 +714,7 @@ pub async fn organization_projects_add(
) )
})?; })?;
let project_item = database::models::Project::get( let project_item = database::models::DBProject::get(
&project_info.project_id, &project_info.project_id,
&**pool, &**pool,
&redis, &redis,
@@ -731,7 +733,7 @@ pub async fn organization_projects_add(
} }
let project_team_member = let project_team_member =
database::models::TeamMember::get_from_user_id_project( database::models::DBTeamMember::get_from_user_id_project(
project_item.inner.id, project_item.inner.id,
current_user.id.into(), current_user.id.into(),
false, false,
@@ -744,7 +746,7 @@ pub async fn organization_projects_add(
) )
})?; })?;
let organization_team_member = let organization_team_member =
database::models::TeamMember::get_from_user_id_organization( database::models::DBTeamMember::get_from_user_id_organization(
organization.id, organization.id,
current_user.id.into(), current_user.id.into(),
false, false,
@@ -814,17 +816,17 @@ pub async fn organization_projects_add(
transaction.commit().await?; transaction.commit().await?;
database::models::User::clear_project_cache( database::models::DBUser::clear_project_cache(
&[current_user.id.into()], &[current_user.id.into()],
&redis, &redis,
) )
.await?; .await?;
database::models::TeamMember::clear_cache( database::models::DBTeamMember::clear_cache(
project_item.inner.team_id, project_item.inner.team_id,
&redis, &redis,
) )
.await?; .await?;
database::models::Project::clear_cache( database::models::DBProject::clear_cache(
project_item.inner.id, project_item.inner.id,
project_item.inner.slug, project_item.inner.slug,
None, None,
@@ -866,17 +868,20 @@ pub async fn organization_projects_remove(
.await? .await?
.1; .1;
let organization = let organization = database::models::DBOrganization::get(
database::models::Organization::get(&organization_id, &**pool, &redis) &organization_id,
.await? &**pool,
.ok_or_else(|| { &redis,
ApiError::InvalidInput( )
"The specified organization does not exist!".to_string(), .await?
) .ok_or_else(|| {
})?; ApiError::InvalidInput(
"The specified organization does not exist!".to_string(),
)
})?;
let project_item = let project_item =
database::models::Project::get(&project_id, &**pool, &redis) database::models::DBProject::get(&project_id, &**pool, &redis)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
@@ -896,7 +901,7 @@ pub async fn organization_projects_remove(
} }
let organization_team_member = let organization_team_member =
database::models::TeamMember::get_from_user_id_organization( database::models::DBTeamMember::get_from_user_id_organization(
organization.id, organization.id,
current_user.id.into(), current_user.id.into(),
false, false,
@@ -916,7 +921,7 @@ pub async fn organization_projects_remove(
.unwrap_or_default(); .unwrap_or_default();
if permissions.contains(OrganizationPermissions::REMOVE_PROJECT) { if permissions.contains(OrganizationPermissions::REMOVE_PROJECT) {
// Now that permissions are confirmed, we confirm the veracity of the new user as an org member // Now that permissions are confirmed, we confirm the veracity of the new user as an org member
database::models::TeamMember::get_from_user_id_organization( database::models::DBTeamMember::get_from_user_id_organization(
organization.id, organization.id,
data.new_owner.into(), data.new_owner.into(),
false, false,
@@ -932,13 +937,14 @@ pub async fn organization_projects_remove(
// Then, we get the team member of the project and that user (if it exists) // Then, we get the team member of the project and that user (if it exists)
// We use the team member get directly // We use the team member get directly
let new_owner = database::models::TeamMember::get_from_user_id_project( let new_owner =
project_item.inner.id, database::models::DBTeamMember::get_from_user_id_project(
data.new_owner.into(), project_item.inner.id,
true, data.new_owner.into(),
&**pool, true,
) &**pool,
.await?; )
.await?;
let mut transaction = pool.begin().await?; let mut transaction = pool.begin().await?;
@@ -951,7 +957,7 @@ pub async fn organization_projects_remove(
&mut transaction, &mut transaction,
) )
.await?; .await?;
let member = TeamMember { let member = DBTeamMember {
id: new_id, id: new_id,
team_id: project_item.inner.team_id, team_id: project_item.inner.team_id,
user_id: data.new_owner.into(), user_id: data.new_owner.into(),
@@ -998,17 +1004,17 @@ pub async fn organization_projects_remove(
.await?; .await?;
transaction.commit().await?; transaction.commit().await?;
database::models::User::clear_project_cache( database::models::DBUser::clear_project_cache(
&[current_user.id.into()], &[current_user.id.into()],
&redis, &redis,
) )
.await?; .await?;
database::models::TeamMember::clear_cache( database::models::DBTeamMember::clear_cache(
project_item.inner.team_id, project_item.inner.team_id,
&redis, &redis,
) )
.await?; .await?;
database::models::Project::clear_cache( database::models::DBProject::clear_cache(
project_item.inner.id, project_item.inner.id,
project_item.inner.slug, project_item.inner.slug,
None, None,
@@ -1052,7 +1058,7 @@ pub async fn organization_icon_edit(
let string = info.into_inner().0; let string = info.into_inner().0;
let organization_item = let organization_item =
database::models::Organization::get(&string, &**pool, &redis) database::models::DBOrganization::get(&string, &**pool, &redis)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
@@ -1061,7 +1067,7 @@ pub async fn organization_icon_edit(
})?; })?;
if !user.role.is_mod() { if !user.role.is_mod() {
let team_member = database::models::TeamMember::get_from_user_id( let team_member = database::models::DBTeamMember::get_from_user_id(
organization_item.team_id, organization_item.team_id,
user.id.into(), user.id.into(),
&**pool, &**pool,
@@ -1125,7 +1131,7 @@ pub async fn organization_icon_edit(
.await?; .await?;
transaction.commit().await?; transaction.commit().await?;
database::models::Organization::clear_cache( database::models::DBOrganization::clear_cache(
organization_item.id, organization_item.id,
Some(organization_item.slug), Some(organization_item.slug),
&redis, &redis,
@@ -1155,7 +1161,7 @@ pub async fn delete_organization_icon(
let string = info.into_inner().0; let string = info.into_inner().0;
let organization_item = let organization_item =
database::models::Organization::get(&string, &**pool, &redis) database::models::DBOrganization::get(&string, &**pool, &redis)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
@@ -1164,7 +1170,7 @@ pub async fn delete_organization_icon(
})?; })?;
if !user.role.is_mod() { if !user.role.is_mod() {
let team_member = database::models::TeamMember::get_from_user_id( let team_member = database::models::DBTeamMember::get_from_user_id(
organization_item.team_id, organization_item.team_id,
user.id.into(), user.id.into(),
&**pool, &**pool,
@@ -1208,7 +1214,7 @@ pub async fn delete_organization_icon(
transaction.commit().await?; transaction.commit().await?;
database::models::Organization::clear_cache( database::models::DBOrganization::clear_cache(
organization_item.id, organization_item.id,
Some(organization_item.slug), Some(organization_item.slug),
&redis, &redis,

View File

@@ -160,7 +160,7 @@ pub async fn paypal_webhook(
transaction.commit().await?; transaction.commit().await?;
crate::database::models::user_item::User::clear_caches( crate::database::models::user_item::DBUser::clear_caches(
&[( &[(
crate::database::models::DBUserId(result.user_id), crate::database::models::DBUserId(result.user_id),
None, None,
@@ -270,7 +270,7 @@ pub async fn tremendous_webhook(
transaction.commit().await?; transaction.commit().await?;
crate::database::models::user_item::User::clear_caches( crate::database::models::user_item::DBUser::clear_caches(
&[( &[(
crate::database::models::DBUserId(result.user_id), crate::database::models::DBUserId(result.user_id),
None, None,
@@ -319,12 +319,12 @@ pub async fn user_payouts(
.1; .1;
let payout_ids = let payout_ids =
crate::database::models::payout_item::Payout::get_all_for_user( crate::database::models::payout_item::DBPayout::get_all_for_user(
user.id.into(), user.id.into(),
&**pool, &**pool,
) )
.await?; .await?;
let payouts = crate::database::models::payout_item::Payout::get_many( let payouts = crate::database::models::payout_item::DBPayout::get_many(
&payout_ids, &payout_ids,
&**pool, &**pool,
) )
@@ -477,7 +477,7 @@ pub async fn create_payout(
} }
let mut payout_item = let mut payout_item =
crate::database::models::payout_item::Payout { crate::database::models::payout_item::DBPayout {
id: payout_id, id: payout_id,
user_id: user.id, user_id: user.id,
created: Utc::now(), created: Utc::now(),
@@ -550,7 +550,7 @@ pub async fn create_payout(
if let Some(email) = user.email { if let Some(email) = user.email {
if user.email_verified { if user.email_verified {
let mut payout_item = let mut payout_item =
crate::database::models::payout_item::Payout { crate::database::models::payout_item::DBPayout {
id: payout_id, id: payout_id,
user_id: user.id, user_id: user.id,
created: Utc::now(), created: Utc::now(),
@@ -633,7 +633,7 @@ pub async fn create_payout(
payout_item.insert(&mut transaction).await?; payout_item.insert(&mut transaction).await?;
transaction.commit().await?; transaction.commit().await?;
crate::database::models::User::clear_caches(&[(user.id, None)], &redis) crate::database::models::DBUser::clear_caches(&[(user.id, None)], &redis)
.await?; .await?;
Ok(HttpResponse::NoContent().finish()) Ok(HttpResponse::NoContent().finish())
@@ -660,7 +660,7 @@ pub async fn cancel_payout(
let id = info.into_inner().0; let id = info.into_inner().0;
let payout = let payout =
crate::database::models::payout_item::Payout::get(id.into(), &**pool) crate::database::models::payout_item::DBPayout::get(id.into(), &**pool)
.await?; .await?;
if let Some(payout) = payout { if let Some(payout) = payout {

View File

@@ -4,7 +4,7 @@ use crate::database::models::loader_fields::{
Loader, LoaderField, LoaderFieldEnumValue, Loader, LoaderField, LoaderFieldEnumValue,
}; };
use crate::database::models::thread_item::ThreadBuilder; use crate::database::models::thread_item::ThreadBuilder;
use crate::database::models::{self, User, image_item}; use crate::database::models::{self, DBUser, image_item};
use crate::database::redis::RedisPool; use crate::database::redis::RedisPool;
use crate::file_hosting::{FileHost, FileHostingError}; use crate::file_hosting::{FileHost, FileHostingError};
use crate::models::error::ApiError; use crate::models::error::ApiError;
@@ -646,7 +646,7 @@ async fn project_create_inner(
let mut members = vec![]; let mut members = vec![];
if let Some(organization_id) = project_create_data.organization_id { if let Some(organization_id) = project_create_data.organization_id {
let org = models::Organization::get_id( let org = models::DBOrganization::get_id(
organization_id.into(), organization_id.into(),
pool, pool,
redis, redis,
@@ -658,7 +658,7 @@ async fn project_create_inner(
) )
})?; })?;
let team_member = models::TeamMember::get_from_user_id( let team_member = models::DBTeamMember::get_from_user_id(
org.team_id, org.team_id,
current_user.id.into(), current_user.id.into(),
pool, pool,
@@ -773,7 +773,7 @@ async fn project_create_inner(
link_urls, link_urls,
gallery_items: gallery_urls gallery_items: gallery_urls
.iter() .iter()
.map(|x| models::project_item::GalleryItem { .map(|x| models::project_item::DBGalleryItem {
image_url: x.url.clone(), image_url: x.url.clone(),
raw_image_url: x.raw_url.clone(), raw_image_url: x.raw_url.clone(),
featured: x.featured, featured: x.featured,
@@ -791,10 +791,10 @@ async fn project_create_inner(
let now = Utc::now(); let now = Utc::now();
let id = project_builder_actual.insert(&mut *transaction).await?; let id = project_builder_actual.insert(&mut *transaction).await?;
User::clear_project_cache(&[current_user.id.into()], redis).await?; DBUser::clear_project_cache(&[current_user.id.into()], redis).await?;
for image_id in project_create_data.uploaded_images { for image_id in project_create_data.uploaded_images {
if let Some(db_image) = image_item::Image::get( if let Some(db_image) = image_item::DBImage::get(
image_id.into(), image_id.into(),
&mut **transaction, &mut **transaction,
redis, redis,
@@ -822,7 +822,8 @@ async fn project_create_inner(
.execute(&mut **transaction) .execute(&mut **transaction)
.await?; .await?;
image_item::Image::clear_cache(image.id.into(), redis).await?; image_item::DBImage::clear_cache(image.id.into(), redis)
.await?;
} else { } else {
return Err(CreateError::InvalidInput(format!( return Err(CreateError::InvalidInput(format!(
"Image {image_id} does not exist" "Image {image_id} does not exist"

View File

@@ -4,9 +4,9 @@ use std::sync::Arc;
use crate::auth::checks::{filter_visible_versions, is_visible_project}; use crate::auth::checks::{filter_visible_versions, is_visible_project};
use crate::auth::{filter_visible_projects, get_user_from_headers}; use crate::auth::{filter_visible_projects, get_user_from_headers};
use crate::database::models::notification_item::NotificationBuilder; use crate::database::models::notification_item::NotificationBuilder;
use crate::database::models::project_item::{GalleryItem, ModCategory}; use crate::database::models::project_item::{DBGalleryItem, DBModCategory};
use crate::database::models::thread_item::ThreadMessageBuilder; use crate::database::models::thread_item::ThreadMessageBuilder;
use crate::database::models::{TeamMember, ids as db_ids, image_item}; use crate::database::models::{DBTeamMember, ids as db_ids, image_item};
use crate::database::redis::RedisPool; use crate::database::redis::RedisPool;
use crate::database::{self, models as db_models}; use crate::database::{self, models as db_models};
use crate::file_hosting::FileHost; use crate::file_hosting::FileHost;
@@ -109,7 +109,7 @@ pub async fn random_projects_get(
.await?; .await?;
let projects_data = let projects_data =
db_models::Project::get_many_ids(&project_ids, &**pool, &redis) db_models::DBProject::get_many_ids(&project_ids, &**pool, &redis)
.await? .await?
.into_iter() .into_iter()
.map(Project::from) .map(Project::from)
@@ -132,7 +132,7 @@ pub async fn projects_get(
) -> Result<HttpResponse, ApiError> { ) -> Result<HttpResponse, ApiError> {
let ids = serde_json::from_str::<Vec<&str>>(&ids.ids)?; let ids = serde_json::from_str::<Vec<&str>>(&ids.ids)?;
let projects_data = let projects_data =
db_models::Project::get_many(&ids, &**pool, &redis).await?; db_models::DBProject::get_many(&ids, &**pool, &redis).await?;
let user_option = get_user_from_headers( let user_option = get_user_from_headers(
&req, &req,
@@ -162,7 +162,7 @@ pub async fn project_get(
let string = info.into_inner().0; let string = info.into_inner().0;
let project_data = let project_data =
db_models::Project::get(&string, &**pool, &redis).await?; db_models::DBProject::get(&string, &**pool, &redis).await?;
let user_option = get_user_from_headers( let user_option = get_user_from_headers(
&req, &req,
&**pool, &**pool,
@@ -268,12 +268,12 @@ pub async fn project_edit(
})?; })?;
let string = info.into_inner().0; let string = info.into_inner().0;
let result = db_models::Project::get(&string, &**pool, &redis).await?; let result = db_models::DBProject::get(&string, &**pool, &redis).await?;
if let Some(project_item) = result { if let Some(project_item) = result {
let id = project_item.inner.id; let id = project_item.inner.id;
let (team_member, organization_team_member) = let (team_member, organization_team_member) =
db_models::TeamMember::get_for_project_permissions( db_models::DBTeamMember::get_for_project_permissions(
&project_item.inner, &project_item.inner,
user.id.into(), user.id.into(),
&**pool, &**pool,
@@ -884,7 +884,7 @@ pub async fn project_edit(
.await?; .await?;
transaction.commit().await?; transaction.commit().await?;
db_models::Project::clear_cache( db_models::DBProject::clear_cache(
project_item.inner.id, project_item.inner.id,
project_item.inner.slug, project_item.inner.slug,
None, None,
@@ -929,7 +929,7 @@ pub async fn edit_project_categories(
let mcategories = category_ids let mcategories = category_ids
.values() .values()
.map(|&category_id| ModCategory { .map(|&category_id| DBModCategory {
project_id, project_id,
category_id, category_id,
is_additional, is_additional,
@@ -937,7 +937,7 @@ pub async fn edit_project_categories(
.collect::<Vec<_>>(); .collect::<Vec<_>>();
mod_categories.extend(mcategories); mod_categories.extend(mcategories);
} }
ModCategory::insert_many(mod_categories, &mut *transaction).await?; DBModCategory::insert_many(mod_categories, &mut *transaction).await?;
Ok(()) Ok(())
} }
@@ -980,7 +980,8 @@ pub async fn project_get_check(
) -> Result<HttpResponse, ApiError> { ) -> Result<HttpResponse, ApiError> {
let slug = info.into_inner().0; let slug = info.into_inner().0;
let project_data = db_models::Project::get(&slug, &**pool, &redis).await?; let project_data =
db_models::DBProject::get(&slug, &**pool, &redis).await?;
if let Some(project) = project_data { if let Some(project) = project_data {
Ok(HttpResponse::Ok().json(json! ({ Ok(HttpResponse::Ok().json(json! ({
@@ -1006,7 +1007,7 @@ pub async fn dependency_list(
) -> Result<HttpResponse, ApiError> { ) -> Result<HttpResponse, ApiError> {
let string = info.into_inner().0; let string = info.into_inner().0;
let result = db_models::Project::get(&string, &**pool, &redis).await?; let result = db_models::DBProject::get(&string, &**pool, &redis).await?;
let user_option = get_user_from_headers( let user_option = get_user_from_headers(
&req, &req,
@@ -1026,7 +1027,7 @@ pub async fn dependency_list(
return Err(ApiError::NotFound); return Err(ApiError::NotFound);
} }
let dependencies = database::Project::get_dependencies( let dependencies = database::DBProject::get_dependencies(
project.inner.id, project.inner.id,
&**pool, &**pool,
&redis, &redis,
@@ -1054,8 +1055,8 @@ pub async fn dependency_list(
.unique() .unique()
.collect::<Vec<db_models::DBVersionId>>(); .collect::<Vec<db_models::DBVersionId>>();
let (projects_result, versions_result) = futures::future::try_join( let (projects_result, versions_result) = futures::future::try_join(
database::Project::get_many_ids(&project_ids, &**pool, &redis), database::DBProject::get_many_ids(&project_ids, &**pool, &redis),
database::Version::get_many(&dep_version_ids, &**pool, &redis), database::DBVersion::get_many(&dep_version_ids, &**pool, &redis),
) )
.await?; .await?;
@@ -1141,7 +1142,8 @@ pub async fn projects_edit(
.collect(); .collect();
let projects_data = let projects_data =
db_models::Project::get_many_ids(&project_ids, &**pool, &redis).await?; db_models::DBProject::get_many_ids(&project_ids, &**pool, &redis)
.await?;
if let Some(id) = project_ids if let Some(id) = project_ids
.iter() .iter()
@@ -1157,7 +1159,7 @@ pub async fn projects_edit(
.iter() .iter()
.map(|x| x.inner.team_id) .map(|x| x.inner.team_id)
.collect::<Vec<db_models::DBTeamId>>(); .collect::<Vec<db_models::DBTeamId>>();
let team_members = db_models::TeamMember::get_from_team_full_many( let team_members = db_models::DBTeamMember::get_from_team_full_many(
&team_ids, &**pool, &redis, &team_ids, &**pool, &redis,
) )
.await?; .await?;
@@ -1166,7 +1168,7 @@ pub async fn projects_edit(
.iter() .iter()
.filter_map(|x| x.inner.organization_id) .filter_map(|x| x.inner.organization_id)
.collect::<Vec<db_models::DBOrganizationId>>(); .collect::<Vec<db_models::DBOrganizationId>>();
let organizations = db_models::Organization::get_many_ids( let organizations = db_models::DBOrganization::get_many_ids(
&organization_ids, &organization_ids,
&**pool, &**pool,
&redis, &redis,
@@ -1178,7 +1180,7 @@ pub async fn projects_edit(
.map(|x| x.team_id) .map(|x| x.team_id)
.collect::<Vec<db_models::DBTeamId>>(); .collect::<Vec<db_models::DBTeamId>>();
let organization_team_members = let organization_team_members =
db_models::TeamMember::get_from_team_full_many( db_models::DBTeamMember::get_from_team_full_many(
&organization_team_ids, &organization_team_ids,
&**pool, &**pool,
&redis, &redis,
@@ -1315,7 +1317,7 @@ pub async fn projects_edit(
} }
} }
db_models::Project::clear_cache( db_models::DBProject::clear_cache(
project.inner.id, project.inner.id,
project.inner.slug, project.inner.slug,
None, None,
@@ -1388,13 +1390,13 @@ pub async fn bulk_edit_project_categories(
)) ))
})? })?
.id; .id;
mod_categories.push(ModCategory { mod_categories.push(DBModCategory {
project_id, project_id,
category_id, category_id,
is_additional, is_additional,
}); });
} }
ModCategory::insert_many(mod_categories, &mut *transaction).await?; DBModCategory::insert_many(mod_categories, &mut *transaction).await?;
} }
Ok(()) Ok(())
@@ -1427,7 +1429,7 @@ pub async fn project_icon_edit(
.1; .1;
let string = info.into_inner().0; let string = info.into_inner().0;
let project_item = db_models::Project::get(&string, &**pool, &redis) let project_item = db_models::DBProject::get(&string, &**pool, &redis)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
@@ -1437,7 +1439,7 @@ pub async fn project_icon_edit(
if !user.role.is_mod() { if !user.role.is_mod() {
let (team_member, organization_team_member) = let (team_member, organization_team_member) =
db_models::TeamMember::get_for_project_permissions( db_models::DBTeamMember::get_for_project_permissions(
&project_item.inner, &project_item.inner,
user.id.into(), user.id.into(),
&**pool, &**pool,
@@ -1508,7 +1510,7 @@ pub async fn project_icon_edit(
.await?; .await?;
transaction.commit().await?; transaction.commit().await?;
db_models::Project::clear_cache( db_models::DBProject::clear_cache(
project_item.inner.id, project_item.inner.id,
project_item.inner.slug, project_item.inner.slug,
None, None,
@@ -1538,7 +1540,7 @@ pub async fn delete_project_icon(
.1; .1;
let string = info.into_inner().0; let string = info.into_inner().0;
let project_item = db_models::Project::get(&string, &**pool, &redis) let project_item = db_models::DBProject::get(&string, &**pool, &redis)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
@@ -1548,7 +1550,7 @@ pub async fn delete_project_icon(
if !user.role.is_mod() { if !user.role.is_mod() {
let (team_member, organization_team_member) = let (team_member, organization_team_member) =
db_models::TeamMember::get_for_project_permissions( db_models::DBTeamMember::get_for_project_permissions(
&project_item.inner, &project_item.inner,
user.id.into(), user.id.into(),
&**pool, &**pool,
@@ -1597,7 +1599,7 @@ pub async fn delete_project_icon(
.await?; .await?;
transaction.commit().await?; transaction.commit().await?;
db_models::Project::clear_cache( db_models::DBProject::clear_cache(
project_item.inner.id, project_item.inner.id,
project_item.inner.slug, project_item.inner.slug,
None, None,
@@ -1645,7 +1647,7 @@ pub async fn add_gallery_item(
.1; .1;
let string = info.into_inner().0; let string = info.into_inner().0;
let project_item = db_models::Project::get(&string, &**pool, &redis) let project_item = db_models::DBProject::get(&string, &**pool, &redis)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
@@ -1662,7 +1664,7 @@ pub async fn add_gallery_item(
if !user.role.is_admin() { if !user.role.is_admin() {
let (team_member, organization_team_member) = let (team_member, organization_team_member) =
db_models::TeamMember::get_for_project_permissions( db_models::DBTeamMember::get_for_project_permissions(
&project_item.inner, &project_item.inner,
user.id.into(), user.id.into(),
&**pool, &**pool,
@@ -1735,7 +1737,7 @@ pub async fn add_gallery_item(
.await?; .await?;
} }
let gallery_item = vec![db_models::project_item::GalleryItem { let gallery_item = vec![db_models::project_item::DBGalleryItem {
image_url: upload_result.url, image_url: upload_result.url,
raw_image_url: upload_result.raw_url, raw_image_url: upload_result.raw_url,
featured: item.featured, featured: item.featured,
@@ -1744,7 +1746,7 @@ pub async fn add_gallery_item(
created: Utc::now(), created: Utc::now(),
ordering: item.ordering.unwrap_or(0), ordering: item.ordering.unwrap_or(0),
}]; }];
GalleryItem::insert_many( DBGalleryItem::insert_many(
gallery_item, gallery_item,
project_item.inner.id, project_item.inner.id,
&mut transaction, &mut transaction,
@@ -1752,7 +1754,7 @@ pub async fn add_gallery_item(
.await?; .await?;
transaction.commit().await?; transaction.commit().await?;
db_models::Project::clear_cache( db_models::DBProject::clear_cache(
project_item.inner.id, project_item.inner.id,
project_item.inner.slug, project_item.inner.slug,
None, None,
@@ -1822,7 +1824,7 @@ pub async fn edit_gallery_item(
)) ))
})?; })?;
let project_item = db_models::Project::get_id( let project_item = db_models::DBProject::get_id(
database::models::DBProjectId(result.mod_id), database::models::DBProjectId(result.mod_id),
&**pool, &**pool,
&redis, &redis,
@@ -1836,7 +1838,7 @@ pub async fn edit_gallery_item(
if !user.role.is_mod() { if !user.role.is_mod() {
let (team_member, organization_team_member) = let (team_member, organization_team_member) =
db_models::TeamMember::get_for_project_permissions( db_models::DBTeamMember::get_for_project_permissions(
&project_item.inner, &project_item.inner,
user.id.into(), user.id.into(),
&**pool, &**pool,
@@ -1935,7 +1937,7 @@ pub async fn edit_gallery_item(
transaction.commit().await?; transaction.commit().await?;
db_models::Project::clear_cache( db_models::DBProject::clear_cache(
project_item.inner.id, project_item.inner.id,
project_item.inner.slug, project_item.inner.slug,
None, None,
@@ -1985,7 +1987,7 @@ pub async fn delete_gallery_item(
)) ))
})?; })?;
let project_item = db_models::Project::get_id( let project_item = db_models::DBProject::get_id(
database::models::DBProjectId(item.mod_id), database::models::DBProjectId(item.mod_id),
&**pool, &**pool,
&redis, &redis,
@@ -1999,7 +2001,7 @@ pub async fn delete_gallery_item(
if !user.role.is_mod() { if !user.role.is_mod() {
let (team_member, organization_team_member) = let (team_member, organization_team_member) =
db_models::TeamMember::get_for_project_permissions( db_models::DBTeamMember::get_for_project_permissions(
&project_item.inner, &project_item.inner,
user.id.into(), user.id.into(),
&**pool, &**pool,
@@ -2049,7 +2051,7 @@ pub async fn delete_gallery_item(
transaction.commit().await?; transaction.commit().await?;
db_models::Project::clear_cache( db_models::DBProject::clear_cache(
project_item.inner.id, project_item.inner.id,
project_item.inner.slug, project_item.inner.slug,
None, None,
@@ -2079,7 +2081,7 @@ pub async fn project_delete(
.1; .1;
let string = info.into_inner().0; let string = info.into_inner().0;
let project = db_models::Project::get(&string, &**pool, &redis) let project = db_models::DBProject::get(&string, &**pool, &redis)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
@@ -2089,7 +2091,7 @@ pub async fn project_delete(
if !user.role.is_admin() { if !user.role.is_admin() {
let (team_member, organization_team_member) = let (team_member, organization_team_member) =
db_models::TeamMember::get_for_project_permissions( db_models::DBTeamMember::get_for_project_permissions(
&project.inner, &project.inner,
user.id.into(), user.id.into(),
&**pool, &**pool,
@@ -2122,9 +2124,10 @@ pub async fn project_delete(
project_id: Some(project.inner.id.into()), project_id: Some(project.inner.id.into()),
}; };
let uploaded_images = let uploaded_images =
db_models::Image::get_many_contexted(context, &mut transaction).await?; db_models::DBImage::get_many_contexted(context, &mut transaction)
.await?;
for image in uploaded_images { for image in uploaded_images {
image_item::Image::remove(image.id, &mut transaction, &redis).await?; image_item::DBImage::remove(image.id, &mut transaction, &redis).await?;
} }
sqlx::query!( sqlx::query!(
@@ -2137,9 +2140,12 @@ pub async fn project_delete(
.execute(&mut *transaction) .execute(&mut *transaction)
.await?; .await?;
let result = let result = db_models::DBProject::remove(
db_models::Project::remove(project.inner.id, &mut transaction, &redis) project.inner.id,
.await?; &mut transaction,
&redis,
)
.await?;
transaction.commit().await?; transaction.commit().await?;
@@ -2178,7 +2184,7 @@ pub async fn project_follow(
.1; .1;
let string = info.into_inner().0; let string = info.into_inner().0;
let result = db_models::Project::get(&string, &**pool, &redis) let result = db_models::DBProject::get(&string, &**pool, &redis)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
@@ -2258,7 +2264,7 @@ pub async fn project_unfollow(
.1; .1;
let string = info.into_inner().0; let string = info.into_inner().0;
let result = db_models::Project::get(&string, &**pool, &redis) let result = db_models::DBProject::get(&string, &**pool, &redis)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
@@ -2336,7 +2342,7 @@ pub async fn project_get_organization(
let user_id = current_user.as_ref().map(|x| x.id.into()); let user_id = current_user.as_ref().map(|x| x.id.into());
let string = info.into_inner().0; let string = info.into_inner().0;
let result = db_models::Project::get(&string, &**pool, &redis) let result = db_models::DBProject::get(&string, &**pool, &redis)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
@@ -2350,7 +2356,7 @@ pub async fn project_get_organization(
)) ))
} else if let Some(organization_id) = result.inner.organization_id { } else if let Some(organization_id) = result.inner.organization_id {
let organization = let organization =
db_models::Organization::get_id(organization_id, &**pool, &redis) db_models::DBOrganization::get_id(organization_id, &**pool, &redis)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
@@ -2358,14 +2364,14 @@ pub async fn project_get_organization(
) )
})?; })?;
let members_data = TeamMember::get_from_team_full( let members_data = DBTeamMember::get_from_team_full(
organization.team_id, organization.team_id,
&**pool, &**pool,
&redis, &redis,
) )
.await?; .await?;
let users = crate::database::models::User::get_many_ids( let users = crate::database::models::DBUser::get_many_ids(
&members_data.iter().map(|x| x.user_id).collect::<Vec<_>>(), &members_data.iter().map(|x| x.user_id).collect::<Vec<_>>(),
&**pool, &**pool,
&redis, &redis,

View File

@@ -87,7 +87,7 @@ pub async fn report_create(
)) ))
})?; })?;
let mut report = crate::database::models::report_item::Report { let mut report = crate::database::models::report_item::DBReport {
id, id,
report_type_id: report_type, report_type_id: report_type,
project_id: None, project_id: None,
@@ -171,7 +171,7 @@ pub async fn report_create(
for image_id in new_report.uploaded_images { for image_id in new_report.uploaded_images {
if let Some(db_image) = if let Some(db_image) =
image_item::Image::get(image_id.into(), &mut *transaction, &redis) image_item::DBImage::get(image_id.into(), &mut *transaction, &redis)
.await? .await?
{ {
let image: Image = db_image.into(); let image: Image = db_image.into();
@@ -195,7 +195,7 @@ pub async fn report_create(
.execute(&mut *transaction) .execute(&mut *transaction)
.await?; .await?;
image_item::Image::clear_cache(image.id.into(), &redis).await?; image_item::DBImage::clear_cache(image.id.into(), &redis).await?;
} else { } else {
return Err(ApiError::InvalidInput(format!( return Err(ApiError::InvalidInput(format!(
"Image {image_id} could not be found" "Image {image_id} could not be found"
@@ -292,11 +292,12 @@ pub async fn reports(
.await? .await?
}; };
let query_reports = crate::database::models::report_item::Report::get_many( let query_reports =
&report_ids, crate::database::models::report_item::DBReport::get_many(
&**pool, &report_ids,
) &**pool,
.await?; )
.await?;
let mut reports: Vec<Report> = Vec::new(); let mut reports: Vec<Report> = Vec::new();
@@ -325,11 +326,12 @@ pub async fn reports_get(
.map(|x| x.into()) .map(|x| x.into())
.collect(); .collect();
let reports_data = crate::database::models::report_item::Report::get_many( let reports_data =
&report_ids, crate::database::models::report_item::DBReport::get_many(
&**pool, &report_ids,
) &**pool,
.await?; )
.await?;
let user = get_user_from_headers( let user = get_user_from_headers(
&req, &req,
@@ -369,7 +371,8 @@ pub async fn report_get(
let id = info.into_inner().0.into(); let id = info.into_inner().0.into();
let report = let report =
crate::database::models::report_item::Report::get(id, &**pool).await?; crate::database::models::report_item::DBReport::get(id, &**pool)
.await?;
if let Some(report) = report { if let Some(report) = report {
if !user.role.is_mod() && report.reporter != user.id.into() { if !user.role.is_mod() && report.reporter != user.id.into() {
@@ -410,7 +413,8 @@ pub async fn report_edit(
let id = info.into_inner().0.into(); let id = info.into_inner().0.into();
let report = let report =
crate::database::models::report_item::Report::get(id, &**pool).await?; crate::database::models::report_item::DBReport::get(id, &**pool)
.await?;
if let Some(report) = report { if let Some(report) = report {
if !user.role.is_mod() && report.reporter != user.id.into() { if !user.role.is_mod() && report.reporter != user.id.into() {
@@ -512,14 +516,16 @@ pub async fn report_delete(
let context = ImageContext::Report { let context = ImageContext::Report {
report_id: Some(id), report_id: Some(id),
}; };
let uploaded_images = let uploaded_images = database::models::DBImage::get_many_contexted(
database::models::Image::get_many_contexted(context, &mut transaction) context,
.await?; &mut transaction,
)
.await?;
for image in uploaded_images { for image in uploaded_images {
image_item::Image::remove(image.id, &mut transaction, &redis).await?; image_item::DBImage::remove(image.id, &mut transaction, &redis).await?;
} }
let result = crate::database::models::report_item::Report::remove_full( let result = crate::database::models::report_item::DBReport::remove_full(
id.into(), id.into(),
&mut transaction, &mut transaction,
) )

View File

@@ -1,9 +1,9 @@
use crate::auth::checks::is_visible_project; use crate::auth::checks::is_visible_project;
use crate::auth::get_user_from_headers; use crate::auth::get_user_from_headers;
use crate::database::Project; use crate::database::DBProject;
use crate::database::models::notification_item::NotificationBuilder; use crate::database::models::notification_item::NotificationBuilder;
use crate::database::models::team_item::TeamAssociationId; use crate::database::models::team_item::TeamAssociationId;
use crate::database::models::{Organization, Team, TeamMember, User}; use crate::database::models::{DBOrganization, DBTeam, DBTeamMember, DBUser};
use crate::database::redis::RedisPool; use crate::database::redis::RedisPool;
use crate::models::ids::TeamId; use crate::models::ids::TeamId;
use crate::models::notifications::NotificationBody; use crate::models::notifications::NotificationBody;
@@ -48,7 +48,8 @@ pub async fn team_members_get_project(
) -> Result<HttpResponse, ApiError> { ) -> Result<HttpResponse, ApiError> {
let string = info.into_inner().0; let string = info.into_inner().0;
let project_data = let project_data =
crate::database::models::Project::get(&string, &**pool, &redis).await?; crate::database::models::DBProject::get(&string, &**pool, &redis)
.await?;
if let Some(project) = project_data { if let Some(project) = project_data {
let current_user = get_user_from_headers( let current_user = get_user_from_headers(
@@ -67,13 +68,13 @@ pub async fn team_members_get_project(
{ {
return Err(ApiError::NotFound); return Err(ApiError::NotFound);
} }
let members_data = TeamMember::get_from_team_full( let members_data = DBTeamMember::get_from_team_full(
project.inner.team_id, project.inner.team_id,
&**pool, &**pool,
&redis, &redis,
) )
.await?; .await?;
let users = User::get_many_ids( let users = DBUser::get_many_ids(
&members_data.iter().map(|x| x.user_id).collect::<Vec<_>>(), &members_data.iter().map(|x| x.user_id).collect::<Vec<_>>(),
&**pool, &**pool,
&redis, &redis,
@@ -83,7 +84,7 @@ pub async fn team_members_get_project(
let user_id = current_user.as_ref().map(|x| x.id.into()); let user_id = current_user.as_ref().map(|x| x.id.into());
let logged_in = if let Some(user_id) = user_id { let logged_in = if let Some(user_id) = user_id {
let (team_member, organization_team_member) = let (team_member, organization_team_member) =
TeamMember::get_for_project_permissions( DBTeamMember::get_for_project_permissions(
&project.inner, &project.inner,
user_id, user_id,
&**pool, &**pool,
@@ -132,7 +133,7 @@ pub async fn team_members_get_organization(
) -> Result<HttpResponse, ApiError> { ) -> Result<HttpResponse, ApiError> {
let string = info.into_inner().0; let string = info.into_inner().0;
let organization_data = let organization_data =
crate::database::models::Organization::get(&string, &**pool, &redis) crate::database::models::DBOrganization::get(&string, &**pool, &redis)
.await?; .await?;
if let Some(organization) = organization_data { if let Some(organization) = organization_data {
@@ -147,13 +148,13 @@ pub async fn team_members_get_organization(
.map(|x| x.1) .map(|x| x.1)
.ok(); .ok();
let members_data = TeamMember::get_from_team_full( let members_data = DBTeamMember::get_from_team_full(
organization.team_id, organization.team_id,
&**pool, &**pool,
&redis, &redis,
) )
.await?; .await?;
let users = crate::database::models::User::get_many_ids( let users = crate::database::models::DBUser::get_many_ids(
&members_data.iter().map(|x| x.user_id).collect::<Vec<_>>(), &members_data.iter().map(|x| x.user_id).collect::<Vec<_>>(),
&**pool, &**pool,
&redis, &redis,
@@ -208,8 +209,8 @@ pub async fn team_members_get(
) -> Result<HttpResponse, ApiError> { ) -> Result<HttpResponse, ApiError> {
let id = info.into_inner().0; let id = info.into_inner().0;
let members_data = let members_data =
TeamMember::get_from_team_full(id.into(), &**pool, &redis).await?; DBTeamMember::get_from_team_full(id.into(), &**pool, &redis).await?;
let users = crate::database::models::User::get_many_ids( let users = crate::database::models::DBUser::get_many_ids(
&members_data.iter().map(|x| x.user_id).collect::<Vec<_>>(), &members_data.iter().map(|x| x.user_id).collect::<Vec<_>>(),
&**pool, &**pool,
&redis, &redis,
@@ -279,8 +280,9 @@ pub async fn teams_get(
.collect::<Vec<crate::database::models::ids::DBTeamId>>(); .collect::<Vec<crate::database::models::ids::DBTeamId>>();
let teams_data = let teams_data =
TeamMember::get_from_team_full_many(&team_ids, &**pool, &redis).await?; DBTeamMember::get_from_team_full_many(&team_ids, &**pool, &redis)
let users = crate::database::models::User::get_many_ids( .await?;
let users = crate::database::models::DBUser::get_many_ids(
&teams_data.iter().map(|x| x.user_id).collect::<Vec<_>>(), &teams_data.iter().map(|x| x.user_id).collect::<Vec<_>>(),
&**pool, &**pool,
&redis, &redis,
@@ -351,7 +353,7 @@ pub async fn join_team(
.await? .await?
.1; .1;
let member = TeamMember::get_from_user_id_pending( let member = DBTeamMember::get_from_user_id_pending(
team_id, team_id,
current_user.id.into(), current_user.id.into(),
&**pool, &**pool,
@@ -367,7 +369,7 @@ pub async fn join_team(
let mut transaction = pool.begin().await?; let mut transaction = pool.begin().await?;
// Edit Team Member to set Accepted to True // Edit Team Member to set Accepted to True
TeamMember::edit_team_member( DBTeamMember::edit_team_member(
team_id, team_id,
current_user.id.into(), current_user.id.into(),
None, None,
@@ -383,8 +385,8 @@ pub async fn join_team(
transaction.commit().await?; transaction.commit().await?;
User::clear_project_cache(&[current_user.id.into()], &redis).await?; DBUser::clear_project_cache(&[current_user.id.into()], &redis).await?;
TeamMember::clear_cache(team_id, &redis).await?; DBTeamMember::clear_cache(team_id, &redis).await?;
} else { } else {
return Err(ApiError::InvalidInput( return Err(ApiError::InvalidInput(
"There is no pending request from this team".to_string(), "There is no pending request from this team".to_string(),
@@ -439,27 +441,30 @@ pub async fn add_team_member(
) )
.await? .await?
.1; .1;
let team_association = Team::get_association(team_id, &**pool) let team_association = DBTeam::get_association(team_id, &**pool)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
"The team specified does not exist".to_string(), "The team specified does not exist".to_string(),
) )
})?; })?;
let member = let member = DBTeamMember::get_from_user_id(
TeamMember::get_from_user_id(team_id, current_user.id.into(), &**pool) team_id,
.await?; current_user.id.into(),
&**pool,
)
.await?;
match team_association { match team_association {
// If team is associated with a project, check if they have permissions to invite users to that project // If team is associated with a project, check if they have permissions to invite users to that project
TeamAssociationId::Project(pid) => { TeamAssociationId::Project(pid) => {
let organization = let organization =
Organization::get_associated_organization_project_id( DBOrganization::get_associated_organization_project_id(
pid, &**pool, pid, &**pool,
) )
.await?; .await?;
let organization_team_member = let organization_team_member =
if let Some(organization) = &organization { if let Some(organization) = &organization {
TeamMember::get_from_user_id( DBTeamMember::get_from_user_id(
organization.team_id, organization.team_id,
current_user.id.into(), current_user.id.into(),
&**pool, &**pool,
@@ -537,7 +542,7 @@ pub async fn add_team_member(
)); ));
} }
let request = TeamMember::get_from_user_id_pending( let request = DBTeamMember::get_from_user_id_pending(
team_id, team_id,
new_member.user_id.into(), new_member.user_id.into(),
&**pool, &**pool,
@@ -556,7 +561,7 @@ pub async fn add_team_member(
)); ));
} }
} }
let new_user = crate::database::models::User::get_id( let new_user = crate::database::models::DBUser::get_id(
new_member.user_id.into(), new_member.user_id.into(),
&**pool, &**pool,
&redis, &redis,
@@ -570,11 +575,13 @@ pub async fn add_team_member(
if let TeamAssociationId::Project(pid) = team_association { if let TeamAssociationId::Project(pid) = team_association {
// We cannot add the owner to a project team in their own org // We cannot add the owner to a project team in their own org
let organization = let organization =
Organization::get_associated_organization_project_id(pid, &**pool) DBOrganization::get_associated_organization_project_id(
.await?; pid, &**pool,
)
.await?;
let new_user_organization_team_member = let new_user_organization_team_member =
if let Some(organization) = &organization { if let Some(organization) = &organization {
TeamMember::get_from_user_id( DBTeamMember::get_from_user_id(
organization.team_id, organization.team_id,
new_user.id, new_user.id,
&**pool, &**pool,
@@ -607,7 +614,7 @@ pub async fn add_team_member(
let new_id = let new_id =
crate::database::models::ids::generate_team_member_id(&mut transaction) crate::database::models::ids::generate_team_member_id(&mut transaction)
.await?; .await?;
TeamMember { DBTeamMember {
id: new_id, id: new_id,
team_id, team_id,
user_id: new_member.user_id.into(), user_id: new_member.user_id.into(),
@@ -653,8 +660,8 @@ pub async fn add_team_member(
} }
transaction.commit().await?; transaction.commit().await?;
TeamMember::clear_cache(team_id, &redis).await?; DBTeamMember::clear_cache(team_id, &redis).await?;
User::clear_project_cache(&[new_member.user_id.into()], &redis).await?; DBUser::clear_project_cache(&[new_member.user_id.into()], &redis).await?;
Ok(HttpResponse::NoContent().body("")) Ok(HttpResponse::NoContent().body(""))
} }
@@ -691,16 +698,16 @@ pub async fn edit_team_member(
.1; .1;
let team_association = let team_association =
Team::get_association(id, &**pool).await?.ok_or_else(|| { DBTeam::get_association(id, &**pool).await?.ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
"The team specified does not exist".to_string(), "The team specified does not exist".to_string(),
) )
})?; })?;
let member = let member =
TeamMember::get_from_user_id(id, current_user.id.into(), &**pool) DBTeamMember::get_from_user_id(id, current_user.id.into(), &**pool)
.await?; .await?;
let edit_member_db = let edit_member_db =
TeamMember::get_from_user_id_pending(id, user_id, &**pool) DBTeamMember::get_from_user_id_pending(id, user_id, &**pool)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::CustomAuthentication( ApiError::CustomAuthentication(
@@ -723,13 +730,13 @@ pub async fn edit_team_member(
match team_association { match team_association {
TeamAssociationId::Project(project_id) => { TeamAssociationId::Project(project_id) => {
let organization = let organization =
Organization::get_associated_organization_project_id( DBOrganization::get_associated_organization_project_id(
project_id, &**pool, project_id, &**pool,
) )
.await?; .await?;
let organization_team_member = let organization_team_member =
if let Some(organization) = &organization { if let Some(organization) = &organization {
TeamMember::get_from_user_id( DBTeamMember::get_from_user_id(
organization.team_id, organization.team_id,
current_user.id.into(), current_user.id.into(),
&**pool, &**pool,
@@ -831,7 +838,7 @@ pub async fn edit_team_member(
} }
} }
TeamMember::edit_team_member( DBTeamMember::edit_team_member(
id, id,
user_id, user_id,
edit_member.permissions, edit_member.permissions,
@@ -846,7 +853,7 @@ pub async fn edit_team_member(
.await?; .await?;
transaction.commit().await?; transaction.commit().await?;
TeamMember::clear_cache(id, &redis).await?; DBTeamMember::clear_cache(id, &redis).await?;
Ok(HttpResponse::NoContent().body("")) Ok(HttpResponse::NoContent().body(""))
} }
@@ -879,9 +886,10 @@ pub async fn transfer_ownership(
// Forbid transferring ownership of a project team that is owned by an organization // Forbid transferring ownership of a project team that is owned by an organization
// These are owned by the organization owner, and must be removed from the organization first // These are owned by the organization owner, and must be removed from the organization first
// There shouldnt be an ownr on these projects in these cases, but just in case. // There shouldnt be an ownr on these projects in these cases, but just in case.
let team_association_id = Team::get_association(id.into(), &**pool).await?; let team_association_id =
DBTeam::get_association(id.into(), &**pool).await?;
if let Some(TeamAssociationId::Project(pid)) = team_association_id { if let Some(TeamAssociationId::Project(pid)) = team_association_id {
let result = Project::get_id(pid, &**pool, &redis).await?; let result = DBProject::get_id(pid, &**pool, &redis).await?;
if let Some(project_item) = result { if let Some(project_item) = result {
if project_item.inner.organization_id.is_some() { if project_item.inner.organization_id.is_some() {
return Err(ApiError::InvalidInput( return Err(ApiError::InvalidInput(
@@ -893,7 +901,7 @@ pub async fn transfer_ownership(
} }
if !current_user.role.is_admin() { if !current_user.role.is_admin() {
let member = TeamMember::get_from_user_id( let member = DBTeamMember::get_from_user_id(
id.into(), id.into(),
current_user.id.into(), current_user.id.into(),
&**pool, &**pool,
@@ -914,7 +922,7 @@ pub async fn transfer_ownership(
} }
} }
let new_member = TeamMember::get_from_user_id( let new_member = DBTeamMember::get_from_user_id(
id.into(), id.into(),
new_owner.user_id.into(), new_owner.user_id.into(),
&**pool, &**pool,
@@ -936,12 +944,12 @@ pub async fn transfer_ownership(
// The following are the only places new_is_owner is modified. // The following are the only places new_is_owner is modified.
if let Some(former_owner) = if let Some(former_owner) =
TeamMember::get_from_team_full(id.into(), &**pool, &redis) DBTeamMember::get_from_team_full(id.into(), &**pool, &redis)
.await? .await?
.into_iter() .into_iter()
.find(|x| x.is_owner) .find(|x| x.is_owner)
{ {
TeamMember::edit_team_member( DBTeamMember::edit_team_member(
id.into(), id.into(),
former_owner.user_id, former_owner.user_id,
None, None,
@@ -956,7 +964,7 @@ pub async fn transfer_ownership(
.await?; .await?;
} }
TeamMember::edit_team_member( DBTeamMember::edit_team_member(
id.into(), id.into(),
new_owner.user_id.into(), new_owner.user_id.into(),
Some(ProjectPermissions::all()), Some(ProjectPermissions::all()),
@@ -1004,7 +1012,7 @@ pub async fn transfer_ownership(
// If the owner of the organization is a member of the project, remove them // If the owner of the organization is a member of the project, remove them
for team_id in team_ids.iter() { for team_id in team_ids.iter() {
TeamMember::delete( DBTeamMember::delete(
*team_id, *team_id,
new_owner.user_id.into(), new_owner.user_id.into(),
&mut transaction, &mut transaction,
@@ -1018,9 +1026,9 @@ pub async fn transfer_ownership(
}; };
transaction.commit().await?; transaction.commit().await?;
TeamMember::clear_cache(id.into(), &redis).await?; DBTeamMember::clear_cache(id.into(), &redis).await?;
for team_id in project_teams_edited { for team_id in project_teams_edited {
TeamMember::clear_cache(team_id, &redis).await?; DBTeamMember::clear_cache(team_id, &redis).await?;
} }
Ok(HttpResponse::NoContent().body("")) Ok(HttpResponse::NoContent().body(""))
@@ -1048,17 +1056,17 @@ pub async fn remove_team_member(
.1; .1;
let team_association = let team_association =
Team::get_association(id, &**pool).await?.ok_or_else(|| { DBTeam::get_association(id, &**pool).await?.ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
"The team specified does not exist".to_string(), "The team specified does not exist".to_string(),
) )
})?; })?;
let member = let member =
TeamMember::get_from_user_id(id, current_user.id.into(), &**pool) DBTeamMember::get_from_user_id(id, current_user.id.into(), &**pool)
.await?; .await?;
let delete_member = let delete_member =
TeamMember::get_from_user_id_pending(id, user_id, &**pool).await?; DBTeamMember::get_from_user_id_pending(id, user_id, &**pool).await?;
if let Some(delete_member) = delete_member { if let Some(delete_member) = delete_member {
if delete_member.is_owner { if delete_member.is_owner {
@@ -1074,13 +1082,13 @@ pub async fn remove_team_member(
match team_association { match team_association {
TeamAssociationId::Project(pid) => { TeamAssociationId::Project(pid) => {
let organization = let organization =
Organization::get_associated_organization_project_id( DBOrganization::get_associated_organization_project_id(
pid, &**pool, pid, &**pool,
) )
.await?; .await?;
let organization_team_member = let organization_team_member =
if let Some(organization) = &organization { if let Some(organization) = &organization {
TeamMember::get_from_user_id( DBTeamMember::get_from_user_id(
organization.team_id, organization.team_id,
current_user.id.into(), current_user.id.into(),
&**pool, &**pool,
@@ -1105,7 +1113,7 @@ pub async fn remove_team_member(
.contains(ProjectPermissions::REMOVE_MEMBER) .contains(ProjectPermissions::REMOVE_MEMBER)
// true as if the permission exists, but the member does not, they are part of an org // true as if the permission exists, but the member does not, they are part of an org
{ {
TeamMember::delete(id, user_id, &mut transaction) DBTeamMember::delete(id, user_id, &mut transaction)
.await?; .await?;
} else { } else {
return Err(ApiError::CustomAuthentication( return Err(ApiError::CustomAuthentication(
@@ -1121,7 +1129,7 @@ pub async fn remove_team_member(
// This is a pending invite rather than a member, so the // This is a pending invite rather than a member, so the
// user being invited or team members with the MANAGE_INVITES // user being invited or team members with the MANAGE_INVITES
// permission can remove it. // permission can remove it.
TeamMember::delete(id, user_id, &mut transaction).await?; DBTeamMember::delete(id, user_id, &mut transaction).await?;
} else { } else {
return Err(ApiError::CustomAuthentication( return Err(ApiError::CustomAuthentication(
"You do not have permission to cancel a team invite" "You do not have permission to cancel a team invite"
@@ -1144,7 +1152,7 @@ pub async fn remove_team_member(
|| organization_permissions || organization_permissions
.contains(OrganizationPermissions::REMOVE_MEMBER) .contains(OrganizationPermissions::REMOVE_MEMBER)
{ {
TeamMember::delete(id, user_id, &mut transaction) DBTeamMember::delete(id, user_id, &mut transaction)
.await?; .await?;
} else { } else {
return Err(ApiError::CustomAuthentication( return Err(ApiError::CustomAuthentication(
@@ -1160,7 +1168,7 @@ pub async fn remove_team_member(
// This is a pending invite rather than a member, so the // This is a pending invite rather than a member, so the
// user being invited or team members with the MANAGE_INVITES // user being invited or team members with the MANAGE_INVITES
// permission can remove it. // permission can remove it.
TeamMember::delete(id, user_id, &mut transaction).await?; DBTeamMember::delete(id, user_id, &mut transaction).await?;
} else { } else {
return Err(ApiError::CustomAuthentication( return Err(ApiError::CustomAuthentication(
"You do not have permission to cancel an organization invite".to_string(), "You do not have permission to cancel an organization invite".to_string(),
@@ -1171,8 +1179,8 @@ pub async fn remove_team_member(
transaction.commit().await?; transaction.commit().await?;
TeamMember::clear_cache(id, &redis).await?; DBTeamMember::clear_cache(id, &redis).await?;
User::clear_project_cache(&[delete_member.user_id], &redis).await?; DBUser::clear_project_cache(&[delete_member.user_id], &redis).await?;
Ok(HttpResponse::NoContent().body("")) Ok(HttpResponse::NoContent().body(""))
} else { } else {

View File

@@ -34,7 +34,7 @@ pub fn config(cfg: &mut web::ServiceConfig) {
} }
pub async fn is_authorized_thread( pub async fn is_authorized_thread(
thread: &database::models::Thread, thread: &database::models::DBThread,
user: &User, user: &User,
pool: &PgPool, pool: &PgPool,
) -> Result<bool, ApiError> { ) -> Result<bool, ApiError> {
@@ -94,7 +94,7 @@ pub async fn is_authorized_thread(
} }
pub async fn filter_authorized_threads( pub async fn filter_authorized_threads(
threads: Vec<database::models::Thread>, threads: Vec<database::models::DBThread>,
user: &User, user: &User,
pool: &web::Data<PgPool>, pool: &web::Data<PgPool>,
redis: &RedisPool, redis: &RedisPool,
@@ -230,7 +230,7 @@ pub async fn filter_authorized_threads(
); );
let users: Vec<User> = let users: Vec<User> =
database::models::User::get_many_ids(&user_ids, &***pool, redis) database::models::DBUser::get_many_ids(&user_ids, &***pool, redis)
.await? .await?
.into_iter() .into_iter()
.map(From::from) .map(From::from)
@@ -278,7 +278,7 @@ pub async fn thread_get(
) -> Result<HttpResponse, ApiError> { ) -> Result<HttpResponse, ApiError> {
let string = info.into_inner().0.into(); let string = info.into_inner().0.into();
let thread_data = database::models::Thread::get(string, &**pool).await?; let thread_data = database::models::DBThread::get(string, &**pool).await?;
let user = get_user_from_headers( let user = get_user_from_headers(
&req, &req,
@@ -308,12 +308,13 @@ pub async fn thread_get(
.collect::<Vec<_>>(), .collect::<Vec<_>>(),
); );
let users: Vec<User> = let users: Vec<User> = database::models::DBUser::get_many_ids(
database::models::User::get_many_ids(authors, &**pool, &redis) authors, &**pool, &redis,
.await? )
.into_iter() .await?
.map(From::from) .into_iter()
.collect(); .map(From::from)
.collect();
return Ok( return Ok(
HttpResponse::Ok().json(Thread::from(data, users, &user)) HttpResponse::Ok().json(Thread::from(data, users, &user))
@@ -352,7 +353,7 @@ pub async fn threads_get(
.collect(); .collect();
let threads_data = let threads_data =
database::models::Thread::get_many(&thread_ids, &**pool).await?; database::models::DBThread::get_many(&thread_ids, &**pool).await?;
let threads = let threads =
filter_authorized_threads(threads_data, &user, &pool, &redis).await?; filter_authorized_threads(threads_data, &user, &pool, &redis).await?;
@@ -405,7 +406,7 @@ pub async fn thread_send_message(
} }
if let Some(replying_to) = replying_to { if let Some(replying_to) = replying_to {
let thread_message = database::models::ThreadMessage::get( let thread_message = database::models::DBThreadMessage::get(
(*replying_to).into(), (*replying_to).into(),
&**pool, &**pool,
) )
@@ -430,7 +431,7 @@ pub async fn thread_send_message(
)); ));
} }
let result = database::models::Thread::get(string, &**pool).await?; let result = database::models::DBThread::get(string, &**pool).await?;
if let Some(thread) = result { if let Some(thread) = result {
if !is_authorized_thread(&thread, &user, &pool).await? { if !is_authorized_thread(&thread, &user, &pool).await? {
@@ -449,16 +450,17 @@ pub async fn thread_send_message(
.await?; .await?;
if let Some(project_id) = thread.project_id { if let Some(project_id) = thread.project_id {
let project = let project = database::models::DBProject::get_id(
database::models::Project::get_id(project_id, &**pool, &redis) project_id, &**pool, &redis,
.await?; )
.await?;
if let Some(project) = project { if let Some(project) = project {
if project.inner.status != ProjectStatus::Processing if project.inner.status != ProjectStatus::Processing
&& user.role.is_mod() && user.role.is_mod()
{ {
let members = let members =
database::models::TeamMember::get_from_team_full( database::models::DBTeamMember::get_from_team_full(
project.inner.team_id, project.inner.team_id,
&**pool, &**pool,
&redis, &redis,
@@ -482,9 +484,10 @@ pub async fn thread_send_message(
} }
} }
} else if let Some(report_id) = thread.report_id { } else if let Some(report_id) = thread.report_id {
let report = let report = database::models::report_item::DBReport::get(
database::models::report_item::Report::get(report_id, &**pool) report_id, &**pool,
.await?; )
.await?;
if let Some(report) = report { if let Some(report) = report {
if report.closed && !user.role.is_mod() { if report.closed && !user.role.is_mod() {
@@ -513,7 +516,7 @@ pub async fn thread_send_message(
} = &new_message.body } = &new_message.body
{ {
for image_id in associated_images { for image_id in associated_images {
if let Some(db_image) = image_item::Image::get( if let Some(db_image) = image_item::DBImage::get(
(*image_id).into(), (*image_id).into(),
&mut *transaction, &mut *transaction,
&redis, &redis,
@@ -543,7 +546,7 @@ pub async fn thread_send_message(
.execute(&mut *transaction) .execute(&mut *transaction)
.await?; .await?;
image_item::Image::clear_cache(image.id.into(), &redis) image_item::DBImage::clear_cache(image.id.into(), &redis)
.await?; .await?;
} else { } else {
return Err(ApiError::InvalidInput(format!( return Err(ApiError::InvalidInput(format!(
@@ -579,7 +582,7 @@ pub async fn message_delete(
.await? .await?
.1; .1;
let result = database::models::ThreadMessage::get( let result = database::models::DBThreadMessage::get(
info.into_inner().0.into(), info.into_inner().0.into(),
&**pool, &**pool,
) )
@@ -598,7 +601,7 @@ pub async fn message_delete(
thread_message_id: Some(thread.id.into()), thread_message_id: Some(thread.id.into()),
}; };
let images = let images =
database::Image::get_many_contexted(context, &mut transaction) database::DBImage::get_many_contexted(context, &mut transaction)
.await?; .await?;
let cdn_url = dotenvy::var("CDN_URL")?; let cdn_url = dotenvy::var("CDN_URL")?;
for image in images { for image in images {
@@ -606,7 +609,8 @@ pub async fn message_delete(
if let Some(icon_path) = name { if let Some(icon_path) = name {
file_host.delete_file_version("", icon_path).await?; file_host.delete_file_version("", icon_path).await?;
} }
database::Image::remove(image.id, &mut transaction, &redis).await?; database::DBImage::remove(image.id, &mut transaction, &redis)
.await?;
} }
let private = if let MessageBody::Text { private, .. } = thread.body { let private = if let MessageBody::Text { private, .. } = thread.body {
@@ -617,7 +621,7 @@ pub async fn message_delete(
false false
}; };
database::models::ThreadMessage::remove_full( database::models::DBThreadMessage::remove_full(
thread.id, thread.id,
private, private,
&mut transaction, &mut transaction,

View File

@@ -4,7 +4,7 @@ use super::{ApiError, oauth_clients::get_user_clients};
use crate::util::img::delete_old_images; use crate::util::img::delete_old_images;
use crate::{ use crate::{
auth::{filter_visible_projects, get_user_from_headers}, auth::{filter_visible_projects, get_user_from_headers},
database::{models::User, redis::RedisPool}, database::{models::DBUser, redis::RedisPool},
file_hosting::FileHost, file_hosting::FileHost,
models::{ models::{
collections::{Collection, CollectionStatus}, collections::{Collection, CollectionStatus},
@@ -88,7 +88,7 @@ pub async fn admin_user_email(
) )
})?; })?;
let user = User::get_id( let user = DBUser::get_id(
crate::database::models::DBUserId(user_id), crate::database::models::DBUserId(user_id),
&**pool, &**pool,
&redis, &redis,
@@ -120,12 +120,12 @@ pub async fn projects_list(
.map(|x| x.1) .map(|x| x.1)
.ok(); .ok();
let id_option = User::get(&info.into_inner().0, &**pool, &redis).await?; let id_option = DBUser::get(&info.into_inner().0, &**pool, &redis).await?;
if let Some(id) = id_option.map(|x| x.id) { if let Some(id) = id_option.map(|x| x.id) {
let project_data = User::get_projects(id, &**pool, &redis).await?; let project_data = DBUser::get_projects(id, &**pool, &redis).await?;
let projects: Vec<_> = crate::database::Project::get_many_ids( let projects: Vec<_> = crate::database::DBProject::get_many_ids(
&project_data, &project_data,
&**pool, &**pool,
&redis, &redis,
@@ -177,7 +177,7 @@ pub async fn users_get(
) -> Result<HttpResponse, ApiError> { ) -> Result<HttpResponse, ApiError> {
let user_ids = serde_json::from_str::<Vec<String>>(&ids.ids)?; let user_ids = serde_json::from_str::<Vec<String>>(&ids.ids)?;
let users_data = User::get_many(&user_ids, &**pool, &redis).await?; let users_data = DBUser::get_many(&user_ids, &**pool, &redis).await?;
let users: Vec<crate::models::users::User> = let users: Vec<crate::models::users::User> =
users_data.into_iter().map(From::from).collect(); users_data.into_iter().map(From::from).collect();
@@ -192,7 +192,7 @@ pub async fn user_get(
redis: web::Data<RedisPool>, redis: web::Data<RedisPool>,
session_queue: web::Data<AuthQueue>, session_queue: web::Data<AuthQueue>,
) -> Result<HttpResponse, ApiError> { ) -> Result<HttpResponse, ApiError> {
let user_data = User::get(&info.into_inner().0, &**pool, &redis).await?; let user_data = DBUser::get(&info.into_inner().0, &**pool, &redis).await?;
if let Some(data) = user_data { if let Some(data) = user_data {
let auth_user = get_user_from_headers( let auth_user = get_user_from_headers(
@@ -237,7 +237,7 @@ pub async fn collections_list(
.map(|x| x.1) .map(|x| x.1)
.ok(); .ok();
let id_option = User::get(&info.into_inner().0, &**pool, &redis).await?; let id_option = DBUser::get(&info.into_inner().0, &**pool, &redis).await?;
if let Some(id) = id_option.map(|x| x.id) { if let Some(id) = id_option.map(|x| x.id) {
let user_id: UserId = id.into(); let user_id: UserId = id.into();
@@ -246,9 +246,9 @@ pub async fn collections_list(
.map(|y| y.role.is_mod() || y.id == user_id) .map(|y| y.role.is_mod() || y.id == user_id)
.unwrap_or(false); .unwrap_or(false);
let project_data = User::get_collections(id, &**pool).await?; let project_data = DBUser::get_collections(id, &**pool).await?;
let response: Vec<_> = crate::database::models::Collection::get_many( let response: Vec<_> = crate::database::models::DBCollection::get_many(
&project_data, &project_data,
&**pool, &**pool,
&redis, &redis,
@@ -285,13 +285,13 @@ pub async fn orgs_list(
.map(|x| x.1) .map(|x| x.1)
.ok(); .ok();
let id_option = User::get(&info.into_inner().0, &**pool, &redis).await?; let id_option = DBUser::get(&info.into_inner().0, &**pool, &redis).await?;
if let Some(id) = id_option.map(|x| x.id) { if let Some(id) = id_option.map(|x| x.id) {
let org_data = User::get_organizations(id, &**pool).await?; let org_data = DBUser::get_organizations(id, &**pool).await?;
let organizations_data = let organizations_data =
crate::database::models::organization_item::Organization::get_many_ids( crate::database::models::organization_item::DBOrganization::get_many_ids(
&org_data, &**pool, &redis, &org_data, &**pool, &redis,
) )
.await?; .await?;
@@ -302,11 +302,11 @@ pub async fn orgs_list(
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let teams_data = let teams_data =
crate::database::models::TeamMember::get_from_team_full_many( crate::database::models::DBTeamMember::get_from_team_full_many(
&team_ids, &**pool, &redis, &team_ids, &**pool, &redis,
) )
.await?; .await?;
let users = User::get_many_ids( let users = DBUser::get_many_ids(
&teams_data.iter().map(|x| x.user_id).collect::<Vec<_>>(), &teams_data.iter().map(|x| x.user_id).collect::<Vec<_>>(),
&**pool, &**pool,
&redis, &redis,
@@ -397,7 +397,7 @@ pub async fn user_edit(
ApiError::Validation(validation_errors_to_string(err, None)) ApiError::Validation(validation_errors_to_string(err, None))
})?; })?;
let id_option = User::get(&info.into_inner().0, &**pool, &redis).await?; let id_option = DBUser::get(&info.into_inner().0, &**pool, &redis).await?;
if let Some(actual_user) = id_option { if let Some(actual_user) = id_option {
let id = actual_user.id; let id = actual_user.id;
@@ -408,7 +408,7 @@ pub async fn user_edit(
if let Some(username) = &new_user.username { if let Some(username) = &new_user.username {
let existing_user_id_option = let existing_user_id_option =
User::get(username, &**pool, &redis).await?; DBUser::get(username, &**pool, &redis).await?;
if existing_user_id_option if existing_user_id_option
.map(|x| UserId::from(x.id)) .map(|x| UserId::from(x.id))
@@ -527,7 +527,7 @@ pub async fn user_edit(
} }
transaction.commit().await?; transaction.commit().await?;
User::clear_caches(&[(id, Some(actual_user.username))], &redis) DBUser::clear_caches(&[(id, Some(actual_user.username))], &redis)
.await?; .await?;
Ok(HttpResponse::NoContent().body("")) Ok(HttpResponse::NoContent().body(""))
} else { } else {
@@ -565,7 +565,7 @@ pub async fn user_icon_edit(
) )
.await? .await?
.1; .1;
let id_option = User::get(&info.into_inner().0, &**pool, &redis).await?; let id_option = DBUser::get(&info.into_inner().0, &**pool, &redis).await?;
if let Some(actual_user) = id_option { if let Some(actual_user) = id_option {
if user.id != actual_user.id.into() && !user.role.is_mod() { if user.id != actual_user.id.into() && !user.role.is_mod() {
@@ -612,7 +612,7 @@ pub async fn user_icon_edit(
) )
.execute(&**pool) .execute(&**pool)
.await?; .await?;
User::clear_caches(&[(actual_user.id, None)], &redis).await?; DBUser::clear_caches(&[(actual_user.id, None)], &redis).await?;
Ok(HttpResponse::NoContent().body("")) Ok(HttpResponse::NoContent().body(""))
} else { } else {
@@ -637,7 +637,7 @@ pub async fn user_icon_delete(
) )
.await? .await?
.1; .1;
let id_option = User::get(&info.into_inner().0, &**pool, &redis).await?; let id_option = DBUser::get(&info.into_inner().0, &**pool, &redis).await?;
if let Some(actual_user) = id_option { if let Some(actual_user) = id_option {
if user.id != actual_user.id.into() && !user.role.is_mod() { if user.id != actual_user.id.into() && !user.role.is_mod() {
@@ -665,7 +665,7 @@ pub async fn user_icon_delete(
.execute(&**pool) .execute(&**pool)
.await?; .await?;
User::clear_caches(&[(actual_user.id, None)], &redis).await?; DBUser::clear_caches(&[(actual_user.id, None)], &redis).await?;
Ok(HttpResponse::NoContent().body("")) Ok(HttpResponse::NoContent().body(""))
} else { } else {
@@ -689,7 +689,7 @@ pub async fn user_delete(
) )
.await? .await?
.1; .1;
let id_option = User::get(&info.into_inner().0, &**pool, &redis).await?; let id_option = DBUser::get(&info.into_inner().0, &**pool, &redis).await?;
if let Some(id) = id_option.map(|x| x.id) { if let Some(id) = id_option.map(|x| x.id) {
if !user.role.is_admin() && user.id != id.into() { if !user.role.is_admin() && user.id != id.into() {
@@ -700,7 +700,7 @@ pub async fn user_delete(
let mut transaction = pool.begin().await?; let mut transaction = pool.begin().await?;
let result = User::remove(id, &mut transaction, &redis).await?; let result = DBUser::remove(id, &mut transaction, &redis).await?;
transaction.commit().await?; transaction.commit().await?;
@@ -730,7 +730,7 @@ pub async fn user_follows(
) )
.await? .await?
.1; .1;
let id_option = User::get(&info.into_inner().0, &**pool, &redis).await?; let id_option = DBUser::get(&info.into_inner().0, &**pool, &redis).await?;
if let Some(id) = id_option.map(|x| x.id) { if let Some(id) = id_option.map(|x| x.id) {
if !user.role.is_admin() && user.id != id.into() { if !user.role.is_admin() && user.id != id.into() {
@@ -739,8 +739,8 @@ pub async fn user_follows(
)); ));
} }
let project_ids = User::get_follows(id, &**pool).await?; let project_ids = DBUser::get_follows(id, &**pool).await?;
let projects: Vec<_> = crate::database::Project::get_many_ids( let projects: Vec<_> = crate::database::DBProject::get_many_ids(
&project_ids, &project_ids,
&**pool, &**pool,
&redis, &redis,
@@ -772,7 +772,7 @@ pub async fn user_notifications(
) )
.await? .await?
.1; .1;
let id_option = User::get(&info.into_inner().0, &**pool, &redis).await?; let id_option = DBUser::get(&info.into_inner().0, &**pool, &redis).await?;
if let Some(id) = id_option.map(|x| x.id) { if let Some(id) = id_option.map(|x| x.id) {
if !user.role.is_admin() && user.id != id.into() { if !user.role.is_admin() && user.id != id.into() {
@@ -782,7 +782,7 @@ pub async fn user_notifications(
} }
let mut notifications: Vec<Notification> = let mut notifications: Vec<Notification> =
crate::database::models::notification_item::Notification::get_many_user( crate::database::models::notification_item::DBNotification::get_many_user(
id, &**pool, &redis, id, &**pool, &redis,
) )
.await? .await?

View File

@@ -7,7 +7,7 @@ use crate::database::models::notification_item::NotificationBuilder;
use crate::database::models::version_item::{ use crate::database::models::version_item::{
DependencyBuilder, VersionBuilder, VersionFileBuilder, DependencyBuilder, VersionBuilder, VersionFileBuilder,
}; };
use crate::database::models::{self, Organization, image_item}; use crate::database::models::{self, DBOrganization, image_item};
use crate::database::redis::RedisPool; use crate::database::redis::RedisPool;
use crate::file_hosting::FileHost; use crate::file_hosting::FileHost;
use crate::models::ids::{ImageId, ProjectId, VersionId}; use crate::models::ids::{ImageId, ProjectId, VersionId};
@@ -216,7 +216,7 @@ async fn version_create_inner(
let project_id: models::DBProjectId = version_create_data.project_id.unwrap().into(); let project_id: models::DBProjectId = version_create_data.project_id.unwrap().into();
// Ensure that the project this version is being added to exists // Ensure that the project this version is being added to exists
if models::Project::get_id(project_id, &mut **transaction, redis) if models::DBProject::get_id(project_id, &mut **transaction, redis)
.await? .await?
.is_none() .is_none()
{ {
@@ -227,7 +227,7 @@ async fn version_create_inner(
// Check that the user creating this version is a team member // Check that the user creating this version is a team member
// of the project the version is being added to. // of the project the version is being added to.
let team_member = models::TeamMember::get_from_user_id_project( let team_member = models::DBTeamMember::get_from_user_id_project(
project_id, project_id,
user.id.into(), user.id.into(),
false, false,
@@ -236,14 +236,14 @@ async fn version_create_inner(
.await?; .await?;
// Get organization attached, if exists, and the member project permissions // Get organization attached, if exists, and the member project permissions
let organization = models::Organization::get_associated_organization_project_id( let organization = models::DBOrganization::get_associated_organization_project_id(
project_id, project_id,
&mut **transaction, &mut **transaction,
) )
.await?; .await?;
let organization_team_member = if let Some(organization) = &organization { let organization_team_member = if let Some(organization) = &organization {
models::TeamMember::get_from_user_id( models::DBTeamMember::get_from_user_id(
organization.team_id, organization.team_id,
user.id.into(), user.id.into(),
&mut **transaction, &mut **transaction,
@@ -481,7 +481,7 @@ async fn version_create_inner(
for image_id in version_data.uploaded_images { for image_id in version_data.uploaded_images {
if let Some(db_image) = if let Some(db_image) =
image_item::Image::get(image_id.into(), &mut **transaction, redis) image_item::DBImage::get(image_id.into(), &mut **transaction, redis)
.await? .await?
{ {
let image: Image = db_image.into(); let image: Image = db_image.into();
@@ -505,7 +505,7 @@ async fn version_create_inner(
.execute(&mut **transaction) .execute(&mut **transaction)
.await?; .await?;
image_item::Image::clear_cache(image.id.into(), redis).await?; image_item::DBImage::clear_cache(image.id.into(), redis).await?;
} else { } else {
return Err(CreateError::InvalidInput(format!( return Err(CreateError::InvalidInput(format!(
"Image {image_id} does not exist" "Image {image_id} does not exist"
@@ -513,7 +513,7 @@ async fn version_create_inner(
} }
} }
models::Project::clear_cache(project_id, None, Some(true), redis).await?; models::DBProject::clear_cache(project_id, None, Some(true), redis).await?;
let project_status = sqlx::query!( let project_status = sqlx::query!(
"SELECT status FROM mods WHERE id = $1", "SELECT status FROM mods WHERE id = $1",
@@ -604,7 +604,7 @@ async fn upload_file_to_version_inner(
.await? .await?
.1; .1;
let result = models::Version::get(version_id, &**client, &redis).await?; let result = models::DBVersion::get(version_id, &**client, &redis).await?;
let version = match result { let version = match result {
Some(v) => v, Some(v) => v,
@@ -629,7 +629,7 @@ async fn upload_file_to_version_inner(
}) })
.collect::<Result<Vec<_>, _>>()?; .collect::<Result<Vec<_>, _>>()?;
if models::Project::get_id( if models::DBProject::get_id(
version.inner.project_id, version.inner.project_id,
&mut **transaction, &mut **transaction,
&redis, &redis,
@@ -643,7 +643,7 @@ async fn upload_file_to_version_inner(
} }
if !user.role.is_admin() { if !user.role.is_admin() {
let team_member = models::TeamMember::get_from_user_id_project( let team_member = models::DBTeamMember::get_from_user_id_project(
version.inner.project_id, version.inner.project_id,
user.id.into(), user.id.into(),
false, false,
@@ -652,7 +652,7 @@ async fn upload_file_to_version_inner(
.await?; .await?;
let organization = let organization =
Organization::get_associated_organization_project_id( DBOrganization::get_associated_organization_project_id(
version.inner.project_id, version.inner.project_id,
&**client, &**client,
) )
@@ -660,7 +660,7 @@ async fn upload_file_to_version_inner(
let organization_team_member = if let Some(organization) = &organization let organization_team_member = if let Some(organization) = &organization
{ {
models::TeamMember::get_from_user_id( models::DBTeamMember::get_from_user_id(
organization.team_id, organization.team_id,
user.id.into(), user.id.into(),
&mut **transaction, &mut **transaction,
@@ -782,7 +782,7 @@ async fn upload_file_to_version_inner(
} }
// Clear version cache // Clear version cache
models::Version::clear_cache(&version, &redis).await?; models::DBVersion::clear_cache(&version, &redis).await?;
Ok(HttpResponse::NoContent().body("")) Ok(HttpResponse::NoContent().body(""))
} }

View File

@@ -56,7 +56,7 @@ pub async fn get_version_from_hash(
.algorithm .algorithm
.clone() .clone()
.unwrap_or_else(|| default_algorithm_from_hashes(&[hash.clone()])); .unwrap_or_else(|| default_algorithm_from_hashes(&[hash.clone()]));
let file = database::models::Version::get_file_from_hash( let file = database::models::DBVersion::get_file_from_hash(
algorithm, algorithm,
hash, hash,
hash_query.version_id.map(|x| x.into()), hash_query.version_id.map(|x| x.into()),
@@ -66,7 +66,7 @@ pub async fn get_version_from_hash(
.await?; .await?;
if let Some(file) = file { if let Some(file) = file {
let version = let version =
database::models::Version::get(file.version_id, &**pool, &redis) database::models::DBVersion::get(file.version_id, &**pool, &redis)
.await?; .await?;
if let Some(version) = version { if let Some(version) = version {
if !is_visible_version(&version.inner, &user_option, &pool, &redis) if !is_visible_version(&version.inner, &user_option, &pool, &redis)
@@ -139,7 +139,7 @@ pub async fn get_update_from_hash(
.map(|x| x.1) .map(|x| x.1)
.ok(); .ok();
let hash = info.into_inner().0.to_lowercase(); let hash = info.into_inner().0.to_lowercase();
if let Some(file) = database::models::Version::get_file_from_hash( if let Some(file) = database::models::DBVersion::get_file_from_hash(
hash_query hash_query
.algorithm .algorithm
.clone() .clone()
@@ -151,11 +151,14 @@ pub async fn get_update_from_hash(
) )
.await? .await?
{ {
if let Some(project) = if let Some(project) = database::models::DBProject::get_id(
database::models::Project::get_id(file.project_id, &**pool, &redis) file.project_id,
.await? &**pool,
&redis,
)
.await?
{ {
let mut versions = database::models::Version::get_many( let mut versions = database::models::DBVersion::get_many(
&project.versions, &project.versions,
&**pool, &**pool,
&redis, &redis,
@@ -241,7 +244,7 @@ pub async fn get_versions_from_hashes(
.clone() .clone()
.unwrap_or_else(|| default_algorithm_from_hashes(&file_data.hashes)); .unwrap_or_else(|| default_algorithm_from_hashes(&file_data.hashes));
let files = database::models::Version::get_files_from_hash( let files = database::models::DBVersion::get_files_from_hash(
algorithm.clone(), algorithm.clone(),
&file_data.hashes, &file_data.hashes,
&**pool, &**pool,
@@ -251,7 +254,7 @@ pub async fn get_versions_from_hashes(
let version_ids = files.iter().map(|x| x.version_id).collect::<Vec<_>>(); let version_ids = files.iter().map(|x| x.version_id).collect::<Vec<_>>();
let versions_data = filter_visible_versions( let versions_data = filter_visible_versions(
database::models::Version::get_many(&version_ids, &**pool, &redis) database::models::DBVersion::get_many(&version_ids, &**pool, &redis)
.await?, .await?,
&user_option, &user_option,
&pool, &pool,
@@ -294,7 +297,7 @@ pub async fn get_projects_from_hashes(
.algorithm .algorithm
.clone() .clone()
.unwrap_or_else(|| default_algorithm_from_hashes(&file_data.hashes)); .unwrap_or_else(|| default_algorithm_from_hashes(&file_data.hashes));
let files = database::models::Version::get_files_from_hash( let files = database::models::DBVersion::get_files_from_hash(
algorithm.clone(), algorithm.clone(),
&file_data.hashes, &file_data.hashes,
&**pool, &**pool,
@@ -305,8 +308,12 @@ pub async fn get_projects_from_hashes(
let project_ids = files.iter().map(|x| x.project_id).collect::<Vec<_>>(); let project_ids = files.iter().map(|x| x.project_id).collect::<Vec<_>>();
let projects_data = filter_visible_projects( let projects_data = filter_visible_projects(
database::models::Project::get_many_ids(&project_ids, &**pool, &redis) database::models::DBProject::get_many_ids(
.await?, &project_ids,
&**pool,
&redis,
)
.await?,
&user_option, &user_option,
&pool, &pool,
false, false,
@@ -343,7 +350,7 @@ pub async fn update_files(
.algorithm .algorithm
.clone() .clone()
.unwrap_or_else(|| default_algorithm_from_hashes(&update_data.hashes)); .unwrap_or_else(|| default_algorithm_from_hashes(&update_data.hashes));
let files = database::models::Version::get_files_from_hash( let files = database::models::DBVersion::get_files_from_hash(
algorithm.clone(), algorithm.clone(),
&update_data.hashes, &update_data.hashes,
&**pool, &**pool,
@@ -378,7 +385,7 @@ pub async fn update_files(
}) })
.await?; .await?;
let versions = database::models::Version::get_many( let versions = database::models::DBVersion::get_many(
&update_version_ids &update_version_ids
.into_iter() .into_iter()
.filter_map(|x| x.1.last().copied()) .filter_map(|x| x.1.last().copied())
@@ -447,7 +454,7 @@ pub async fn update_individual_files(
.collect::<Vec<_>>(), .collect::<Vec<_>>(),
) )
}); });
let files = database::models::Version::get_files_from_hash( let files = database::models::DBVersion::get_files_from_hash(
algorithm.clone(), algorithm.clone(),
&update_data &update_data
.hashes .hashes
@@ -459,13 +466,13 @@ pub async fn update_individual_files(
) )
.await?; .await?;
let projects = database::models::Project::get_many_ids( let projects = database::models::DBProject::get_many_ids(
&files.iter().map(|x| x.project_id).collect::<Vec<_>>(), &files.iter().map(|x| x.project_id).collect::<Vec<_>>(),
&**pool, &**pool,
&redis, &redis,
) )
.await?; .await?;
let all_versions = database::models::Version::get_many( let all_versions = database::models::DBVersion::get_many(
&projects &projects
.iter() .iter()
.flat_map(|x| x.versions.clone()) .flat_map(|x| x.versions.clone())
@@ -574,7 +581,7 @@ pub async fn delete_file(
.algorithm .algorithm
.clone() .clone()
.unwrap_or_else(|| default_algorithm_from_hashes(&[hash.clone()])); .unwrap_or_else(|| default_algorithm_from_hashes(&[hash.clone()]));
let file = database::models::Version::get_file_from_hash( let file = database::models::DBVersion::get_file_from_hash(
algorithm.clone(), algorithm.clone(),
hash, hash,
hash_query.version_id.map(|x| x.into()), hash_query.version_id.map(|x| x.into()),
@@ -586,7 +593,7 @@ pub async fn delete_file(
if let Some(row) = file { if let Some(row) = file {
if !user.role.is_admin() { if !user.role.is_admin() {
let team_member = let team_member =
database::models::TeamMember::get_from_user_id_version( database::models::DBTeamMember::get_from_user_id_version(
row.version_id, row.version_id,
user.id.into(), user.id.into(),
&**pool, &**pool,
@@ -595,26 +602,27 @@ pub async fn delete_file(
.map_err(ApiError::Database)?; .map_err(ApiError::Database)?;
let organization = let organization =
database::models::Organization::get_associated_organization_project_id( database::models::DBOrganization::get_associated_organization_project_id(
row.project_id, row.project_id,
&**pool, &**pool,
) )
.await .await
.map_err(ApiError::Database)?; .map_err(ApiError::Database)?;
let organization_team_member = let organization_team_member = if let Some(organization) =
if let Some(organization) = &organization { &organization
database::models::TeamMember::get_from_user_id_organization( {
organization.id, database::models::DBTeamMember::get_from_user_id_organization(
user.id.into(), organization.id,
false, user.id.into(),
&**pool, false,
) &**pool,
.await )
.map_err(ApiError::Database)? .await
} else { .map_err(ApiError::Database)?
None } else {
}; None
};
let permissions = ProjectPermissions::get_permissions_by_role( let permissions = ProjectPermissions::get_permissions_by_role(
&user.role, &user.role,
@@ -632,7 +640,7 @@ pub async fn delete_file(
} }
let version = let version =
database::models::Version::get(row.version_id, &**pool, &redis) database::models::DBVersion::get(row.version_id, &**pool, &redis)
.await?; .await?;
if let Some(version) = version { if let Some(version) = version {
if version.files.len() < 2 { if version.files.len() < 2 {
@@ -642,7 +650,7 @@ pub async fn delete_file(
)); ));
} }
database::models::Version::clear_cache(&version, &redis).await?; database::models::DBVersion::clear_cache(&version, &redis).await?;
} }
let mut transaction = pool.begin().await?; let mut transaction = pool.begin().await?;
@@ -705,7 +713,7 @@ pub async fn download_version(
.algorithm .algorithm
.clone() .clone()
.unwrap_or_else(|| default_algorithm_from_hashes(&[hash.clone()])); .unwrap_or_else(|| default_algorithm_from_hashes(&[hash.clone()]));
let file = database::models::Version::get_file_from_hash( let file = database::models::DBVersion::get_file_from_hash(
algorithm.clone(), algorithm.clone(),
hash, hash,
hash_query.version_id.map(|x| x.into()), hash_query.version_id.map(|x| x.into()),
@@ -716,7 +724,7 @@ pub async fn download_version(
if let Some(file) = file { if let Some(file) = file {
let version = let version =
database::models::Version::get(file.version_id, &**pool, &redis) database::models::DBVersion::get(file.version_id, &**pool, &redis)
.await?; .await?;
if let Some(version) = version { if let Some(version) = version {

View File

@@ -9,8 +9,10 @@ use crate::database;
use crate::database::models::loader_fields::{ use crate::database::models::loader_fields::{
self, LoaderField, LoaderFieldEnumValue, VersionField, self, LoaderField, LoaderFieldEnumValue, VersionField,
}; };
use crate::database::models::version_item::{DependencyBuilder, LoaderVersion}; use crate::database::models::version_item::{
use crate::database::models::{Organization, image_item}; DBLoaderVersion, DependencyBuilder,
};
use crate::database::models::{DBOrganization, image_item};
use crate::database::redis::RedisPool; use crate::database::redis::RedisPool;
use crate::models; use crate::models;
use crate::models::ids::VersionId; use crate::models::ids::VersionId;
@@ -70,7 +72,8 @@ pub async fn version_project_get_helper(
redis: web::Data<RedisPool>, redis: web::Data<RedisPool>,
session_queue: web::Data<AuthQueue>, session_queue: web::Data<AuthQueue>,
) -> Result<HttpResponse, ApiError> { ) -> Result<HttpResponse, ApiError> {
let result = database::models::Project::get(&id.0, &**pool, &redis).await?; let result =
database::models::DBProject::get(&id.0, &**pool, &redis).await?;
let user_option = get_user_from_headers( let user_option = get_user_from_headers(
&req, &req,
@@ -90,7 +93,7 @@ pub async fn version_project_get_helper(
return Err(ApiError::NotFound); return Err(ApiError::NotFound);
} }
let versions = database::models::Version::get_many( let versions = database::models::DBVersion::get_many(
&project.versions, &project.versions,
&**pool, &**pool,
&redis, &redis,
@@ -134,7 +137,7 @@ pub async fn versions_get(
.map(|x| x.into()) .map(|x| x.into())
.collect::<Vec<database::models::DBVersionId>>(); .collect::<Vec<database::models::DBVersionId>>();
let versions_data = let versions_data =
database::models::Version::get_many(&version_ids, &**pool, &redis) database::models::DBVersion::get_many(&version_ids, &**pool, &redis)
.await?; .await?;
let user_option = get_user_from_headers( let user_option = get_user_from_headers(
@@ -174,7 +177,7 @@ pub async fn version_get_helper(
session_queue: web::Data<AuthQueue>, session_queue: web::Data<AuthQueue>,
) -> Result<HttpResponse, ApiError> { ) -> Result<HttpResponse, ApiError> {
let version_data = let version_data =
database::models::Version::get(id.into(), &**pool, &redis).await?; database::models::DBVersion::get(id.into(), &**pool, &redis).await?;
let user_option = get_user_from_headers( let user_option = get_user_from_headers(
&req, &req,
@@ -290,11 +293,11 @@ pub async fn version_edit_helper(
let version_id = info.0.into(); let version_id = info.0.into();
let result = let result =
database::models::Version::get(version_id, &**pool, &redis).await?; database::models::DBVersion::get(version_id, &**pool, &redis).await?;
if let Some(version_item) = result { if let Some(version_item) = result {
let team_member = let team_member =
database::models::TeamMember::get_from_user_id_project( database::models::DBTeamMember::get_from_user_id_project(
version_item.inner.project_id, version_item.inner.project_id,
user.id.into(), user.id.into(),
false, false,
@@ -303,7 +306,7 @@ pub async fn version_edit_helper(
.await?; .await?;
let organization = let organization =
Organization::get_associated_organization_project_id( DBOrganization::get_associated_organization_project_id(
version_item.inner.project_id, version_item.inner.project_id,
&**pool, &**pool,
) )
@@ -311,7 +314,7 @@ pub async fn version_edit_helper(
let organization_team_member = if let Some(organization) = &organization let organization_team_member = if let Some(organization) = &organization
{ {
database::models::TeamMember::get_from_user_id( database::models::DBTeamMember::get_from_user_id(
organization.team_id, organization.team_id,
user.id.into(), user.id.into(),
&**pool, &**pool,
@@ -513,15 +516,15 @@ pub async fn version_edit_helper(
.to_string(), .to_string(),
) )
})?; })?;
loader_versions.push(LoaderVersion { loader_versions.push(DBLoaderVersion {
loader_id, loader_id,
version_id, version_id,
}); });
} }
LoaderVersion::insert_many(loader_versions, &mut transaction) DBLoaderVersion::insert_many(loader_versions, &mut transaction)
.await?; .await?;
crate::database::models::Project::clear_cache( crate::database::models::DBProject::clear_cache(
version_item.inner.project_id, version_item.inner.project_id,
None, None,
None, None,
@@ -679,9 +682,9 @@ pub async fn version_edit_helper(
.await?; .await?;
transaction.commit().await?; transaction.commit().await?;
database::models::Version::clear_cache(&version_item, &redis) database::models::DBVersion::clear_cache(&version_item, &redis)
.await?; .await?;
database::models::Project::clear_cache( database::models::DBProject::clear_cache(
version_item.inner.project_id, version_item.inner.project_id,
None, None,
Some(true), Some(true),
@@ -726,7 +729,7 @@ pub async fn version_list(
let string = info.into_inner().0; let string = info.into_inner().0;
let result = let result =
database::models::Project::get(&string, &**pool, &redis).await?; database::models::DBProject::get(&string, &**pool, &redis).await?;
let user_option = get_user_from_headers( let user_option = get_user_from_headers(
&req, &req,
@@ -753,7 +756,7 @@ pub async fn version_list(
let loader_filters = filters.loaders.as_ref().map(|x| { let loader_filters = filters.loaders.as_ref().map(|x| {
serde_json::from_str::<Vec<String>>(x).unwrap_or_default() serde_json::from_str::<Vec<String>>(x).unwrap_or_default()
}); });
let mut versions = database::models::Version::get_many( let mut versions = database::models::DBVersion::get_many(
&project.versions, &project.versions,
&**pool, &**pool,
&redis, &redis,
@@ -886,7 +889,7 @@ pub async fn version_delete(
.1; .1;
let id = info.into_inner().0; let id = info.into_inner().0;
let version = database::models::Version::get(id.into(), &**pool, &redis) let version = database::models::DBVersion::get(id.into(), &**pool, &redis)
.await? .await?
.ok_or_else(|| { .ok_or_else(|| {
ApiError::InvalidInput( ApiError::InvalidInput(
@@ -896,7 +899,7 @@ pub async fn version_delete(
if !user.role.is_admin() { if !user.role.is_admin() {
let team_member = let team_member =
database::models::TeamMember::get_from_user_id_project( database::models::DBTeamMember::get_from_user_id_project(
version.inner.project_id, version.inner.project_id,
user.id.into(), user.id.into(),
false, false,
@@ -906,7 +909,7 @@ pub async fn version_delete(
.map_err(ApiError::Database)?; .map_err(ApiError::Database)?;
let organization = let organization =
Organization::get_associated_organization_project_id( DBOrganization::get_associated_organization_project_id(
version.inner.project_id, version.inner.project_id,
&**pool, &**pool,
) )
@@ -914,7 +917,7 @@ pub async fn version_delete(
let organization_team_member = if let Some(organization) = &organization let organization_team_member = if let Some(organization) = &organization
{ {
database::models::TeamMember::get_from_user_id( database::models::DBTeamMember::get_from_user_id(
organization.team_id, organization.team_id,
user.id.into(), user.id.into(),
&**pool, &**pool,
@@ -942,14 +945,16 @@ pub async fn version_delete(
let context = ImageContext::Version { let context = ImageContext::Version {
version_id: Some(version.inner.id.into()), version_id: Some(version.inner.id.into()),
}; };
let uploaded_images = let uploaded_images = database::models::DBImage::get_many_contexted(
database::models::Image::get_many_contexted(context, &mut transaction) context,
.await?; &mut transaction,
)
.await?;
for image in uploaded_images { for image in uploaded_images {
image_item::Image::remove(image.id, &mut transaction, &redis).await?; image_item::DBImage::remove(image.id, &mut transaction, &redis).await?;
} }
let result = database::models::Version::remove_full( let result = database::models::DBVersion::remove_full(
version.inner.id, version.inner.id,
&redis, &redis,
&mut transaction, &mut transaction,
@@ -957,7 +962,7 @@ pub async fn version_delete(
.await?; .await?;
transaction.commit().await?; transaction.commit().await?;
remove_documents(&[version.inner.id.into()], &search_config).await?; remove_documents(&[version.inner.id.into()], &search_config).await?;
database::models::Project::clear_cache( database::models::DBProject::clear_cache(
version.inner.project_id, version.inner.project_id,
None, None,
Some(true), Some(true),

View File

@@ -199,7 +199,7 @@ pub async fn delete_unused_images(
redis: &RedisPool, redis: &RedisPool,
) -> Result<(), ApiError> { ) -> Result<(), ApiError> {
let uploaded_images = let uploaded_images =
database::models::Image::get_many_contexted(context, transaction) database::models::DBImage::get_many_contexted(context, transaction)
.await?; .await?;
for image in uploaded_images { for image in uploaded_images {
@@ -212,8 +212,8 @@ pub async fn delete_unused_images(
} }
if should_delete { if should_delete {
image_item::Image::remove(image.id, transaction, redis).await?; image_item::DBImage::remove(image.id, transaction, redis).await?;
image_item::Image::clear_cache(image.id, redis).await?; image_item::DBImage::clear_cache(image.id, redis).await?;
} }
} }

View File

@@ -47,7 +47,7 @@ async fn get_webhook_metadata(
redis: &RedisPool, redis: &RedisPool,
emoji: bool, emoji: bool,
) -> Result<Option<WebhookMetadata>, ApiError> { ) -> Result<Option<WebhookMetadata>, ApiError> {
let project = crate::database::models::project_item::Project::get_id( let project = crate::database::models::project_item::DBProject::get_id(
project_id.into(), project_id.into(),
pool, pool,
redis, redis,
@@ -58,7 +58,7 @@ async fn get_webhook_metadata(
let mut owner = None; let mut owner = None;
if let Some(organization_id) = project.inner.organization_id { if let Some(organization_id) = project.inner.organization_id {
let organization = crate::database::models::organization_item::Organization::get_id( let organization = crate::database::models::organization_item::DBOrganization::get_id(
organization_id, organization_id,
pool, pool,
redis, redis,
@@ -77,7 +77,7 @@ async fn get_webhook_metadata(
}); });
} }
} else { } else {
let team = crate::database::models::team_item::TeamMember::get_from_team_full( let team = crate::database::models::team_item::DBTeamMember::get_from_team_full(
project.inner.team_id, project.inner.team_id,
pool, pool,
redis, redis,
@@ -85,7 +85,7 @@ async fn get_webhook_metadata(
.await?; .await?;
if let Some(member) = team.into_iter().find(|x| x.is_owner) { if let Some(member) = team.into_iter().find(|x| x.is_owner) {
let user = crate::database::models::user_item::User::get_id( let user = crate::database::models::user_item::DBUser::get_id(
member.user_id, member.user_id,
pool, pool,
redis, redis,

View File

@@ -18,7 +18,7 @@ pub async fn create_test_pat(
) -> String { ) -> String {
let mut transaction = db.pool.begin().await.unwrap(); let mut transaction = db.pool.begin().await.unwrap();
let id = generate_pat_id(&mut transaction).await.unwrap(); let id = generate_pat_id(&mut transaction).await.unwrap();
let pat = database::models::pat_item::PersonalAccessToken { let pat = database::models::pat_item::DBPersonalAccessToken {
id, id,
name: format!("test_pat_{}", scopes.bits()), name: format!("test_pat_{}", scopes.bits()),
access_token: format!("mrp_{}", id.0), access_token: format!("mrp_{}", id.0),

View File

@@ -86,10 +86,6 @@ impl_base62_display!(Base62Id);
#[macro_export] #[macro_export]
macro_rules! base62_id { macro_rules! base62_id {
($struct:ident) => { ($struct:ident) => {
$crate::ids::base62_id!($struct, "ariadne::ids::Base62Id");
};
($struct:ident, $base_type:expr) => {
#[derive( #[derive(
Copy, Copy,
Clone, Clone,
@@ -100,8 +96,8 @@ macro_rules! base62_id {
Debug, Debug,
Hash, Hash,
)] )]
#[serde(from = $base_type)] #[serde(from = "ariadne::ids::Base62Id")]
#[serde(into = $base_type)] #[serde(into = "ariadne::ids::Base62Id")]
pub struct $struct(pub u64); pub struct $struct(pub u64);
$crate::ids::impl_base62_display!($struct); $crate::ids::impl_base62_display!($struct);
@@ -120,7 +116,8 @@ macro_rules! base62_id {
}; };
} }
base62_id!(UserId, "crate::ids::Base62Id"); use crate as ariadne; // Hack because serde(from) and serde(into) don't work with $crate
base62_id!(UserId);
pub use {base62_id, impl_base62_display}; pub use {base62_id, impl_base62_display};