GlobalState stores an array of prepared statements instead of separate fields

This commit is contained in:
Slavasil 2025-05-04 10:41:08 +03:00
parent a06099710f
commit 928912cbfe
2 changed files with 13 additions and 8 deletions

View File

@ -3,20 +3,25 @@ use tokio_postgres::{Client, Error, Statement};
use crate::GlobalState;
pub const STATEMENT_GET_LINK: usize = 0;
pub const STATEMENT_ADD_LINK: usize = 1;
pub const N_STATEMENTS: usize = 2;
pub async fn get_link(state: &Mutex<GlobalState>, link: &str) -> Result<Option<String>, Error> {
let lock = state.lock().await;
Ok(lock.db_client.query_opt(&lock.stmt_get_link, &[&link]).await?.map(|row| row.get(0)))
Ok(lock.db_client.query_opt(&lock.statements[STATEMENT_GET_LINK], &[&link]).await?.map(|row| row.get(0)))
}
pub async fn add_link(state: &Mutex<GlobalState>, link: &str, url: &str) -> Result<(), Error> {
let lock = state.lock().await;
lock.db_client.execute(&lock.stmt_add_link, &[&link, &url]).await?;
lock.db_client.execute(&lock.statements[STATEMENT_ADD_LINK], &[&link, &url]).await?;
Ok(())
}
pub async fn prepare_statements(db: &Client) -> Result<(Statement, Statement), Error> {
Ok((db.prepare("SELECT url FROM links WHERE id = $1").await?,
db.prepare("INSERT INTO links (id, url) VALUES ($1, $2)").await?))
pub async fn prepare_statements(db: &Client) -> Result<[Statement; N_STATEMENTS], Error> {
Ok([db.prepare("SELECT url FROM links WHERE id = $1").await?,
db.prepare("INSERT INTO links (id, url) VALUES ($1, $2)").await?,
])
}
pub async fn prepare_tables(db: &Client) -> Result<(), Error> {

View File

@ -1,3 +1,4 @@
use db::N_STATEMENTS;
use rocket::{futures::lock::Mutex, get, fs::FileServer, http::Status, response::Redirect, response::content::RawHtml, routes, State};
use tokio_postgres::{Client, NoTls, Statement};
use std::fs::File;
@ -11,8 +12,7 @@ const LINK_PREFIX: &str = "https://slavasil.ru/";
pub struct GlobalState {
db_client: Client,
stmt_get_link: Statement,
stmt_add_link: Statement,
statements: [Statement; N_STATEMENTS],
}
#[tokio::main]
async fn main() {
@ -27,7 +27,7 @@ async fn main() {
let statements = db::prepare_statements(&client).await.unwrap();
let mut config = rocket::Config::default();
config.port = 3020;
let state = GlobalState { db_client: client, stmt_get_link: statements.0, stmt_add_link: statements.1 };
let state = GlobalState { db_client: client, statements };
rocket::build()
.mount("/", routes![create, go_to_link])
.manage(Mutex::new(state))