Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hooking DB #17

Merged
merged 12 commits into from
Aug 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added .vsb
Empty file.
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@
},
"prettier.tabWidth": 4,
"css.lint.unknownProperties": "ignore",
"rust-analyzer.showUnlinkedFileNotification": false,
}
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# Vizia Sample Browser

An audio sample browser application.

| Header 1 | Header 2 |
| --- | --- |
| Table 1 | Table 2 |
18 changes: 16 additions & 2 deletions src/app_data.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,27 @@
use std::sync::{Arc, Mutex};

use vizia::prelude::*;

use crate::state::browser::BrowserState;
use crate::{
database::prelude::{AudioFile, CollectionID, Database, DatabaseAudioFileHandler},
state::browser::{BrowserState, Directory},
};

#[derive(Lens)]
pub struct AppData {
pub database: Arc<Mutex<Database>>,
pub browser: BrowserState,
pub browser_width: f32,
pub table_height: f32,
pub table_headers: Vec<String>,
pub table_rows: Vec<Vec<String>>,
pub table_rows: Vec<AudioFile>,
pub search_text: String,
}

pub enum AppEvent {
SetBrowserWidth(f32),
SetTableHeight(f32),
ViewCollection(CollectionID),
}

impl Model for AppData {
Expand All @@ -24,6 +31,13 @@ impl Model for AppData {
event.map(|app_event, _| match app_event {
AppEvent::SetBrowserWidth(width) => self.browser_width = *width,
AppEvent::SetTableHeight(height) => self.table_height = *height,
AppEvent::ViewCollection(id) => {
if let Ok(db) = self.database.lock() {
if let Ok(audio_files) = db.get_child_audio_files(*id) {
self.table_rows = audio_files;
}
}
}
});
}
}
1 change: 0 additions & 1 deletion src/app_event.rs

This file was deleted.

23 changes: 12 additions & 11 deletions src/database/audio_file.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
use vizia::prelude::*;

use super::{CollectionID, Database, DatabaseConnectionHandle, DatabaseError};
use serde::{Deserialize, Serialize};

pub type AudioFileID = usize;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Data, Lens)]
pub struct AudioFile {
id: AudioFileID,
name: String,
collection: CollectionID,
duration: f32,
sample_rate: f32,
bit_depth: f32,
bpm: Option<f32>,
key: Option<f32>,
size: f32,
pub id: AudioFileID,
pub name: String,
pub collection: CollectionID,
pub duration: f32,
pub sample_rate: f32,
pub bit_depth: f32,
pub bpm: Option<f32>,
pub key: Option<f32>,
pub size: f32,
}

impl AudioFile {
Expand Down Expand Up @@ -101,7 +103,6 @@ impl DatabaseAudioFileHandler for Database {
audio_file.bit_depth,
audio_file.bpm,
audio_file.key,
audio_file.key,
audio_file.size,
),
)?;
Expand Down
61 changes: 43 additions & 18 deletions src/database/collection.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::path::{Path, PathBuf};

use super::{Database, DatabaseConnectionHandle, DatabaseError};
use serde::{Deserialize, Serialize};

Expand All @@ -7,11 +9,17 @@ pub struct Collection {
id: CollectionID,
parent_collection: Option<CollectionID>,
name: String,
path: PathBuf,
}

impl Collection {
pub fn new(id: CollectionID, parent_collection: Option<CollectionID>, name: String) -> Self {
Self { id, parent_collection, name }
pub fn new(
id: CollectionID,
parent_collection: Option<CollectionID>,
name: String,
path: PathBuf,
) -> Self {
Self { id, parent_collection, name, path }
}

pub fn id(&self) -> usize {
Expand All @@ -25,6 +33,10 @@ impl Collection {
pub fn name(&self) -> &str {
self.name.as_ref()
}

pub fn path(&self) -> &PathBuf {
&self.path
}
}

pub trait DatabaseCollectionHandler {
Expand All @@ -39,11 +51,17 @@ impl DatabaseCollectionHandler for Database {
fn get_root_collection(&self) -> Result<Collection, DatabaseError> {
if let Some(connection) = self.get_connection() {
let mut query = connection.prepare(
"SELECT id, parent_collection, name FROM collections WHERE parent_collection IS NULL",
"SELECT id, parent_collection, name, path FROM collections WHERE parent_collection IS NULL",
)?;

let col: Collection = query.query_row([], |row| {
Ok(Collection { id: row.get(0)?, parent_collection: None, name: row.get(2)? })
let path: String = row.get(3)?;
Ok(Collection::new(
row.get(0)?,
row.get(1)?,
row.get(2)?,
Path::new(&path).to_path_buf(),
))
})?;

return Ok(col);
Expand All @@ -55,14 +73,19 @@ impl DatabaseCollectionHandler for Database {
fn get_all_collections(&self) -> Result<Vec<Collection>, DatabaseError> {
if let Some(connection) = self.get_connection() {
let mut query =
connection.prepare("SELECT id, parent_collection, name FROM collections")?;
connection.prepare("SELECT id, parent_collection, name, path FROM collections")?;

let collections = query.query_map([], |row| {
Ok(Collection {
id: row.get(0)?,
parent_collection: row.get(1)?,
name: row.get(2)?,
})
Ok(Collection::new(
row.get(0)?,
row.get(1)?,
row.get(2)?,
Path::new(&{
let s: String = row.get(3)?;
s
})
.to_path_buf(),
))
})?;

return Ok(collections.map(|v| v.unwrap()).collect());
Expand All @@ -77,15 +100,17 @@ impl DatabaseCollectionHandler for Database {
) -> Result<Vec<Collection>, DatabaseError> {
if let Some(connection) = self.get_connection() {
let mut query = connection.prepare(
"SELECT id, parent_collection, name FROM collections WHERE parent_collection = (?1)",
"SELECT id, parent_collection, name, path FROM collections WHERE parent_collection = (?1)",
)?;

let collections = query.query_map([parent], |row| {
Ok(Collection {
id: row.get(0)?,
name: row.get(2)?,
parent_collection: row.get(1)?,
})
let path: String = row.get(3)?;
Ok(Collection::new(
row.get(0)?,
row.get(1)?,
row.get(2)?,
Path::new(&path).to_path_buf(),
))
})?;

return Ok(collections.map(|v| v.unwrap()).collect());
Expand All @@ -97,8 +122,8 @@ impl DatabaseCollectionHandler for Database {
fn insert_collection(&mut self, collection: Collection) -> Result<(), DatabaseError> {
if let Some(connection) = self.get_connection() {
connection.execute(
"INSERT INTO collections (id, parent_collection, name) VALUES (?1, ?2, ?3)",
(collection.id, collection.parent_collection, collection.name),
"INSERT INTO collections (id, parent_collection, name, path) VALUES (?1, ?2, ?3, ?4)",
(collection.id, collection.parent_collection, collection.name, collection.path.to_str().unwrap()),
)?;
}

Expand Down
2 changes: 1 addition & 1 deletion src/database/error.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#[derive(Debug)]
pub enum DatabaseError {
ConnectionClosed,
PathNotDirecotry,
PathNotDirectory,
RusqliteError(rusqlite::Error),
IOError(std::io::Error),
}
Expand Down
81 changes: 14 additions & 67 deletions src/database/handler.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::state::browser::Directory;

use super::*;
use itertools::Itertools;
use rusqlite::Connection;
use std::{
any::Any,
Expand All @@ -13,11 +12,12 @@ use std::{
rc::Rc,
sync::atomic::AtomicUsize,
};
use vizia::prelude::*;

pub const DATABASE_FILE_NAME: &str = ".database.vsb";
pub const AUDIO_FILE_EXTENSIONS: [&'static str; 1] = ["wav"];

#[derive(Debug)]
#[derive(Debug, Lens)]
pub struct Database {
pub(super) path: PathBuf,
pub(super) conn: Option<Connection>,
Expand All @@ -28,7 +28,7 @@ impl Database {
pub fn from_directory(path: PathBuf) -> Result<Self, DatabaseError> {
// Check file is directory
if !directory_exists(&path) {
return Err(DatabaseError::PathNotDirecotry);
return Err(DatabaseError::PathNotDirectory);
}

// Open connection
Expand All @@ -39,8 +39,8 @@ impl Database {

s.open_connection()?;

s.initialize_empty_database();
// if !database_exists {
// s.initialize_empty_database();
// } else {
// s.update_database();
// }
Expand Down Expand Up @@ -68,6 +68,10 @@ impl Database {
let mut colls = collections.borrow_mut();

let name = path.file_name().unwrap().to_str().unwrap().to_string();
if name == ".vsb-meta" {
return;
}

let id = collection_count.load(std::sync::atomic::Ordering::Relaxed);
collection_count.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let parent_id = match parent_path.is_none() {
Expand All @@ -76,7 +80,7 @@ impl Database {
};

// Insert collection
let collection = Collection::new(id, parent_id, name);
let collection = Collection::new(id, parent_id, name, path.clone());

db.insert_collection(collection);

Expand Down Expand Up @@ -154,67 +158,10 @@ where
Ok(())
}

#[derive(Clone, Debug)]
struct RecursiveDir {
id: CollectionID,
parent_id: Option<CollectionID>,
name: String,
children: Vec<RecursiveDir>,
}

fn query_to_recursive(db: &Database) -> RecursiveDir {
let collections = db.get_all_collections().unwrap();

let mut hm: HashMap<CollectionID, RecursiveDir> = HashMap::new();

for coll in collections {
hm.insert(
coll.id(),
RecursiveDir {
id: coll.id(),
parent_id: coll.parent_collection(),
name: coll.name().to_string(),
children: Vec::new(),
},
);
}

fn children_of_collection(
map: &HashMap<CollectionID, RecursiveDir>,
coll: CollectionID,
) -> VecDeque<CollectionID> {
map.values().filter(|v| v.parent_id == Some(coll)).map(|v| v.id).collect()
}

let mut root_dir = hm.values().find(|v| v.parent_id.is_none()).unwrap().clone();

let mut collection_stack: VecDeque<CollectionID> = children_of_collection(&hm, root_dir.id);

while let Some(coll) = collection_stack.pop_front() {
let mut children = children_of_collection(&hm, coll);
collection_stack.append(&mut children);

let coll_data = hm.get(&coll).unwrap().clone();
root_dir.children.push(coll_data);
}

root_dir
}

#[test]
fn query_to_recursive_test() {
let mut handle = Database::from_connection("", Some(Connection::open_in_memory().unwrap()));
handle.get_connection().unwrap().execute_batch(include_str!("sqls/schema.sql")).unwrap();
handle.get_connection().unwrap().execute_batch(include_str!("sqls/test.sql")).unwrap();

let root = query_to_recursive(&handle);

print_directory(&root);
}

fn print_directory(dir: &RecursiveDir) {
println!("{:?}", dir.name);
for child in dir.children.iter() {
print_directory(child)
impl PartialEq for Database {
fn eq(&self, other: &Self) -> bool {
self.path == other.path
&& self.conn.is_some() == other.conn.is_some()
&& self.meta == other.meta
}
}
1 change: 1 addition & 0 deletions src/database/sqls/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ CREATE TABLE collections (
id integer UNIQUE PRIMARY KEY,
parent_collection integer NULL,
name nvarchar(255),
path nvarchar(255),

FOREIGN KEY(parent_collection) REFERENCES collections(id)
);
Expand Down
10 changes: 5 additions & 5 deletions src/database/sqls/test.sql
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
INSERT INTO collections(id, parent_collection, name) VALUES (0, NULL, "Sample Library");
INSERT INTO collections(id, parent_collection, name) VALUES (1, 0, "Library 1");
INSERT INTO collections(id, parent_collection, name) VALUES (2, 0, "Library 2");
INSERT INTO collections(id, parent_collection, name) VALUES (3, 1, "Sub Library 1.1");
INSERT INTO collections(id, parent_collection, name) VALUES (4, 1, "Sub Library 1.2");
INSERT INTO collections(id, parent_collection, name, path) VALUES (0, NULL, "Sample Library", "");
INSERT INTO collections(id, parent_collection, name, path) VALUES (1, 0, "Library 1", "");
INSERT INTO collections(id, parent_collection, name, path) VALUES (2, 0, "Library 2", "");
INSERT INTO collections(id, parent_collection, name, path) VALUES (3, 1, "Sub Library 1.1", "");
INSERT INTO collections(id, parent_collection, name, path) VALUES (4, 1, "Sub Library 1.2", "");

INSERT INTO audio_files(id, name, collection, duration, sample_rate, bit_depth, bpm, key, size) VALUES (0, "Audio File 0", 0, 0, 0, 0, 0, 0, 0);
INSERT INTO audio_files(id, name, collection, duration, sample_rate, bit_depth, bpm, key, size) VALUES (1, "Audio File 1", 1, 0, 0, 0, 0, 0, 0);
Expand Down
Loading
Loading