presentation_model using sqlx

This commit is contained in:
Chris Cochrun 2024-09-25 11:21:49 -05:00
parent d871f68ca5
commit ee03777c10

View file

@ -182,15 +182,12 @@ mod presentation_model {
use crate::presentation_model::presentation_model::QMap_QString_QVariant; use crate::presentation_model::presentation_model::QMap_QString_QVariant;
use crate::reveal_js; use crate::reveal_js;
use crate::schema::presentations::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 sqlx::Connection;
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::presentation_model::{ use self::presentation_model::{
PresRoles, QHash_i32_QByteArray, QVector_i32, PresRoles, QHash_i32_QByteArray, QVector_i32,
@ -205,12 +202,35 @@ pub struct Presentation {
page_count: i32, page_count: i32,
} }
#[derive(Default, Debug)] #[derive(Debug)]
pub struct PresentationModelRust { pub struct PresentationModelRust {
count: i32, count: i32,
highest_id: i32, highest_id: i32,
presentations: Vec<Presentation>, presentations: Vec<Presentation>,
inner_presentations: Vec<Presentation>, inner_presentations: Vec<Presentation>,
db: SqliteConnection
}
impl Default for PresentationModelRust {
fn default() -> Self {
Self {
count: 0,
highest_id: 0,
presentations: vec![],
inner_presentations: 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 presentation_model::PresentationModel { impl presentation_model::PresentationModel {
@ -223,102 +243,52 @@ impl presentation_model::PresentationModel {
} }
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();
// let table_info = diesel::sql_query("PRAGMA table_info(presentations)").load(db); rt.block_on(async {
// println!("{:?}", table_info); let result = query_as!(Presentation, r#"SELECT id as "id: i32", title as "title!", filePath as "path!", html as "html!", pageCount as "page_count!: i32" from presentations"#).fetch_all(&mut self.as_mut().rust_mut().db).await;
let results = presentations match result {
.load::<crate::models::Presentation>(db) Ok(p) => p.into_iter().for_each(|p| self.as_mut().add_presentation(p)),
.expect("Error loading presentations"); Err(e) => error!("There was an error in converting songs: {e}"),
self.as_mut().rust_mut().highest_id = 0;
println!("SHOWING PRESENTATIONS");
println!("--------------");
for presentation in results {
println!("{}", presentation.title);
println!("{}", presentation.id);
println!("{}", presentation.path);
println!("{}", presentation.html);
println!("--------------");
if &self.as_mut().highest_id < &presentation.id {
self.as_mut().rust_mut().highest_id = presentation.id;
} }
});
let pres = self::Presentation {
id: presentation.id,
title: presentation.title,
html: presentation.path.ends_with(".html"),
path: presentation.path,
page_count: presentation.page_count.unwrap(),
};
let count = self.as_ref().count;
self.as_mut().set_count(count + 1);
self.as_mut().add_presentation(pres);
}
println!("--------------------------------------");
println!("{:?}", self.as_mut().presentations);
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.presentations.len() { if index < 0 || (index as usize) >= self.presentations.len() {
return false; return false;
} }
let db = &mut self.as_mut().get_db(); let rt = tokio::runtime::Runtime::new().unwrap();
let presentation_id = rt.block_on(async {
self.presentations.get(index as usize).unwrap().id; let result = query!("delete from presentations where id = ?", index).execute(&mut self.as_mut().rust_mut().db).await;
match result {
let result = Ok(_i) => {
delete(presentations.filter(id.eq(presentation_id))) unsafe {
.execute(db); self.as_mut().begin_remove_rows(
&QModelIndex::default(),
match result { index,
Ok(_i) => { index,
unsafe { );
self.as_mut().begin_remove_rows( self.as_mut()
&QModelIndex::default(), .rust_mut()
index, .presentations
index, .remove(index as usize);
); self.as_mut()
self.as_mut() .rust_mut()
.rust_mut() .inner_presentations
.presentations .remove(index as usize);
.remove(index as usize); self.as_mut().end_remove_rows();
self.as_mut() }
.rust_mut() debug!("removed-item-at-index: {:?}", index);
.inner_presentations true
.remove(index as usize); }
self.as_mut().end_remove_rows(); Err(e) => {
error!("Cannot connect to database: {e}");
false
} }
println!(
"removed-item-at-index: {:?}",
presentation_id
);
println!(
"new-Vec: {:?}",
self.as_mut().presentations
);
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( pub fn new_item(
@ -361,8 +331,6 @@ impl presentation_model::PresentationModel {
presentation_html: bool, presentation_html: bool,
new_page_count: i32, new_page_count: i32,
) -> bool { ) -> bool {
let db = &mut self.as_mut().get_db();
// println!("{:?}", db);
let mut actual_page_count = new_page_count; let mut actual_page_count = new_page_count;
if presentation_html { if presentation_html {
let actual_path = let actual_path =
@ -375,37 +343,40 @@ impl presentation_model::PresentationModel {
html = presentation_html html = presentation_html
); );
let presentation = self::Presentation { let rt = tokio::runtime::Runtime::new().unwrap();
id: presentation_id, rt.block_on(async {
title: presentation_title.clone().to_string(), let presentation_title = presentation_title.to_string();
html: presentation_html, let presentation_path = presentation_path.to_string();
path: presentation_path.clone().to_string(), let result = query!(r#"INSERT into presentations (id, title, filePath, html, pageCount) VALUES (?, ?, ?, ?, ?)"#,
page_count: actual_page_count, presentation_id,
}; presentation_title,
println!("{:?}", presentation); presentation_path,
presentation_html,
actual_page_count)
.execute(&mut self.as_mut().rust_mut().db).await;
let result = insert_into(presentations) match result {
.values(( Ok(_i) => {
id.eq(&presentation_id), let presentation = Presentation {
title.eq(&presentation_title.to_string()), id: presentation_id,
path.eq(&presentation_path.to_string()), title: presentation_title.to_string(),
html.eq(&presentation_html), path: presentation_path.to_string(),
page_count.eq(&presentation.page_count), html: presentation_html,
)) page_count: actual_page_count,
.execute(db); };
println!("{:?}", result); self.as_mut().add_presentation(presentation);
debug!("{:?}", self.as_mut().presentations);
match result { true
Ok(_i) => { }
self.as_mut().add_presentation(presentation); Err(e) => {
println!("{:?}", self.as_mut().presentations); error!(
true "Cannot connect to database: {e}"
);
false
}
} }
Err(_e) => { });
println!("Cannot connect to database"); true
false
}
}
} }
fn add_presentation( fn add_presentation(
@ -511,34 +482,40 @@ impl presentation_model::PresentationModel {
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(presentations.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 presentations SET title = ? where id = ?", title, index)
match result { .execute(&mut self.as_mut().rust_mut().db)
Ok(_i) => { .await;
for presentation in self match result {
.as_mut() Ok(_i) => {
.rust_mut() for presentation in self
.presentations .as_mut()
.iter_mut() .rust_mut()
.filter(|x| x.id == index) .presentations
{ .iter_mut()
presentation.title = updated_title.to_string(); .filter(|x| x.id == index)
println!("rust-title: {:?}", presentation.title); {
presentation.title = title.clone();
debug!(title = presentation.title,
title = title,
"updated presentation title");
}
self.as_mut().data_changed(
model_index,
model_index,
&vector_roles,
);
true
} }
// TODO this seems to not be updating in the actual list Err(e) => {
self.as_mut().data_changed( error!("Error connecting to db: {e}");
model_index, false
model_index, },
&vector_roles,
);
// self.as_mut().emit_title_changed();
println!("rust-title: {:?}", updated_title);
true
} }
Err(_e) => false, });
} true
} }
pub fn update_page_count( pub fn update_page_count(
@ -552,37 +529,39 @@ impl presentation_model::PresentationModel {
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(presentations.filter(id.eq(index))) rt.block_on(async {
.set(page_count.eq(updated_page_count)) let result = query!("UPDATE presentations SET pageCount = ? where id = ?", updated_page_count, index)
.execute(db); .execute(&mut self.as_mut().rust_mut().db)
match result { .await;
Ok(_i) => { match result {
for presentation in self Ok(_i) => {
.as_mut() for presentation in self
.rust_mut() .as_mut()
.presentations .rust_mut()
.iter_mut() .presentations
.filter(|x| x.id == index) .iter_mut()
{ .filter(|x| x.id == index)
presentation.page_count = updated_page_count; {
println!( presentation.page_count = updated_page_count.clone();
"rust-page_count: {:?}", debug!(title = presentation.title,
presentation.page_count page_count = updated_page_count,
"updated presentation page_count");
}
self.as_mut().data_changed(
model_index,
model_index,
&vector_roles,
); );
true
} }
// TODO this seems to not be updating in the actual list Err(e) => {
self.as_mut().data_changed( error!("Error connecting to db: {e}");
model_index, false
model_index, },
&vector_roles,
);
// self.as_mut().emit_page_count_changed();
println!("rust-page_count: {:?}", updated_page_count);
true
} }
Err(_e) => false, });
} true
} }
fn search(mut self: Pin<&mut Self>, search_term: QString) { fn search(mut self: Pin<&mut Self>, search_term: QString) {