From 1a99989486c1b4bae165dab483dfa20aef2810b1 Mon Sep 17 00:00:00 2001 From: s1q1ch4n Date: Tue, 12 Mar 2024 13:59:00 +0800 Subject: [PATCH] optimize v2 undelegations. (#239) --- explorer/src/service/api.rs | 2 +- explorer/src/service/v2/undelegation.rs | 32 ++++++++++++++++--------- 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/explorer/src/service/api.rs b/explorer/src/service/api.rs index 785ba19..1fc8b2f 100644 --- a/explorer/src/service/api.rs +++ b/explorer/src/service/api.rs @@ -822,7 +822,7 @@ impl Api { )] async fn v2_get_undelegations( &self, - address: Query, + address: Query>, page: Query>, page_size: Query>, ) -> poem::Result { diff --git a/explorer/src/service/v2/undelegation.rs b/explorer/src/service/v2/undelegation.rs index 4accc88..eacd8cb 100644 --- a/explorer/src/service/v2/undelegation.rs +++ b/explorer/src/service/v2/undelegation.rs @@ -105,25 +105,35 @@ pub struct V2UndelegationsData { pub async fn v2_get_undelegations( api: &Api, - address: Query, + address: Query>, page: Query>, page_size: Query>, ) -> Result { let mut conn = api.storage.lock().await.acquire().await?; let page = page.0.unwrap_or(1); let page_size = page_size.0.unwrap_or(10); - let sql_count = format!( - "SELECT count(*) AS cnt FROM undelegations WHERE sender='{}'", - address.0.to_lowercase() - ); - let row_cnt = sqlx::query(sql_count.as_str()).fetch_one(&mut conn).await?; - let total: i64 = row_cnt.try_get("cnt")?; - let sql_query = format!( - "SELECT tx,block,sender,amount,target_validator,new_delegator,height,timestamp,content FROM undelegations WHERE sender='{}' ORDER BY timestamp DESC LIMIT {} OFFSET {}", - address.0.to_lowercase(), page_size, (page-1)*page_size - ); + let (sql_count, sql_query) = if let Some(addr) = address.0 { + ( + format!( + "SELECT count(*) AS cnt FROM undelegations WHERE sender='{}'", + addr.to_lowercase() + ), + format!( + "SELECT tx,block,sender,amount,target_validator,new_delegator,height,timestamp,content \ + FROM undelegations WHERE sender='{}' ORDER BY timestamp DESC LIMIT {} OFFSET {}", + addr.to_lowercase(), page_size, (page-1)*page_size), + ) + } else { + ( + "SELECT count(*) AS cnt FROM undelegations".to_string(), + format!("SELECT tx,block,sender,amount,target_validator,new_delegator,height,timestamp,content \ + FROM undelegations ORDER BY timestamp DESC LIMIT {} OFFSET {}", page_size, (page-1)*page_size) + ) + }; + let row_cnt = sqlx::query(sql_count.as_str()).fetch_one(&mut conn).await?; + let total: i64 = row_cnt.try_get("cnt")?; let mut res: Vec = vec![]; let rows = sqlx::query(sql_query.as_str()).fetch_all(&mut conn).await?; for row in rows {