1
0
Fork 0
forked from 2sys/phonograph
phonograph/interim-server/src/bases.rs
2025-07-08 14:37:03 -07:00

75 lines
1.6 KiB
Rust

use derive_builder::Builder;
use sqlx::{query_as, PgExecutor};
use uuid::Uuid;
pub struct Base {
pub id: Uuid,
pub name: String,
pub url: String,
pub owner_id: Uuid,
pub user_role_prefix: String,
}
impl Base {
pub fn insertable_builder() -> InsertableBaseBuilder {
InsertableBaseBuilder::default()
}
pub async fn fetch_by_id<'a, E: PgExecutor<'a>>(
id: Uuid,
app_db: E,
) -> Result<Option<Base>, sqlx::Error> {
query_as!(Self, "select * from bases where id = $1", &id)
.fetch_optional(app_db)
.await
}
pub async fn fetch_by_perm_any<'a, E: PgExecutor<'a>>(
user_id: Uuid,
perms: Vec<&str>,
app_db: E,
) -> Result<Vec<Base>, sqlx::Error> {
let perms = perms
.into_iter()
.map(ToOwned::to_owned)
.collect::<Vec<String>>();
query_as!(
Self,
"
select bases.*
from bases inner join base_user_perms as p
on p.base_id = bases.id
where p.user_id = $1 and perm = ANY($2)
",
user_id,
perms.as_slice(),
)
.fetch_all(app_db)
.await
}
}
#[derive(Builder)]
pub struct InsertableBase {
url: String,
owner_id: Uuid,
}
impl InsertableBase {
pub async fn insert<'a, E: PgExecutor<'a>>(self, app_db: E) -> Result<Base, sqlx::Error> {
query_as!(
Base,
"
insert into bases
(id, url, owner_id)
values ($1, $2, $3)
returning *
",
Uuid::now_v7(),
self.url,
self.owner_id
)
.fetch_one(app_db)
.await
}
}