From 68a7d136705133dc5d3a5d43b9ff4da28eeb6d5b Mon Sep 17 00:00:00 2001 From: cel 🌸 Date: Tue, 18 Feb 2025 01:01:17 +0000 Subject: database work --- jid/Cargo.toml | 1 + jid/src/lib.rs | 46 ++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 45 insertions(+), 2 deletions(-) (limited to 'jid') diff --git a/jid/Cargo.toml b/jid/Cargo.toml index 15049c9..0d817c9 100644 --- a/jid/Cargo.toml +++ b/jid/Cargo.toml @@ -4,3 +4,4 @@ version = "0.1.0" edition = "2021" [dependencies] +sqlx = { version = "0.8.3", features = ["sqlite"] } diff --git a/jid/src/lib.rs b/jid/src/lib.rs index ff1d82b..5b648d9 100644 --- a/jid/src/lib.rs +++ b/jid/src/lib.rs @@ -1,6 +1,8 @@ -use std::str::FromStr; +use std::{error::Error, fmt::Display, str::FromStr}; -#[derive(PartialEq, Debug, Clone)] +use sqlx::Sqlite; + +#[derive(PartialEq, Debug, Clone, sqlx::Type, sqlx::Encode)] pub struct JID { // TODO: validate localpart (length, char] pub localpart: Option, @@ -8,6 +10,33 @@ pub struct JID { pub resourcepart: Option, } +// TODO: feature gate +impl sqlx::Type for JID { + fn type_info() -> ::TypeInfo { + <&str as sqlx::Type>::type_info() + } +} + +impl sqlx::Decode<'_, Sqlite> for JID { + fn decode( + value: ::ValueRef<'_>, + ) -> Result { + let value = <&str as sqlx::Decode>::decode(value)?; + + Ok(value.parse()?) + } +} + +impl sqlx::Encode<'_, Sqlite> for JID { + fn encode_by_ref( + &self, + buf: &mut ::ArgumentBuffer<'_>, + ) -> Result { + let jid = self.to_string(); + >::encode(jid, buf) + } +} + pub enum JIDError { NoResourcePart, ParseError(ParseError), @@ -19,6 +48,19 @@ pub enum ParseError { Malformed(String), } +impl Display for ParseError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ParseError::Empty => f.write_str("JID parse error: Empty"), + ParseError::Malformed(j) => { + f.write_str(format!("JID parse error: malformed; got '{}'", j).as_str()) + } + } + } +} + +impl Error for ParseError {} + impl JID { pub fn new( localpart: Option, -- cgit