1
0
Fork 0
forked from 2sys/phonograph
phonograph/interim-models/src/workspace.rs

90 lines
2 KiB
Rust
Raw Normal View History

2025-08-04 13:59:42 -07:00
use derive_builder::Builder;
use redact::Secret;
2025-08-04 13:59:42 -07:00
use sqlx::query_as;
use url::Url;
2025-08-04 13:59:42 -07:00
use uuid::Uuid;
use crate::client::AppDbClient;
/// A workspace is 1:1 with a Postgres "database".
2025-08-04 13:59:42 -07:00
#[derive(Clone, Debug)]
pub struct Workspace {
/// Primary key (defaults to UUIDv7).
2025-08-04 13:59:42 -07:00
pub id: Uuid,
/// Human friendly name for the workspace.
2025-08-04 13:59:42 -07:00
pub name: String,
/// `postgresql://` URL of the instance and database hosting this workspace.
// TODO: Encrypt values in Postgres using `pgp_sym_encrypt()`.
pub url: Secret<String>,
/// ID of the user account that created this workspace.
2025-08-04 13:59:42 -07:00
pub owner_id: Uuid,
}
impl Workspace {
/// Build an insert statement to create a new workspace.
2025-10-22 00:43:53 -07:00
pub fn insert() -> InsertBuilder {
InsertBuilder::default()
2025-08-04 13:59:42 -07:00
}
/// Build a single-field query by workspace ID.
2025-08-04 13:59:42 -07:00
pub fn with_id(id: Uuid) -> WithIdQuery {
WithIdQuery { id }
}
}
pub struct WithIdQuery {
id: Uuid,
}
impl WithIdQuery {
pub async fn fetch_optional(
self,
app_db: &mut AppDbClient,
) -> Result<Option<Workspace>, sqlx::Error> {
query_as!(
Workspace,
"select * from workspaces where id = $1",
&self.id
)
.fetch_optional(&mut *app_db.conn)
.await
2025-08-04 13:59:42 -07:00
}
pub async fn fetch_one(self, app_db: &mut AppDbClient) -> Result<Workspace, sqlx::Error> {
query_as!(
Workspace,
"select * from workspaces where id = $1",
&self.id
)
.fetch_one(&mut *app_db.conn)
.await
2025-08-04 13:59:42 -07:00
}
}
#[derive(Builder)]
2025-10-22 00:43:53 -07:00
pub struct Insert {
url: Url,
2025-08-04 13:59:42 -07:00
owner_id: Uuid,
}
2025-10-22 00:43:53 -07:00
impl Insert {
pub async fn insert(self, app_db: &mut AppDbClient) -> Result<Workspace, sqlx::Error> {
2025-08-04 13:59:42 -07:00
query_as!(
Workspace,
2025-08-04 13:59:42 -07:00
"
insert into workspaces
(url, owner_id)
values ($1, $2)
2025-08-04 13:59:42 -07:00
returning *
",
self.url.to_string(),
2025-08-04 13:59:42 -07:00
self.owner_id
)
.fetch_one(&mut *app_db.conn)
.await
}
}