Skip to content

Commit

Permalink
optimize v2 delegation. (#238)
Browse files Browse the repository at this point in the history
  • Loading branch information
ch4ns1q1 authored Mar 12, 2024
1 parent 8330682 commit 36386c2
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 11 deletions.
2 changes: 1 addition & 1 deletion explorer/src/service/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -793,7 +793,7 @@ impl Api {
)]
async fn v2_get_delegations(
&self,
address: Query<String>,
address: Query<Option<String>>,
page: Query<Option<i64>>,
page_size: Query<Option<i64>>,
) -> poem::Result<V2DelegationsResponse> {
Expand Down
36 changes: 26 additions & 10 deletions explorer/src/service/v2/delegation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,25 +102,41 @@ pub struct V2DelegationTxsData {

pub async fn v2_get_delegations(
api: &Api,
address: Query<String>,
address: Query<Option<String>>,
page: Query<Option<i64>>,
page_size: Query<Option<i64>>,
) -> Result<V2DelegationsResponse> {
let page = page.0.unwrap_or(1);
let page_size = page_size.0.unwrap_or(10);
let mut conn = api.storage.lock().await.acquire().await?;
let sql_count = format!(
"SELECT count(*) AS cnt FROM delegations WHERE sender='{}'",
address.0.to_lowercase()
);

let (sql_count, sql_query) = if let Some(addr) = address.0 {
(
format!(
"SELECT count(*) AS cnt FROM delegations WHERE sender='{}'",
addr.to_lowercase()
),
format!(
"SELECT tx,block,sender,amount,validator,new_validator,timestamp,height,content FROM delegations WHERE sender='{}' ORDER BY timestamp DESC LIMIT {} OFFSET {}",
addr.to_lowercase(),
page_size,
(page - 1) * page_size
),
)
} else {
(
"SELECT count(*) AS cnt FROM delegations".to_string(),
format!(
"SELECT tx,block,sender,amount,validator,new_validator,timestamp,height,content FROM delegations 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 sql_query = format!(
"SELECT tx,block,sender,amount,validator,new_validator,timestamp,height,content FROM delegations WHERE sender='{}' ORDER BY timestamp DESC LIMIT {} OFFSET {}",
address.0.to_lowercase(), page_size, (page-1)*page_size
);

let mut res: Vec<V2Delegation> = vec![];
let rows = sqlx::query(sql_query.as_str()).fetch_all(&mut conn).await?;
for row in rows {
Expand Down

0 comments on commit 36386c2

Please sign in to comment.