Remove database-specific code from utils::caip2 module

This commit is contained in:
silverpill 2023-02-12 01:43:50 +00:00
parent f1972be8db
commit bcef9bb989
7 changed files with 79 additions and 56 deletions

View file

@ -34,7 +34,7 @@ impl From<DbInvoice> for Invoice {
InvoiceStatus::Forwarded => "forwarded", InvoiceStatus::Forwarded => "forwarded",
InvoiceStatus::Timeout => "timeout", InvoiceStatus::Timeout => "timeout",
}; };
let expires_at = if value.chain_id.is_monero() { let expires_at = if value.chain_id.inner().is_monero() {
value.created_at + Duration::seconds(MONERO_INVOICE_TIMEOUT) value.created_at + Duration::seconds(MONERO_INVOICE_TIMEOUT)
} else { } else {
// Epoch 0 // Epoch 0

View file

@ -9,7 +9,7 @@ use crate::utils::{
caip2::ChainId, caip2::ChainId,
id::generate_ulid, id::generate_ulid,
}; };
use super::types::{DbInvoice, InvoiceStatus}; use super::types::{DbChainId, DbInvoice, InvoiceStatus};
pub async fn create_invoice( pub async fn create_invoice(
db_client: &impl DatabaseClient, db_client: &impl DatabaseClient,
@ -37,7 +37,7 @@ pub async fn create_invoice(
&invoice_id, &invoice_id,
&sender_id, &sender_id,
&recipient_id, &recipient_id,
&chain_id, &DbChainId::new(chain_id),
&payment_address, &payment_address,
&amount, &amount,
], ],
@ -72,7 +72,7 @@ pub async fn get_invoice_by_address(
SELECT invoice SELECT invoice
FROM invoice WHERE chain_id = $1 AND payment_address = $2 FROM invoice WHERE chain_id = $1 AND payment_address = $2
", ",
&[&chain_id, &payment_address], &[&DbChainId::new(chain_id), &payment_address],
).await?; ).await?;
let row = maybe_row.ok_or(DatabaseError::NotFound("invoice"))?; let row = maybe_row.ok_or(DatabaseError::NotFound("invoice"))?;
let invoice = row.try_get("invoice")?; let invoice = row.try_get("invoice")?;
@ -89,7 +89,7 @@ pub async fn get_invoices_by_status(
SELECT invoice SELECT invoice
FROM invoice WHERE chain_id = $1 AND invoice_status = $2 FROM invoice WHERE chain_id = $1 AND invoice_status = $2
", ",
&[&chain_id, &status], &[&DbChainId::new(chain_id), &status],
).await?; ).await?;
let invoices = rows.iter() let invoices = rows.iter()
.map(|row| row.try_get("invoice")) .map(|row| row.try_get("invoice"))
@ -157,7 +157,7 @@ mod tests {
).await.unwrap(); ).await.unwrap();
assert_eq!(invoice.sender_id, sender.id); assert_eq!(invoice.sender_id, sender.id);
assert_eq!(invoice.recipient_id, recipient.id); assert_eq!(invoice.recipient_id, recipient.id);
assert_eq!(invoice.chain_id, chain_id); assert_eq!(invoice.chain_id.into_inner(), chain_id);
assert_eq!(invoice.payment_address, payment_address); assert_eq!(invoice.payment_address, payment_address);
assert_eq!(invoice.amount, amount); assert_eq!(invoice.amount, amount);
assert_eq!(invoice.invoice_status, InvoiceStatus::Open); assert_eq!(invoice.invoice_status, InvoiceStatus::Open);

View file

@ -1,5 +1,14 @@
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use postgres_types::FromSql; use postgres_protocol::types::{text_from_sql, text_to_sql};
use postgres_types::{
accepts,
private::BytesMut,
to_sql_checked,
FromSql,
IsNull,
ToSql,
Type,
};
use uuid::Uuid; use uuid::Uuid;
use crate::database::{ use crate::database::{
@ -8,6 +17,59 @@ use crate::database::{
}; };
use crate::utils::caip2::ChainId; use crate::utils::caip2::ChainId;
#[derive(Debug)]
pub struct DbChainId(ChainId);
impl DbChainId {
pub fn new(chain_id: &ChainId) -> Self {
Self(chain_id.clone())
}
pub fn inner(&self) -> &ChainId {
let Self(chain_id) = self;
chain_id
}
pub fn into_inner(self) -> ChainId {
let Self(chain_id) = self;
chain_id
}
}
impl PartialEq<ChainId> for DbChainId {
fn eq(&self, other: &ChainId) -> bool {
self.inner() == other
}
}
impl<'a> FromSql<'a> for DbChainId {
fn from_sql(
_: &Type,
raw: &'a [u8],
) -> Result<Self, Box<dyn std::error::Error + Sync + Send>> {
let value_str = text_from_sql(raw)?;
let value: ChainId = value_str.parse()?;
Ok(Self(value))
}
accepts!(VARCHAR);
}
impl ToSql for DbChainId {
fn to_sql(
&self,
_: &Type,
out: &mut BytesMut,
) -> Result<IsNull, Box<dyn std::error::Error + Sync + Send>> {
let value_str = self.inner().to_string();
text_to_sql(&value_str, out);
Ok(IsNull::No)
}
accepts!(VARCHAR, TEXT);
to_sql_checked!();
}
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub enum InvoiceStatus { pub enum InvoiceStatus {
Open, Open,
@ -51,7 +113,7 @@ pub struct DbInvoice {
pub id: Uuid, pub id: Uuid,
pub sender_id: Uuid, pub sender_id: Uuid,
pub recipient_id: Uuid, pub recipient_id: Uuid,
pub chain_id: ChainId, pub chain_id: DbChainId,
pub payment_address: String, pub payment_address: String,
pub amount: i64, // requested payment amount pub amount: i64, // requested payment amount
pub invoice_status: InvoiceStatus, pub invoice_status: InvoiceStatus,

View file

@ -7,6 +7,7 @@ use crate::database::{
DatabaseError, DatabaseError,
}; };
use crate::models::{ use crate::models::{
invoices::types::DbChainId,
profiles::types::PaymentType, profiles::types::PaymentType,
relationships::queries::{subscribe, subscribe_opt}, relationships::queries::{subscribe, subscribe_opt},
relationships::types::RelationshipType, relationships::types::RelationshipType,
@ -41,7 +42,7 @@ pub async fn create_subscription(
&sender_id, &sender_id,
&sender_address, &sender_address,
&recipient_id, &recipient_id,
&chain_id, &DbChainId::new(chain_id),
&expires_at, &expires_at,
&updated_at, &updated_at,
], ],
@ -71,7 +72,7 @@ pub async fn update_subscription(
", ",
&[ &[
&subscription_id, &subscription_id,
&chain_id, &DbChainId::new(chain_id),
&expires_at, &expires_at,
&updated_at, &updated_at,
], ],

View file

@ -4,8 +4,10 @@ use tokio_postgres::Row;
use uuid::Uuid; use uuid::Uuid;
use crate::database::DatabaseError; use crate::database::DatabaseError;
use crate::models::profiles::types::DbActorProfile; use crate::models::{
use crate::utils::caip2::ChainId; invoices::types::DbChainId,
profiles::types::DbActorProfile,
};
#[derive(FromSql)] #[derive(FromSql)]
#[postgres(name = "subscription")] #[postgres(name = "subscription")]
@ -14,7 +16,7 @@ pub struct DbSubscription {
pub sender_id: Uuid, pub sender_id: Uuid,
pub sender_address: Option<String>, pub sender_address: Option<String>,
pub recipient_id: Uuid, pub recipient_id: Uuid,
pub chain_id: ChainId, pub chain_id: DbChainId,
pub expires_at: DateTime<Utc>, pub expires_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>, pub updated_at: DateTime<Utc>,
} }

View file

@ -173,7 +173,7 @@ pub async fn check_monero_subscriptions(
update_subscription( update_subscription(
db_client, db_client,
subscription.id, subscription.id,
&subscription.chain_id, subscription.chain_id.inner(),
&expires_at, &expires_at,
&Utc::now(), &Utc::now(),
).await?; ).await?;

View file

@ -109,48 +109,6 @@ impl<'de> Deserialize<'de> for ChainId {
} }
} }
mod sql {
use postgres_protocol::types::{text_from_sql, text_to_sql};
use postgres_types::{
accepts,
private::BytesMut,
to_sql_checked,
FromSql,
IsNull,
ToSql,
Type,
};
use super::ChainId;
impl<'a> FromSql<'a> for ChainId {
fn from_sql(
_: &Type,
raw: &'a [u8],
) -> Result<Self, Box<dyn std::error::Error + Sync + Send>> {
let value_str = text_from_sql(raw)?;
let value: Self = value_str.parse()?;
Ok(value)
}
accepts!(VARCHAR);
}
impl ToSql for ChainId {
fn to_sql(
&self,
_: &Type,
out: &mut BytesMut,
) -> Result<IsNull, Box<dyn std::error::Error + Sync + Send>> {
let value_str = self.to_string();
text_to_sql(&value_str, out);
Ok(IsNull::No)
}
accepts!(VARCHAR, TEXT);
to_sql_checked!();
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;