feat(database): add function `create_tables()`

This commit is contained in:
MedzikUser 2022-06-18 15:22:43 +02:00
parent 7de60b0729
commit 85f577f933
No known key found for this signature in database
GPG Key ID: A5FAC1E185C112DB
2 changed files with 29 additions and 13 deletions

View File

@ -13,7 +13,9 @@ async fn main() {
let config = Config::parse().expect("parse config");
// open database connection
let db = Database::open("homedisk.db").await.expect("open database file");
let db = Database::open("homedisk.db")
.await
.expect("open database file");
// change the type from Vec<String> to Vec<HeaderValue> so that the http server can correctly detect CORS hosts
let origins = config
@ -31,7 +33,9 @@ async fn main() {
);
// start http server
serve_http(host, origins, db, config).await.expect("start http server");
serve_http(host, origins, db, config)
.await
.expect("start http server");
}
/// Init logger

View File

@ -37,6 +37,27 @@ impl Database {
Ok(Self { conn })
}
/// Create all required tabled for HomeDisk
/// ```
/// use homedisk_database::Database;
///
/// #[tokio::main]
/// async fn main() -> anyhow::Result<()> {
/// // open database in memory
/// let db = Database::open("sqlite::memory:").await?;
///
/// // create tables
/// db.create_tables().await?;
///
/// Ok(())
/// }
/// ```
pub async fn create_tables(&self) -> Result<SqliteQueryResult, Error> {
let query = sqlx::query(include_str!("../../tables.sql"));
Ok(self.conn.execute(query).await?)
}
/// Create a new User
/// ```no_run
/// use homedisk_database::{Database, User};
@ -170,10 +191,6 @@ impl Database {
#[cfg(test)]
mod tests {
use std::fs;
use sqlx::Executor;
use crate::{Database, User};
const USERNAME: &str = "medzik";
@ -186,13 +203,8 @@ mod tests {
/// Utils to create a new user in tests
async fn new_user(db: &Database) {
// create user table
db.conn
.execute(sqlx::query(
&fs::read_to_string("../tables.sql").expect("open tables file"),
))
.await
.expect("create tables");
// create tables
db.create_tables().await.expect("create tables");
// create new user
let user = User::new(USERNAME, PASSWORD);