mirror-chhoto-url/actix/src/database.rs

48 lines
1.3 KiB
Rust
Raw Normal View History

2023-04-03 20:46:22 +00:00
use rusqlite::Connection;
2023-04-03 03:26:23 +00:00
pub fn find_url(shortlink: &str) -> String {
2023-04-03 20:46:22 +00:00
let db = Connection::open("./urls.sqlite").expect("Unable to open database!");
let mut statement = db
.prepare_cached("SELECT long_url FROM urls WHERE short_url = ?1")
.unwrap();
let links = statement
.query_map([shortlink], |row| Ok(row.get("long_url")?))
.unwrap();
let mut longlink = "".to_string();
for link in links {
longlink = link.unwrap();
2023-04-03 03:26:23 +00:00
}
2023-04-03 20:46:22 +00:00
add_hit(shortlink);
longlink
2023-04-03 03:26:23 +00:00
}
2023-04-03 16:55:27 +00:00
pub fn getall() -> Vec<String> {
2023-04-03 20:46:22 +00:00
let db = Connection::open("./urls.sqlite").expect("Unable to open database!");
let mut statement = db.prepare_cached("SELECT * FROM urls").unwrap();
2023-04-03 16:55:27 +00:00
2023-04-03 20:46:22 +00:00
let mut data = statement.query([]).unwrap();
2023-04-03 16:55:27 +00:00
let mut links: Vec<String> = Vec::new();
2023-04-03 20:46:22 +00:00
while let Some(row) = data.next().unwrap() {
let short_url: String = row.get("short_url").unwrap();
let long_url: String = row.get("long_url").unwrap();
let hits: i64 = row.get("hits").unwrap();
2023-04-03 16:55:27 +00:00
links.push(format!("{short_url},{long_url},{hits}"));
}
links
}
2023-04-03 20:46:22 +00:00
fn add_hit(shortlink: &str) -> () {
let db = Connection::open("./urls.sqlite").expect("Unable to open database!");
db.execute(
"UPDATE urls SET hits = hits + 1 WHERE short_url = ?1",
[shortlink],
)
.unwrap();
}