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

75 lines
1.9 KiB
Rust
Raw Normal View History

2023-04-03 20:46:22 +00:00
use rusqlite::Connection;
2024-03-31 20:38:59 +00:00
use serde::Serialize;
#[derive(Serialize)]
2024-03-31 21:07:33 +00:00
pub struct DBRow {
2024-03-31 20:38:59 +00:00
shortlink: String,
longlink: String,
hits: i64,
}
2023-04-03 03:26:23 +00:00
pub fn find_url(shortlink: &str, db: &Connection) -> Option<String> {
2023-04-03 20:46:22 +00:00
let mut statement = db
.prepare_cached("SELECT long_url FROM urls WHERE short_url = ?1")
.unwrap();
statement
.query_row([shortlink], |row| row.get("long_url"))
.ok()
2023-04-03 03:26:23 +00:00
}
2023-04-03 16:55:27 +00:00
2024-03-31 21:07:33 +00:00
pub fn getall(db: &Connection) -> Vec<DBRow> {
2023-04-03 20:46:22 +00:00
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
2024-03-31 21:07:33 +00:00
let mut links: Vec<DBRow> = Vec::new();
2023-04-03 20:46:22 +00:00
while let Some(row) = data.next().unwrap() {
2024-03-31 21:07:33 +00:00
let row_struct = DBRow {
2024-03-31 20:38:59 +00:00
shortlink: row.get("short_url").unwrap(),
longlink: row.get("long_url").unwrap(),
hits: row.get("hits").unwrap(),
};
links.push(row_struct);
2023-04-03 16:55:27 +00:00
}
links
}
2023-04-03 20:46:22 +00:00
2023-04-26 19:40:54 +00:00
pub fn add_hit(shortlink: &str, db: &Connection) {
2023-04-03 20:46:22 +00:00
db.execute(
"UPDATE urls SET hits = hits + 1 WHERE short_url = ?1",
[shortlink],
)
.unwrap();
}
2023-04-03 22:40:37 +00:00
2023-04-03 23:52:17 +00:00
pub fn add_link(shortlink: String, longlink: String, db: &Connection) -> bool {
2023-04-26 19:40:54 +00:00
db.execute(
2023-04-03 22:40:37 +00:00
"INSERT INTO urls (long_url, short_url, hits) VALUES (?1, ?2, ?3)",
(longlink, shortlink, 0),
2023-04-26 19:40:54 +00:00
)
.is_ok()
2023-04-03 22:40:37 +00:00
}
2023-04-03 22:58:19 +00:00
pub fn delete_link(shortlink: String, db: &Connection) -> bool {
let out = db.execute("DELETE FROM urls WHERE short_url = ?1", [shortlink]);
out.is_ok() && (out.unwrap() > 0)
2023-04-03 22:58:19 +00:00
}
2023-04-03 23:52:17 +00:00
pub fn open_db(path: String) -> Connection {
let db = Connection::open(path).expect("Unable to open database!");
2023-04-08 20:36:33 +00:00
// Create table if it doesn't exist
2023-04-03 23:52:17 +00:00
db.execute(
"CREATE TABLE IF NOT EXISTS urls (
id INTEGER PRIMARY KEY AUTOINCREMENT,
long_url TEXT NOT NULL,
short_url TEXT NOT NULL,
hits INTEGER NOT NULL
)",
[],
)
.unwrap();
db
}