From 6c75f59ba12d6c48f54040747508332c56b2b384 Mon Sep 17 00:00:00 2001 From: binarybaron <86064887+binarybaron@users.noreply.github.com> Date: Sun, 12 Nov 2023 14:50:00 +0100 Subject: [PATCH] Use type safe query! macro for database retrieval of states --- swap/sqlite_dev_setup.sh | 1 + swap/sqlx-data.json | 18 ++++++++++++++++++ swap/src/database/sqlite.rs | 8 ++++---- 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/swap/sqlite_dev_setup.sh b/swap/sqlite_dev_setup.sh index 67d2c9da..39d51c0f 100755 --- a/swap/sqlite_dev_setup.sh +++ b/swap/sqlite_dev_setup.sh @@ -2,6 +2,7 @@ # run this script from the swap dir # make sure you have sqlx-cli installed: cargo install sqlx-cli +# it's advised for the sqlx-cli to be the same version as specified in cargo.toml # this script creates a temporary sqlite database # then runs the migration scripts to create the tables (migrations folder) diff --git a/swap/sqlx-data.json b/swap/sqlx-data.json index 3afb7065..f24a50e6 100644 --- a/swap/sqlx-data.json +++ b/swap/sqlx-data.json @@ -177,5 +177,23 @@ } }, "query": "\n SELECT DISTINCT address\n FROM peer_addresses\n WHERE peer_id = ?\n " + }, + "e05620f420f8c1022971eeb66a803323a8cf258cbebb2834e3f7cf8f812fa646": { + "describe": { + "columns": [ + { + "name": "state", + "ordinal": 0, + "type_info": "Text" + } + ], + "nullable": [ + false + ], + "parameters": { + "Right": 1 + } + }, + "query": "\n SELECT state\n FROM swap_states\n WHERE swap_id = ?\n " } } \ No newline at end of file diff --git a/swap/src/database/sqlite.rs b/swap/src/database/sqlite.rs index 30a7b2b7..751f76aa 100644 --- a/swap/src/database/sqlite.rs +++ b/swap/src/database/sqlite.rs @@ -5,7 +5,7 @@ use anyhow::{anyhow, Context, Result}; use async_trait::async_trait; use libp2p::{Multiaddr, PeerId}; use sqlx::sqlite::Sqlite; -use sqlx::{Pool, Row, SqlitePool}; +use sqlx::{Pool, SqlitePool}; use std::collections::HashMap; use std::path::Path; use std::str::FromStr; @@ -276,21 +276,21 @@ impl Database for SqliteDatabase { // TODO: We should use query! instead of query here to allow for at-compile-time validation // I didn't manage to generate the mappings for the query! macro because of problems with sqlx-cli - let rows = sqlx::query( + let rows = sqlx::query!( r#" SELECT state FROM swap_states WHERE swap_id = ? "#, + swap_id ) - .bind(swap_id) .fetch_all(&mut conn) .await?; let result = rows .iter() .map(|row| { - let state_str: &str = row.try_get("state")?; + let state_str: &str = &row.state; let state = match serde_json::from_str::(state_str) { Ok(a) => Ok(State::from(a)),