image_model transition to sqlx

This commit is contained in:
Chris Cochrun 2024-09-25 11:08:14 -05:00
parent a697e4d89c
commit 9b8ed5a1cb

View file

@ -156,15 +156,12 @@ mod image_model {
} }
} }
use crate::models::run_migrations;
use crate::schema::images::dsl::*;
use cxx_qt::CxxQtType; use cxx_qt::CxxQtType;
use cxx_qt_lib::{QModelIndex, QString, QUrl, QVariant}; use cxx_qt_lib::{QModelIndex, QString, QUrl, QVariant};
use diesel::sqlite::SqliteConnection; use sqlx::{query, query_as, Connection, SqliteConnection};
use diesel::{delete, insert_into, prelude::*, update};
use std::path::PathBuf; use std::path::PathBuf;
use std::pin::Pin; use std::pin::Pin;
use tracing::debug; use tracing::{debug, error};
use self::image_model::{ use self::image_model::{
ImageRoles, QHash_i32_QByteArray, QMap_QString_QVariant, ImageRoles, QHash_i32_QByteArray, QMap_QString_QVariant,
@ -172,19 +169,41 @@ use self::image_model::{
}; };
#[derive(Default, Clone, Debug)] #[derive(Default, Clone, Debug)]
/// Idk what this is but it's cool
pub struct Image { pub struct Image {
id: i32, id: i32,
title: String, title: String,
path: String, path: String,
} }
#[derive(Default, Debug)] #[derive(Debug)]
pub struct ImageModelRust { pub struct ImageModelRust {
count: i32, count: i32,
highest_id: i32, highest_id: i32,
images: Vec<Image>, images: Vec<Image>,
inner_images: Vec<Image>, inner_images: Vec<Image>,
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 { impl image_model::ImageModel {
@ -197,48 +216,25 @@ impl image_model::ImageModel {
} }
pub fn setup(mut self: Pin<&mut Self>) { pub fn setup(mut self: Pin<&mut Self>) {
let db = &mut self.as_mut().get_db(); let rt = tokio::runtime::Runtime::new().unwrap();
run_migrations(db); rt.block_on(async {
let results = images 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;
.load::<crate::models::Image>(db) match result {
.expect("Error loading images"); Ok(i) => i.into_iter().for_each(|i| self.as_mut().add_image(i)),
self.as_mut().rust_mut().highest_id = 0; Err(e) => error!("There was an error in converting songs: {e}"),
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 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 { pub fn remove_item(mut self: Pin<&mut Self>, index: i32) -> bool {
if index < 0 || (index as usize) >= self.images.len() { if index < 0 || (index as usize) >= self.images.len() {
return false; 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);
rt.block_on(async {
let result = query!("delete from images where id = ?", index).execute(&mut self.as_mut().rust_mut().db).await;
match result { match result {
Ok(_i) => { Ok(_i) => {
unsafe { unsafe {
@ -257,28 +253,16 @@ impl image_model::ImageModel {
.remove(index as usize); .remove(index as usize);
self.as_mut().end_remove_rows(); self.as_mut().end_remove_rows();
} }
println!("removed-item-at-index: {:?}", image_id); debug!("removed-item-at-index: {:?}", index);
println!("new-Vec: {:?}", self.as_mut().images);
true true
} }
Err(_e) => { Err(e) => {
println!("Cannot connect to database"); error!("Cannot connect to database: {e}");
false false
} }
} }
} });
true
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)
})
} }
pub fn new_item(mut self: Pin<&mut Self>, url: QUrl) { pub fn new_item(mut self: Pin<&mut Self>, url: QUrl) {
@ -303,35 +287,36 @@ impl image_model::ImageModel {
image_title: QString, image_title: QString,
image_path: QString, image_path: QString,
) -> bool { ) -> bool {
let db = &mut self.as_mut().get_db(); let rt = tokio::runtime::Runtime::new().unwrap();
// println!("{:?}", db); rt.block_on(async {
let image = self::Image { let image_title = image_title.to_string();
id: image_id, let image_path = image_path.to_string();
title: image_title.clone().to_string(), let result = query!(r#"INSERT into images (id, title, filePath) VALUES (?, ?, ?)"#,
path: image_path.clone().to_string(), image_id,
}; image_title,
println!("{:?}", image); 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 { match result {
Ok(_i) => { Ok(_i) => {
let image = Image {
id: image_id,
title: image_title.to_string(),
path: image_path.to_string(),
};
self.as_mut().add_image(image); self.as_mut().add_image(image);
println!("{:?}", self.as_mut().images); debug!("{:?}", self.as_mut().images);
true true
} }
Err(_e) => { Err(e) => {
println!("Cannot connect to database"); error!(
"Cannot connect to database: {e}"
);
false false
} }
} }
});
true
} }
fn add_image(mut self: Pin<&mut Self>, image: self::Image) { fn add_image(mut self: Pin<&mut Self>, image: self::Image) {
@ -362,10 +347,12 @@ impl image_model::ImageModel {
let model_index = let model_index =
&self.as_ref().index(index, 0, &QModelIndex::default()); &self.as_ref().index(index, 0, &QModelIndex::default());
let db = &mut self.as_mut().get_db(); let rt = tokio::runtime::Runtime::new().unwrap();
let result = update(images.filter(id.eq(index))) rt.block_on(async {
.set(title.eq(updated_title.to_string())) let title = updated_title.to_string();
.execute(db); let result = query!("UPDATE images SET title = ? where id = ?", title, index)
.execute(&mut self.as_mut().rust_mut().db)
.await;
match result { match result {
Ok(_i) => { Ok(_i) => {
for image in self for image in self
@ -375,8 +362,10 @@ impl image_model::ImageModel {
.iter_mut() .iter_mut()
.filter(|x| x.id == index) .filter(|x| x.id == index)
{ {
image.title = updated_title.clone().to_string(); image.title = title.clone();
println!("rust-title: {:?}", image.title); debug!(title = image.title,
title = title,
"updated image title");
} }
self.as_mut().data_changed( self.as_mut().data_changed(
model_index, model_index,
@ -385,14 +374,19 @@ impl image_model::ImageModel {
); );
true true
} }
Err(_e) => false, Err(e) => {
error!("Error connecting to db: {e}");
false
},
} }
});
true
} }
pub fn update_file_path( pub fn update_file_path(
mut self: Pin<&mut Self>, mut self: Pin<&mut Self>,
index: i32, index: i32,
updated_file_path: QString, updated_path: QString,
) -> bool { ) -> bool {
let mut vector_roles = QVector_i32::default(); let mut vector_roles = QVector_i32::default();
vector_roles vector_roles
@ -400,10 +394,12 @@ impl image_model::ImageModel {
let model_index = let model_index =
&self.as_ref().index(index, 0, &QModelIndex::default()); &self.as_ref().index(index, 0, &QModelIndex::default());
let db = &mut self.as_mut().get_db(); let rt = tokio::runtime::Runtime::new().unwrap();
let result = update(images.filter(id.eq(index))) rt.block_on(async {
.set(path.eq(updated_file_path.to_string())) let updated_path = updated_path.to_string();
.execute(db); let result = query!("UPDATE images SET filePath = ? where id = ?", updated_path, index)
.execute(&mut self.as_mut().rust_mut().db)
.await;
match result { match result {
Ok(_i) => { Ok(_i) => {
for image in self for image in self
@ -413,9 +409,10 @@ impl image_model::ImageModel {
.iter_mut() .iter_mut()
.filter(|x| x.id == index) .filter(|x| x.id == index)
{ {
image.path = image.path = updated_path.clone();
updated_file_path.clone().to_string(); debug!(title = image.title,
println!("rust-title: {:?}", image.path); path = updated_path,
"updated image path");
} }
self.as_mut().data_changed( self.as_mut().data_changed(
model_index, model_index,
@ -424,8 +421,13 @@ impl image_model::ImageModel {
); );
true true
} }
Err(_e) => false, Err(e) => {
error!("Error connecting to db: {e}");
false
},
} }
});
true
} }
pub fn get_item( pub fn get_item(