fix db connection

This commit is contained in:
deneb 2024-02-10 13:31:23 +01:00
parent 0a5ab5a199
commit 8c478ace92
2 changed files with 18 additions and 7 deletions

5
.gitignore vendored
View file

@ -1 +1,6 @@
/target
/.vscode
*.db
*.sqlite

View file

@ -1,5 +1,7 @@
use std::str::FromStr;
use secrecy::ExposeSecret;
use sqlx::{query, query_as, Connection, SqliteConnection};
use sqlx::{query, query_as, sqlite::SqliteConnectOptions, Connection, SqliteConnection};
use crate::secrets::UserToken;
@ -21,8 +23,12 @@ pub struct SqliteDatabase {
impl SqliteDatabase {
pub async fn open() -> Self {
let options = SqliteConnectOptions::from_str(DB_URI_DEFAULT)
.expect("Invalid database URI")
.create_if_missing(true);
let mut db = Self {
conn: SqliteConnection::connect(DB_URI_DEFAULT)
conn: SqliteConnection::connect_with(&options)
.await
.expect("Failed to open SQLite database"),
};
@ -33,7 +39,7 @@ impl SqliteDatabase {
}
pub async fn init(&mut self) {
query(
query(&format!(
"CREATE TABLE IF NOT EXISTS {TABLE_USER_TOKENS} (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username VARCHAR(255) NOT NULL,
@ -41,8 +47,8 @@ impl SqliteDatabase {
valid BOOLEAN NOT NULL,
created DATETIME NOT NULL,
last_used DATETIME
)",
)
)"
))
.execute(&mut self.conn)
.await
.expect("Failed to initialize table user_tokens");
@ -69,13 +75,13 @@ impl Database for SqliteDatabase {
}
async fn save_token(&mut self, username: &str, token: &UserToken) -> Result<(), sqlx::Error> {
query(
query(&format!(
"INSERT INTO {TABLE_USER_TOKENS}
(username, token, created, valid)
VALUES
(?, ?, DATETIME('NOW'), TRUE)
",
)
))
.bind(username)
.bind(token.0.expose_secret())
.execute(&mut self.conn)