From df07b13b2871db21cc8a4a75dddcb2b8d2e2f4bc Mon Sep 17 00:00:00 2001 From: Chris Cochrun Date: Wed, 25 Sep 2024 06:35:31 -0500 Subject: [PATCH] trying to add sqlx to the video_model --- rustfmt.toml | 3 +- src/rust/songs/song_model.rs | 17 --- src/rust/video_model.rs | 268 +++++++++++++++++------------------ 3 files changed, 130 insertions(+), 158 deletions(-) diff --git a/rustfmt.toml b/rustfmt.toml index 5e461f8..91b451d 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,2 +1,3 @@ max_width = 70 -version = "Two" \ No newline at end of file +style_edition = "2024" +# version = "Two" \ No newline at end of file diff --git a/src/rust/songs/song_model.rs b/src/rust/songs/song_model.rs index ab2a8c4..8de3193 100644 --- a/src/rust/songs/song_model.rs +++ b/src/rust/songs/song_model.rs @@ -240,19 +240,14 @@ pub mod song_model { } } -use crate::models::*; -use crate::schema::songs::dsl::*; use crate::songs::song_editor::song_editor::QList_QString; use cxx_qt::{CxxQtType, Threading}; use cxx_qt_lib::{ QByteArray, QModelIndex, QString, QStringList, QVariant, }; -// use diesel::sqlite::SqliteConnection; -use diesel::{delete, insert_into, prelude::*, update}; use sqlx::{query, query_as, Connection, SqliteConnection}; use std::collections::HashMap; use std::pin::Pin; -use std::slice::Iter; use tracing::{debug, error}; use self::song_model::{ @@ -330,15 +325,7 @@ impl song_model::SongModel { } pub fn setup(mut self: Pin<&mut Self>) { - - 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); static DATABASE_URL: &str = "sqlite:///home/chris/.local/share/lumina/library-db.sqlite3"; - let thread = self.qt_thread(); let rt = tokio::runtime::Runtime::new().unwrap(); rt.block_on(async { let result = query_as!(Song, r#"SELECT vorder as "verse_order!", fontSize as "font_size!: i32", backgroundType as "background_type!", horizontalTextAlignment as "horizontal_text_alignment!", verticalTextAlignment as "vertical_text_alignment!", title as "title!", font as "font!", background as "background!", lyrics as "lyrics!", ccli as "ccli!", author as "author!", audio as "audio!", id as "id: i32" from songs"#).fetch_all(&mut self.as_mut().rust_mut().db).await; @@ -393,10 +380,6 @@ impl song_model::SongModel { true } - fn get_db(self: Pin<&mut Self>) -> SqliteConnection { - todo!() - } - pub fn new_song(mut self: Pin<&mut Self>) -> bool { let song_id = self.rust().highest_id + 1; let song_title = String::from("title"); diff --git a/src/rust/video_model.rs b/src/rust/video_model.rs index 7748190..5650d6d 100644 --- a/src/rust/video_model.rs +++ b/src/rust/video_model.rs @@ -178,15 +178,12 @@ mod video_model { } } -use crate::models::run_migrations; -use crate::schema::videos::dsl::*; -use cxx_qt::CxxQtType; +use cxx_qt::{CxxQtType, Threading}; use cxx_qt_lib::{QByteArray, QModelIndex, QString, QUrl, QVariant}; -use diesel::sqlite::SqliteConnection; -use diesel::{delete, insert_into, prelude::*, update}; +use sqlx::{query, query_as, SqliteConnection}; use std::path::PathBuf; use std::pin::Pin; -use tracing::debug; +use tracing::{debug, error}; use self::video_model::{ QHash_i32_QByteArray, QMap_QString_QVariant, QVector_i32, @@ -203,12 +200,35 @@ pub struct Video { looping: bool, } -#[derive(Default, Debug)] +#[derive(Debug)] pub struct VideoModelRust { count: i32, highest_id: i32, videos: Vec, inner_videos: Vec, + db: SqliteConnection, +} + +impl Default for VideoModelRust { + fn default() -> Self { + Self { + count: 0, + highest_id: 0, + videos: vec![], + inner_videos: 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 video_model::VideoModel { @@ -221,91 +241,54 @@ impl video_model::VideoModel { } pub fn setup(mut self: Pin<&mut Self>) { - let db = &mut self.as_mut().get_db(); - run_migrations(db); - let results = videos - .load::(db) - .expect("Error loading videos"); - self.as_mut().rust_mut().highest_id = 0; - - println!("SHOWING VIDEOS"); - println!("--------------"); - for video in results { - println!("{}", video.title); - println!("{}", video.id); - println!("{}", video.path); - println!("--------------"); - if self.as_mut().highest_id < video.id { - self.as_mut().rust_mut().highest_id = video.id; + let rt = tokio::runtime::Runtime::new().unwrap(); + rt.block_on(async { + let result = query_as!(Video, r#"SELECT id as "id: i32", title as "title!", filePath as "path!", startTime as "start_time!: f32", endTime as "end_time!: f32", loop as "looping!" from videos"#).fetch_all(&mut self.as_mut().rust_mut().db).await; + match result { + Ok(v) => v.into_iter().for_each(|v| self.as_mut().add_video(v)), + Err(e) => error!("There was an error in converting songs: {e}"), } - - let img = self::Video { - id: video.id, - title: video.title, - path: video.path, - start_time: video.start_time.unwrap_or(0.0), - end_time: video.end_time.unwrap_or(0.0), - looping: video.looping, - }; - - self.as_mut().add_video(img); - } - println!("--------------------------------------"); - println!("{:?}", self.as_mut().videos); - println!("--------------------------------------"); + }); } pub fn remove_item(mut self: Pin<&mut Self>, index: i32) -> bool { if index < 0 || (index as usize) >= self.videos.len() { return false; } - let db = &mut self.as_mut().get_db(); - let video_id = self.videos.get(index as usize).unwrap().id; + let thread = self.qt_thread(); + let rt = tokio::runtime::Runtime::new().unwrap(); - let result = - delete(videos.filter(id.eq(video_id))).execute(db); - - match result { - Ok(_i) => { - unsafe { - self.as_mut().begin_remove_rows( - &QModelIndex::default(), - index, - index, - ); - self.as_mut() - .rust_mut() - .videos - .remove(index as usize); - self.as_mut() - .rust_mut() - .inner_videos - .remove(index as usize); - self.as_mut().end_remove_rows(); + rt.block_on(async { + let result = query!("delete from videos where id = ?", video_id).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() + .videos + .remove(index as usize); + self.as_mut() + .rust_mut() + .inner_videos + .remove(index as usize); + self.as_mut().end_remove_rows(); + } + debug!("removed-item-at-index: {:?}", video_id); + true + } + Err(e) => { + error!("Cannot connect to database: {e}"); + false } - println!("removed-item-at-index: {:?}", video_id); - println!("new-Vec: {:?}", self.as_mut().videos); - 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) { @@ -330,43 +313,41 @@ impl video_model::VideoModel { video_title: QString, video_path: QString, ) -> bool { - let db = &mut self.as_mut().get_db(); - // println!("{:?}", db); - let video = self::Video { - id: video_id, - title: video_title.clone().to_string(), - path: video_path.clone().to_string(), - start_time: 0.0, - end_time: 0.0, - looping: false, - }; - println!("{:?}", video); + let rt = tokio::runtime::Runtime::new().unwrap(); + rt.block_on(async { + let video_title = video_title.to_string(); + let video_path = video_path.to_string(); + let result = query!(r#"INSERT into videos (id, title, filePath, startTime, endTime, loop) VALUES (?, ?, ?, ?, ?, ?)"#, + video_id, + video_title, + video_path, + 0.0, + 0.0, + false).execute(&mut self.as_mut().rust_mut().db).await; - let result = insert_into(videos) - .values(( - id.eq(&video_id), - title.eq(&video_title.to_string()), - path.eq(&video_path.to_string()), - start_time.eq(&video.start_time), - end_time.eq(&video.end_time), - looping.eq(&video.looping), - )) - .execute(db); - println!("{:?}", result); - - match result { - Ok(_i) => { - self.as_mut().add_video(video); - println!("{:?}", self.as_mut().videos); - true + match result { + Ok(_i) => { + let video = Video { + id: video_id, + title: video_title.to_string(), + path: video_path.to_string(), + start_time: 0.0, + end_time: 0.0, + looping: false + }; + self.as_mut().add_video(video); + debug!("{:?}", self.as_mut().videos); + true + } + Err(e) => { + error!( + "Cannot connect to database: {e}" + ); + false + } } - Err(_e) => { - println!( - "Cannot connect to database or there was an error in inserting the video" - ); - false - } - } + }); + true } fn add_video(mut self: Pin<&mut Self>, video: self::Video) { @@ -435,32 +416,39 @@ impl video_model::VideoModel { println!("rust-video: {:?}", index); println!("rust-loop: {:?}", loop_value); - let db = &mut self.as_mut().get_db(); - let result = update(videos.filter(id.eq(index))) - .set(looping.eq(loop_value)) - .execute(db); - match result { - Ok(_i) => { - for video in self - .as_mut() - .rust_mut() - .videos - .iter_mut() - .filter(|x| x.id == index) - { - video.looping = loop_value; - println!("rust-video: {:?}", video.title); + let rt = tokio::runtime::Runtime::new().unwrap(); + rt.block_on(async { + let result = query!("UPDATE videos SET loop = ? where id = ?", loop_value, index) + .execute(&mut self.as_mut().rust_mut().db) + .await; + match result { + Ok(_i) => { + for video in self + .as_mut() + .rust_mut() + .videos + .iter_mut() + .filter(|x| x.id == index) + { + video.looping = loop_value; + debug!(title = video.title, + looping = loop_value, + "updated video loop"); + } + self.as_mut().data_changed( + model_index, + model_index, + &vector_roles, + ); + true } - self.as_mut().data_changed( - model_index, - model_index, - &vector_roles, - ); - println!("rust-looping: {:?}", loop_value); - true + Err(e) => { + error!("Error connecting to db: {e}"); + false + }, } - Err(_e) => false, - } + }); + true } pub fn update_end_time(