Use database connection directly

This commit is contained in:
Elias Projahn 2023-02-11 13:35:26 +01:00
parent a3f585aadf
commit 75d4e82cf8
28 changed files with 893 additions and 889 deletions

View file

@ -1,11 +1,11 @@
use db::SqliteConnection;
use gio::traits::SettingsExt; use gio::traits::SettingsExt;
use log::warn; use log::warn;
use musicus_database::Database;
use std::{ use std::{
cell::{Cell, RefCell}, cell::{Cell, RefCell},
path::PathBuf, path::PathBuf,
rc::Rc, rc::Rc,
sync::Arc, sync::{Arc, Mutex},
}; };
use tokio::sync::{broadcast, broadcast::Sender}; use tokio::sync::{broadcast, broadcast::Sender};
@ -59,7 +59,7 @@ pub struct Backend {
library_updated_sender: Sender<()>, library_updated_sender: Sender<()>,
/// The database. This can be assumed to exist, when the state is set to BackendState::Ready. /// The database. This can be assumed to exist, when the state is set to BackendState::Ready.
database: RefCell<Option<Rc<Database>>>, database: RefCell<Option<Arc<Mutex<SqliteConnection>>>>,
/// The player handling playlist and playback. This can be assumed to exist, when the state is /// The player handling playlist and playback. This can be assumed to exist, when the state is
/// set to BackendState::Ready. /// set to BackendState::Ready.

View file

@ -1,9 +1,10 @@
use crate::{Backend, BackendState, Player, Result}; use crate::{Backend, BackendState, Player, Result};
use gio::prelude::*; use gio::prelude::*;
use log::warn; use log::warn;
use musicus_database::Database; use musicus_database::SqliteConnection;
use std::path::PathBuf; use std::path::PathBuf;
use std::rc::Rc; use std::rc::Rc;
use std::sync::{Arc, Mutex};
impl Backend { impl Backend {
/// Initialize the music library if it is set in the settings. /// Initialize the music library if it is set in the settings.
@ -41,8 +42,11 @@ impl Backend {
let mut db_path = path.clone(); let mut db_path = path.clone();
db_path.push("musicus.db"); db_path.push("musicus.db");
let database = Rc::new(Database::new(db_path.to_str().unwrap())?); let database = Arc::new(Mutex::new(musicus_database::connect(
self.database.replace(Some(Rc::clone(&database))); db_path.to_str().unwrap(),
)?));
self.database.replace(Some(database));
let player = Player::new(path); let player = Player::new(path);
self.player.replace(Some(player)); self.player.replace(Some(player));
@ -60,7 +64,7 @@ impl Backend {
} }
/// Get an interface to the database and panic if there is none. /// Get an interface to the database and panic if there is none.
pub fn db(&self) -> Rc<Database> { pub fn db(&self) -> Arc<Mutex<SqliteConnection>> {
self.database.borrow().clone().unwrap() self.database.borrow().clone().unwrap()
} }

View file

@ -1,6 +1,7 @@
use crate::{Backend, Error, Result}; use crate::{Backend, Error, Result};
use db::Track;
use glib::clone; use glib::clone;
use musicus_database::Track; use musicus_database as db;
use std::cell::{Cell, RefCell}; use std::cell::{Cell, RefCell};
use std::path::PathBuf; use std::path::PathBuf;
use std::rc::Rc; use std::rc::Rc;
@ -458,7 +459,7 @@ impl TrackGenerator for RandomTrackGenerator {
} }
fn next(&self) -> Vec<Track> { fn next(&self) -> Vec<Track> {
vec![self.backend.db().random_track().unwrap()] vec![db::random_track(&mut self.backend.db().lock().unwrap()).unwrap()]
} }
} }
@ -479,7 +480,7 @@ impl TrackGenerator for RandomRecordingGenerator {
} }
fn next(&self) -> Vec<Track> { fn next(&self) -> Vec<Track> {
let recording = self.backend.db().random_recording().unwrap(); let recording = db::random_recording(&mut self.backend.db().lock().unwrap()).unwrap();
self.backend.db().get_tracks(&recording.id).unwrap() db::get_tracks(&mut self.backend.db().lock().unwrap(), &recording.id).unwrap()
} }
} }

View file

@ -1,9 +1,9 @@
use super::schema::ensembles;
use super::{Database, Result};
use chrono::Utc; use chrono::Utc;
use diesel::prelude::*; use diesel::prelude::*;
use log::info; use log::info;
use crate::{Result, schema::ensembles, defer_foreign_keys};
/// An ensemble that takes part in recordings. /// An ensemble that takes part in recordings.
#[derive(Insertable, Queryable, PartialEq, Eq, Hash, Debug, Clone)] #[derive(Insertable, Queryable, PartialEq, Eq, Hash, Debug, Clone)]
pub struct Ensemble { pub struct Ensemble {
@ -24,54 +24,51 @@ impl Ensemble {
} }
} }
impl Database { /// Update an existing ensemble or insert a new one.
/// Update an existing ensemble or insert a new one. pub fn update_ensemble(connection: &mut SqliteConnection, mut ensemble: Ensemble) -> Result<()> {
pub fn update_ensemble(&self, mut ensemble: Ensemble) -> Result<()> { info!("Updating ensemble {:?}", ensemble);
info!("Updating ensemble {:?}", ensemble); defer_foreign_keys(connection)?;
self.defer_foreign_keys()?;
ensemble.last_used = Some(Utc::now().timestamp()); ensemble.last_used = Some(Utc::now().timestamp());
self.connection.lock().unwrap().transaction(|connection| { connection.transaction(|connection| {
diesel::replace_into(ensembles::table) diesel::replace_into(ensembles::table)
.values(ensemble) .values(ensemble)
.execute(connection) .execute(connection)
})?; })?;
Ok(()) Ok(())
} }
/// Get an existing ensemble. /// Get an existing ensemble.
pub fn get_ensemble(&self, id: &str) -> Result<Option<Ensemble>> { pub fn get_ensemble(connection: &mut SqliteConnection, id: &str) -> Result<Option<Ensemble>> {
let ensemble = ensembles::table let ensemble = ensembles::table
.filter(ensembles::id.eq(id)) .filter(ensembles::id.eq(id))
.load::<Ensemble>(&mut *self.connection.lock().unwrap())? .load::<Ensemble>(connection)?
.into_iter() .into_iter()
.next(); .next();
Ok(ensemble) Ok(ensemble)
} }
/// Delete an existing ensemble. /// Delete an existing ensemble.
pub fn delete_ensemble(&self, id: &str) -> Result<()> { pub fn delete_ensemble(connection: &mut SqliteConnection, id: &str) -> Result<()> {
info!("Deleting ensemble {}", id); info!("Deleting ensemble {}", id);
diesel::delete(ensembles::table.filter(ensembles::id.eq(id))) diesel::delete(ensembles::table.filter(ensembles::id.eq(id))).execute(connection)?;
.execute(&mut *self.connection.lock().unwrap())?; Ok(())
Ok(()) }
}
/// Get all existing ensembles.
/// Get all existing ensembles. pub fn get_ensembles(connection: &mut SqliteConnection) -> Result<Vec<Ensemble>> {
pub fn get_ensembles(&self) -> Result<Vec<Ensemble>> { let ensembles = ensembles::table.load::<Ensemble>(connection)?;
let ensembles = ensembles::table.load::<Ensemble>(&mut *self.connection.lock().unwrap())?; Ok(ensembles)
Ok(ensembles) }
}
/// Get recently used ensembles.
/// Get recently used ensembles. pub fn get_recent_ensembles(connection: &mut SqliteConnection) -> Result<Vec<Ensemble>> {
pub fn get_recent_ensembles(&self) -> Result<Vec<Ensemble>> { let ensembles = ensembles::table
let ensembles = ensembles::table .order(ensembles::last_used.desc())
.order(ensembles::last_used.desc()) .load::<Ensemble>(connection)?;
.load::<Ensemble>(&mut *self.connection.lock().unwrap())?;
Ok(ensembles)
Ok(ensembles)
}
} }

View file

@ -1,9 +1,9 @@
use super::schema::instruments;
use super::{Database, Result};
use chrono::Utc; use chrono::Utc;
use diesel::prelude::*; use diesel::prelude::*;
use log::info; use log::info;
use crate::{defer_foreign_keys, schema::instruments, Result};
/// An instrument or any other possible role within a recording. /// An instrument or any other possible role within a recording.
#[derive(Insertable, Queryable, PartialEq, Eq, Hash, Debug, Clone)] #[derive(Insertable, Queryable, PartialEq, Eq, Hash, Debug, Clone)]
pub struct Instrument { pub struct Instrument {
@ -24,57 +24,56 @@ impl Instrument {
} }
} }
impl Database { /// Update an existing instrument or insert a new one.
/// Update an existing instrument or insert a new one. pub fn update_instrument(
pub fn update_instrument(&self, mut instrument: Instrument) -> Result<()> { connection: &mut SqliteConnection,
info!("Updating instrument {:?}", instrument); mut instrument: Instrument,
self.defer_foreign_keys()?; ) -> Result<()> {
info!("Updating instrument {:?}", instrument);
defer_foreign_keys(connection)?;
instrument.last_used = Some(Utc::now().timestamp()); instrument.last_used = Some(Utc::now().timestamp());
self.connection.lock().unwrap().transaction(|connection| { connection.transaction(|connection| {
diesel::replace_into(instruments::table) diesel::replace_into(instruments::table)
.values(instrument) .values(instrument)
.execute(connection) .execute(connection)
})?; })?;
Ok(()) Ok(())
} }
/// Get an existing instrument. /// Get an existing instrument.
pub fn get_instrument(&self, id: &str) -> Result<Option<Instrument>> { pub fn get_instrument(connection: &mut SqliteConnection, id: &str) -> Result<Option<Instrument>> {
let instrument = instruments::table let instrument = instruments::table
.filter(instruments::id.eq(id)) .filter(instruments::id.eq(id))
.load::<Instrument>(&mut *self.connection.lock().unwrap())? .load::<Instrument>(connection)?
.into_iter() .into_iter()
.next(); .next();
Ok(instrument) Ok(instrument)
} }
/// Delete an existing instrument. /// Delete an existing instrument.
pub fn delete_instrument(&self, id: &str) -> Result<()> { pub fn delete_instrument(connection: &mut SqliteConnection, id: &str) -> Result<()> {
info!("Deleting instrument {}", id); info!("Deleting instrument {}", id);
diesel::delete(instruments::table.filter(instruments::id.eq(id))) diesel::delete(instruments::table.filter(instruments::id.eq(id))).execute(connection)?;
.execute(&mut *self.connection.lock().unwrap())?;
Ok(())
Ok(()) }
}
/// Get all existing instruments.
/// Get all existing instruments. pub fn get_instruments(connection: &mut SqliteConnection) -> Result<Vec<Instrument>> {
pub fn get_instruments(&self) -> Result<Vec<Instrument>> { let instruments = instruments::table.load::<Instrument>(connection)?;
let instruments =
instruments::table.load::<Instrument>(&mut *self.connection.lock().unwrap())?; Ok(instruments)
}
Ok(instruments)
} /// Get recently used instruments.
pub fn get_recent_instruments(connection: &mut SqliteConnection) -> Result<Vec<Instrument>> {
/// Get recently used instruments. let instruments = instruments::table
pub fn get_recent_instruments(&self) -> Result<Vec<Instrument>> { .order(instruments::last_used.desc())
let instruments = instruments::table .load::<Instrument>(connection)?;
.order(instruments::last_used.desc())
.load::<Instrument>(&mut *self.connection.lock().unwrap())?; Ok(instruments)
Ok(instruments)
}
} }

View file

@ -1,9 +1,9 @@
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
use std::sync::{Arc, Mutex};
use diesel::prelude::*; use diesel::prelude::*;
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
use log::info; use log::info;
pub use diesel::SqliteConnection;
pub mod ensembles; pub mod ensembles;
pub use ensembles::*; pub use ensembles::*;
@ -30,35 +30,25 @@ mod schema;
// This makes the SQL migration scripts accessible from the code. // This makes the SQL migration scripts accessible from the code.
const MIGRATIONS: EmbeddedMigrations = embed_migrations!(); const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
/// Connect to a Musicus database running migrations if necessary.
pub fn connect(file_name: &str) -> Result<SqliteConnection> {
info!("Opening database file '{}'", file_name);
let mut connection = SqliteConnection::establish(file_name)?;
diesel::sql_query("PRAGMA foreign_keys = ON").execute(&mut connection)?;
info!("Running migrations if necessary");
connection.run_pending_migrations(MIGRATIONS)?;
Ok(connection)
}
/// Generate a random string suitable as an item ID. /// Generate a random string suitable as an item ID.
pub fn generate_id() -> String { pub fn generate_id() -> String {
uuid::Uuid::new_v4().simple().to_string() uuid::Uuid::new_v4().simple().to_string()
} }
/// Interface to a Musicus database. /// Defer all foreign keys for the next transaction.
pub struct Database { fn defer_foreign_keys(connection: &mut SqliteConnection) -> Result<()> {
connection: Arc<Mutex<SqliteConnection>>, diesel::sql_query("PRAGMA defer_foreign_keys = ON").execute(connection)?;
} Ok(())
impl Database {
/// Create a new database interface and run migrations if necessary.
pub fn new(file_name: &str) -> Result<Database> {
info!("Opening database file '{}'", file_name);
let mut connection = SqliteConnection::establish(file_name)?;
diesel::sql_query("PRAGMA foreign_keys = ON").execute(&mut connection)?;
info!("Running migrations if necessary");
connection.run_pending_migrations(MIGRATIONS)?;
Ok(Database {
connection: Arc::new(Mutex::new(connection)),
})
}
/// Defer all foreign keys for the next transaction.
fn defer_foreign_keys(&self) -> Result<()> {
diesel::sql_query("PRAGMA defer_foreign_keys = ON")
.execute(&mut *self.connection.lock().unwrap())?;
Ok(())
}
} }

View file

@ -1,10 +1,13 @@
use super::generate_id;
use super::schema::{ensembles, mediums, performances, persons, recordings, tracks};
use super::{Database, Error, Recording, Result};
use chrono::{DateTime, TimeZone, Utc}; use chrono::{DateTime, TimeZone, Utc};
use diesel::prelude::*; use diesel::prelude::*;
use log::info; use log::info;
use crate::{
defer_foreign_keys, generate_id, get_recording,
schema::{ensembles, mediums, performances, persons, recordings, tracks},
update_recording, Error, Recording, Result,
};
/// Representation of someting like a physical audio disc or a folder with /// Representation of someting like a physical audio disc or a folder with
/// audio files (i.e. a collection of tracks for one or more recordings). /// audio files (i.e. a collection of tracks for one or more recordings).
#[derive(PartialEq, Eq, Hash, Debug, Clone)] #[derive(PartialEq, Eq, Hash, Debug, Clone)]
@ -103,244 +106,246 @@ struct TrackRow {
pub last_played: Option<i64>, pub last_played: Option<i64>,
} }
impl Database { /// Update an existing medium or insert a new one.
/// Update an existing medium or insert a new one. pub fn update_medium(connection: &mut SqliteConnection, medium: Medium) -> Result<()> {
pub fn update_medium(&self, medium: Medium) -> Result<()> { info!("Updating medium {:?}", medium);
info!("Updating medium {:?}", medium); defer_foreign_keys(connection)?;
self.defer_foreign_keys()?;
self.connection connection.transaction::<(), Error, _>(|connection| {
.lock() let medium_id = &medium.id;
.unwrap()
.transaction::<(), Error, _>(|connection| {
let medium_id = &medium.id;
// This will also delete the tracks. // This will also delete the tracks.
self.delete_medium(medium_id)?; delete_medium(connection, medium_id)?;
// Add the new medium. // Add the new medium.
let medium_row = MediumRow { let medium_row = MediumRow {
id: medium_id.to_owned(), id: medium_id.to_owned(),
name: medium.name.clone(), name: medium.name.clone(),
discid: medium.discid.clone(), discid: medium.discid.clone(),
last_used: Some(Utc::now().timestamp()), last_used: Some(Utc::now().timestamp()),
last_played: medium.last_played.map(|t| t.timestamp()), last_played: medium.last_played.map(|t| t.timestamp()),
};
diesel::insert_into(mediums::table)
.values(medium_row)
.execute(connection)?;
for (index, track) in medium.tracks.iter().enumerate() {
// Add associated items from the server, if they don't already exist.
if self.get_recording(&track.recording.id)?.is_none() {
self.update_recording(track.recording.clone())?;
}
// Add the actual track data.
let work_parts = track
.work_parts
.iter()
.map(|part_index| part_index.to_string())
.collect::<Vec<String>>()
.join(",");
let track_row = TrackRow {
id: generate_id(),
medium: Some(medium_id.to_owned()),
index: index as i32,
recording: track.recording.id.clone(),
work_parts,
source_index: track.source_index as i32,
path: track.path.clone(),
last_used: Some(Utc::now().timestamp()),
last_played: track.last_played.map(|t| t.timestamp()),
};
diesel::insert_into(tracks::table)
.values(track_row)
.execute(connection)?;
}
Ok(())
})?;
Ok(())
}
/// Get an existing medium.
pub fn get_medium(&self, id: &str) -> Result<Option<Medium>> {
let row = mediums::table
.filter(mediums::id.eq(id))
.load::<MediumRow>(&mut *self.connection.lock().unwrap())?
.into_iter()
.next();
let medium = match row {
Some(row) => Some(self.get_medium_data(row)?),
None => None,
}; };
Ok(medium) diesel::insert_into(mediums::table)
} .values(medium_row)
.execute(connection)?;
/// Get mediums that have a specific source ID. for (index, track) in medium.tracks.iter().enumerate() {
pub fn get_mediums_by_source_id(&self, source_id: &str) -> Result<Vec<Medium>> { // Add associated items from the server, if they don't already exist.
let mut mediums: Vec<Medium> = Vec::new();
let rows = mediums::table if get_recording(connection, &track.recording.id)?.is_none() {
.filter(mediums::discid.nullable().eq(source_id)) update_recording(connection, track.recording.clone())?;
.load::<MediumRow>(&mut *self.connection.lock().unwrap())?;
for row in rows {
let medium = self.get_medium_data(row)?;
mediums.push(medium);
}
Ok(mediums)
}
/// Get mediums on which this person is performing.
pub fn get_mediums_for_person(&self, person_id: &str) -> Result<Vec<Medium>> {
let mut mediums: Vec<Medium> = Vec::new();
let rows = mediums::table
.inner_join(tracks::table.on(tracks::medium.eq(mediums::id.nullable())))
.inner_join(recordings::table.on(recordings::id.eq(tracks::recording)))
.inner_join(performances::table.on(performances::recording.eq(recordings::id)))
.inner_join(persons::table.on(persons::id.nullable().eq(performances::person)))
.filter(persons::id.eq(person_id))
.select(mediums::table::all_columns())
.distinct()
.load::<MediumRow>(&mut *self.connection.lock().unwrap())?;
for row in rows {
let medium = self.get_medium_data(row)?;
mediums.push(medium);
}
Ok(mediums)
}
/// Get mediums on which this ensemble is performing.
pub fn get_mediums_for_ensemble(&self, ensemble_id: &str) -> Result<Vec<Medium>> {
let mut mediums: Vec<Medium> = Vec::new();
let rows = mediums::table
.inner_join(tracks::table.on(tracks::medium.eq(tracks::id.nullable())))
.inner_join(recordings::table.on(recordings::id.eq(tracks::recording)))
.inner_join(performances::table.on(performances::recording.eq(recordings::id)))
.inner_join(ensembles::table.on(ensembles::id.nullable().eq(performances::ensemble)))
.filter(ensembles::id.eq(ensemble_id))
.select(mediums::table::all_columns())
.distinct()
.load::<MediumRow>(&mut *self.connection.lock().unwrap())?;
for row in rows {
let medium = self.get_medium_data(row)?;
mediums.push(medium);
}
Ok(mediums)
}
/// Delete a medium and all of its tracks. This will fail, if the music
/// library contains audio files referencing any of those tracks.
pub fn delete_medium(&self, id: &str) -> Result<()> {
info!("Deleting medium {}", id);
diesel::delete(mediums::table.filter(mediums::id.eq(id)))
.execute(&mut *self.connection.lock().unwrap())?;
Ok(())
}
/// Get all available tracks for a recording.
pub fn get_tracks(&self, recording_id: &str) -> Result<Vec<Track>> {
let mut tracks: Vec<Track> = Vec::new();
let rows = tracks::table
.inner_join(recordings::table.on(recordings::id.eq(tracks::recording)))
.filter(recordings::id.eq(recording_id))
.select(tracks::table::all_columns())
.load::<TrackRow>(&mut *self.connection.lock().unwrap())?;
for row in rows {
let track = self.get_track_from_row(row)?;
tracks.push(track);
}
Ok(tracks)
}
/// Get a random track from the database.
pub fn random_track(&self) -> Result<Track> {
let row = diesel::sql_query("SELECT * FROM tracks ORDER BY RANDOM() LIMIT 1")
.load::<TrackRow>(&mut *self.connection.lock().unwrap())?
.into_iter()
.next()
.ok_or(Error::Other("Failed to generate random track"))?;
self.get_track_from_row(row)
}
/// Retrieve all available information on a medium from related tables.
fn get_medium_data(&self, row: MediumRow) -> Result<Medium> {
let track_rows = tracks::table
.filter(tracks::medium.eq(&row.id))
.order_by(tracks::index)
.load::<TrackRow>(&mut *self.connection.lock().unwrap())?;
let mut tracks = Vec::new();
for track_row in track_rows {
let track = self.get_track_from_row(track_row)?;
tracks.push(track);
}
let medium = Medium {
id: row.id,
name: row.name,
discid: row.discid,
tracks,
last_used: row.last_used.map(|t| Utc.timestamp_opt(t, 0).unwrap()),
last_played: row.last_played.map(|t| Utc.timestamp_opt(t, 0).unwrap()),
};
Ok(medium)
}
/// Convert a track row from the database to an actual track.
fn get_track_from_row(&self, row: TrackRow) -> Result<Track> {
let recording_id = row.recording;
let recording = self
.get_recording(&recording_id)?
.ok_or(Error::MissingItem("recording", recording_id))?;
let mut part_indices = Vec::new();
let work_parts = row.work_parts.split(',');
for part_index in work_parts {
if !part_index.is_empty() {
let index = str::parse(part_index)
.map_err(|_| Error::ParsingError("part index", String::from(part_index)))?;
part_indices.push(index);
} }
// Add the actual track data.
let work_parts = track
.work_parts
.iter()
.map(|part_index| part_index.to_string())
.collect::<Vec<String>>()
.join(",");
let track_row = TrackRow {
id: generate_id(),
medium: Some(medium_id.to_owned()),
index: index as i32,
recording: track.recording.id.clone(),
work_parts,
source_index: track.source_index as i32,
path: track.path.clone(),
last_used: Some(Utc::now().timestamp()),
last_played: track.last_played.map(|t| t.timestamp()),
};
diesel::insert_into(tracks::table)
.values(track_row)
.execute(connection)?;
} }
let track = Track { Ok(())
recording, })?;
work_parts: part_indices,
source_index: row.source_index as usize,
path: row.path,
last_used: row.last_used.map(|t| Utc.timestamp_opt(t, 0).unwrap()),
last_played: row.last_played.map(|t| Utc.timestamp_opt(t, 0).unwrap()),
};
Ok(track) Ok(())
} }
/// Get an existing medium.
pub fn get_medium(connection: &mut SqliteConnection, id: &str) -> Result<Option<Medium>> {
let row = mediums::table
.filter(mediums::id.eq(id))
.load::<MediumRow>(connection)?
.into_iter()
.next();
let medium = match row {
Some(row) => Some(get_medium_data(connection, row)?),
None => None,
};
Ok(medium)
}
/// Get mediums that have a specific source ID.
pub fn get_mediums_by_source_id(
connection: &mut SqliteConnection,
source_id: &str,
) -> Result<Vec<Medium>> {
let mut mediums: Vec<Medium> = Vec::new();
let rows = mediums::table
.filter(mediums::discid.nullable().eq(source_id))
.load::<MediumRow>(connection)?;
for row in rows {
let medium = get_medium_data(connection, row)?;
mediums.push(medium);
}
Ok(mediums)
}
/// Get mediums on which this person is performing.
pub fn get_mediums_for_person(
connection: &mut SqliteConnection,
person_id: &str,
) -> Result<Vec<Medium>> {
let mut mediums: Vec<Medium> = Vec::new();
let rows = mediums::table
.inner_join(tracks::table.on(tracks::medium.eq(mediums::id.nullable())))
.inner_join(recordings::table.on(recordings::id.eq(tracks::recording)))
.inner_join(performances::table.on(performances::recording.eq(recordings::id)))
.inner_join(persons::table.on(persons::id.nullable().eq(performances::person)))
.filter(persons::id.eq(person_id))
.select(mediums::table::all_columns())
.distinct()
.load::<MediumRow>(connection)?;
for row in rows {
let medium = get_medium_data(connection, row)?;
mediums.push(medium);
}
Ok(mediums)
}
/// Get mediums on which this ensemble is performing.
pub fn get_mediums_for_ensemble(
connection: &mut SqliteConnection,
ensemble_id: &str,
) -> Result<Vec<Medium>> {
let mut mediums: Vec<Medium> = Vec::new();
let rows = mediums::table
.inner_join(tracks::table.on(tracks::medium.eq(tracks::id.nullable())))
.inner_join(recordings::table.on(recordings::id.eq(tracks::recording)))
.inner_join(performances::table.on(performances::recording.eq(recordings::id)))
.inner_join(ensembles::table.on(ensembles::id.nullable().eq(performances::ensemble)))
.filter(ensembles::id.eq(ensemble_id))
.select(mediums::table::all_columns())
.distinct()
.load::<MediumRow>(connection)?;
for row in rows {
let medium = get_medium_data(connection, row)?;
mediums.push(medium);
}
Ok(mediums)
}
/// Delete a medium and all of its tracks. This will fail, if the music
/// library contains audio files referencing any of those tracks.
pub fn delete_medium(connection: &mut SqliteConnection, id: &str) -> Result<()> {
info!("Deleting medium {}", id);
diesel::delete(mediums::table.filter(mediums::id.eq(id))).execute(connection)?;
Ok(())
}
/// Get all available tracks for a recording.
pub fn get_tracks(connection: &mut SqliteConnection, recording_id: &str) -> Result<Vec<Track>> {
let mut tracks: Vec<Track> = Vec::new();
let rows = tracks::table
.inner_join(recordings::table.on(recordings::id.eq(tracks::recording)))
.filter(recordings::id.eq(recording_id))
.select(tracks::table::all_columns())
.load::<TrackRow>(connection)?;
for row in rows {
let track = get_track_from_row(connection, row)?;
tracks.push(track);
}
Ok(tracks)
}
/// Get a random track from the database.
pub fn random_track(connection: &mut SqliteConnection) -> Result<Track> {
let row = diesel::sql_query("SELECT * FROM tracks ORDER BY RANDOM() LIMIT 1")
.load::<TrackRow>(connection)?
.into_iter()
.next()
.ok_or(Error::Other("Failed to generate random track"))?;
get_track_from_row(connection, row)
}
/// Retrieve all available information on a medium from related tables.
fn get_medium_data(connection: &mut SqliteConnection, row: MediumRow) -> Result<Medium> {
let track_rows = tracks::table
.filter(tracks::medium.eq(&row.id))
.order_by(tracks::index)
.load::<TrackRow>(connection)?;
let mut tracks = Vec::new();
for track_row in track_rows {
let track = get_track_from_row(connection, track_row)?;
tracks.push(track);
}
let medium = Medium {
id: row.id,
name: row.name,
discid: row.discid,
tracks,
last_used: row.last_used.map(|t| Utc.timestamp_opt(t, 0).unwrap()),
last_played: row.last_played.map(|t| Utc.timestamp_opt(t, 0).unwrap()),
};
Ok(medium)
}
/// Convert a track row from the database to an actual track.
fn get_track_from_row(connection: &mut SqliteConnection, row: TrackRow) -> Result<Track> {
let recording_id = row.recording;
let recording = get_recording(connection, &recording_id)?
.ok_or(Error::MissingItem("recording", recording_id))?;
let mut part_indices = Vec::new();
let work_parts = row.work_parts.split(',');
for part_index in work_parts {
if !part_index.is_empty() {
let index = str::parse(part_index)
.map_err(|_| Error::ParsingError("part index", String::from(part_index)))?;
part_indices.push(index);
}
}
let track = Track {
recording,
work_parts: part_indices,
source_index: row.source_index as usize,
path: row.path,
last_used: row.last_used.map(|t| Utc.timestamp_opt(t, 0).unwrap()),
last_played: row.last_played.map(|t| Utc.timestamp_opt(t, 0).unwrap()),
};
Ok(track)
} }

View file

@ -1,9 +1,9 @@
use super::schema::persons;
use super::{Database, Result};
use chrono::Utc; use chrono::Utc;
use diesel::prelude::*; use diesel::prelude::*;
use log::info; use log::info;
use crate::{defer_foreign_keys, schema::persons, Result};
/// A person that is a composer, an interpret or both. /// A person that is a composer, an interpret or both.
#[derive(Insertable, Queryable, PartialEq, Eq, Hash, Debug, Clone)] #[derive(Insertable, Queryable, PartialEq, Eq, Hash, Debug, Clone)]
pub struct Person { pub struct Person {
@ -35,56 +35,52 @@ impl Person {
format!("{}, {}", self.last_name, self.first_name) format!("{}, {}", self.last_name, self.first_name)
} }
} }
/// Update an existing person or insert a new one.
pub fn update_person(connection: &mut SqliteConnection, mut person: Person) -> Result<()> {
info!("Updating person {:?}", person);
defer_foreign_keys(connection)?;
impl Database { person.last_used = Some(Utc::now().timestamp());
/// Update an existing person or insert a new one.
pub fn update_person(&self, mut person: Person) -> Result<()> {
info!("Updating person {:?}", person);
self.defer_foreign_keys()?;
person.last_used = Some(Utc::now().timestamp()); connection.transaction(|connection| {
diesel::replace_into(persons::table)
.values(person)
.execute(connection)
})?;
self.connection.lock().unwrap().transaction(|connection| { Ok(())
diesel::replace_into(persons::table) }
.values(person)
.execute(connection) /// Get an existing person.
})?; pub fn get_person(connection: &mut SqliteConnection, id: &str) -> Result<Option<Person>> {
let person = persons::table
Ok(()) .filter(persons::id.eq(id))
} .load::<Person>(connection)?
.into_iter()
/// Get an existing person. .next();
pub fn get_person(&self, id: &str) -> Result<Option<Person>> {
let person = persons::table Ok(person)
.filter(persons::id.eq(id)) }
.load::<Person>(&mut *self.connection.lock().unwrap())?
.into_iter() /// Delete an existing person.
.next(); pub fn delete_person(connection: &mut SqliteConnection, id: &str) -> Result<()> {
info!("Deleting person {}", id);
Ok(person) diesel::delete(persons::table.filter(persons::id.eq(id))).execute(connection)?;
} Ok(())
}
/// Delete an existing person.
pub fn delete_person(&self, id: &str) -> Result<()> { /// Get all existing persons.
info!("Deleting person {}", id); pub fn get_persons(connection: &mut SqliteConnection) -> Result<Vec<Person>> {
diesel::delete(persons::table.filter(persons::id.eq(id))) let persons = persons::table.load::<Person>(connection)?;
.execute(&mut *self.connection.lock().unwrap())?;
Ok(()) Ok(persons)
} }
/// Get all existing persons. /// Get recently used persons.
pub fn get_persons(&self) -> Result<Vec<Person>> { pub fn get_recent_persons(connection: &mut SqliteConnection) -> Result<Vec<Person>> {
let persons = persons::table.load::<Person>(&mut *self.connection.lock().unwrap())?; let persons = persons::table
.order(persons::last_used.desc())
Ok(persons) .load::<Person>(connection)?;
}
Ok(persons)
/// Get recently used persons.
pub fn get_recent_persons(&self) -> Result<Vec<Person>> {
let persons = persons::table
.order(persons::last_used.desc())
.load::<Person>(&mut *self.connection.lock().unwrap())?;
Ok(persons)
}
} }

View file

@ -1,10 +1,14 @@
use super::generate_id;
use super::schema::{ensembles, performances, persons, recordings};
use super::{Database, Ensemble, Error, Instrument, Person, Result, Work};
use chrono::{DateTime, TimeZone, Utc}; use chrono::{DateTime, TimeZone, Utc};
use diesel::prelude::*; use diesel::prelude::*;
use log::info; use log::info;
use crate::{
defer_foreign_keys, generate_id, get_ensemble, get_instrument, get_person, get_work,
schema::{ensembles, performances, persons, recordings},
update_ensemble, update_instrument, update_person, update_work, Ensemble, Error, Instrument,
Person, Result, Work,
};
/// A specific recording of a work. /// A specific recording of a work.
#[derive(PartialEq, Eq, Hash, Debug, Clone)] #[derive(PartialEq, Eq, Hash, Debug, Clone)]
pub struct Recording { pub struct Recording {
@ -125,223 +129,222 @@ struct PerformanceRow {
pub role: Option<String>, pub role: Option<String>,
} }
impl Database { /// Update an existing recording or insert a new one.
/// Update an existing recording or insert a new one. // TODO: Think about whether to also insert the other items.
// TODO: Think about whether to also insert the other items. pub fn update_recording(connection: &mut SqliteConnection, recording: Recording) -> Result<()> {
pub fn update_recording(&self, recording: Recording) -> Result<()> { info!("Updating recording {:?}", recording);
info!("Updating recording {:?}", recording); defer_foreign_keys(connection)?;
self.defer_foreign_keys()?;
self.connection
.lock()
.unwrap()
.transaction::<(), Error, _>(|connection| {
let recording_id = &recording.id;
self.delete_recording(recording_id)?;
// Add associated items from the server, if they don't already exist. connection.transaction::<(), Error, _>(|connection| {
let recording_id = &recording.id;
delete_recording(connection, recording_id)?;
if self.get_work(&recording.work.id)?.is_none() { // Add associated items from the server, if they don't already exist.
self.update_work(recording.work.clone())?;
}
for performance in &recording.performances { if get_work(connection, &recording.work.id)?.is_none() {
match &performance.performer { update_work(connection, recording.work.clone())?;
PersonOrEnsemble::Person(person) => { }
if self.get_person(&person.id)?.is_none() {
self.update_person(person.clone())?;
}
}
PersonOrEnsemble::Ensemble(ensemble) => {
if self.get_ensemble(&ensemble.id)?.is_none() {
self.update_ensemble(ensemble.clone())?;
}
}
}
if let Some(role) = &performance.role { for performance in &recording.performances {
if self.get_instrument(&role.id)?.is_none() { match &performance.performer {
self.update_instrument(role.clone())?; PersonOrEnsemble::Person(person) => {
} if get_person(connection, &person.id)?.is_none() {
update_person(connection, person.clone())?;
} }
} }
PersonOrEnsemble::Ensemble(ensemble) => {
// Add the actual recording. if get_ensemble(connection, &ensemble.id)?.is_none() {
update_ensemble(connection, ensemble.clone())?;
let row: RecordingRow = recording.clone().into(); }
diesel::insert_into(recordings::table)
.values(row)
.execute(connection)?;
for performance in recording.performances {
let (person, ensemble) = match performance.performer {
PersonOrEnsemble::Person(person) => (Some(person.id), None),
PersonOrEnsemble::Ensemble(ensemble) => (None, Some(ensemble.id)),
};
let row = PerformanceRow {
id: rand::random(),
recording: recording_id.to_string(),
person,
ensemble,
role: performance.role.map(|role| role.id),
};
diesel::insert_into(performances::table)
.values(row)
.execute(connection)?;
} }
}
Ok(()) if let Some(role) = &performance.role {
})?; if get_instrument(connection, &role.id)?.is_none() {
update_instrument(connection, role.clone())?;
}
}
}
// Add the actual recording.
let row: RecordingRow = recording.clone().into();
diesel::insert_into(recordings::table)
.values(row)
.execute(connection)?;
for performance in recording.performances {
let (person, ensemble) = match performance.performer {
PersonOrEnsemble::Person(person) => (Some(person.id), None),
PersonOrEnsemble::Ensemble(ensemble) => (None, Some(ensemble.id)),
};
let row = PerformanceRow {
id: rand::random(),
recording: recording_id.to_string(),
person,
ensemble,
role: performance.role.map(|role| role.id),
};
diesel::insert_into(performances::table)
.values(row)
.execute(connection)?;
}
Ok(()) Ok(())
} })?;
/// Check whether the database contains a recording. Ok(())
pub fn recording_exists(&self, id: &str) -> Result<bool> { }
let exists = recordings::table
.filter(recordings::id.eq(id)) /// Check whether the database contains a recording.
.load::<RecordingRow>(&mut *self.connection.lock().unwrap())? pub fn recording_exists(connection: &mut SqliteConnection, id: &str) -> Result<bool> {
.first() let exists = recordings::table
.is_some(); .filter(recordings::id.eq(id))
.load::<RecordingRow>(connection)?
Ok(exists) .first()
} .is_some();
/// Get an existing recording. Ok(exists)
pub fn get_recording(&self, id: &str) -> Result<Option<Recording>> { }
let row = recordings::table
.filter(recordings::id.eq(id)) /// Get an existing recording.
.load::<RecordingRow>(&mut *self.connection.lock().unwrap())? pub fn get_recording(connection: &mut SqliteConnection, id: &str) -> Result<Option<Recording>> {
.into_iter() let row = recordings::table
.next(); .filter(recordings::id.eq(id))
.load::<RecordingRow>(connection)?
let recording = match row { .into_iter()
Some(row) => Some(self.get_recording_data(row)?), .next();
None => None,
}; let recording = match row {
Some(row) => Some(get_recording_data(connection, row)?),
Ok(recording) None => None,
} };
/// Get a random recording from the database. Ok(recording)
pub fn random_recording(&self) -> Result<Recording> { }
let row = diesel::sql_query("SELECT * FROM recordings ORDER BY RANDOM() LIMIT 1")
.load::<RecordingRow>(&mut *self.connection.lock().unwrap())? /// Get a random recording from the database.
.into_iter() pub fn random_recording(connection: &mut SqliteConnection) -> Result<Recording> {
.next() let row = diesel::sql_query("SELECT * FROM recordings ORDER BY RANDOM() LIMIT 1")
.ok_or(Error::Other("Failed to find random recording."))?; .load::<RecordingRow>(connection)?
.into_iter()
self.get_recording_data(row) .next()
} .ok_or(Error::Other("Failed to find random recording."))?;
/// Retrieve all available information on a recording from related tables. get_recording_data(connection, row)
fn get_recording_data(&self, row: RecordingRow) -> Result<Recording> { }
let mut performance_descriptions: Vec<Performance> = Vec::new();
/// Retrieve all available information on a recording from related tables.
let performance_rows = performances::table fn get_recording_data(connection: &mut SqliteConnection, row: RecordingRow) -> Result<Recording> {
.filter(performances::recording.eq(&row.id)) let mut performance_descriptions: Vec<Performance> = Vec::new();
.load::<PerformanceRow>(&mut *self.connection.lock().unwrap())?;
let performance_rows = performances::table
for row in performance_rows { .filter(performances::recording.eq(&row.id))
performance_descriptions.push(Performance { .load::<PerformanceRow>(connection)?;
performer: if let Some(id) = row.person {
PersonOrEnsemble::Person( for row in performance_rows {
self.get_person(&id)? performance_descriptions.push(Performance {
.ok_or(Error::MissingItem("person", id))?, performer: if let Some(id) = row.person {
) PersonOrEnsemble::Person(
} else if let Some(id) = row.ensemble { get_person(connection, &id)?.ok_or(Error::MissingItem("person", id))?,
PersonOrEnsemble::Ensemble( )
self.get_ensemble(&id)? } else if let Some(id) = row.ensemble {
.ok_or(Error::MissingItem("ensemble", id))?, PersonOrEnsemble::Ensemble(
) get_ensemble(connection, &id)?.ok_or(Error::MissingItem("ensemble", id))?,
} else { )
return Err(Error::Other("Performance without performer")); } else {
}, return Err(Error::Other("Performance without performer"));
role: match row.role { },
Some(id) => Some( role: match row.role {
self.get_instrument(&id)? Some(id) => Some(
.ok_or(Error::MissingItem("instrument", id))?, get_instrument(connection, &id)?.ok_or(Error::MissingItem("instrument", id))?,
), ),
None => None, None => None,
}, },
}); });
} }
let work_id = row.work; let work_id = row.work;
let work = self let work = get_work(connection, &work_id)?.ok_or(Error::MissingItem("work", work_id))?;
.get_work(&work_id)?
.ok_or(Error::MissingItem("work", work_id))?; let recording_description = Recording {
id: row.id,
let recording_description = Recording { work,
id: row.id, comment: row.comment,
work, performances: performance_descriptions,
comment: row.comment, last_used: row.last_used.map(|t| Utc.timestamp_opt(t, 0).unwrap()),
performances: performance_descriptions, last_played: row.last_played.map(|t| Utc.timestamp_opt(t, 0).unwrap()),
last_used: row.last_used.map(|t| Utc.timestamp_opt(t, 0).unwrap()), };
last_played: row.last_played.map(|t| Utc.timestamp_opt(t, 0).unwrap()),
}; Ok(recording_description)
}
Ok(recording_description)
} /// Get all available information on all recordings where a person is performing.
pub fn get_recordings_for_person(
/// Get all available information on all recordings where a person is performing. connection: &mut SqliteConnection,
pub fn get_recordings_for_person(&self, person_id: &str) -> Result<Vec<Recording>> { person_id: &str,
let mut recordings: Vec<Recording> = Vec::new(); ) -> Result<Vec<Recording>> {
let mut recordings: Vec<Recording> = Vec::new();
let rows = recordings::table
.inner_join(performances::table.on(performances::recording.eq(recordings::id))) let rows = recordings::table
.inner_join(persons::table.on(persons::id.nullable().eq(performances::person))) .inner_join(performances::table.on(performances::recording.eq(recordings::id)))
.filter(persons::id.eq(person_id)) .inner_join(persons::table.on(persons::id.nullable().eq(performances::person)))
.select(recordings::table::all_columns()) .filter(persons::id.eq(person_id))
.load::<RecordingRow>(&mut *self.connection.lock().unwrap())?; .select(recordings::table::all_columns())
.load::<RecordingRow>(connection)?;
for row in rows {
recordings.push(self.get_recording_data(row)?); for row in rows {
} recordings.push(get_recording_data(connection, row)?);
}
Ok(recordings)
} Ok(recordings)
}
/// Get all available information on all recordings where an ensemble is performing.
pub fn get_recordings_for_ensemble(&self, ensemble_id: &str) -> Result<Vec<Recording>> { /// Get all available information on all recordings where an ensemble is performing.
let mut recordings: Vec<Recording> = Vec::new(); pub fn get_recordings_for_ensemble(
connection: &mut SqliteConnection,
let rows = recordings::table ensemble_id: &str,
.inner_join(performances::table.on(performances::recording.eq(recordings::id))) ) -> Result<Vec<Recording>> {
.inner_join(ensembles::table.on(ensembles::id.nullable().eq(performances::ensemble))) let mut recordings: Vec<Recording> = Vec::new();
.filter(ensembles::id.eq(ensemble_id))
.select(recordings::table::all_columns()) let rows = recordings::table
.load::<RecordingRow>(&mut *self.connection.lock().unwrap())?; .inner_join(performances::table.on(performances::recording.eq(recordings::id)))
.inner_join(ensembles::table.on(ensembles::id.nullable().eq(performances::ensemble)))
for row in rows { .filter(ensembles::id.eq(ensemble_id))
recordings.push(self.get_recording_data(row)?); .select(recordings::table::all_columns())
} .load::<RecordingRow>(connection)?;
Ok(recordings) for row in rows {
} recordings.push(get_recording_data(connection, row)?);
}
/// Get allavailable information on all recordings of a work.
pub fn get_recordings_for_work(&self, work_id: &str) -> Result<Vec<Recording>> { Ok(recordings)
let mut recordings: Vec<Recording> = Vec::new(); }
let rows = recordings::table /// Get allavailable information on all recordings of a work.
.filter(recordings::work.eq(work_id)) pub fn get_recordings_for_work(
.load::<RecordingRow>(&mut *self.connection.lock().unwrap())?; connection: &mut SqliteConnection,
work_id: &str,
for row in rows { ) -> Result<Vec<Recording>> {
recordings.push(self.get_recording_data(row)?); let mut recordings: Vec<Recording> = Vec::new();
}
let rows = recordings::table
Ok(recordings) .filter(recordings::work.eq(work_id))
} .load::<RecordingRow>(connection)?;
/// Delete an existing recording. This will fail if there are still references to this for row in rows {
/// recording from other tables that are not directly part of the recording data. recordings.push(get_recording_data(connection, row)?);
pub fn delete_recording(&self, id: &str) -> Result<()> { }
info!("Deleting recording {}", id);
diesel::delete(recordings::table.filter(recordings::id.eq(id))) Ok(recordings)
.execute(&mut *self.connection.lock().unwrap())?; }
Ok(())
} /// Delete an existing recording. This will fail if there are still references to this
/// recording from other tables that are not directly part of the recording data.
pub fn delete_recording(connection: &mut SqliteConnection, id: &str) -> Result<()> {
info!("Deleting recording {}", id);
diesel::delete(recordings::table.filter(recordings::id.eq(id))).execute(connection)?;
Ok(())
} }

View file

@ -1,11 +1,13 @@
use super::generate_id;
use super::schema::{instrumentations, work_parts, works};
use super::{Database, Error, Instrument, Person, Result};
use chrono::{DateTime, TimeZone, Utc}; use chrono::{DateTime, TimeZone, Utc};
use diesel::prelude::*; use diesel::{prelude::*, Insertable, Queryable};
use diesel::{Insertable, Queryable};
use log::info; use log::info;
use crate::{
defer_foreign_keys, generate_id, get_instrument, get_person,
schema::{instrumentations, work_parts, works},
update_instrument, update_person, Error, Instrument, Person, Result,
};
/// Table row data for a work. /// Table row data for a work.
#[derive(Insertable, Queryable, Debug, Clone)] #[derive(Insertable, Queryable, Debug, Clone)]
#[table_name = "works"] #[table_name = "works"]
@ -105,155 +107,146 @@ impl Work {
} }
} }
impl Database { /// Update an existing work or insert a new one.
/// Update an existing work or insert a new one. // TODO: Think about also inserting related items.
// TODO: Think about also inserting related items. pub fn update_work(connection: &mut SqliteConnection, work: Work) -> Result<()> {
pub fn update_work(&self, work: Work) -> Result<()> { info!("Updating work {:?}", work);
info!("Updating work {:?}", work); defer_foreign_keys(connection)?;
self.defer_foreign_keys()?;
self.connection connection.transaction::<(), Error, _>(|connection| {
.lock() let work_id = &work.id;
.unwrap() delete_work(connection, work_id)?;
.transaction::<(), Error, _>(|connection| {
let work_id = &work.id;
self.delete_work(work_id)?;
// Add associated items from the server, if they don't already exist. // Add associated items from the server, if they don't already exist.
if self.get_person(&work.composer.id)?.is_none() { if get_person(connection, &work.composer.id)?.is_none() {
self.update_person(work.composer.clone())?; update_person(connection, work.composer.clone())?;
} }
for instrument in &work.instruments { for instrument in &work.instruments {
if self.get_instrument(&instrument.id)?.is_none() { if get_instrument(connection, &instrument.id)?.is_none() {
self.update_instrument(instrument.clone())?; update_instrument(connection, instrument.clone())?;
} }
} }
// Add the actual work. // Add the actual work.
let row: WorkRow = work.clone().into(); let row: WorkRow = work.clone().into();
diesel::insert_into(works::table) diesel::insert_into(works::table)
.values(row) .values(row)
.execute(&mut *self.connection.lock().unwrap())?; .execute(connection)?;
let Work { let Work {
instruments, parts, .. instruments, parts, ..
} = work; } = work;
for instrument in instruments { for instrument in instruments {
let row = InstrumentationRow { let row = InstrumentationRow {
id: rand::random(), id: rand::random(),
work: work_id.to_string(), work: work_id.to_string(),
instrument: instrument.id, instrument: instrument.id,
}; };
diesel::insert_into(instrumentations::table) diesel::insert_into(instrumentations::table)
.values(row) .values(row)
.execute(connection)?; .execute(connection)?;
} }
for (index, part) in parts.into_iter().enumerate() { for (index, part) in parts.into_iter().enumerate() {
let row = WorkPartRow { let row = WorkPartRow {
id: rand::random(), id: rand::random(),
work: work_id.to_string(), work: work_id.to_string(),
part_index: index as i64, part_index: index as i64,
title: part.title, title: part.title,
}; };
diesel::insert_into(work_parts::table) diesel::insert_into(work_parts::table)
.values(row) .values(row)
.execute(connection)?; .execute(connection)?;
} }
Ok(())
})?;
Ok(()) Ok(())
} })?;
/// Get an existing work. Ok(())
pub fn get_work(&self, id: &str) -> Result<Option<Work>> { }
let row = works::table
.filter(works::id.eq(id)) /// Get an existing work.
.load::<WorkRow>(&mut *self.connection.lock().unwrap())? pub fn get_work(connection: &mut SqliteConnection, id: &str) -> Result<Option<Work>> {
.first() let row = works::table
.cloned(); .filter(works::id.eq(id))
.load::<WorkRow>(connection)?
let work = match row { .first()
Some(row) => Some(self.get_work_data(row)?), .cloned();
None => None,
}; let work = match row {
Some(row) => Some(get_work_data(connection, row)?),
Ok(work) None => None,
} };
/// Retrieve all available information on a work from related tables. Ok(work)
fn get_work_data(&self, row: WorkRow) -> Result<Work> { }
let mut instruments: Vec<Instrument> = Vec::new();
/// Retrieve all available information on a work from related tables.
let instrumentations = instrumentations::table fn get_work_data(connection: &mut SqliteConnection, row: WorkRow) -> Result<Work> {
.filter(instrumentations::work.eq(&row.id)) let mut instruments: Vec<Instrument> = Vec::new();
.load::<InstrumentationRow>(&mut *self.connection.lock().unwrap())?;
let instrumentations = instrumentations::table
for instrumentation in instrumentations { .filter(instrumentations::work.eq(&row.id))
let id = instrumentation.instrument; .load::<InstrumentationRow>(connection)?;
instruments.push(
self.get_instrument(&id)? for instrumentation in instrumentations {
.ok_or(Error::MissingItem("instrument", id))?, let id = instrumentation.instrument;
); instruments
} .push(get_instrument(connection, &id)?.ok_or(Error::MissingItem("instrument", id))?);
}
let mut parts: Vec<WorkPart> = Vec::new();
let mut parts: Vec<WorkPart> = Vec::new();
let part_rows = work_parts::table
.filter(work_parts::work.eq(&row.id)) let part_rows = work_parts::table
.load::<WorkPartRow>(&mut *self.connection.lock().unwrap())?; .filter(work_parts::work.eq(&row.id))
.load::<WorkPartRow>(connection)?;
for part_row in part_rows {
parts.push(WorkPart { for part_row in part_rows {
title: part_row.title, parts.push(WorkPart {
}); title: part_row.title,
} });
}
let person_id = row.composer;
let person = self let person_id = row.composer;
.get_person(&person_id)? let person =
.ok_or(Error::MissingItem("person", person_id))?; get_person(connection, &person_id)?.ok_or(Error::MissingItem("person", person_id))?;
Ok(Work { Ok(Work {
id: row.id, id: row.id,
composer: person, composer: person,
title: row.title, title: row.title,
instruments, instruments,
parts, parts,
last_used: row.last_used.map(|t| Utc.timestamp_opt(t, 0).unwrap()), last_used: row.last_used.map(|t| Utc.timestamp_opt(t, 0).unwrap()),
last_played: row.last_played.map(|t| Utc.timestamp_opt(t, 0).unwrap()), last_played: row.last_played.map(|t| Utc.timestamp_opt(t, 0).unwrap()),
}) })
} }
/// Delete an existing work. This will fail if there are still other tables that relate to /// Delete an existing work. This will fail if there are still other tables that relate to
/// this work except for the things that are part of the information on the work it /// this work except for the things that are part of the information on the work it
pub fn delete_work(&self, id: &str) -> Result<()> { pub fn delete_work(connection: &mut SqliteConnection, id: &str) -> Result<()> {
info!("Deleting work {}", id); info!("Deleting work {}", id);
diesel::delete(works::table.filter(works::id.eq(id))) diesel::delete(works::table.filter(works::id.eq(id))).execute(connection)?;
.execute(&mut *self.connection.lock().unwrap())?; Ok(())
Ok(()) }
}
/// Get all existing works by a composer and related information from other tables.
/// Get all existing works by a composer and related information from other tables. pub fn get_works(connection: &mut SqliteConnection, composer_id: &str) -> Result<Vec<Work>> {
pub fn get_works(&self, composer_id: &str) -> Result<Vec<Work>> { let mut works: Vec<Work> = Vec::new();
let mut works: Vec<Work> = Vec::new();
let rows = works::table
let rows = works::table .filter(works::composer.eq(composer_id))
.filter(works::composer.eq(composer_id)) .load::<WorkRow>(connection)?;
.load::<WorkRow>(&mut *self.connection.lock().unwrap())?;
for row in rows {
for row in rows { works.push(get_work_data(connection, row)?);
works.push(self.get_work_data(row)?); }
}
Ok(works)
Ok(works)
}
} }

View file

@ -3,7 +3,7 @@ use crate::widgets::{Editor, Section, Widget};
use anyhow::Result; use anyhow::Result;
use gettextrs::gettext; use gettextrs::gettext;
use gtk::{builders::ListBoxBuilder, glib::clone, prelude::*}; use gtk::{builders::ListBoxBuilder, glib::clone, prelude::*};
use musicus_backend::db::{generate_id, Ensemble}; use musicus_backend::db::{generate_id, Ensemble, self};
use std::rc::Rc; use std::rc::Rc;
/// A dialog for creating or editing a ensemble. /// A dialog for creating or editing a ensemble.
@ -88,7 +88,7 @@ impl EnsembleEditor {
let ensemble = Ensemble::new(self.id.clone(), name.to_string()); let ensemble = Ensemble::new(self.id.clone(), name.to_string());
self.handle.backend.db().update_ensemble(ensemble.clone())?; db::update_ensemble(&mut self.handle.backend.db().lock().unwrap(), ensemble.clone())?;
self.handle.backend.library_changed(); self.handle.backend.library_changed();
Ok(ensemble) Ok(ensemble)

View file

@ -3,7 +3,7 @@ use crate::widgets::{Editor, Section, Widget};
use anyhow::Result; use anyhow::Result;
use gettextrs::gettext; use gettextrs::gettext;
use gtk::{builders::ListBoxBuilder, glib::clone, prelude::*}; use gtk::{builders::ListBoxBuilder, glib::clone, prelude::*};
use musicus_backend::db::{generate_id, Instrument}; use musicus_backend::db::{self, generate_id, Instrument};
use std::rc::Rc; use std::rc::Rc;
/// A dialog for creating or editing a instrument. /// A dialog for creating or editing a instrument.
@ -88,10 +88,11 @@ impl InstrumentEditor {
let instrument = Instrument::new(self.id.clone(), name.to_string()); let instrument = Instrument::new(self.id.clone(), name.to_string());
self.handle db::update_instrument(
.backend &mut self.handle.backend.db().lock().unwrap(),
.db() instrument.clone(),
.update_instrument(instrument.clone())?; )?;
self.handle.backend.library_changed(); self.handle.backend.library_changed();
Ok(instrument) Ok(instrument)

View file

@ -4,7 +4,7 @@ use anyhow::Result;
use gettextrs::gettext; use gettextrs::gettext;
use glib::clone; use glib::clone;
use gtk::{builders::ListBoxBuilder, prelude::*}; use gtk::{builders::ListBoxBuilder, prelude::*};
use musicus_backend::db::{generate_id, Person}; use musicus_backend::db::{generate_id, Person, self};
use std::rc::Rc; use std::rc::Rc;
/// A dialog for creating or editing a person. /// A dialog for creating or editing a person.
@ -110,7 +110,11 @@ impl PersonEditor {
last_name.to_string(), last_name.to_string(),
); );
self.handle.backend.db().update_person(person.clone())?; db::update_person(
&mut self.handle.backend.db().lock().unwrap(),
person.clone(),
)?;
self.handle.backend.library_changed(); self.handle.backend.library_changed();
Ok(person) Ok(person)

View file

@ -8,7 +8,7 @@ use anyhow::Result;
use gettextrs::gettext; use gettextrs::gettext;
use glib::clone; use glib::clone;
use gtk_macros::get_widget; use gtk_macros::get_widget;
use musicus_backend::db::{generate_id, Performance, Recording, Work}; use musicus_backend::db::{self, generate_id, Performance, Recording, Work};
use std::cell::RefCell; use std::cell::RefCell;
use std::rc::Rc; use std::rc::Rc;
@ -188,10 +188,11 @@ impl RecordingEditor {
self.performances.borrow().clone(), self.performances.borrow().clone(),
); );
self.handle db::update_recording(
.backend &mut self.handle.backend.db().lock().unwrap(),
.db() recording.clone(),
.update_recording(recording.clone())?; )?;
self.handle.backend.library_changed(); self.handle.backend.library_changed();
Ok(recording) Ok(recording)

View file

@ -8,7 +8,7 @@ use anyhow::Result;
use gettextrs::gettext; use gettextrs::gettext;
use glib::clone; use glib::clone;
use gtk_macros::get_widget; use gtk_macros::get_widget;
use musicus_backend::db::{generate_id, Instrument, Person, Work, WorkPart}; use musicus_backend::db::{self, generate_id, Instrument, Person, Work, WorkPart};
use std::cell::RefCell; use std::cell::RefCell;
use std::rc::Rc; use std::rc::Rc;
@ -261,7 +261,7 @@ impl WorkEditor {
self.parts.borrow().clone(), self.parts.borrow().clone(),
); );
self.handle.backend.db().update_work(work.clone())?; db::update_work(&mut self.handle.backend.db().lock().unwrap(), work.clone())?;
self.handle.backend.library_changed(); self.handle.backend.library_changed();
Ok(work) Ok(work)

View file

@ -7,7 +7,7 @@ use adw::builders::ActionRowBuilder;
use adw::prelude::*; use adw::prelude::*;
use glib::clone; use glib::clone;
use gtk_macros::get_widget; use gtk_macros::get_widget;
use musicus_backend::db::Medium; use musicus_backend::db::{self, Medium};
use musicus_backend::import::ImportSession; use musicus_backend::import::ImportSession;
use std::rc::Rc; use std::rc::Rc;
use std::sync::Arc; use std::sync::Arc;
@ -29,7 +29,10 @@ impl ImportScreen {
let this = self; let this = self;
spawn!(@clone this, async move { spawn!(@clone this, async move {
let mediums = this.handle.backend.db().get_mediums_by_source_id(this.session.source_id()); let mediums = db::get_mediums_by_source_id(
&mut this.handle.backend.db().lock().unwrap(),
this.session.source_id()
);
match mediums { match mediums {
Ok(mediums) => { Ok(mediums) => {
@ -110,7 +113,7 @@ impl Screen<Arc<ImportSession>, ()> for ImportScreen {
get_widget!(builder, adw::ActionRow, error_row); get_widget!(builder, adw::ActionRow, error_row);
get_widget!(builder, gtk::ListBox, matching_list); get_widget!(builder, gtk::ListBox, matching_list);
get_widget!(builder, gtk::Button, select_button); get_widget!(builder, gtk::Button, select_button);
get_widget!(builder, gtk::Button, add_button); get_widget!(builder, gtk::Button, add_medium_button);
let this = Rc::new(Self { let this = Rc::new(Self {
handle, handle,
@ -139,7 +142,7 @@ impl Screen<Arc<ImportSession>, ()> for ImportScreen {
}); });
})); }));
add_button.connect_clicked(clone!(@weak this => move |_| { add_medium_button.connect_clicked(clone!(@weak this => move |_| {
spawn!(@clone this, async move { spawn!(@clone this, async move {
if let Some(medium) = push!(this.handle, MediumEditor, (Arc::clone(&this.session), None)).await { if let Some(medium) = push!(this.handle, MediumEditor, (Arc::clone(&this.session), None)).await {
this.select_medium(medium); this.select_medium(medium);
@ -151,7 +154,7 @@ impl Screen<Arc<ImportSession>, ()> for ImportScreen {
this.load_matches(); this.load_matches();
// Copy the tracks in the background, if neccessary. // Copy the tracks in the background, if necessary.
this.session.copy(); this.session.copy();
this this

View file

@ -8,7 +8,7 @@ use glib::clone;
use gtk::builders::{FrameBuilder, ListBoxBuilder}; use gtk::builders::{FrameBuilder, ListBoxBuilder};
use gtk::prelude::*; use gtk::prelude::*;
use gtk_macros::get_widget; use gtk_macros::get_widget;
use musicus_backend::db::Medium; use musicus_backend::db::{self, Medium};
use musicus_backend::import::{ImportSession, State}; use musicus_backend::import::{ImportSession, State};
use std::cell::RefCell; use std::cell::RefCell;
use std::path::PathBuf; use std::path::PathBuf;
@ -226,7 +226,7 @@ impl MediumPreview {
); );
let directory = PathBuf::from(&directory_name); let directory = PathBuf::from(&directory_name);
std::fs::create_dir(&music_library_path.join(&directory))?; std::fs::create_dir(music_library_path.join(&directory))?;
// Copy the tracks to the music library. // Copy the tracks to the music library.
@ -243,7 +243,7 @@ impl MediumPreview {
track.path = track_path.to_str().unwrap().to_owned(); track.path = track_path.to_str().unwrap().to_owned();
// Copy the corresponding audio file to the music library. // Copy the corresponding audio file to the music library.
std::fs::copy(&import_track.path, &music_library_path.join(&track_path))?; std::fs::copy(&import_track.path, music_library_path.join(&track_path))?;
tracks.push(track); tracks.push(track);
} }
@ -257,7 +257,7 @@ impl MediumPreview {
tracks, tracks,
); );
self.handle.backend.db().update_medium(medium)?; db::update_medium(&mut self.handle.backend.db().lock().unwrap(), medium)?;
self.handle.backend.library_changed(); self.handle.backend.library_changed();
Ok(()) Ok(())

View file

@ -7,7 +7,7 @@ use adw::builders::ActionRowBuilder;
use adw::prelude::*; use adw::prelude::*;
use gettextrs::gettext; use gettextrs::gettext;
use glib::clone; use glib::clone;
use musicus_backend::db::{Ensemble, Medium, Recording}; use musicus_backend::db::{self, Ensemble, Medium, Recording};
use std::cell::RefCell; use std::cell::RefCell;
use std::rc::Rc; use std::rc::Rc;
@ -60,7 +60,7 @@ impl Screen<Ensemble, ()> for EnsembleScreen {
&gettext("Delete ensemble"), &gettext("Delete ensemble"),
clone!(@weak this => move || { clone!(@weak this => move || {
spawn!(@clone this, async move { spawn!(@clone this, async move {
this.handle.backend.db().delete_ensemble(&this.ensemble.id).unwrap(); db::delete_ensemble(&mut this.handle.backend.db().lock().unwrap(), &this.ensemble.id).unwrap();
this.handle.backend.library_changed(); this.handle.backend.library_changed();
}); });
}), }),
@ -131,19 +131,17 @@ impl Screen<Ensemble, ()> for EnsembleScreen {
// Load the content. // Load the content.
let recordings = this let recordings = db::get_recordings_for_ensemble(
.handle &mut this.handle.backend.db().lock().unwrap(),
.backend &this.ensemble.id,
.db() )
.get_recordings_for_ensemble(&this.ensemble.id) .unwrap();
.unwrap();
let mediums = this let mediums = db::get_mediums_for_ensemble(
.handle &mut this.handle.backend.db().lock().unwrap(),
.backend &this.ensemble.id,
.db() )
.get_mediums_for_ensemble(&this.ensemble.id) .unwrap();
.unwrap();
if !recordings.is_empty() { if !recordings.is_empty() {
let length = recordings.len(); let length = recordings.len();

View file

@ -9,7 +9,7 @@ use adw::prelude::*;
use gettextrs::gettext; use gettextrs::gettext;
use glib::clone; use glib::clone;
use gtk_macros::get_widget; use gtk_macros::get_widget;
use musicus_backend::db::PersonOrEnsemble; use musicus_backend::db::{self, PersonOrEnsemble};
use std::cell::RefCell; use std::cell::RefCell;
use std::rc::Rc; use std::rc::Rc;
@ -142,8 +142,9 @@ impl Screen<(), ()> for MainScreen {
); );
play_button.connect_clicked(clone!(@weak this => move |_| { play_button.connect_clicked(clone!(@weak this => move |_| {
if let Ok(recording) = this.handle.backend.db().random_recording() { let recording = db::random_recording(&mut this.handle.backend.db().lock().unwrap());
this.handle.backend.pl().add_items(this.handle.backend.db().get_tracks(&recording.id).unwrap()).unwrap(); if let Ok(recording) = recording {
this.handle.backend.pl().add_items(db::get_tracks(&mut this.handle.backend.db().lock().unwrap(), &recording.id).unwrap()).unwrap();
} }
})); }));
@ -164,8 +165,8 @@ impl Screen<(), ()> for MainScreen {
let mut poes = Vec::new(); let mut poes = Vec::new();
let persons = this.handle.backend.db().get_persons().unwrap(); let persons = db::get_persons(&mut this.handle.backend.db().lock().unwrap(), ).unwrap();
let ensembles = this.handle.backend.db().get_ensembles().unwrap(); let ensembles = db::get_ensembles(&mut this.handle.backend.db().lock().unwrap(), ).unwrap();
for person in persons { for person in persons {
poes.push(PersonOrEnsemble::Person(person)); poes.push(PersonOrEnsemble::Person(person));

View file

@ -7,7 +7,7 @@ use adw::builders::ActionRowBuilder;
use adw::prelude::*; use adw::prelude::*;
use gettextrs::gettext; use gettextrs::gettext;
use glib::clone; use glib::clone;
use musicus_backend::db::{Medium, Person, Recording, Work}; use musicus_backend::db::{self, Medium, Person, Recording, Work};
use std::cell::RefCell; use std::cell::RefCell;
use std::rc::Rc; use std::rc::Rc;
@ -65,7 +65,7 @@ impl Screen<Person, ()> for PersonScreen {
&gettext("Delete person"), &gettext("Delete person"),
clone!(@weak this => move || { clone!(@weak this => move || {
spawn!(@clone this, async move { spawn!(@clone this, async move {
this.handle.backend.db().delete_person(&this.person.id).unwrap(); db::delete_person(&mut this.handle.backend.db().lock().unwrap(), &this.person.id).unwrap();
this.handle.backend.library_changed(); this.handle.backend.library_changed();
}); });
}), }),
@ -165,21 +165,23 @@ impl Screen<Person, ()> for PersonScreen {
// Load the content. // Load the content.
let works = this.handle.backend.db().get_works(&this.person.id).unwrap(); let works = db::get_works(
&mut this.handle.backend.db().lock().unwrap(),
&this.person.id,
)
.unwrap();
let recordings = this let recordings = db::get_recordings_for_person(
.handle &mut this.handle.backend.db().lock().unwrap(),
.backend &this.person.id,
.db() )
.get_recordings_for_person(&this.person.id) .unwrap();
.unwrap();
let mediums = this let mediums = db::get_mediums_for_person(
.handle &mut this.handle.backend.db().lock().unwrap(),
.backend &this.person.id,
.db() )
.get_mediums_for_person(&this.person.id) .unwrap();
.unwrap();
if !works.is_empty() { if !works.is_empty() {
let length = works.len(); let length = works.len();

View file

@ -6,7 +6,7 @@ use adw::builders::ActionRowBuilder;
use adw::prelude::*; use adw::prelude::*;
use gettextrs::gettext; use gettextrs::gettext;
use glib::clone; use glib::clone;
use musicus_backend::db::{Recording, Track}; use musicus_backend::db::{self, Recording, Track};
use std::cell::RefCell; use std::cell::RefCell;
use std::rc::Rc; use std::rc::Rc;
@ -64,7 +64,7 @@ impl Screen<Recording, ()> for RecordingScreen {
&gettext("Delete recording"), &gettext("Delete recording"),
clone!(@weak this => move || { clone!(@weak this => move || {
spawn!(@clone this, async move { spawn!(@clone this, async move {
this.handle.backend.db().delete_recording(&this.recording.id).unwrap(); db::delete_recording(&mut this.handle.backend.db().lock().unwrap(), &this.recording.id).unwrap();
this.handle.backend.library_changed(); this.handle.backend.library_changed();
}); });
}), }),
@ -94,12 +94,11 @@ impl Screen<Recording, ()> for RecordingScreen {
// Load the content. // Load the content.
let tracks = this let tracks = db::get_tracks(
.handle &mut this.handle.backend.db().lock().unwrap(),
.backend &this.recording.id,
.db() )
.get_tracks(&this.recording.id) .unwrap();
.unwrap();
this.show_tracks(tracks); this.show_tracks(tracks);
this.widget.ready(); this.widget.ready();

View file

@ -7,7 +7,7 @@ use adw::builders::ActionRowBuilder;
use adw::prelude::*; use adw::prelude::*;
use gettextrs::gettext; use gettextrs::gettext;
use glib::clone; use glib::clone;
use musicus_backend::db::{Recording, Work}; use musicus_backend::db::{self, Recording, Work};
use std::cell::RefCell; use std::cell::RefCell;
use std::rc::Rc; use std::rc::Rc;
@ -56,7 +56,7 @@ impl Screen<Work, ()> for WorkScreen {
&gettext("Delete work"), &gettext("Delete work"),
clone!(@weak this => move || { clone!(@weak this => move || {
spawn!(@clone this, async move { spawn!(@clone this, async move {
this.handle.backend.db().delete_work(&this.work.id).unwrap(); db::delete_work(&mut this.handle.backend.db().lock().unwrap(), &this.work.id).unwrap();
this.handle.backend.library_changed(); this.handle.backend.library_changed();
}); });
}), }),
@ -98,12 +98,11 @@ impl Screen<Work, ()> for WorkScreen {
// Load the content. // Load the content.
let recordings = this let recordings = db::get_recordings_for_work(
.handle &mut this.handle.backend.db().lock().unwrap(),
.backend &this.work.id,
.db() )
.get_recordings_for_work(&this.work.id) .unwrap();
.unwrap();
if !recordings.is_empty() { if !recordings.is_empty() {
let length = recordings.len(); let length = recordings.len();

View file

@ -7,7 +7,7 @@ use adw::prelude::*;
use gettextrs::gettext; use gettextrs::gettext;
use glib::clone; use glib::clone;
use log::warn; use log::warn;
use musicus_backend::db::Ensemble; use musicus_backend::db::{Ensemble, self};
use std::rc::Rc; use std::rc::Rc;
/// A screen for selecting a ensemble. /// A screen for selecting a ensemble.
@ -50,7 +50,7 @@ impl Screen<(), Ensemble> for EnsembleSelector {
let ensemble = ensemble.to_owned(); let ensemble = ensemble.to_owned();
row.connect_activated(clone!(@weak this => move |_| { row.connect_activated(clone!(@weak this => move |_| {
if let Err(err) = this.handle.backend.db().update_ensemble(ensemble.clone()) { if let Err(err) = db::update_ensemble(&mut this.handle.backend.db().lock().unwrap(), ensemble.clone()) {
warn!("Failed to update access time. {err}"); warn!("Failed to update access time. {err}");
} }
@ -64,7 +64,7 @@ impl Screen<(), Ensemble> for EnsembleSelector {
.set_filter(|search, ensemble| ensemble.name.to_lowercase().contains(search)); .set_filter(|search, ensemble| ensemble.name.to_lowercase().contains(search));
this.selector this.selector
.set_items(this.handle.backend.db().get_recent_ensembles().unwrap()); .set_items(db::get_recent_ensembles(&mut this.handle.backend.db().lock().unwrap(), ).unwrap());
this this
} }

View file

@ -7,7 +7,7 @@ use adw::prelude::*;
use gettextrs::gettext; use gettextrs::gettext;
use glib::clone; use glib::clone;
use log::warn; use log::warn;
use musicus_backend::db::Instrument; use musicus_backend::db::{Instrument, self};
use std::rc::Rc; use std::rc::Rc;
/// A screen for selecting a instrument. /// A screen for selecting a instrument.
@ -50,7 +50,7 @@ impl Screen<(), Instrument> for InstrumentSelector {
let instrument = instrument.to_owned(); let instrument = instrument.to_owned();
row.connect_activated(clone!(@weak this => move |_| { row.connect_activated(clone!(@weak this => move |_| {
if let Err(err) = this.handle.backend.db().update_instrument(instrument.clone()) { if let Err(err) = db::update_instrument(&mut this.handle.backend.db().lock().unwrap(), instrument.clone()) {
warn!("Failed to update access time. {err}"); warn!("Failed to update access time. {err}");
} }
@ -64,7 +64,7 @@ impl Screen<(), Instrument> for InstrumentSelector {
.set_filter(|search, instrument| instrument.name.to_lowercase().contains(search)); .set_filter(|search, instrument| instrument.name.to_lowercase().contains(search));
this.selector this.selector
.set_items(this.handle.backend.db().get_recent_instruments().unwrap()); .set_items(db::get_recent_instruments(&mut this.handle.backend.db().lock().unwrap(), ).unwrap());
this this
} }

View file

@ -6,7 +6,7 @@ use adw::prelude::*;
use gettextrs::gettext; use gettextrs::gettext;
use glib::clone; use glib::clone;
use log::warn; use log::warn;
use musicus_backend::db::{Medium, PersonOrEnsemble}; use musicus_backend::db::{self, Medium, PersonOrEnsemble};
use std::rc::Rc; use std::rc::Rc;
/// A screen for selecting a medium. /// A screen for selecting a medium.
@ -56,8 +56,10 @@ impl Screen<(), Medium> for MediumSelector {
let mut poes = Vec::new(); let mut poes = Vec::new();
let persons = this.handle.backend.db().get_recent_persons().unwrap(); let persons =
let ensembles = this.handle.backend.db().get_recent_ensembles().unwrap(); db::get_recent_persons(&mut this.handle.backend.db().lock().unwrap()).unwrap();
let ensembles =
db::get_recent_ensembles(&mut this.handle.backend.db().lock().unwrap()).unwrap();
for person in persons { for person in persons {
poes.push(PersonOrEnsemble::Person(person)); poes.push(PersonOrEnsemble::Person(person));
@ -111,7 +113,7 @@ impl Screen<PersonOrEnsemble, Medium> for MediumSelectorMediumScreen {
let medium = medium.to_owned(); let medium = medium.to_owned();
row.connect_activated(clone!(@weak this => move |_| { row.connect_activated(clone!(@weak this => move |_| {
if let Err(err) = this.handle.backend.db().update_medium(medium.clone()) { if let Err(err) = db::update_medium(&mut this.handle.backend.db().lock().unwrap(), medium.clone()) {
warn!("Failed to update access time. {err}"); warn!("Failed to update access time. {err}");
} }
@ -128,20 +130,20 @@ impl Screen<PersonOrEnsemble, Medium> for MediumSelectorMediumScreen {
match this.poe.clone() { match this.poe.clone() {
PersonOrEnsemble::Person(person) => { PersonOrEnsemble::Person(person) => {
this.selector.set_items( this.selector.set_items(
this.handle db::get_mediums_for_person(
.backend &mut this.handle.backend.db().lock().unwrap(),
.db() &person.id,
.get_mediums_for_person(&person.id) )
.unwrap(), .unwrap(),
); );
} }
PersonOrEnsemble::Ensemble(ensemble) => { PersonOrEnsemble::Ensemble(ensemble) => {
this.selector.set_items( this.selector.set_items(
this.handle db::get_mediums_for_ensemble(
.backend &mut this.handle.backend.db().lock().unwrap(),
.db() &ensemble.id,
.get_mediums_for_ensemble(&ensemble.id) )
.unwrap(), .unwrap(),
); );
} }
} }

View file

@ -7,7 +7,7 @@ use adw::prelude::*;
use gettextrs::gettext; use gettextrs::gettext;
use glib::clone; use glib::clone;
use log::warn; use log::warn;
use musicus_backend::db::Person; use musicus_backend::db::{Person, self};
use std::rc::Rc; use std::rc::Rc;
/// A screen for selecting a person. /// A screen for selecting a person.
@ -50,7 +50,7 @@ impl Screen<(), Person> for PersonSelector {
let person = person.to_owned(); let person = person.to_owned();
row.connect_activated(clone!(@weak this => move |_| { row.connect_activated(clone!(@weak this => move |_| {
if let Err(err) = this.handle.backend.db().update_person(person.clone()) { if let Err(err) = db::update_person(&mut this.handle.backend.db().lock().unwrap(), person.clone()) {
warn!("Failed to update access time. {err}"); warn!("Failed to update access time. {err}");
} }
@ -64,7 +64,7 @@ impl Screen<(), Person> for PersonSelector {
.set_filter(|search, person| person.name_fl().to_lowercase().contains(search)); .set_filter(|search, person| person.name_fl().to_lowercase().contains(search));
this.selector this.selector
.set_items(this.handle.backend.db().get_recent_persons().unwrap()); .set_items(db::get_recent_persons(&mut this.handle.backend.db().lock().unwrap(), ).unwrap());
this this
} }

View file

@ -7,7 +7,7 @@ use adw::prelude::*;
use gettextrs::gettext; use gettextrs::gettext;
use glib::clone; use glib::clone;
use log::warn; use log::warn;
use musicus_backend::db::{Person, Recording, Work}; use musicus_backend::db::{self, Person, Recording, Work};
use std::rc::Rc; use std::rc::Rc;
/// A screen for selecting a recording. /// A screen for selecting a recording.
@ -81,8 +81,9 @@ impl Screen<(), Recording> for RecordingSelector {
this.selector this.selector
.set_filter(|search, person| person.name_fl().to_lowercase().contains(search)); .set_filter(|search, person| person.name_fl().to_lowercase().contains(search));
this.selector this.selector.set_items(
.set_items(this.handle.backend.db().get_recent_persons().unwrap()); db::get_recent_persons(&mut this.handle.backend.db().lock().unwrap()).unwrap(),
);
this this
} }
@ -144,8 +145,13 @@ impl Screen<Person, Work> for RecordingSelectorWorkScreen {
this.selector this.selector
.set_filter(|search, work| work.title.to_lowercase().contains(search)); .set_filter(|search, work| work.title.to_lowercase().contains(search));
this.selector this.selector.set_items(
.set_items(this.handle.backend.db().get_works(&this.person.id).unwrap()); db::get_works(
&mut this.handle.backend.db().lock().unwrap(),
&this.person.id,
)
.unwrap(),
);
this this
} }
@ -198,7 +204,7 @@ impl Screen<Work, Recording> for RecordingSelectorRecordingScreen {
let recording = recording.to_owned(); let recording = recording.to_owned();
row.connect_activated(clone!(@weak this => move |_| { row.connect_activated(clone!(@weak this => move |_| {
if let Err(err) = this.handle.backend.db().update_recording(recording.clone()) { if let Err(err) = db::update_recording(&mut this.handle.backend.db().lock().unwrap(), recording.clone()) {
warn!("Failed to update access time. {err}"); warn!("Failed to update access time. {err}");
} }
@ -213,11 +219,11 @@ impl Screen<Work, Recording> for RecordingSelectorRecordingScreen {
}); });
this.selector.set_items( this.selector.set_items(
this.handle db::get_recordings_for_work(
.backend &mut this.handle.backend.db().lock().unwrap(),
.db() &this.work.id,
.get_recordings_for_work(&this.work.id) )
.unwrap(), .unwrap(),
); );
this this

View file

@ -7,7 +7,7 @@ use adw::prelude::*;
use gettextrs::gettext; use gettextrs::gettext;
use glib::clone; use glib::clone;
use log::warn; use log::warn;
use musicus_backend::db::{Person, Work}; use musicus_backend::db::{Person, Work, self};
use std::rc::Rc; use std::rc::Rc;
/// A screen for selecting a work. /// A screen for selecting a work.
@ -72,7 +72,7 @@ impl Screen<(), Work> for WorkSelector {
.set_filter(|search, person| person.name_fl().to_lowercase().contains(search)); .set_filter(|search, person| person.name_fl().to_lowercase().contains(search));
this.selector this.selector
.set_items(this.handle.backend.db().get_recent_persons().unwrap()); .set_items(db::get_recent_persons(&mut this.handle.backend.db().lock().unwrap()).unwrap());
this this
} }
@ -125,7 +125,7 @@ impl Screen<Person, Work> for WorkSelectorWorkScreen {
let work = work.to_owned(); let work = work.to_owned();
row.connect_activated(clone!(@weak this => move |_| { row.connect_activated(clone!(@weak this => move |_| {
if let Err(err) = this.handle.backend.db().update_work(work.clone()) { if let Err(err) = db::update_work(&mut this.handle.backend.db().lock().unwrap(), work.clone()) {
warn!("Failed to update access time. {err}"); warn!("Failed to update access time. {err}");
} }
@ -139,7 +139,7 @@ impl Screen<Person, Work> for WorkSelectorWorkScreen {
.set_filter(|search, work| work.title.to_lowercase().contains(search)); .set_filter(|search, work| work.title.to_lowercase().contains(search));
this.selector this.selector
.set_items(this.handle.backend.db().get_works(&this.person.id).unwrap()); .set_items(db::get_works(&mut this.handle.backend.db().lock().unwrap(), &this.person.id).unwrap());
this this
} }