summaryrefslogtreecommitdiff
path: root/src/database.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/database.rs')
-rw-r--r--src/database.rs15
1 files changed, 11 insertions, 4 deletions
diff --git a/src/database.rs b/src/database.rs
index edb2fc7..a73aafd 100644
--- a/src/database.rs
+++ b/src/database.rs
@@ -1,9 +1,9 @@
use std::str::FromStr;
use futures::TryStreamExt;
-use log::{debug, error, info, warn};
use sqlx::Row;
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
+use tracing::debug;
use crate::user::User;
@@ -15,11 +15,13 @@ pub async fn open(file_path: &str) -> Result<DbPool, sqlx::Error> {
let opt =
SqliteConnectOptions::from_str(format!("sqlite://{}", file_path).as_str())?
.create_if_missing(true);
+ debug!("Opening database pool...");
let pool = SqlitePoolOptions::new()
.max_connections(SQLITE_THREAD_POOL_SIZE)
.connect_with(opt).await?;
// create table
+ debug!("Creating user table if not exist...");
sqlx::query(r#"CREATE TABLE IF NOT EXISTS "user" (
"id" INTEGER NOT NULL CHECK(id >= 0) UNIQUE,
"name" TEXT,
@@ -28,10 +30,12 @@ pub async fn open(file_path: &str) -> Result<DbPool, sqlx::Error> {
PRIMARY KEY("id","token","chat_id")
)"#).execute(&pool).await?;
+ debug!("Finish opening database.");
Ok(pool)
}
pub async fn get_user(db: &DbPool, sql: &str, param: &str) -> Result<Option<User>, sqlx::Error> {
+ debug!(sql, param, "Database query.");
let mut rows =
sqlx::query(sql)
.bind(param).fetch(db);
@@ -52,20 +56,23 @@ pub async fn get_user(db: &DbPool, sql: &str, param: &str) -> Result<Option<User
}
pub async fn get_user_by_token(db: &DbPool, token: &str) -> Result<Option<User>, sqlx::Error> {
+ debug!(token, "Get user by token.");
get_user(db, "SELECT id, name, token, chat_id FROM user WHERE token=$1 LIMIT 1",
token).await
}
pub async fn get_user_by_chat_id(db: &DbPool, chat_id: u64) -> Result<Option<User>, sqlx::Error> {
+ debug!(chat_id, "Get user by chat_id.");
get_user(db, "SELECT id, name, token, chat_id FROM user WHERE chat_id=$1 LIMIT 1",
chat_id.to_string().as_str()).await
}
-pub async fn create_user(db: &DbPool, user: User) -> sqlx::Result<()> {
+pub async fn create_user(db: &DbPool, user: &User) -> sqlx::Result<()> {
+ debug!("Create user: {}", user);
sqlx::query("INSERT INTO user (id, name, token, chat_id) VALUES ($1,$2,$3,$4)")
.bind(user.id.to_string())
- .bind(user.name)
- .bind(user.token)
+ .bind(user.name.clone())
+ .bind(user.token.clone())
.bind(user.chat_id.to_string())
.execute(db).await?;
Ok(())