ig_client/storage/
utils.rs

1use crate::application::models::transaction::Transaction;
2use crate::error::AppError;
3use serde::Serialize;
4use serde::de::DeserializeOwned;
5use serde_json;
6use sqlx::Executor;
7
8/// Stores a list of transactions in the database
9///
10/// # Arguments
11/// * `pool` - PostgreSQL connection pool
12/// * `txs` - List of transactions to store
13///
14/// # Returns
15/// * `Result<usize, AppError>` - Number of transactions inserted or an error
16pub async fn store_transactions(
17    pool: &sqlx::PgPool,
18    txs: &[Transaction],
19) -> Result<usize, AppError> {
20    let mut tx = pool.begin().await?;
21    let mut inserted = 0;
22
23    for t in txs {
24        let result = tx
25            .execute(
26                sqlx::query(
27                    r#"
28                    INSERT INTO ig_options (
29                        reference, deal_date, underlying, strike,
30                        option_type, expiry, transaction_type, pnl_eur, is_fee, raw
31                    )
32                    VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)
33                    ON CONFLICT (raw_hash) DO NOTHING
34                    "#,
35                )
36                .bind(&t.reference)
37                .bind(t.deal_date)
38                .bind(&t.underlying)
39                .bind(t.strike)
40                .bind(&t.option_type)
41                .bind(t.expiry)
42                .bind(&t.transaction_type)
43                .bind(t.pnl_eur)
44                .bind(t.is_fee)
45                .bind(&t.raw_json),
46            )
47            .await?;
48
49        inserted += result.rows_affected() as usize;
50    }
51
52    tx.commit().await?;
53    Ok(inserted)
54}
55
56/// Serializes a value to a JSON string
57pub fn serialize_to_json<T: Serialize>(value: &T) -> Result<String, serde_json::Error> {
58    serde_json::to_string(value)
59}
60
61/// Deserializes a JSON string into a value
62pub fn deserialize_from_json<T: DeserializeOwned>(s: &str) -> Result<T, serde_json::Error> {
63    serde_json::from_str(s)
64}