use chrono::{DateTime, Utc}; use derive_builder::Builder; use interim_pgtypes::pg_acl::PgPrivilegeType; use sqlx::{PgExecutor, postgres::types::Oid, query_as}; use uuid::Uuid; #[derive(Clone, Debug)] pub struct RelInvitation { pub id: Uuid, pub email: String, pub base_id: Uuid, pub class_oid: Oid, pub created_by: Uuid, pub privilege: String, pub expires_at: Option>, } impl RelInvitation { pub async fn fetch_by_class_oid<'a, E: PgExecutor<'a>>( oid: Oid, app_db: E, ) -> Result, sqlx::Error> { query_as!( Self, " select * from rel_invitations where class_oid = $1 ", oid ) .fetch_all(app_db) .await } pub fn upsertable() -> UpsertableRelInvitationBuilder { UpsertableRelInvitationBuilder::default() } } #[derive(Builder, Clone, Debug)] pub struct UpsertableRelInvitation { email: String, base_id: Uuid, class_oid: Oid, created_by: Uuid, privilege: PgPrivilegeType, #[builder(default, setter(strip_option))] expires_at: Option>, } impl UpsertableRelInvitation { pub async fn upsert<'a, E: PgExecutor<'a>>( self, app_db: E, ) -> Result { query_as!( RelInvitation, " insert into rel_invitations (id, email, base_id, class_oid, privilege, created_by, expires_at) values ($1, $2, $3, $4, $5, $6, $7) on conflict (email, base_id, class_oid, privilege) do update set created_by = excluded.created_by, expires_at = excluded.expires_at returning * ", Uuid::now_v7(), self.email, self.base_id, self.class_oid, self.privilege.to_abbrev().to_string(), self.created_by, self.expires_at, ) .fetch_one(app_db) .await } }