Implement sqlx Encode, Decode, Type for Rights bitflag object.

This commit is contained in:
Quat3rnion 2024-06-03 22:58:05 -04:00
parent 7548f0e592
commit 85aa854953
1 changed files with 31 additions and 0 deletions

View File

@ -4,6 +4,10 @@
use bitflags::bitflags; use bitflags::bitflags;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tokio::io::AsyncWriteExt;
#[cfg(feature = "sqlx")]
use sqlx::{{Decode, Encode, MySql}, database::{HasArguments, HasValueRef}, encode::IsNull, error::BoxDynError, mysql::MySqlValueRef};
bitflags! { bitflags! {
/// Rights are instance-wide, per-user permissions for everything you may perform on the instance, /// Rights are instance-wide, per-user permissions for everything you may perform on the instance,
@ -129,6 +133,33 @@ bitflags! {
} }
} }
#[cfg(feature = "sqlx")]
impl sqlx::Type<MySql> for Rights {
fn type_info() -> <sqlx::MySql as sqlx::Database>::TypeInfo {
u64::type_info()
}
fn compatible(ty: &<sqlx::MySql as sqlx::Database>::TypeInfo) -> bool {
u64::compatible(ty)
}
}
#[cfg(feature = "sqlx")]
impl<'q> Encode<'q, MySql> for Rights {
fn encode_by_ref(&self, buf: &mut <MySql as HasArguments<'q>>::ArgumentBuffer) -> IsNull {
<u64 as Encode<MySql>>::encode_by_ref(&self.0.0, buf)
}
}
#[cfg(feature = "sqlx")]
impl<'r> Decode<'r, MySql> for Rights {
fn decode(value: <MySql as HasValueRef<'r>>::ValueRef) -> Result<Self, BoxDynError> {
let raw = <u64 as Decode<MySql>>::decode(value)?;
Ok(Rights::from_bits(raw).unwrap())
}
}
impl Rights { impl Rights {
pub fn any(&self, permission: Rights, check_operator: bool) -> bool { pub fn any(&self, permission: Rights, check_operator: bool) -> bool {
(check_operator && self.contains(Rights::OPERATOR)) || self.contains(permission) (check_operator && self.contains(Rights::OPERATOR)) || self.contains(permission)