polymesh_api_tester/
db.rs

1use sqlx::sqlite::*;
2
3use polymesh_api::client::AccountId;
4use polymesh_api::{Api, ChainApi};
5
6use crate::error::Result;
7
8#[derive(Clone)]
9pub struct Db {
10  api: Api,
11  pool: SqlitePool,
12}
13
14impl Db {
15  pub async fn open(api: Api, file: &str) -> Result<Self> {
16    let pool = SqlitePool::connect(file).await?;
17    Ok(Self { api, pool })
18  }
19
20  pub async fn get_next_nonce(&self, account: AccountId) -> Result<u32> {
21    // Get the nonce from the chain.  (to check if the db nonce is old).
22    let nonce = self.api.get_nonce(account).await?;
23
24    let id = account.to_string();
25    // Save the nonce to the database.
26    let rec = sqlx::query!(
27      r#"
28      INSERT INTO accounts(account, nonce) VALUES(?, ?)
29        ON CONFLICT(account) DO UPDATE SET nonce=MAX(nonce+1, excluded.nonce)
30      RETURNING nonce
31      "#,
32      id,
33      nonce
34    )
35    .fetch_one(&self.pool)
36    .await?;
37
38    Ok(rec.nonce as u32)
39  }
40}