chore(database): if database file does not exists create it

This commit is contained in:
MedzikUser 2022-07-04 16:52:25 +02:00
parent a99f54ec0d
commit 32198c69b0
No known key found for this signature in database
GPG Key ID: A5FAC1E185C112DB
3 changed files with 37 additions and 17 deletions

View File

@ -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

View File

@ -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

View File

@ -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<String> to Vec<HeaderValue> 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};