version 0.1
This commit is contained in:
25
src/db.rs
Normal file
25
src/db.rs
Normal file
@@ -0,0 +1,25 @@
|
||||
use rocket::futures::lock::Mutex;
|
||||
use tokio_postgres::{Client, Error, Statement};
|
||||
|
||||
use crate::GlobalState;
|
||||
|
||||
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)))
|
||||
}
|
||||
|
||||
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?;
|
||||
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_tables(db: &Client) -> Result<(), Error> {
|
||||
db.execute("CREATE TABLE IF NOT EXISTS links (id TEXT PRIMARY KEY, url TEXT NOT NULL)", &[]).await?;
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user