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