From 32198c69b0e38c77f90e35fea8c4521ffe41f1c9 Mon Sep 17 00:00:00 2001 From: MedzikUser Date: Mon, 4 Jul 2022 16:52:25 +0200 Subject: [PATCH] chore(database): if database file does not exists create it --- README.md | 7 ++----- core/src/lib.rs | 7 ------- core/src/main.rs | 40 +++++++++++++++++++++++++++++++++++----- 3 files changed, 37 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index bcd8918..8e0b5a0 100644 --- a/README.md +++ b/README.md @@ -28,9 +28,6 @@ To build run the command: `cargo build --release` The compiled binary can be found in `./target/release/homedisk` -## 🖴 Creating tables in a SQLite database +## Configure -#### Requirements -- SQLite3 - -Run command `sqlite3 homedisk.db < tables.sql` to create SQLite database +Go to [config](https://homedisk-doc.medzik.xyz/homedisk_types/config) module diff --git a/core/src/lib.rs b/core/src/lib.rs index b56fcaf..87679cb 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -29,13 +29,6 @@ //! //! The compiled binary can be found in `./target/release/homedisk` //! -//! ## 🖴 Create an empty SQLite database from a tables template -//! -//! ### Requirements -//! - [SQLite3](https://sqlite.org) -//! -//! Run command `sqlite3 homedisk.db < tables.sql` to create SQLite database -//! //! ## Configure //! //! Go to [config](homedisk_types::config) module diff --git a/core/src/main.rs b/core/src/main.rs index a0e11bf..6bbbe7c 100644 --- a/core/src/main.rs +++ b/core/src/main.rs @@ -1,6 +1,11 @@ +use std::{fs::File, path::Path}; + use homedisk_database::Database; use homedisk_server::serve_http; use homedisk_types::config::Config; +use log::{info, warn}; + +pub const DATABASE_FILE: &str = "homedisk.db"; #[tokio::main] async fn main() { @@ -13,9 +18,36 @@ 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 = + // if database file doesn't exists create it + if !Path::new(DATABASE_FILE).exists() { + warn!("Database file doesn't exists."); + info!("Creating database file..."); + + // create an empty database file + File::create(DATABASE_FILE).expect("create a database file"); + + // open database file + let db = Database::open(DATABASE_FILE) + .await + .expect("open database file"); + + // create tables in the database + db.create_tables() + .await + .expect("create tables in the database"); + + db + } + // if database file exists + else { + // open database connection + let db = Database::open(DATABASE_FILE) + .await + .expect("open database file"); + + db + }; // change the type from Vec to Vec so that the http server can correctly detect CORS hosts let origins = config @@ -39,8 +71,6 @@ async fn main() { } fn init_logger() -> anyhow::Result<()> { - use std::fs::File; - use log::LevelFilter; use simplelog::{ColorChoice, CombinedLogger, Config, TermLogger, TerminalMode, WriteLogger};