Use anyhow for backend errors

This commit is contained in:
Elias Projahn 2020-10-11 19:53:36 +02:00
parent b2ab93cefa
commit 95f939cb07
8 changed files with 336 additions and 340 deletions

View file

@ -4,6 +4,7 @@ version = "0.1.0"
edition = "2018" edition = "2018"
[dependencies] [dependencies]
anyhow = "1.0.33"
diesel = { version = "1.4.5", features = ["sqlite"] } diesel = { version = "1.4.5", features = ["sqlite"] }
diesel_migrations = "1.4.0" diesel_migrations = "1.4.0"
gio = "0.9.1" gio = "0.9.1"

View file

@ -1,25 +1,26 @@
use super::database::*; use super::database::*;
use anyhow::Result;
use glib::Sender; use glib::Sender;
enum BackendAction { enum BackendAction {
UpdatePerson(Person, Sender<Result<(), String>>), UpdatePerson(Person, Sender<Result<()>>),
GetPerson(i64, Sender<Option<Person>>), GetPerson(i64, Sender<Result<Person>>),
DeletePerson(i64, Sender<Result<(), String>>), DeletePerson(i64, Sender<Result<()>>),
GetPersons(Sender<Vec<Person>>), GetPersons(Sender<Result<Vec<Person>>>),
UpdateInstrument(Instrument, Sender<Result<(), String>>), UpdateInstrument(Instrument, Sender<Result<()>>),
GetInstrument(i64, Sender<Option<Instrument>>), GetInstrument(i64, Sender<Result<Instrument>>),
DeleteInstrument(i64, Sender<Result<(), String>>), DeleteInstrument(i64, Sender<Result<()>>),
GetInstruments(Sender<Vec<Instrument>>), GetInstruments(Sender<Result<Vec<Instrument>>>),
UpdateWork(WorkInsertion, Sender<Result<(), String>>), UpdateWork(WorkInsertion, Sender<Result<()>>),
GetWorkDescriptions(i64, Sender<Vec<WorkDescription>>), GetWorkDescriptions(i64, Sender<Result<Vec<WorkDescription>>>),
UpdateEnsemble(Ensemble, Sender<Result<(), String>>), UpdateEnsemble(Ensemble, Sender<Result<()>>),
GetEnsemble(i64, Sender<Option<Ensemble>>), GetEnsemble(i64, Sender<Result<Ensemble>>),
DeleteEnsemble(i64, Sender<Result<(), String>>), DeleteEnsemble(i64, Sender<Result<()>>),
GetEnsembles(Sender<Vec<Ensemble>>), GetEnsembles(Sender<Result<Vec<Ensemble>>>),
UpdateRecording(RecordingInsertion, Sender<Result<(), String>>), UpdateRecording(RecordingInsertion, Sender<Result<()>>),
GetRecordingsForPerson(i64, Sender<Vec<RecordingDescription>>), GetRecordingsForPerson(i64, Sender<Result<Vec<RecordingDescription>>>),
GetRecordingsForEnsemble(i64, Sender<Vec<RecordingDescription>>), GetRecordingsForEnsemble(i64, Sender<Result<Vec<RecordingDescription>>>),
GetRecordingsForWork(i64, Sender<Vec<RecordingDescription>>), GetRecordingsForWork(i64, Sender<Result<Vec<RecordingDescription>>>),
} }
use BackendAction::*; use BackendAction::*;
@ -35,7 +36,7 @@ impl Backend {
let (action_sender, action_receiver) = std::sync::mpsc::channel::<BackendAction>(); let (action_sender, action_receiver) = std::sync::mpsc::channel::<BackendAction>();
std::thread::spawn(move || { std::thread::spawn(move || {
let db = Database::new(&url); let db = Database::new(&url).expect("Failed to open database!");
for action in action_receiver { for action in action_receiver {
match action { match action {
@ -156,13 +157,8 @@ impl Backend {
} }
} }
pub fn update_person<F: Fn(Result<(), String>) -> () + 'static>( pub fn update_person<F: Fn(Result<()>) -> () + 'static>(&self, person: Person, callback: F) {
&self, let (sender, receiver) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);
person: Person,
callback: F,
) {
let (sender, receiver) =
glib::MainContext::channel::<Result<(), String>>(glib::PRIORITY_DEFAULT);
receiver.attach(None, move |result| { receiver.attach(None, move |result| {
callback(result); callback(result);
@ -174,9 +170,8 @@ impl Backend {
.expect("Failed to send action to database thread!"); .expect("Failed to send action to database thread!");
} }
pub fn get_person<F: Fn(Option<Person>) -> () + 'static>(&self, id: i64, callback: F) { pub fn get_person<F: Fn(Result<Person>) -> () + 'static>(&self, id: i64, callback: F) {
let (sender, receiver) = let (sender, receiver) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);
glib::MainContext::channel::<Option<Person>>(glib::PRIORITY_DEFAULT);
receiver.attach(None, move |result| { receiver.attach(None, move |result| {
callback(result); callback(result);
@ -188,9 +183,8 @@ impl Backend {
.expect("Failed to send action to database thread!"); .expect("Failed to send action to database thread!");
} }
pub fn delete_person<F: Fn(Result<(), String>) -> () + 'static>(&self, id: i64, callback: F) { pub fn delete_person<F: Fn(Result<()>) -> () + 'static>(&self, id: i64, callback: F) {
let (sender, receiver) = let (sender, receiver) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);
glib::MainContext::channel::<Result<(), String>>(glib::PRIORITY_DEFAULT);
receiver.attach(None, move |result| { receiver.attach(None, move |result| {
callback(result); callback(result);
@ -202,8 +196,8 @@ impl Backend {
.expect("Failed to send action to database thread!"); .expect("Failed to send action to database thread!");
} }
pub fn get_persons<F: Fn(Vec<Person>) -> () + 'static>(&self, callback: F) { pub fn get_persons<F: Fn(Result<Vec<Person>>) -> () + 'static>(&self, callback: F) {
let (sender, receiver) = glib::MainContext::channel::<Vec<Person>>(glib::PRIORITY_DEFAULT); let (sender, receiver) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);
receiver.attach(None, move |result| { receiver.attach(None, move |result| {
callback(result); callback(result);
@ -215,13 +209,12 @@ impl Backend {
.expect("Failed to send action to database thread!"); .expect("Failed to send action to database thread!");
} }
pub fn update_instrument<F: Fn(Result<(), String>) -> () + 'static>( pub fn update_instrument<F: Fn(Result<()>) -> () + 'static>(
&self, &self,
instrument: Instrument, instrument: Instrument,
callback: F, callback: F,
) { ) {
let (sender, receiver) = let (sender, receiver) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);
glib::MainContext::channel::<Result<(), String>>(glib::PRIORITY_DEFAULT);
receiver.attach(None, move |result| { receiver.attach(None, move |result| {
callback(result); callback(result);
@ -233,9 +226,8 @@ impl Backend {
.expect("Failed to send action to database thread!"); .expect("Failed to send action to database thread!");
} }
pub fn get_instrument<F: Fn(Option<Instrument>) -> () + 'static>(&self, id: i64, callback: F) { pub fn get_instrument<F: Fn(Result<Instrument>) -> () + 'static>(&self, id: i64, callback: F) {
let (sender, receiver) = let (sender, receiver) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);
glib::MainContext::channel::<Option<Instrument>>(glib::PRIORITY_DEFAULT);
receiver.attach(None, move |result| { receiver.attach(None, move |result| {
callback(result); callback(result);
@ -247,13 +239,8 @@ impl Backend {
.expect("Failed to send action to database thread!"); .expect("Failed to send action to database thread!");
} }
pub fn delete_instrument<F: Fn(Result<(), String>) -> () + 'static>( pub fn delete_instrument<F: Fn(Result<()>) -> () + 'static>(&self, id: i64, callback: F) {
&self, let (sender, receiver) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);
id: i64,
callback: F,
) {
let (sender, receiver) =
glib::MainContext::channel::<Result<(), String>>(glib::PRIORITY_DEFAULT);
receiver.attach(None, move |result| { receiver.attach(None, move |result| {
callback(result); callback(result);
@ -265,9 +252,8 @@ impl Backend {
.expect("Failed to send action to database thread!"); .expect("Failed to send action to database thread!");
} }
pub fn get_instruments<F: Fn(Vec<Instrument>) -> () + 'static>(&self, callback: F) { pub fn get_instruments<F: Fn(Result<Vec<Instrument>>) -> () + 'static>(&self, callback: F) {
let (sender, receiver) = let (sender, receiver) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);
glib::MainContext::channel::<Vec<Instrument>>(glib::PRIORITY_DEFAULT);
receiver.attach(None, move |result| { receiver.attach(None, move |result| {
callback(result); callback(result);
@ -279,13 +265,8 @@ impl Backend {
.expect("Failed to send action to database thread!"); .expect("Failed to send action to database thread!");
} }
pub fn update_work<F: Fn(Result<(), String>) -> () + 'static>( pub fn update_work<F: Fn(Result<()>) -> () + 'static>(&self, work: WorkInsertion, callback: F) {
&self, let (sender, receiver) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);
work: WorkInsertion,
callback: F,
) {
let (sender, receiver) =
glib::MainContext::channel::<Result<(), String>>(glib::PRIORITY_DEFAULT);
receiver.attach(None, move |result| { receiver.attach(None, move |result| {
callback(result); callback(result);
@ -297,13 +278,12 @@ impl Backend {
.expect("Failed to send action to database thread!"); .expect("Failed to send action to database thread!");
} }
pub fn get_work_descriptions<F: Fn(Vec<WorkDescription>) -> () + 'static>( pub fn get_work_descriptions<F: Fn(Result<Vec<WorkDescription>>) -> () + 'static>(
&self, &self,
id: i64, id: i64,
callback: F, callback: F,
) { ) {
let (sender, receiver) = let (sender, receiver) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);
glib::MainContext::channel::<Vec<WorkDescription>>(glib::PRIORITY_DEFAULT);
receiver.attach(None, move |result| { receiver.attach(None, move |result| {
callback(result); callback(result);
@ -315,13 +295,12 @@ impl Backend {
.expect("Failed to send action to database thread!"); .expect("Failed to send action to database thread!");
} }
pub fn update_ensemble<F: Fn(Result<(), String>) -> () + 'static>( pub fn update_ensemble<F: Fn(Result<()>) -> () + 'static>(
&self, &self,
ensemble: Ensemble, ensemble: Ensemble,
callback: F, callback: F,
) { ) {
let (sender, receiver) = let (sender, receiver) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);
glib::MainContext::channel::<Result<(), String>>(glib::PRIORITY_DEFAULT);
receiver.attach(None, move |result| { receiver.attach(None, move |result| {
callback(result); callback(result);
@ -333,9 +312,8 @@ impl Backend {
.expect("Failed to send action to database thread!"); .expect("Failed to send action to database thread!");
} }
pub fn get_ensemble<F: Fn(Option<Ensemble>) -> () + 'static>(&self, id: i64, callback: F) { pub fn get_ensemble<F: Fn(Result<Ensemble>) -> () + 'static>(&self, id: i64, callback: F) {
let (sender, receiver) = let (sender, receiver) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);
glib::MainContext::channel::<Option<Ensemble>>(glib::PRIORITY_DEFAULT);
receiver.attach(None, move |result| { receiver.attach(None, move |result| {
callback(result); callback(result);
@ -347,9 +325,8 @@ impl Backend {
.expect("Failed to send action to database thread!"); .expect("Failed to send action to database thread!");
} }
pub fn delete_ensemble<F: Fn(Result<(), String>) -> () + 'static>(&self, id: i64, callback: F) { pub fn delete_ensemble<F: Fn(Result<()>) -> () + 'static>(&self, id: i64, callback: F) {
let (sender, receiver) = let (sender, receiver) = glib::MainContext::channel::<Result<()>>(glib::PRIORITY_DEFAULT);
glib::MainContext::channel::<Result<(), String>>(glib::PRIORITY_DEFAULT);
receiver.attach(None, move |result| { receiver.attach(None, move |result| {
callback(result); callback(result);
@ -361,9 +338,8 @@ impl Backend {
.expect("Failed to send action to database thread!"); .expect("Failed to send action to database thread!");
} }
pub fn get_ensembles<F: Fn(Vec<Ensemble>) -> () + 'static>(&self, callback: F) { pub fn get_ensembles<F: Fn(Result<Vec<Ensemble>>) -> () + 'static>(&self, callback: F) {
let (sender, receiver) = let (sender, receiver) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);
glib::MainContext::channel::<Vec<Ensemble>>(glib::PRIORITY_DEFAULT);
receiver.attach(None, move |result| { receiver.attach(None, move |result| {
callback(result); callback(result);
@ -375,13 +351,12 @@ impl Backend {
.expect("Failed to send action to database thread!"); .expect("Failed to send action to database thread!");
} }
pub fn update_recording<F: Fn(Result<(), String>) -> () + 'static>( pub fn update_recording<F: Fn(Result<()>) -> () + 'static>(
&self, &self,
recording: RecordingInsertion, recording: RecordingInsertion,
callback: F, callback: F,
) { ) {
let (sender, receiver) = let (sender, receiver) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);
glib::MainContext::channel::<Result<(), String>>(glib::PRIORITY_DEFAULT);
receiver.attach(None, move |result| { receiver.attach(None, move |result| {
callback(result); callback(result);
@ -393,13 +368,12 @@ impl Backend {
.expect("Failed to send action to database thread!"); .expect("Failed to send action to database thread!");
} }
pub fn get_recordings_for_person<F: Fn(Vec<RecordingDescription>) -> () + 'static>( pub fn get_recordings_for_person<F: Fn(Result<Vec<RecordingDescription>>) -> () + 'static>(
&self, &self,
id: i64, id: i64,
callback: F, callback: F,
) { ) {
let (sender, receiver) = let (sender, receiver) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);
glib::MainContext::channel::<Vec<RecordingDescription>>(glib::PRIORITY_DEFAULT);
receiver.attach(None, move |result| { receiver.attach(None, move |result| {
callback(result); callback(result);
@ -411,13 +385,12 @@ impl Backend {
.expect("Failed to send action to database thread!"); .expect("Failed to send action to database thread!");
} }
pub fn get_recordings_for_ensemble<F: Fn(Vec<RecordingDescription>) -> () + 'static>( pub fn get_recordings_for_ensemble<F: Fn(Result<Vec<RecordingDescription>>) -> () + 'static>(
&self, &self,
id: i64, id: i64,
callback: F, callback: F,
) { ) {
let (sender, receiver) = let (sender, receiver) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);
glib::MainContext::channel::<Vec<RecordingDescription>>(glib::PRIORITY_DEFAULT);
receiver.attach(None, move |result| { receiver.attach(None, move |result| {
callback(result); callback(result);
@ -429,13 +402,12 @@ impl Backend {
.expect("Failed to send action to database thread!"); .expect("Failed to send action to database thread!");
} }
pub fn get_recordings_for_work<F: Fn(Vec<RecordingDescription>) -> () + 'static>( pub fn get_recordings_for_work<F: Fn(Result<Vec<RecordingDescription>>) -> () + 'static>(
&self, &self,
id: i64, id: i64,
callback: F, callback: F,
) { ) {
let (sender, receiver) = let (sender, receiver) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);
glib::MainContext::channel::<Vec<RecordingDescription>>(glib::PRIORITY_DEFAULT);
receiver.attach(None, move |result| { receiver.attach(None, move |result| {
callback(result); callback(result);

View file

@ -1,6 +1,7 @@
use super::models::*; use super::models::*;
use super::schema::*; use super::schema::*;
use super::tables::*; use super::tables::*;
use anyhow::{anyhow, Result};
use diesel::prelude::*; use diesel::prelude::*;
embed_migrations!(); embed_migrations!();
@ -10,89 +11,80 @@ pub struct Database {
} }
impl Database { impl Database {
pub fn new(path: &str) -> Database { pub fn new(path: &str) -> Result<Database> {
let c = SqliteConnection::establish(path) let c = SqliteConnection::establish(path)?;
.expect(&format!("Failed to connect to database at \"{}\"!", path));
diesel::sql_query("PRAGMA foreign_keys = ON;") diesel::sql_query("PRAGMA foreign_keys = ON;").execute(&c)?;
.execute(&c) embedded_migrations::run(&c)?;
.expect("Failed to activate foreign key support!");
embedded_migrations::run(&c).expect("Failed to run migrations!"); Ok(Database { c: c })
Database { c: c }
} }
pub fn update_person(&self, person: Person) { pub fn update_person(&self, person: Person) -> Result<()> {
self.defer_foreign_keys(); self.defer_foreign_keys();
self.c self.c.transaction(|| {
.transaction(|| {
diesel::replace_into(persons::table) diesel::replace_into(persons::table)
.values(person) .values(person)
.execute(&self.c) .execute(&self.c)
}) })?;
.expect("Failed to insert person!");
Ok(())
} }
pub fn get_person(&self, id: i64) -> Option<Person> { pub fn get_person(&self, id: i64) -> Result<Person> {
persons::table persons::table
.filter(persons::id.eq(id)) .filter(persons::id.eq(id))
.load::<Person>(&self.c) .load::<Person>(&self.c)?
.expect("Error loading person!")
.first() .first()
.cloned() .cloned()
.ok_or(anyhow!("No person with ID: {}", id))
} }
pub fn delete_person(&self, id: i64) { pub fn delete_person(&self, id: i64) -> Result<()> {
diesel::delete(persons::table.filter(persons::id.eq(id))) diesel::delete(persons::table.filter(persons::id.eq(id))).execute(&self.c)?;
.execute(&self.c) Ok(())
.expect("Failed to delete person!");
} }
pub fn get_persons(&self) -> Vec<Person> { pub fn get_persons(&self) -> Result<Vec<Person>> {
persons::table let persons = persons::table.load::<Person>(&self.c)?;
.load::<Person>(&self.c) Ok(persons)
.expect("Error loading persons!")
} }
pub fn update_instrument(&self, instrument: Instrument) { pub fn update_instrument(&self, instrument: Instrument) -> Result<()> {
self.defer_foreign_keys(); self.defer_foreign_keys();
self.c self.c.transaction(|| {
.transaction(|| {
diesel::replace_into(instruments::table) diesel::replace_into(instruments::table)
.values(instrument) .values(instrument)
.execute(&self.c) .execute(&self.c)
}) })?;
.expect("Failed to insert instrument!");
Ok(())
} }
pub fn get_instrument(&self, id: i64) -> Option<Instrument> { pub fn get_instrument(&self, id: i64) -> Result<Instrument> {
instruments::table instruments::table
.filter(instruments::id.eq(id)) .filter(instruments::id.eq(id))
.load::<Instrument>(&self.c) .load::<Instrument>(&self.c)?
.expect("Error loading instrument!")
.first() .first()
.cloned() .cloned()
.ok_or(anyhow!("No instrument with ID: {}", id))
} }
pub fn delete_instrument(&self, id: i64) { pub fn delete_instrument(&self, id: i64) -> Result<()> {
diesel::delete(instruments::table.filter(instruments::id.eq(id))) diesel::delete(instruments::table.filter(instruments::id.eq(id))).execute(&self.c)?;
.execute(&self.c) Ok(())
.expect("Failed to delete instrument!");
} }
pub fn get_instruments(&self) -> Vec<Instrument> { pub fn get_instruments(&self) -> Result<Vec<Instrument>> {
instruments::table let instruments = instruments::table.load::<Instrument>(&self.c)?;
.load::<Instrument>(&self.c) Ok(instruments)
.expect("Error loading instruments!")
} }
pub fn update_work(&self, work_insertion: WorkInsertion) { pub fn update_work(&self, work_insertion: WorkInsertion) -> Result<()> {
let id = work_insertion.work.id; let id = work_insertion.work.id;
self.defer_foreign_keys(); self.defer_foreign_keys();
self.c self.c.transaction(|| {
.transaction(|| {
self.delete_work(id); self.delete_work(id);
diesel::insert_into(works::table) diesel::insert_into(works::table)
@ -134,140 +126,148 @@ impl Database {
} }
diesel::result::QueryResult::Ok(()) diesel::result::QueryResult::Ok(())
}) })?;
.expect("Failed to update work!");
Ok(())
} }
pub fn get_work(&self, id: i64) -> Option<Work> { pub fn get_work(&self, id: i64) -> Result<Work> {
works::table works::table
.filter(works::id.eq(id)) .filter(works::id.eq(id))
.load::<Work>(&self.c) .load::<Work>(&self.c)?
.expect("Error loading work!")
.first() .first()
.cloned() .cloned()
.ok_or(anyhow!("No work with ID: {}", id))
} }
pub fn get_work_description_for_work(&self, work: &Work) -> WorkDescription { pub fn get_work_description_for_work(&self, work: &Work) -> Result<WorkDescription> {
WorkDescription { let mut instruments: Vec<Instrument> = Vec::new();
id: work.id,
composer: self let instrumentations = instrumentations::table
.get_person(work.composer)
.expect("Could not find composer for work!"),
title: work.title.clone(),
instruments: instrumentations::table
.filter(instrumentations::work.eq(work.id)) .filter(instrumentations::work.eq(work.id))
.load::<Instrumentation>(&self.c) .load::<Instrumentation>(&self.c)?;
.expect("Failed to load instrumentations!")
.iter() for instrumentation in instrumentations {
.map(|instrumentation| { instruments.push(self.get_instrument(instrumentation.instrument)?);
self.get_instrument(instrumentation.instrument) }
.expect("Could not find instrument for instrumentation!")
}) let mut part_descriptions: Vec<WorkPartDescription> = Vec::new();
.collect(),
parts: work_parts::table let work_parts = work_parts::table
.filter(work_parts::work.eq(work.id)) .filter(work_parts::work.eq(work.id))
.load::<WorkPart>(&self.c) .load::<WorkPart>(&self.c)?;
.expect("Failed to load work parts!")
.iter() for work_part in work_parts {
.map(|work_part| WorkPartDescription { let mut part_instruments: Vec<Instrument> = Vec::new();
let part_instrumentations = part_instrumentations::table
.filter(part_instrumentations::work_part.eq(work_part.id))
.load::<PartInstrumentation>(&self.c)?;
for part_instrumentation in part_instrumentations {
part_instruments.push(self.get_instrument(part_instrumentation.instrument)?);
}
part_descriptions.push(WorkPartDescription {
composer: match work_part.composer { composer: match work_part.composer {
Some(composer) => Some( Some(composer) => Some(self.get_person(composer)?),
self.get_person(composer)
.expect("Could not find composer for work part!"),
),
None => None, None => None,
}, },
title: work_part.title.clone(), title: work_part.title.clone(),
instruments: part_instrumentations::table instruments: part_instruments,
.filter(part_instrumentations::work_part.eq(work_part.id)) });
.load::<PartInstrumentation>(&self.c) }
.expect("Failed to load part instrumentations!")
.iter() let mut section_descriptions: Vec<WorkSectionDescription> = Vec::new();
.map(|part_instrumentation| {
self.get_instrument(part_instrumentation.instrument) let sections = work_sections::table
.expect("Could not find instrument for part instrumentation!")
})
.collect(),
})
.collect(),
sections: work_sections::table
.filter(work_sections::work.eq(work.id)) .filter(work_sections::work.eq(work.id))
.load::<WorkSection>(&self.c) .load::<WorkSection>(&self.c)?;
.expect("Failed to load work sections!")
.iter() for section in sections {
.map(|section| WorkSectionDescription { section_descriptions.push(WorkSectionDescription {
title: section.title.clone(), title: section.title.clone(),
before_index: section.before_index, before_index: section.before_index,
}) });
.collect(),
}
} }
pub fn get_work_description(&self, id: i64) -> Option<WorkDescription> { let work_description = WorkDescription {
match self.get_work(id) { id: work.id,
Some(work) => Some(self.get_work_description_for_work(&work)), composer: self.get_person(work.composer)?,
None => None, title: work.title.clone(),
} instruments: instruments,
parts: part_descriptions,
sections: section_descriptions,
};
Ok(work_description)
} }
pub fn delete_work(&self, id: i64) { pub fn get_work_description(&self, id: i64) -> Result<WorkDescription> {
diesel::delete(works::table.filter(works::id.eq(id))) let work = self.get_work(id)?;
.execute(&self.c) let work_description = self.get_work_description_for_work(&work)?;
.expect("Failed to delete work!"); Ok(work_description)
} }
pub fn get_works(&self, composer_id: i64) -> Vec<Work> { pub fn delete_work(&self, id: i64) -> Result<()> {
works::table diesel::delete(works::table.filter(works::id.eq(id))).execute(&self.c)?;
Ok(())
}
pub fn get_works(&self, composer_id: i64) -> Result<Vec<Work>> {
let works = works::table
.filter(works::composer.eq(composer_id)) .filter(works::composer.eq(composer_id))
.load::<Work>(&self.c) .load::<Work>(&self.c)?;
.expect("Error loading works!")
Ok(works)
} }
pub fn get_work_descriptions(&self, composer_id: i64) -> Vec<WorkDescription> { pub fn get_work_descriptions(&self, composer_id: i64) -> Result<Vec<WorkDescription>> {
self.get_works(composer_id) let mut work_descriptions: Vec<WorkDescription> = Vec::new();
.iter()
.map(|work| self.get_work_description_for_work(work)) let works = self.get_works(composer_id)?;
.collect() for work in works {
work_descriptions.push(self.get_work_description_for_work(&work)?);
} }
pub fn update_ensemble(&self, ensemble: Ensemble) { Ok(work_descriptions)
}
pub fn update_ensemble(&self, ensemble: Ensemble) -> Result<()> {
self.defer_foreign_keys(); self.defer_foreign_keys();
self.c self.c.transaction(|| {
.transaction(|| {
diesel::replace_into(ensembles::table) diesel::replace_into(ensembles::table)
.values(ensemble) .values(ensemble)
.execute(&self.c) .execute(&self.c)
}) })?;
.expect("Failed to insert ensemble!");
Ok(())
} }
pub fn get_ensemble(&self, id: i64) -> Option<Ensemble> { pub fn get_ensemble(&self, id: i64) -> Result<Ensemble> {
ensembles::table ensembles::table
.filter(ensembles::id.eq(id)) .filter(ensembles::id.eq(id))
.load::<Ensemble>(&self.c) .load::<Ensemble>(&self.c)?
.expect("Error loading ensemble!")
.first() .first()
.cloned() .cloned()
.ok_or(anyhow!("No ensemble with ID: {}", id))
} }
pub fn delete_ensemble(&self, id: i64) { pub fn delete_ensemble(&self, id: i64) -> Result<()> {
diesel::delete(ensembles::table.filter(ensembles::id.eq(id))) diesel::delete(ensembles::table.filter(ensembles::id.eq(id))).execute(&self.c)?;
.execute(&self.c) Ok(())
.expect("Failed to delete ensemble!");
} }
pub fn get_ensembles(&self) -> Vec<Ensemble> { pub fn get_ensembles(&self) -> Result<Vec<Ensemble>> {
ensembles::table let ensembles = ensembles::table.load::<Ensemble>(&self.c)?;
.load::<Ensemble>(&self.c) Ok(ensembles)
.expect("Error loading ensembles!")
} }
pub fn update_recording(&self, recording_insertion: RecordingInsertion) { pub fn update_recording(&self, recording_insertion: RecordingInsertion) -> Result<()> {
let id = recording_insertion.recording.id; let id = recording_insertion.recording.id;
self.defer_foreign_keys(); self.defer_foreign_keys();
self.c self.c.transaction(|| {
.transaction(|| {
self.delete_recording(id); self.delete_recording(id);
diesel::insert_into(recordings::table) diesel::insert_into(recordings::table)
@ -281,114 +281,122 @@ impl Database {
} }
diesel::result::QueryResult::Ok(()) diesel::result::QueryResult::Ok(())
}) })?;
.expect("Failed to insert performance!");
Ok(())
} }
pub fn get_recording(&self, id: i64) -> Option<Recording> { pub fn get_recording(&self, id: i64) -> Result<Recording> {
recordings::table recordings::table
.filter(recordings::id.eq(id)) .filter(recordings::id.eq(id))
.load::<Recording>(&self.c) .load::<Recording>(&self.c)?
.expect("Error loading recording!")
.first() .first()
.cloned() .cloned()
.ok_or(anyhow!("No recording with ID: {}", id))
} }
pub fn get_recording_description_for_recording( pub fn get_recording_description_for_recording(
&self, &self,
recording: Recording, recording: &Recording,
) -> RecordingDescription { ) -> Result<RecordingDescription> {
RecordingDescription { let mut performance_descriptions: Vec<PerformanceDescription> = Vec::new();
id: recording.id,
work: self let performances = performances::table
.get_work_description(recording.work)
.expect("Could not find work for recording!"),
comment: recording.comment,
performances: performances::table
.filter(performances::recording.eq(recording.id)) .filter(performances::recording.eq(recording.id))
.load::<Performance>(&self.c) .load::<Performance>(&self.c)?;
.expect("Failed to load performances!")
.iter()
.map(|performance| PerformanceDescription {
person: performance.person.map(|id| {
self.get_person(id)
.expect("Could not find person for performance!")
}),
ensemble: performance.ensemble.map(|id| {
self.get_ensemble(id)
.expect("Could not find ensemble for performance!")
}),
role: performance.role.map(|id| {
self.get_instrument(id)
.expect("Could not find role for performance!")
}),
})
.collect(),
}
}
pub fn get_recording_description(&self, id: i64) -> Option<RecordingDescription> { for performance in performances {
match self.get_recording(id) { performance_descriptions.push(PerformanceDescription {
Some(recording) => Some(self.get_recording_description_for_recording(recording)), person: match performance.person {
Some(id) => Some(self.get_person(id)?),
None => None, None => None,
} },
ensemble: match performance.ensemble {
Some(id) => Some(self.get_ensemble(id)?),
None => None,
},
role: match performance.role {
Some(id) => Some(self.get_instrument(id)?),
None => None,
},
});
} }
pub fn get_recordings_for_person(&self, id: i64) -> Vec<RecordingDescription> { Ok(RecordingDescription {
id: recording.id,
work: self.get_work_description(recording.work)?,
comment: recording.comment.clone(),
performances: performance_descriptions,
})
}
pub fn get_recording_description(&self, id: i64) -> Result<RecordingDescription> {
let recording = self.get_recording(id)?;
let recording_description = self.get_recording_description_for_recording(&recording)?;
Ok(recording_description)
}
pub fn get_recordings_for_person(&self, id: i64) -> Result<Vec<RecordingDescription>> {
let mut recording_descriptions: Vec<RecordingDescription> = Vec::new();
let recordings = recordings::table let recordings = recordings::table
.inner_join(performances::table.on(performances::recording.eq(recordings::id))) .inner_join(performances::table.on(performances::recording.eq(recordings::id)))
.inner_join(persons::table.on(persons::id.nullable().eq(performances::person))) .inner_join(persons::table.on(persons::id.nullable().eq(performances::person)))
.filter(persons::id.eq(id)) .filter(persons::id.eq(id))
.select(recordings::table::all_columns()) .select(recordings::table::all_columns())
.load::<Recording>(&self.c) .load::<Recording>(&self.c)?;
.expect("Error loading recordings for person!");
recordings for recording in recordings {
.iter() recording_descriptions.push(self.get_recording_description_for_recording(&recording)?);
.map(|recording| self.get_recording_description_for_recording(recording.clone()))
.collect()
} }
pub fn get_recordings_for_ensemble(&self, id: i64) -> Vec<RecordingDescription> { Ok(recording_descriptions)
}
pub fn get_recordings_for_ensemble(&self, id: i64) -> Result<Vec<RecordingDescription>> {
let mut recording_descriptions: Vec<RecordingDescription> = Vec::new();
let recordings = recordings::table let recordings = recordings::table
.inner_join(performances::table.on(performances::recording.eq(recordings::id))) .inner_join(performances::table.on(performances::recording.eq(recordings::id)))
.inner_join(ensembles::table.on(ensembles::id.nullable().eq(performances::ensemble))) .inner_join(ensembles::table.on(ensembles::id.nullable().eq(performances::ensemble)))
.filter(ensembles::id.eq(id)) .filter(ensembles::id.eq(id))
.select(recordings::table::all_columns()) .select(recordings::table::all_columns())
.load::<Recording>(&self.c) .load::<Recording>(&self.c)?;
.expect("Error loading recordings for ensemble!");
recordings for recording in recordings {
.iter() recording_descriptions.push(self.get_recording_description_for_recording(&recording)?);
.map(|recording| self.get_recording_description_for_recording(recording.clone()))
.collect()
} }
pub fn get_recordings_for_work(&self, id: i64) -> Vec<RecordingDescription> { Ok(recording_descriptions)
}
pub fn get_recordings_for_work(&self, id: i64) -> Result<Vec<RecordingDescription>> {
let mut recording_descriptions: Vec<RecordingDescription> = Vec::new();
let recordings = recordings::table let recordings = recordings::table
.inner_join(works::table.on(works::id.eq(recordings::work))) .inner_join(works::table.on(works::id.eq(recordings::work)))
.filter(works::id.eq(id)) .filter(works::id.eq(id))
.select(recordings::table::all_columns()) .select(recordings::table::all_columns())
.load::<Recording>(&self.c) .load::<Recording>(&self.c)?;
.expect("Error loading recordings for work!");
recordings for recording in recordings {
.iter() recording_descriptions.push(self.get_recording_description_for_recording(&recording)?);
.map(|recording| self.get_recording_description_for_recording(recording.clone()))
.collect()
} }
pub fn delete_recording(&self, id: i64) { Ok(recording_descriptions)
diesel::delete(recordings::table.filter(recordings::id.eq(id)))
.execute(&self.c)
.expect("Failed to delete recording!");
} }
pub fn get_recordings(&self, work_id: i64) -> Vec<Recording> { pub fn delete_recording(&self, id: i64) -> Result<()> {
recordings::table diesel::delete(recordings::table.filter(recordings::id.eq(id))).execute(&self.c)?;
Ok(())
}
pub fn get_recordings(&self, work_id: i64) -> Result<Vec<Recording>> {
let recordings = recordings::table
.filter(recordings::work.eq(work_id)) .filter(recordings::work.eq(work_id))
.load::<Recording>(&self.c) .load::<Recording>(&self.c)?;
.expect("Error loading recordings!")
Ok(recordings)
} }
fn defer_foreign_keys(&self) { fn defer_foreign_keys(&self) {

View file

@ -44,6 +44,8 @@ where
result result
.backend .backend
.get_ensembles(clone!(@strong result => move |ensembles| { .get_ensembles(clone!(@strong result => move |ensembles| {
let ensembles = ensembles.unwrap();
for (index, ensemble) in ensembles.iter().enumerate() { for (index, ensemble) in ensembles.iter().enumerate() {
let label = gtk::Label::new(Some(&ensemble.name)); let label = gtk::Label::new(Some(&ensemble.name));
label.set_halign(gtk::Align::Start); label.set_halign(gtk::Align::Start);

View file

@ -44,6 +44,8 @@ where
result result
.backend .backend
.get_instruments(clone!(@strong result => move |instruments| { .get_instruments(clone!(@strong result => move |instruments| {
let instruments = instruments.unwrap();
for (index, instrument) in instruments.iter().enumerate() { for (index, instrument) in instruments.iter().enumerate() {
let label = gtk::Label::new(Some(&instrument.name)); let label = gtk::Label::new(Some(&instrument.name));
label.set_halign(gtk::Align::Start); label.set_halign(gtk::Align::Start);

View file

@ -44,6 +44,8 @@ where
result result
.backend .backend
.get_persons(clone!(@strong result => move |persons| { .get_persons(clone!(@strong result => move |persons| {
let persons = persons.unwrap();
for (index, person) in persons.iter().enumerate() { for (index, person) in persons.iter().enumerate() {
let label = gtk::Label::new(Some(&person.name_lf())); let label = gtk::Label::new(Some(&person.name_lf()));
label.set_halign(gtk::Align::Start); label.set_halign(gtk::Align::Start);

View file

@ -124,7 +124,7 @@ where
Loading => { Loading => {
self.backend self.backend
.get_persons(clone!(@strong self as self_ => move |persons| { .get_persons(clone!(@strong self as self_ => move |persons| {
self_.clone().set_state(Persons(persons)); self_.clone().set_state(Persons(persons.unwrap()));
})); }));
self.sidebar_stack.set_visible_child_name("loading"); self.sidebar_stack.set_visible_child_name("loading");
@ -184,7 +184,7 @@ where
self.backend.get_work_descriptions( self.backend.get_work_descriptions(
person.id, person.id,
clone!(@strong self as self_ => move |works| { clone!(@strong self as self_ => move |works| {
self_.clone().set_state(Person(works)); self_.clone().set_state(Person(works.unwrap()));
}), }),
); );

View file

@ -300,7 +300,9 @@ impl Window {
Loading => { Loading => {
self.backend self.backend
.get_persons(clone!(@strong self as self_ => move |persons| { .get_persons(clone!(@strong self as self_ => move |persons| {
let persons = persons.unwrap();
self_.backend.get_ensembles(clone!(@strong self_ => move |ensembles| { self_.backend.get_ensembles(clone!(@strong self_ => move |ensembles| {
let ensembles = ensembles.unwrap();
let mut poes: Vec<PersonOrEnsemble> = Vec::new(); let mut poes: Vec<PersonOrEnsemble> = Vec::new();
for person in &persons { for person in &persons {
@ -393,9 +395,11 @@ impl Window {
self.backend.get_work_descriptions( self.backend.get_work_descriptions(
person.id, person.id,
clone!(@strong self as self_, @strong poe => move |works| { clone!(@strong self as self_, @strong poe => move |works| {
let works = works.unwrap();
self_.backend.get_recordings_for_person( self_.backend.get_recordings_for_person(
person.id, person.id,
clone!(@strong self_, @strong poe => move |recordings| { clone!(@strong self_, @strong poe => move |recordings| {
let recordings = recordings.unwrap();
self_.clone().set_state(OverviewScreen(poe.clone(), works.clone(), recordings, String::from(""))); self_.clone().set_state(OverviewScreen(poe.clone(), works.clone(), recordings, String::from("")));
}), }),
); );
@ -426,6 +430,7 @@ impl Window {
self.backend.get_recordings_for_ensemble( self.backend.get_recordings_for_ensemble(
ensemble.id, ensemble.id,
clone!(@strong self as self_ => move |recordings| { clone!(@strong self as self_ => move |recordings| {
let recordings = recordings.unwrap();
self_.clone().set_state(OverviewScreen(poe.clone(), Vec::new(), recordings, String::from(""))); self_.clone().set_state(OverviewScreen(poe.clone(), Vec::new(), recordings, String::from("")));
}), }),
); );
@ -550,6 +555,7 @@ impl Window {
self.backend.get_recordings_for_work( self.backend.get_recordings_for_work(
work.id, work.id,
clone!(@strong self as self_ => move |recordings| { clone!(@strong self as self_ => move |recordings| {
let recordings = recordings.unwrap();
self_.clone().set_state(WorkScreen(poe.clone(), work.clone(), recordings, String::new())); self_.clone().set_state(WorkScreen(poe.clone(), work.clone(), recordings, String::new()));
}), }),
); );
@ -592,7 +598,10 @@ impl Window {
} }
} }
match self.work_details_recording_list_row_activated_handler_id.take() { match self
.work_details_recording_list_row_activated_handler_id
.take()
{
Some(id) => self.work_details_recording_list.disconnect(id), Some(id) => self.work_details_recording_list.disconnect(id),
None => (), None => (),
} }