From 8c478ace92c716ebbfdba93a28ec4f1907e31f85 Mon Sep 17 00:00:00 2001 From: DenebTM Date: Sat, 10 Feb 2024 13:31:23 +0100 Subject: [PATCH] fix db connection --- .gitignore | 5 +++++ src/db.rs | 20 +++++++++++++------- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index ea8c4bf..e03d9cf 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,6 @@ /target + +/.vscode + +*.db +*.sqlite diff --git a/src/db.rs b/src/db.rs index 37df86b..f284d87 100644 --- a/src/db.rs +++ b/src/db.rs @@ -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)