From 9b8ed5a1cb442d43f8af7282e21b73a04da76c02 Mon Sep 17 00:00:00 2001 From: Chris Cochrun Date: Wed, 25 Sep 2024 11:08:14 -0500 Subject: [PATCH] image_model transition to sqlx --- src/rust/image_model.rs | 308 ++++++++++++++++++++-------------------- 1 file changed, 155 insertions(+), 153 deletions(-) diff --git a/src/rust/image_model.rs b/src/rust/image_model.rs index 18b83e8..ed4e9cd 100644 --- a/src/rust/image_model.rs +++ b/src/rust/image_model.rs @@ -156,15 +156,12 @@ mod image_model { } } -use crate::models::run_migrations; -use crate::schema::images::dsl::*; use cxx_qt::CxxQtType; use cxx_qt_lib::{QModelIndex, QString, QUrl, QVariant}; -use diesel::sqlite::SqliteConnection; -use diesel::{delete, insert_into, prelude::*, update}; +use sqlx::{query, query_as, Connection, SqliteConnection}; use std::path::PathBuf; use std::pin::Pin; -use tracing::debug; +use tracing::{debug, error}; use self::image_model::{ ImageRoles, QHash_i32_QByteArray, QMap_QString_QVariant, @@ -172,19 +169,41 @@ use self::image_model::{ }; #[derive(Default, Clone, Debug)] -/// Idk what this is but it's cool pub struct Image { id: i32, title: String, path: String, } -#[derive(Default, Debug)] +#[derive(Debug)] pub struct ImageModelRust { count: i32, highest_id: i32, images: Vec, inner_images: Vec, + db: SqliteConnection +} + +impl Default for ImageModelRust { + fn default() -> Self { + Self { + count: 0, + highest_id: 0, + images: vec![], + inner_images: vec![], + db: { + let rt = tokio::runtime::Runtime::new().unwrap(); + let mut data = dirs::data_local_dir().unwrap(); + data.push("lumina"); + data.push("library-db.sqlite3"); + let mut db_url = String::from("sqlite://"); + db_url.push_str(data.to_str().unwrap()); + rt.block_on(async { + SqliteConnection::connect(&db_url).await.expect("problems") + }) + } + } + } } impl image_model::ImageModel { @@ -197,88 +216,53 @@ impl image_model::ImageModel { } pub fn setup(mut self: Pin<&mut Self>) { - let db = &mut self.as_mut().get_db(); - run_migrations(db); - let results = images - .load::(db) - .expect("Error loading images"); - self.as_mut().rust_mut().highest_id = 0; - - println!("SHOWING IMAGES"); - println!("--------------"); - for image in results { - println!("{}", image.title); - println!("{}", image.id); - println!("{}", image.path); - println!("--------------"); - if &self.as_mut().highest_id < &image.id { - self.as_mut().rust_mut().highest_id = image.id; + let rt = tokio::runtime::Runtime::new().unwrap(); + rt.block_on(async { + let result = query_as!(Image, r#"SELECT id as "id: i32", title as "title!", filePath as "path!" from images"#).fetch_all(&mut self.as_mut().rust_mut().db).await; + match result { + Ok(i) => i.into_iter().for_each(|i| self.as_mut().add_image(i)), + Err(e) => error!("There was an error in converting songs: {e}"), } - - let img = self::Image { - id: image.id, - title: image.title, - path: image.path, - }; - - self.as_mut().add_image(img); - } - println!("--------------------------------------"); - println!("{:?}", self.as_mut().images); - println!("--------------------------------------"); + }); } pub fn remove_item(mut self: Pin<&mut Self>, index: i32) -> bool { if index < 0 || (index as usize) >= self.images.len() { return false; } - let db = &mut self.as_mut().get_db(); - let image_id = self.images.get(index as usize).unwrap().id; + let rt = tokio::runtime::Runtime::new().unwrap(); - let result = - delete(images.filter(id.eq(image_id))).execute(db); - - match result { - Ok(_i) => { - unsafe { - self.as_mut().begin_remove_rows( - &QModelIndex::default(), - index, - index, - ); - self.as_mut() - .rust_mut() - .images - .remove(index as usize); - self.as_mut() - .rust_mut() - .inner_images - .remove(index as usize); - self.as_mut().end_remove_rows(); + rt.block_on(async { + let result = query!("delete from images where id = ?", index).execute(&mut self.as_mut().rust_mut().db).await; + match result { + Ok(_i) => { + unsafe { + self.as_mut().begin_remove_rows( + &QModelIndex::default(), + index, + index, + ); + self.as_mut() + .rust_mut() + .images + .remove(index as usize); + self.as_mut() + .rust_mut() + .inner_images + .remove(index as usize); + self.as_mut().end_remove_rows(); + } + debug!("removed-item-at-index: {:?}", index); + true + } + Err(e) => { + error!("Cannot connect to database: {e}"); + false } - println!("removed-item-at-index: {:?}", image_id); - println!("new-Vec: {:?}", self.as_mut().images); - true } - Err(_e) => { - println!("Cannot connect to database"); - false - } - } - } - - fn get_db(self: Pin<&mut Self>) -> SqliteConnection { - let mut data = dirs::data_local_dir().unwrap(); - data.push("lumina"); - data.push("library-db.sqlite3"); - let mut db_url = String::from("sqlite://"); - db_url.push_str(data.to_str().unwrap()); - println!("DB: {:?}", db_url); - - SqliteConnection::establish(&db_url).unwrap_or_else(|_| { - panic!("error connecting to {}", db_url) - }) + }); + true } pub fn new_item(mut self: Pin<&mut Self>, url: QUrl) { @@ -303,35 +287,36 @@ impl image_model::ImageModel { image_title: QString, image_path: QString, ) -> bool { - let db = &mut self.as_mut().get_db(); - // println!("{:?}", db); - let image = self::Image { - id: image_id, - title: image_title.clone().to_string(), - path: image_path.clone().to_string(), - }; - println!("{:?}", image); + let rt = tokio::runtime::Runtime::new().unwrap(); + rt.block_on(async { + let image_title = image_title.to_string(); + let image_path = image_path.to_string(); + let result = query!(r#"INSERT into images (id, title, filePath) VALUES (?, ?, ?)"#, + image_id, + image_title, + image_path) + .execute(&mut self.as_mut().rust_mut().db).await; - let result = insert_into(images) - .values(( - id.eq(&image_id), - title.eq(&image_title.to_string()), - path.eq(&image_path.to_string()), - )) - .execute(db); - println!("{:?}", result); - - match result { - Ok(_i) => { - self.as_mut().add_image(image); - println!("{:?}", self.as_mut().images); - true + match result { + Ok(_i) => { + let image = Image { + id: image_id, + title: image_title.to_string(), + path: image_path.to_string(), + }; + self.as_mut().add_image(image); + debug!("{:?}", self.as_mut().images); + true + } + Err(e) => { + error!( + "Cannot connect to database: {e}" + ); + false + } } - Err(_e) => { - println!("Cannot connect to database"); - false - } - } + }); + true } fn add_image(mut self: Pin<&mut Self>, image: self::Image) { @@ -362,37 +347,46 @@ impl image_model::ImageModel { let model_index = &self.as_ref().index(index, 0, &QModelIndex::default()); - let db = &mut self.as_mut().get_db(); - let result = update(images.filter(id.eq(index))) - .set(title.eq(updated_title.to_string())) - .execute(db); - match result { - Ok(_i) => { - for image in self - .as_mut() - .rust_mut() - .images - .iter_mut() - .filter(|x| x.id == index) - { - image.title = updated_title.clone().to_string(); - println!("rust-title: {:?}", image.title); + let rt = tokio::runtime::Runtime::new().unwrap(); + rt.block_on(async { + let title = updated_title.to_string(); + let result = query!("UPDATE images SET title = ? where id = ?", title, index) + .execute(&mut self.as_mut().rust_mut().db) + .await; + match result { + Ok(_i) => { + for image in self + .as_mut() + .rust_mut() + .images + .iter_mut() + .filter(|x| x.id == index) + { + image.title = title.clone(); + debug!(title = image.title, + title = title, + "updated image title"); + } + self.as_mut().data_changed( + model_index, + model_index, + &vector_roles, + ); + true } - self.as_mut().data_changed( - model_index, - model_index, - &vector_roles, - ); - true + Err(e) => { + error!("Error connecting to db: {e}"); + false + }, } - Err(_e) => false, - } + }); + true } pub fn update_file_path( mut self: Pin<&mut Self>, index: i32, - updated_file_path: QString, + updated_path: QString, ) -> bool { let mut vector_roles = QVector_i32::default(); vector_roles @@ -400,32 +394,40 @@ impl image_model::ImageModel { let model_index = &self.as_ref().index(index, 0, &QModelIndex::default()); - let db = &mut self.as_mut().get_db(); - let result = update(images.filter(id.eq(index))) - .set(path.eq(updated_file_path.to_string())) - .execute(db); - match result { - Ok(_i) => { - for image in self - .as_mut() - .rust_mut() - .images - .iter_mut() - .filter(|x| x.id == index) - { - image.path = - updated_file_path.clone().to_string(); - println!("rust-title: {:?}", image.path); + let rt = tokio::runtime::Runtime::new().unwrap(); + rt.block_on(async { + let updated_path = updated_path.to_string(); + let result = query!("UPDATE images SET filePath = ? where id = ?", updated_path, index) + .execute(&mut self.as_mut().rust_mut().db) + .await; + match result { + Ok(_i) => { + for image in self + .as_mut() + .rust_mut() + .images + .iter_mut() + .filter(|x| x.id == index) + { + image.path = updated_path.clone(); + debug!(title = image.title, + path = updated_path, + "updated image path"); + } + self.as_mut().data_changed( + model_index, + model_index, + &vector_roles, + ); + true } - self.as_mut().data_changed( - model_index, - model_index, - &vector_roles, - ); - true + Err(e) => { + error!("Error connecting to db: {e}"); + false + }, } - Err(_e) => false, - } + }); + true } pub fn get_item(