sql.rs (2279B)
1 /* 2 This file is part of TALER 3 Copyright (C) 2022-2025 Taler Systems SA 4 5 TALER is free software; you can redistribute it and/or modify it under the 6 terms of the GNU Affero General Public License as published by the Free Software 7 Foundation; either version 3, or (at your option) any later version. 8 9 TALER is distributed in the hope that it will be useful, but WITHOUT ANY 10 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 11 A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. 12 13 You should have received a copy of the GNU Affero General Public License along with 14 TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/> 15 */ 16 17 use bitcoin::{Address, Amount as BtcAmount, Txid, address::NetworkUnchecked, hashes::Hash}; 18 use sqlx::Row; 19 use sqlx::postgres::PgRow; 20 use taler_api::db::TypeHelper; 21 use taler_common::types::{ 22 amount::Currency, 23 payto::{PaytoImpl as _, PaytoURI}, 24 }; 25 26 use crate::{payto::BtcWallet, taler_utils::taler_to_btc}; 27 28 /// Bitcoin amount from sql 29 pub fn sql_btc_amount(row: &PgRow, idx: usize, currency: &Currency) -> sqlx::Result<BtcAmount> { 30 let amount = row.try_get_amount_i(idx, currency)?; 31 Ok(taler_to_btc(&amount)) 32 } 33 34 /// Bitcoin address from sql 35 pub fn sql_addr(row: &PgRow, idx: usize) -> sqlx::Result<Address> { 36 Ok(row 37 .try_get_parse::<_, _, Address<NetworkUnchecked>>(idx)? 38 .assume_checked()) 39 } 40 41 /// Bitcoin transaction id from sql 42 pub fn sql_txid(row: &PgRow, idx: usize) -> sqlx::Result<Txid> { 43 row.try_get_map(idx, Txid::from_slice) 44 } 45 46 pub fn sql_payto<I: sqlx::ColumnIndex<PgRow>>( 47 r: &PgRow, 48 addr: I, 49 name: I, 50 ) -> sqlx::Result<PaytoURI> { 51 let addr = r 52 .try_get_parse::<_, _, bitcoin::Address<NetworkUnchecked>>(addr)? 53 .assume_checked(); 54 let name: Option<&str> = r.try_get(name)?; 55 56 Ok(BtcWallet(addr) 57 .as_payto() 58 .as_full_payto(name.unwrap_or("Bitcoin User"))) 59 } 60 61 pub fn sql_generic_payto<I: sqlx::ColumnIndex<PgRow>>( 62 row: &PgRow, 63 idx: I, 64 ) -> sqlx::Result<PaytoURI> { 65 let addr = row 66 .try_get_parse::<_, _, bitcoin::Address<NetworkUnchecked>>(idx)? 67 .assume_checked(); 68 69 Ok(BtcWallet(addr).as_payto().as_full_payto("Bitcoin User")) 70 }