trying to add sqlx to the video_model

This commit is contained in:
Chris Cochrun 2024-09-25 06:35:31 -05:00
parent e0d7159328
commit df07b13b28
3 changed files with 130 additions and 158 deletions

View file

@ -1,2 +1,3 @@
max_width = 70 max_width = 70
version = "Two" style_edition = "2024"
# version = "Two"

View file

@ -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 crate::songs::song_editor::song_editor::QList_QString;
use cxx_qt::{CxxQtType, Threading}; use cxx_qt::{CxxQtType, Threading};
use cxx_qt_lib::{ use cxx_qt_lib::{
QByteArray, QModelIndex, QString, QStringList, QVariant, QByteArray, QModelIndex, QString, QStringList, QVariant,
}; };
// use diesel::sqlite::SqliteConnection;
use diesel::{delete, insert_into, prelude::*, update};
use sqlx::{query, query_as, Connection, SqliteConnection}; use sqlx::{query, query_as, Connection, SqliteConnection};
use std::collections::HashMap; use std::collections::HashMap;
use std::pin::Pin; use std::pin::Pin;
use std::slice::Iter;
use tracing::{debug, error}; use tracing::{debug, error};
use self::song_model::{ use self::song_model::{
@ -330,15 +325,7 @@ impl song_model::SongModel {
} }
pub fn setup(mut self: Pin<&mut Self>) { 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"; 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(); let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async { 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; 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 true
} }
fn get_db(self: Pin<&mut Self>) -> SqliteConnection {
todo!()
}
pub fn new_song(mut self: Pin<&mut Self>) -> bool { pub fn new_song(mut self: Pin<&mut Self>) -> bool {
let song_id = self.rust().highest_id + 1; let song_id = self.rust().highest_id + 1;
let song_title = String::from("title"); let song_title = String::from("title");

View file

@ -178,15 +178,12 @@ mod video_model {
} }
} }
use crate::models::run_migrations; use cxx_qt::{CxxQtType, Threading};
use crate::schema::videos::dsl::*;
use cxx_qt::CxxQtType;
use cxx_qt_lib::{QByteArray, QModelIndex, QString, QUrl, QVariant}; use cxx_qt_lib::{QByteArray, QModelIndex, QString, QUrl, QVariant};
use diesel::sqlite::SqliteConnection; use sqlx::{query, query_as, 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::video_model::{ use self::video_model::{
QHash_i32_QByteArray, QMap_QString_QVariant, QVector_i32, QHash_i32_QByteArray, QMap_QString_QVariant, QVector_i32,
@ -203,12 +200,35 @@ pub struct Video {
looping: bool, looping: bool,
} }
#[derive(Default, Debug)] #[derive(Debug)]
pub struct VideoModelRust { pub struct VideoModelRust {
count: i32, count: i32,
highest_id: i32, highest_id: i32,
videos: Vec<self::Video>, videos: Vec<self::Video>,
inner_videos: Vec<self::Video>, inner_videos: Vec<self::Video>,
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 { impl video_model::VideoModel {
@ -221,91 +241,54 @@ impl video_model::VideoModel {
} }
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 = videos 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;
.load::<crate::models::Video>(db) match result {
.expect("Error loading videos"); Ok(v) => v.into_iter().for_each(|v| self.as_mut().add_video(v)),
self.as_mut().rust_mut().highest_id = 0; Err(e) => error!("There was an error in converting songs: {e}"),
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 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 { pub fn remove_item(mut self: Pin<&mut Self>, index: i32) -> bool {
if index < 0 || (index as usize) >= self.videos.len() { if index < 0 || (index as usize) >= self.videos.len() {
return false; return false;
} }
let db = &mut self.as_mut().get_db();
let video_id = self.videos.get(index as usize).unwrap().id; 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 = rt.block_on(async {
delete(videos.filter(id.eq(video_id))).execute(db); let result = query!("delete from videos where id = ?", video_id).execute(&mut self.as_mut().rust_mut().db).await;
match result {
match result { Ok(_i) => {
Ok(_i) => { unsafe {
unsafe { self.as_mut().begin_remove_rows(
self.as_mut().begin_remove_rows( &QModelIndex::default(),
&QModelIndex::default(), index,
index, index,
index, );
); self.as_mut()
self.as_mut() .rust_mut()
.rust_mut() .videos
.videos .remove(index as usize);
.remove(index as usize); self.as_mut()
self.as_mut() .rust_mut()
.rust_mut() .inner_videos
.inner_videos .remove(index as usize);
.remove(index as usize); self.as_mut().end_remove_rows();
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"); true
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)
})
} }
pub fn new_item(mut self: Pin<&mut Self>, url: QUrl) { pub fn new_item(mut self: Pin<&mut Self>, url: QUrl) {
@ -330,43 +313,41 @@ impl video_model::VideoModel {
video_title: QString, video_title: QString,
video_path: QString, video_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 video = self::Video { let video_title = video_title.to_string();
id: video_id, let video_path = video_path.to_string();
title: video_title.clone().to_string(), let result = query!(r#"INSERT into videos (id, title, filePath, startTime, endTime, loop) VALUES (?, ?, ?, ?, ?, ?)"#,
path: video_path.clone().to_string(), video_id,
start_time: 0.0, video_title,
end_time: 0.0, video_path,
looping: false, 0.0,
}; 0.0,
println!("{:?}", video); false).execute(&mut self.as_mut().rust_mut().db).await;
let result = insert_into(videos) match result {
.values(( Ok(_i) => {
id.eq(&video_id), let video = Video {
title.eq(&video_title.to_string()), id: video_id,
path.eq(&video_path.to_string()), title: video_title.to_string(),
start_time.eq(&video.start_time), path: video_path.to_string(),
end_time.eq(&video.end_time), start_time: 0.0,
looping.eq(&video.looping), end_time: 0.0,
)) looping: false
.execute(db); };
println!("{:?}", result); self.as_mut().add_video(video);
debug!("{:?}", self.as_mut().videos);
match result { true
Ok(_i) => { }
self.as_mut().add_video(video); Err(e) => {
println!("{:?}", self.as_mut().videos); error!(
true "Cannot connect to database: {e}"
);
false
}
} }
Err(_e) => { });
println!( true
"Cannot connect to database or there was an error in inserting the video"
);
false
}
}
} }
fn add_video(mut self: Pin<&mut Self>, video: self::Video) { 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-video: {:?}", index);
println!("rust-loop: {:?}", loop_value); println!("rust-loop: {:?}", loop_value);
let db = &mut self.as_mut().get_db(); let rt = tokio::runtime::Runtime::new().unwrap();
let result = update(videos.filter(id.eq(index))) rt.block_on(async {
.set(looping.eq(loop_value)) let result = query!("UPDATE videos SET loop = ? where id = ?", loop_value, index)
.execute(db); .execute(&mut self.as_mut().rust_mut().db)
match result { .await;
Ok(_i) => { match result {
for video in self Ok(_i) => {
.as_mut() for video in self
.rust_mut() .as_mut()
.videos .rust_mut()
.iter_mut() .videos
.filter(|x| x.id == index) .iter_mut()
{ .filter(|x| x.id == index)
video.looping = loop_value; {
println!("rust-video: {:?}", video.title); 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( Err(e) => {
model_index, error!("Error connecting to db: {e}");
model_index, false
&vector_roles, },
);
println!("rust-looping: {:?}", loop_value);
true
} }
Err(_e) => false, });
} true
} }
pub fn update_end_time( pub fn update_end_time(