mirror of
https://github.com/johrpan/musicus.git
synced 2025-10-26 19:57:25 +01:00
Move crates to toplevel directory
This commit is contained in:
parent
d16961efa8
commit
0ffe68e04f
127 changed files with 15 additions and 13 deletions
1
database/.gitignore
vendored
Normal file
1
database/.gitignore
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
test.sqlite
|
||||
14
database/Cargo.toml
Normal file
14
database/Cargo.toml
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
[package]
|
||||
name = "musicus_database"
|
||||
version = "0.1.0"
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
diesel = { version = "1.4.5", features = ["sqlite"] }
|
||||
diesel_migrations = "1.4.0"
|
||||
futures-channel = "0.3.5"
|
||||
rand = "0.7.3"
|
||||
serde = { version = "1.0.117", features = ["derive"] }
|
||||
serde_json = "1.0.59"
|
||||
thiserror = "1.0.23"
|
||||
uuid = { version = "0.8", features = ["v4"] }
|
||||
2
database/diesel.toml
Normal file
2
database/diesel.toml
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
[print_schema]
|
||||
file = "src/schema.rs"
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
PRAGMA defer_foreign_keys;
|
||||
|
||||
DROP TABLE "persons";
|
||||
DROP TABLE "instruments";
|
||||
DROP TABLE "works";
|
||||
DROP TABLE "instrumentations";
|
||||
DROP TABLE "work_parts";
|
||||
DROP TABLE "work_sections";
|
||||
DROP TABLE "ensembles";
|
||||
DROP TABLE "recordings";
|
||||
DROP TABLE "performances";
|
||||
DROP TABLE "mediums";
|
||||
DROP TABLE "track_sets";
|
||||
DROP TABLE "tracks";
|
||||
|
||||
77
database/migrations/2020-09-27-201047_initial_schema/up.sql
Normal file
77
database/migrations/2020-09-27-201047_initial_schema/up.sql
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
CREATE TABLE "persons" (
|
||||
"id" TEXT NOT NULL PRIMARY KEY,
|
||||
"first_name" TEXT NOT NULL,
|
||||
"last_name" TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE "instruments" (
|
||||
"id" TEXT NOT NULL PRIMARY KEY,
|
||||
"name" TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE "works" (
|
||||
"id" TEXT NOT NULL PRIMARY KEY,
|
||||
"composer" TEXT NOT NULL REFERENCES "persons"("id"),
|
||||
"title" TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE "instrumentations" (
|
||||
"id" BIGINT NOT NULL PRIMARY KEY,
|
||||
"work" TEXT NOT NULL REFERENCES "works"("id") ON DELETE CASCADE,
|
||||
"instrument" TEXT NOT NULL REFERENCES "instruments"("id") ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE "work_parts" (
|
||||
"id" BIGINT NOT NULL PRIMARY KEY,
|
||||
"work" TEXT NOT NULL REFERENCES "works"("id") ON DELETE CASCADE,
|
||||
"part_index" BIGINT NOT NULL,
|
||||
"title" TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE "work_sections" (
|
||||
"id" BIGINT NOT NULL PRIMARY KEY,
|
||||
"work" TEXT NOT NULL REFERENCES "works"("id") ON DELETE CASCADE,
|
||||
"title" TEXT NOT NULL,
|
||||
"before_index" BIGINT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE "ensembles" (
|
||||
"id" TEXT NOT NULL PRIMARY KEY,
|
||||
"name" TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE "recordings" (
|
||||
"id" TEXT NOT NULL PRIMARY KEY,
|
||||
"work" TEXT NOT NULL REFERENCES "works"("id"),
|
||||
"comment" TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE "performances" (
|
||||
"id" BIGINT NOT NULL PRIMARY KEY,
|
||||
"recording" TEXT NOT NULL REFERENCES "recordings"("id") ON DELETE CASCADE,
|
||||
"person" TEXT REFERENCES "persons"("id"),
|
||||
"ensemble" TEXT REFERENCES "ensembles"("id"),
|
||||
"role" TEXT REFERENCES "instruments"("id")
|
||||
);
|
||||
|
||||
CREATE TABLE "mediums" (
|
||||
"id" TEXT NOT NULL PRIMARY KEY,
|
||||
"name" TEXT NOT NULL,
|
||||
"discid" TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE "track_sets" (
|
||||
"id" TEXT NOT NULL PRIMARY KEY,
|
||||
"medium" TEXT NOT NULL REFERENCES "mediums"("id") ON DELETE CASCADE,
|
||||
"index" INTEGER NOT NULL,
|
||||
"recording" TEXT NOT NULL REFERENCES "recordings"("id")
|
||||
);
|
||||
|
||||
CREATE TABLE "tracks" (
|
||||
"id" TEXT NOT NULL PRIMARY KEY,
|
||||
"track_set" TEXT NOT NULL REFERENCES "track_sets"("id") ON DELETE CASCADE,
|
||||
"index" INTEGER NOT NULL,
|
||||
"work_parts" TEXT NOT NULL,
|
||||
"path" TEXT NOT NULL
|
||||
);
|
||||
|
||||
52
database/src/ensembles.rs
Normal file
52
database/src/ensembles.rs
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
use super::schema::ensembles;
|
||||
use super::{Database, Result};
|
||||
use diesel::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// An ensemble that takes part in recordings.
|
||||
#[derive(Serialize, Deserialize, Insertable, Queryable, Debug, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Ensemble {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
impl Database {
|
||||
/// Update an existing ensemble or insert a new one.
|
||||
pub fn update_ensemble(&self, ensemble: Ensemble) -> Result<()> {
|
||||
self.defer_foreign_keys()?;
|
||||
|
||||
self.connection.transaction(|| {
|
||||
diesel::replace_into(ensembles::table)
|
||||
.values(ensemble)
|
||||
.execute(&self.connection)
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get an existing ensemble.
|
||||
pub fn get_ensemble(&self, id: &str) -> Result<Option<Ensemble>> {
|
||||
let ensemble = ensembles::table
|
||||
.filter(ensembles::id.eq(id))
|
||||
.load::<Ensemble>(&self.connection)?
|
||||
.into_iter()
|
||||
.next();
|
||||
|
||||
Ok(ensemble)
|
||||
}
|
||||
|
||||
/// Delete an existing ensemble.
|
||||
pub fn delete_ensemble(&self, id: &str) -> Result<()> {
|
||||
diesel::delete(ensembles::table.filter(ensembles::id.eq(id))).execute(&self.connection)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get all existing ensembles.
|
||||
pub fn get_ensembles(&self) -> Result<Vec<Ensemble>> {
|
||||
let ensembles = ensembles::table.load::<Ensemble>(&self.connection)?;
|
||||
|
||||
Ok(ensembles)
|
||||
}
|
||||
}
|
||||
24
database/src/error.rs
Normal file
24
database/src/error.rs
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
/// Error that happens within the database module.
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
pub enum Error {
|
||||
#[error(transparent)]
|
||||
ConnectionError(#[from] diesel::result::ConnectionError),
|
||||
|
||||
#[error(transparent)]
|
||||
MigrationsError(#[from] diesel_migrations::RunMigrationsError),
|
||||
|
||||
#[error(transparent)]
|
||||
QueryError(#[from] diesel::result::Error),
|
||||
|
||||
#[error(transparent)]
|
||||
SendError(#[from] std::sync::mpsc::SendError<super::thread::Action>),
|
||||
|
||||
#[error(transparent)]
|
||||
ReceiveError(#[from] futures_channel::oneshot::Canceled),
|
||||
|
||||
#[error("Database error: {0}")]
|
||||
Other(String),
|
||||
}
|
||||
|
||||
/// Return type for database methods.
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
53
database/src/instruments.rs
Normal file
53
database/src/instruments.rs
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
use super::schema::instruments;
|
||||
use super::{Database, Result};
|
||||
use diesel::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// An instrument or any other possible role within a recording.
|
||||
#[derive(Serialize, Deserialize, Insertable, Queryable, Debug, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Instrument {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
impl Database {
|
||||
/// Update an existing instrument or insert a new one.
|
||||
pub fn update_instrument(&self, instrument: Instrument) -> Result<()> {
|
||||
self.defer_foreign_keys()?;
|
||||
|
||||
self.connection.transaction(|| {
|
||||
diesel::replace_into(instruments::table)
|
||||
.values(instrument)
|
||||
.execute(&self.connection)
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get an existing instrument.
|
||||
pub fn get_instrument(&self, id: &str) -> Result<Option<Instrument>> {
|
||||
let instrument = instruments::table
|
||||
.filter(instruments::id.eq(id))
|
||||
.load::<Instrument>(&self.connection)?
|
||||
.into_iter()
|
||||
.next();
|
||||
|
||||
Ok(instrument)
|
||||
}
|
||||
|
||||
/// Delete an existing instrument.
|
||||
pub fn delete_instrument(&self, id: &str) -> Result<()> {
|
||||
diesel::delete(instruments::table.filter(instruments::id.eq(id)))
|
||||
.execute(&self.connection)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get all existing instruments.
|
||||
pub fn get_instruments(&self) -> Result<Vec<Instrument>> {
|
||||
let instruments = instruments::table.load::<Instrument>(&self.connection)?;
|
||||
|
||||
Ok(instruments)
|
||||
}
|
||||
}
|
||||
69
database/src/lib.rs
Normal file
69
database/src/lib.rs
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
// Required for schema.rs
|
||||
#[macro_use]
|
||||
extern crate diesel;
|
||||
|
||||
// Required for embed_migrations macro in database.rs
|
||||
#[macro_use]
|
||||
extern crate diesel_migrations;
|
||||
|
||||
use diesel::prelude::*;
|
||||
|
||||
pub mod ensembles;
|
||||
pub use ensembles::*;
|
||||
|
||||
pub mod error;
|
||||
pub use error::*;
|
||||
|
||||
pub mod instruments;
|
||||
pub use instruments::*;
|
||||
|
||||
pub mod medium;
|
||||
pub use medium::*;
|
||||
|
||||
pub mod persons;
|
||||
pub use persons::*;
|
||||
|
||||
pub mod recordings;
|
||||
pub use recordings::*;
|
||||
|
||||
pub mod thread;
|
||||
pub use thread::*;
|
||||
|
||||
pub mod works;
|
||||
pub use works::*;
|
||||
|
||||
mod schema;
|
||||
|
||||
// This makes the SQL migration scripts accessible from the code.
|
||||
embed_migrations!();
|
||||
|
||||
/// Generate a random string suitable as an item ID.
|
||||
pub fn generate_id() -> String {
|
||||
let mut buffer = uuid::Uuid::encode_buffer();
|
||||
let id = uuid::Uuid::new_v4().to_simple().encode_lower(&mut buffer);
|
||||
|
||||
id.to_string()
|
||||
}
|
||||
|
||||
/// Interface to a Musicus database.
|
||||
pub struct Database {
|
||||
connection: SqliteConnection,
|
||||
}
|
||||
|
||||
impl Database {
|
||||
/// Create a new database interface and run migrations if necessary.
|
||||
pub fn new(file_name: &str) -> Result<Database> {
|
||||
let connection = SqliteConnection::establish(file_name)?;
|
||||
|
||||
diesel::sql_query("PRAGMA foreign_keys = ON").execute(&connection)?;
|
||||
embedded_migrations::run(&connection)?;
|
||||
|
||||
Ok(Database { connection })
|
||||
}
|
||||
|
||||
/// Defer all foreign keys for the next transaction.
|
||||
fn defer_foreign_keys(&self) -> Result<()> {
|
||||
diesel::sql_query("PRAGMA defer_foreign_keys = ON").execute(&self.connection)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
306
database/src/medium.rs
Normal file
306
database/src/medium.rs
Normal file
|
|
@ -0,0 +1,306 @@
|
|||
use super::generate_id;
|
||||
use super::schema::{ensembles, mediums, performances, persons, recordings, track_sets, tracks};
|
||||
use super::{Database, Error, Recording, Result};
|
||||
use diesel::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// 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).
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Medium {
|
||||
/// An unique ID for the medium.
|
||||
pub id: String,
|
||||
|
||||
/// The human identifier for the medium.
|
||||
pub name: String,
|
||||
|
||||
/// If applicable, the MusicBrainz DiscID.
|
||||
pub discid: Option<String>,
|
||||
|
||||
/// The tracks of the medium, grouped by recording.
|
||||
pub tracks: Vec<TrackSet>,
|
||||
}
|
||||
|
||||
/// A set of tracks of one recording within a medium.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TrackSet {
|
||||
/// The recording to which the tracks belong.
|
||||
pub recording: Recording,
|
||||
|
||||
/// The actual tracks.
|
||||
pub tracks: Vec<Track>,
|
||||
}
|
||||
|
||||
/// A track within a recording on a medium.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Track {
|
||||
/// The work parts that are played on this track. They are indices to the
|
||||
/// work parts of the work that is associated with the recording.
|
||||
pub work_parts: Vec<usize>,
|
||||
|
||||
/// The path to the audio file containing this track. This will not be
|
||||
/// included when communicating with the server.
|
||||
#[serde(skip)]
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
/// Table data for a [`Medium`].
|
||||
#[derive(Insertable, Queryable, Debug, Clone)]
|
||||
#[table_name = "mediums"]
|
||||
struct MediumRow {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub discid: Option<String>,
|
||||
}
|
||||
|
||||
/// Table data for a [`TrackSet`].
|
||||
#[derive(Insertable, Queryable, Debug, Clone)]
|
||||
#[table_name = "track_sets"]
|
||||
struct TrackSetRow {
|
||||
pub id: String,
|
||||
pub medium: String,
|
||||
pub index: i32,
|
||||
pub recording: String,
|
||||
}
|
||||
|
||||
/// Table data for a [`Track`].
|
||||
#[derive(Insertable, Queryable, Debug, Clone)]
|
||||
#[table_name = "tracks"]
|
||||
struct TrackRow {
|
||||
pub id: String,
|
||||
pub track_set: String,
|
||||
pub index: i32,
|
||||
pub work_parts: String,
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
impl Database {
|
||||
/// Update an existing medium or insert a new one.
|
||||
pub fn update_medium(&self, medium: Medium) -> Result<()> {
|
||||
self.defer_foreign_keys()?;
|
||||
|
||||
self.connection.transaction::<(), Error, _>(|| {
|
||||
let medium_id = &medium.id;
|
||||
|
||||
// This will also delete the track sets and tracks.
|
||||
self.delete_medium(medium_id)?;
|
||||
|
||||
// Add the new medium.
|
||||
|
||||
let medium_row = MediumRow {
|
||||
id: medium_id.to_owned(),
|
||||
name: medium.name.clone(),
|
||||
discid: medium.discid.clone(),
|
||||
};
|
||||
|
||||
diesel::insert_into(mediums::table)
|
||||
.values(medium_row)
|
||||
.execute(&self.connection)?;
|
||||
|
||||
for (index, track_set) in medium.tracks.iter().enumerate() {
|
||||
// Add associated items from the server, if they don't already
|
||||
// exist.
|
||||
|
||||
if self.get_recording(&track_set.recording.id)?.is_none() {
|
||||
self.update_recording(track_set.recording.clone())?;
|
||||
}
|
||||
|
||||
// Add the actual track set data.
|
||||
|
||||
let track_set_id = generate_id();
|
||||
|
||||
let track_set_row = TrackSetRow {
|
||||
id: track_set_id.clone(),
|
||||
medium: medium_id.to_owned(),
|
||||
index: index as i32,
|
||||
recording: track_set.recording.id.clone(),
|
||||
};
|
||||
|
||||
diesel::insert_into(track_sets::table)
|
||||
.values(track_set_row)
|
||||
.execute(&self.connection)?;
|
||||
|
||||
for (index, track) in track_set.tracks.iter().enumerate() {
|
||||
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(),
|
||||
track_set: track_set_id.clone(),
|
||||
index: index as i32,
|
||||
work_parts,
|
||||
path: track.path.clone(),
|
||||
};
|
||||
|
||||
diesel::insert_into(tracks::table)
|
||||
.values(track_row)
|
||||
.execute(&self.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>(&self.connection)?
|
||||
.into_iter()
|
||||
.next();
|
||||
|
||||
let medium = match row {
|
||||
Some(row) => Some(self.get_medium_data(row)?),
|
||||
None => None,
|
||||
};
|
||||
|
||||
Ok(medium)
|
||||
}
|
||||
|
||||
/// 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(track_sets::table.on(track_sets::medium.eq(mediums::id)))
|
||||
.inner_join(recordings::table.on(recordings::id.eq(track_sets::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>(&self.connection)?;
|
||||
|
||||
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(track_sets::table.on(track_sets::medium.eq(mediums::id)))
|
||||
.inner_join(recordings::table.on(recordings::id.eq(track_sets::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>(&self.connection)?;
|
||||
|
||||
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<()> {
|
||||
diesel::delete(mediums::table.filter(mediums::id.eq(id))).execute(&self.connection)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get all available track sets for a recording.
|
||||
pub fn get_track_sets(&self, recording_id: &str) -> Result<Vec<TrackSet>> {
|
||||
let mut track_sets: Vec<TrackSet> = Vec::new();
|
||||
|
||||
let rows = track_sets::table
|
||||
.inner_join(recordings::table.on(recordings::id.eq(track_sets::recording)))
|
||||
.filter(recordings::id.eq(recording_id))
|
||||
.select(track_sets::table::all_columns())
|
||||
.load::<TrackSetRow>(&self.connection)?;
|
||||
|
||||
for row in rows {
|
||||
let track_set = self.get_track_set_from_row(row)?;
|
||||
track_sets.push(track_set);
|
||||
}
|
||||
|
||||
Ok(track_sets)
|
||||
}
|
||||
|
||||
/// Retrieve all available information on a medium from related tables.
|
||||
fn get_medium_data(&self, row: MediumRow) -> Result<Medium> {
|
||||
let track_set_rows = track_sets::table
|
||||
.filter(track_sets::medium.eq(&row.id))
|
||||
.order_by(track_sets::index)
|
||||
.load::<TrackSetRow>(&self.connection)?;
|
||||
|
||||
let mut track_sets = Vec::new();
|
||||
|
||||
for track_set_row in track_set_rows {
|
||||
let track_set = self.get_track_set_from_row(track_set_row)?;
|
||||
track_sets.push(track_set);
|
||||
}
|
||||
|
||||
let medium = Medium {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
discid: row.discid,
|
||||
tracks: track_sets,
|
||||
};
|
||||
|
||||
Ok(medium)
|
||||
}
|
||||
|
||||
/// Convert a track set row from the database to an actual track set.
|
||||
fn get_track_set_from_row(&self, row: TrackSetRow) -> Result<TrackSet> {
|
||||
let recording_id = row.recording;
|
||||
|
||||
let recording = self
|
||||
.get_recording(&recording_id)?
|
||||
.ok_or(Error::Other(format!(
|
||||
"Failed to get recording ({}) for track set ({}).",
|
||||
recording_id,
|
||||
row.id,
|
||||
)))?;
|
||||
|
||||
let track_rows = tracks::table
|
||||
.filter(tracks::track_set.eq(row.id))
|
||||
.order_by(tracks::index)
|
||||
.load::<TrackRow>(&self.connection)?;
|
||||
|
||||
let mut tracks = Vec::new();
|
||||
|
||||
for track_row in track_rows {
|
||||
let work_parts = track_row
|
||||
.work_parts
|
||||
.split(',')
|
||||
.map(|part_index| {
|
||||
str::parse(part_index)
|
||||
.or(Err(Error::Other(
|
||||
format!("Failed to parse part index from '{}'.", track_row.work_parts,
|
||||
))))
|
||||
})
|
||||
.collect::<Result<Vec<usize>>>()?;
|
||||
|
||||
let track = Track {
|
||||
work_parts,
|
||||
path: track_row.path,
|
||||
};
|
||||
|
||||
tracks.push(track);
|
||||
}
|
||||
|
||||
let track_set = TrackSet { recording, tracks };
|
||||
|
||||
Ok(track_set)
|
||||
}
|
||||
}
|
||||
65
database/src/persons.rs
Normal file
65
database/src/persons.rs
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
use super::schema::persons;
|
||||
use super::{Database, Result};
|
||||
use diesel::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// A person that is a composer, an interpret or both.
|
||||
#[derive(Serialize, Deserialize, Insertable, Queryable, Debug, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Person {
|
||||
pub id: String,
|
||||
pub first_name: String,
|
||||
pub last_name: String,
|
||||
}
|
||||
|
||||
impl Person {
|
||||
/// Get the full name in the form "First Last".
|
||||
pub fn name_fl(&self) -> String {
|
||||
format!("{} {}", self.first_name, self.last_name)
|
||||
}
|
||||
|
||||
/// Get the full name in the form "Last, First".
|
||||
pub fn name_lf(&self) -> String {
|
||||
format!("{}, {}", self.last_name, self.first_name)
|
||||
}
|
||||
}
|
||||
|
||||
impl Database {
|
||||
/// Update an existing person or insert a new one.
|
||||
pub fn update_person(&self, person: Person) -> Result<()> {
|
||||
self.defer_foreign_keys()?;
|
||||
|
||||
self.connection.transaction(|| {
|
||||
diesel::replace_into(persons::table)
|
||||
.values(person)
|
||||
.execute(&self.connection)
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get an existing person.
|
||||
pub fn get_person(&self, id: &str) -> Result<Option<Person>> {
|
||||
let person = persons::table
|
||||
.filter(persons::id.eq(id))
|
||||
.load::<Person>(&self.connection)?
|
||||
.into_iter()
|
||||
.next();
|
||||
|
||||
Ok(person)
|
||||
}
|
||||
|
||||
/// Delete an existing person.
|
||||
pub fn delete_person(&self, id: &str) -> Result<()> {
|
||||
diesel::delete(persons::table.filter(persons::id.eq(id))).execute(&self.connection)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get all existing persons.
|
||||
pub fn get_persons(&self) -> Result<Vec<Person>> {
|
||||
let persons = persons::table.load::<Person>(&self.connection)?;
|
||||
|
||||
Ok(persons)
|
||||
}
|
||||
}
|
||||
331
database/src/recordings.rs
Normal file
331
database/src/recordings.rs
Normal file
|
|
@ -0,0 +1,331 @@
|
|||
use super::generate_id;
|
||||
use super::schema::{ensembles, performances, persons, recordings};
|
||||
use super::{Database, Ensemble, Error, Instrument, Person, Result, Work};
|
||||
use diesel::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Database table data for a recording.
|
||||
#[derive(Insertable, Queryable, Debug, Clone)]
|
||||
#[table_name = "recordings"]
|
||||
struct RecordingRow {
|
||||
pub id: String,
|
||||
pub work: String,
|
||||
pub comment: String,
|
||||
}
|
||||
|
||||
impl From<Recording> for RecordingRow {
|
||||
fn from(recording: Recording) -> Self {
|
||||
RecordingRow {
|
||||
id: recording.id,
|
||||
work: recording.work.id,
|
||||
comment: recording.comment,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Database table data for a performance.
|
||||
#[derive(Insertable, Queryable, Debug, Clone)]
|
||||
#[table_name = "performances"]
|
||||
struct PerformanceRow {
|
||||
pub id: i64,
|
||||
pub recording: String,
|
||||
pub person: Option<String>,
|
||||
pub ensemble: Option<String>,
|
||||
pub role: Option<String>,
|
||||
}
|
||||
|
||||
/// How a person or ensemble was involved in a recording.
|
||||
// TODO: Replace person/ensemble with an enum.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Performance {
|
||||
pub person: Option<Person>,
|
||||
pub ensemble: Option<Ensemble>,
|
||||
pub role: Option<Instrument>,
|
||||
}
|
||||
|
||||
impl Performance {
|
||||
/// Get a string representation of the performance.
|
||||
// TODO: Replace with impl Display.
|
||||
pub fn get_title(&self) -> String {
|
||||
let mut text = String::from(if self.is_person() {
|
||||
self.unwrap_person().name_fl()
|
||||
} else {
|
||||
self.unwrap_ensemble().name
|
||||
});
|
||||
|
||||
if self.has_role() {
|
||||
text = text + " (" + &self.unwrap_role().name + ")";
|
||||
}
|
||||
|
||||
text
|
||||
}
|
||||
|
||||
pub fn is_person(&self) -> bool {
|
||||
self.person.is_some()
|
||||
}
|
||||
|
||||
pub fn unwrap_person(&self) -> Person {
|
||||
self.person.clone().unwrap()
|
||||
}
|
||||
|
||||
pub fn unwrap_ensemble(&self) -> Ensemble {
|
||||
self.ensemble.clone().unwrap()
|
||||
}
|
||||
|
||||
pub fn has_role(&self) -> bool {
|
||||
self.role.clone().is_some()
|
||||
}
|
||||
|
||||
pub fn unwrap_role(&self) -> Instrument {
|
||||
self.role.clone().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
/// A specific recording of a work.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Recording {
|
||||
pub id: String,
|
||||
pub work: Work,
|
||||
pub comment: String,
|
||||
pub performances: Vec<Performance>,
|
||||
}
|
||||
|
||||
impl Recording {
|
||||
/// Initialize a new recording with a work.
|
||||
pub fn new(work: Work) -> Self {
|
||||
Self {
|
||||
id: generate_id(),
|
||||
work,
|
||||
comment: String::new(),
|
||||
performances: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a string representation of the performances in this recording.
|
||||
// TODO: Maybe replace with impl Display?
|
||||
pub fn get_performers(&self) -> String {
|
||||
let texts: Vec<String> = self
|
||||
.performances
|
||||
.iter()
|
||||
.map(|performance| performance.get_title())
|
||||
.collect();
|
||||
|
||||
texts.join(", ")
|
||||
}
|
||||
}
|
||||
|
||||
impl Database {
|
||||
/// Update an existing recording or insert a new one.
|
||||
// TODO: Think about whether to also insert the other items.
|
||||
pub fn update_recording(&self, recording: Recording) -> Result<()> {
|
||||
self.defer_foreign_keys()?;
|
||||
self.connection.transaction::<(), Error, _>(|| {
|
||||
let recording_id = &recording.id;
|
||||
self.delete_recording(recording_id)?;
|
||||
|
||||
// Add associated items from the server, if they don't already exist.
|
||||
|
||||
if self.get_work(&recording.work.id)?.is_none() {
|
||||
self.update_work(recording.work.clone())?;
|
||||
}
|
||||
|
||||
for performance in &recording.performances {
|
||||
if let Some(person) = &performance.person {
|
||||
if self.get_person(&person.id)?.is_none() {
|
||||
self.update_person(person.clone())?;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ensemble) = &performance.ensemble {
|
||||
if self.get_ensemble(&ensemble.id)?.is_none() {
|
||||
self.update_ensemble(ensemble.clone())?;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(role) = &performance.role {
|
||||
if self.get_instrument(&role.id)?.is_none() {
|
||||
self.update_instrument(role.clone())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add the actual recording.
|
||||
|
||||
let row: RecordingRow = recording.clone().into();
|
||||
diesel::insert_into(recordings::table)
|
||||
.values(row)
|
||||
.execute(&self.connection)?;
|
||||
|
||||
for performance in recording.performances {
|
||||
let row = PerformanceRow {
|
||||
id: rand::random(),
|
||||
recording: recording_id.to_string(),
|
||||
person: performance.person.map(|person| person.id),
|
||||
ensemble: performance.ensemble.map(|ensemble| ensemble.id),
|
||||
role: performance.role.map(|role| role.id),
|
||||
};
|
||||
|
||||
diesel::insert_into(performances::table)
|
||||
.values(row)
|
||||
.execute(&self.connection)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check whether the database contains a recording.
|
||||
pub fn recording_exists(&self, id: &str) -> Result<bool> {
|
||||
let exists = recordings::table
|
||||
.filter(recordings::id.eq(id))
|
||||
.load::<RecordingRow>(&self.connection)?
|
||||
.first()
|
||||
.is_some();
|
||||
|
||||
Ok(exists)
|
||||
}
|
||||
|
||||
/// Get an existing recording.
|
||||
pub fn get_recording(&self, id: &str) -> Result<Option<Recording>> {
|
||||
let row = recordings::table
|
||||
.filter(recordings::id.eq(id))
|
||||
.load::<RecordingRow>(&self.connection)?
|
||||
.into_iter()
|
||||
.next();
|
||||
|
||||
let recording = match row {
|
||||
Some(row) => Some(self.get_recording_data(row)?),
|
||||
None => None,
|
||||
};
|
||||
|
||||
Ok(recording)
|
||||
}
|
||||
|
||||
/// Retrieve all available information on a recording from related tables.
|
||||
fn get_recording_data(&self, row: RecordingRow) -> Result<Recording> {
|
||||
let mut performance_descriptions: Vec<Performance> = Vec::new();
|
||||
|
||||
let performance_rows = performances::table
|
||||
.filter(performances::recording.eq(&row.id))
|
||||
.load::<PerformanceRow>(&self.connection)?;
|
||||
|
||||
for row in performance_rows {
|
||||
performance_descriptions.push(Performance {
|
||||
person: match row.person {
|
||||
Some(id) => Some(
|
||||
self.get_person(&id)?
|
||||
.ok_or(Error::Other(format!(
|
||||
"Failed to get person ({}) for recording ({}).",
|
||||
id,
|
||||
row.id,
|
||||
)))?
|
||||
),
|
||||
None => None,
|
||||
},
|
||||
ensemble: match row.ensemble {
|
||||
Some(id) => Some(
|
||||
self.get_ensemble(&id)?
|
||||
.ok_or(Error::Other(format!(
|
||||
"Failed to get ensemble ({}) for recording ({}).",
|
||||
id,
|
||||
row.id,
|
||||
)))?
|
||||
),
|
||||
None => None,
|
||||
},
|
||||
role: match row.role {
|
||||
Some(id) => Some(
|
||||
self.get_instrument(&id)?
|
||||
.ok_or(Error::Other(format!(
|
||||
"Failed to get instrument ({}) for recording ({}).",
|
||||
id,
|
||||
row.id,
|
||||
)))?
|
||||
),
|
||||
None => None,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
let work_id = &row.work;
|
||||
let work = self
|
||||
.get_work(work_id)?
|
||||
.ok_or(Error::Other(format!(
|
||||
"Failed to get work ({}) for recording ({}).",
|
||||
work_id,
|
||||
row.id,
|
||||
)))?;
|
||||
|
||||
let recording_description = Recording {
|
||||
id: row.id,
|
||||
work,
|
||||
comment: row.comment.clone(),
|
||||
performances: performance_descriptions,
|
||||
};
|
||||
|
||||
Ok(recording_description)
|
||||
}
|
||||
|
||||
/// Get all available information on all recordings where a person is performing.
|
||||
pub fn get_recordings_for_person(&self, person_id: &str) -> Result<Vec<Recording>> {
|
||||
let mut recordings: Vec<Recording> = Vec::new();
|
||||
|
||||
let rows = recordings::table
|
||||
.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(recordings::table::all_columns())
|
||||
.load::<RecordingRow>(&self.connection)?;
|
||||
|
||||
for row in rows {
|
||||
recordings.push(self.get_recording_data(row)?);
|
||||
}
|
||||
|
||||
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>> {
|
||||
let mut recordings: Vec<Recording> = Vec::new();
|
||||
|
||||
let rows = recordings::table
|
||||
.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(recordings::table::all_columns())
|
||||
.load::<RecordingRow>(&self.connection)?;
|
||||
|
||||
for row in rows {
|
||||
recordings.push(self.get_recording_data(row)?);
|
||||
}
|
||||
|
||||
Ok(recordings)
|
||||
}
|
||||
|
||||
/// Get allavailable information on all recordings of a work.
|
||||
pub fn get_recordings_for_work(&self, work_id: &str) -> Result<Vec<Recording>> {
|
||||
let mut recordings: Vec<Recording> = Vec::new();
|
||||
|
||||
let rows = recordings::table
|
||||
.filter(recordings::work.eq(work_id))
|
||||
.load::<RecordingRow>(&self.connection)?;
|
||||
|
||||
for row in rows {
|
||||
recordings.push(self.get_recording_data(row)?);
|
||||
}
|
||||
|
||||
Ok(recordings)
|
||||
}
|
||||
|
||||
/// 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(&self, id: &str) -> Result<()> {
|
||||
diesel::delete(recordings::table.filter(recordings::id.eq(id)))
|
||||
.execute(&self.connection)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
129
database/src/schema.rs
Normal file
129
database/src/schema.rs
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
table! {
|
||||
ensembles (id) {
|
||||
id -> Text,
|
||||
name -> Text,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
instrumentations (id) {
|
||||
id -> BigInt,
|
||||
work -> Text,
|
||||
instrument -> Text,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
instruments (id) {
|
||||
id -> Text,
|
||||
name -> Text,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
mediums (id) {
|
||||
id -> Text,
|
||||
name -> Text,
|
||||
discid -> Nullable<Text>,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
performances (id) {
|
||||
id -> BigInt,
|
||||
recording -> Text,
|
||||
person -> Nullable<Text>,
|
||||
ensemble -> Nullable<Text>,
|
||||
role -> Nullable<Text>,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
persons (id) {
|
||||
id -> Text,
|
||||
first_name -> Text,
|
||||
last_name -> Text,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
recordings (id) {
|
||||
id -> Text,
|
||||
work -> Text,
|
||||
comment -> Text,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
track_sets (id) {
|
||||
id -> Text,
|
||||
medium -> Text,
|
||||
index -> Integer,
|
||||
recording -> Text,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
tracks (id) {
|
||||
id -> Text,
|
||||
track_set -> Text,
|
||||
index -> Integer,
|
||||
work_parts -> Text,
|
||||
path -> Text,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
work_parts (id) {
|
||||
id -> BigInt,
|
||||
work -> Text,
|
||||
part_index -> BigInt,
|
||||
title -> Text,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
work_sections (id) {
|
||||
id -> BigInt,
|
||||
work -> Text,
|
||||
title -> Text,
|
||||
before_index -> BigInt,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
works (id) {
|
||||
id -> Text,
|
||||
composer -> Text,
|
||||
title -> Text,
|
||||
}
|
||||
}
|
||||
|
||||
joinable!(instrumentations -> instruments (instrument));
|
||||
joinable!(instrumentations -> works (work));
|
||||
joinable!(performances -> ensembles (ensemble));
|
||||
joinable!(performances -> instruments (role));
|
||||
joinable!(performances -> persons (person));
|
||||
joinable!(performances -> recordings (recording));
|
||||
joinable!(recordings -> works (work));
|
||||
joinable!(track_sets -> mediums (medium));
|
||||
joinable!(track_sets -> recordings (recording));
|
||||
joinable!(tracks -> track_sets (track_set));
|
||||
joinable!(work_parts -> works (work));
|
||||
joinable!(work_sections -> works (work));
|
||||
joinable!(works -> persons (composer));
|
||||
|
||||
allow_tables_to_appear_in_same_query!(
|
||||
ensembles,
|
||||
instrumentations,
|
||||
instruments,
|
||||
mediums,
|
||||
performances,
|
||||
persons,
|
||||
recordings,
|
||||
track_sets,
|
||||
tracks,
|
||||
work_parts,
|
||||
work_sections,
|
||||
works,
|
||||
);
|
||||
376
database/src/thread.rs
Normal file
376
database/src/thread.rs
Normal file
|
|
@ -0,0 +1,376 @@
|
|||
use super::*;
|
||||
use futures_channel::oneshot;
|
||||
use futures_channel::oneshot::Sender;
|
||||
use std::sync::mpsc;
|
||||
use std::thread;
|
||||
|
||||
/// An action the database thread can perform.
|
||||
pub enum Action {
|
||||
UpdatePerson(Person, Sender<Result<()>>),
|
||||
GetPerson(String, Sender<Result<Option<Person>>>),
|
||||
DeletePerson(String, Sender<Result<()>>),
|
||||
GetPersons(Sender<Result<Vec<Person>>>),
|
||||
UpdateInstrument(Instrument, Sender<Result<()>>),
|
||||
GetInstrument(String, Sender<Result<Option<Instrument>>>),
|
||||
DeleteInstrument(String, Sender<Result<()>>),
|
||||
GetInstruments(Sender<Result<Vec<Instrument>>>),
|
||||
UpdateWork(Work, Sender<Result<()>>),
|
||||
DeleteWork(String, Sender<Result<()>>),
|
||||
GetWorks(String, Sender<Result<Vec<Work>>>),
|
||||
UpdateEnsemble(Ensemble, Sender<Result<()>>),
|
||||
GetEnsemble(String, Sender<Result<Option<Ensemble>>>),
|
||||
DeleteEnsemble(String, Sender<Result<()>>),
|
||||
GetEnsembles(Sender<Result<Vec<Ensemble>>>),
|
||||
UpdateRecording(Recording, Sender<Result<()>>),
|
||||
DeleteRecording(String, Sender<Result<()>>),
|
||||
GetRecordingsForPerson(String, Sender<Result<Vec<Recording>>>),
|
||||
GetRecordingsForEnsemble(String, Sender<Result<Vec<Recording>>>),
|
||||
GetRecordingsForWork(String, Sender<Result<Vec<Recording>>>),
|
||||
RecordingExists(String, Sender<Result<bool>>),
|
||||
UpdateMedium(Medium, Sender<Result<()>>),
|
||||
GetMedium(String, Sender<Result<Option<Medium>>>),
|
||||
GetMediumsForPerson(String, Sender<Result<Vec<Medium>>>),
|
||||
GetMediumsForEnsemble(String, Sender<Result<Vec<Medium>>>),
|
||||
DeleteMedium(String, Sender<Result<()>>),
|
||||
GetTrackSets(String, Sender<Result<Vec<TrackSet>>>),
|
||||
Stop(Sender<()>),
|
||||
}
|
||||
|
||||
use Action::*;
|
||||
|
||||
/// A database running within a thread.
|
||||
pub struct DbThread {
|
||||
action_sender: mpsc::Sender<Action>,
|
||||
}
|
||||
|
||||
impl DbThread {
|
||||
/// Create a new database connection in a background thread.
|
||||
pub async fn new(path: String) -> Result<Self> {
|
||||
let (action_sender, action_receiver) = mpsc::channel();
|
||||
let (ready_sender, ready_receiver) = oneshot::channel();
|
||||
|
||||
thread::spawn(move || {
|
||||
let db = match Database::new(&path) {
|
||||
Ok(db) => {
|
||||
ready_sender.send(Ok(())).unwrap();
|
||||
db
|
||||
}
|
||||
Err(error) => {
|
||||
ready_sender.send(Err(error)).unwrap();
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
for action in action_receiver {
|
||||
match action {
|
||||
UpdatePerson(person, sender) => {
|
||||
sender.send(db.update_person(person)).unwrap();
|
||||
}
|
||||
GetPerson(id, sender) => {
|
||||
sender.send(db.get_person(&id)).unwrap();
|
||||
}
|
||||
DeletePerson(id, sender) => {
|
||||
sender.send(db.delete_person(&id)).unwrap();
|
||||
}
|
||||
GetPersons(sender) => {
|
||||
sender.send(db.get_persons()).unwrap();
|
||||
}
|
||||
UpdateInstrument(instrument, sender) => {
|
||||
sender.send(db.update_instrument(instrument)).unwrap();
|
||||
}
|
||||
GetInstrument(id, sender) => {
|
||||
sender.send(db.get_instrument(&id)).unwrap();
|
||||
}
|
||||
DeleteInstrument(id, sender) => {
|
||||
sender.send(db.delete_instrument(&id)).unwrap();
|
||||
}
|
||||
GetInstruments(sender) => {
|
||||
sender.send(db.get_instruments()).unwrap();
|
||||
}
|
||||
UpdateWork(work, sender) => {
|
||||
sender.send(db.update_work(work)).unwrap();
|
||||
}
|
||||
DeleteWork(id, sender) => {
|
||||
sender.send(db.delete_work(&id)).unwrap();
|
||||
}
|
||||
GetWorks(id, sender) => {
|
||||
sender.send(db.get_works(&id)).unwrap();
|
||||
}
|
||||
UpdateEnsemble(ensemble, sender) => {
|
||||
sender.send(db.update_ensemble(ensemble)).unwrap();
|
||||
}
|
||||
GetEnsemble(id, sender) => {
|
||||
sender.send(db.get_ensemble(&id)).unwrap();
|
||||
}
|
||||
DeleteEnsemble(id, sender) => {
|
||||
sender.send(db.delete_ensemble(&id)).unwrap();
|
||||
}
|
||||
GetEnsembles(sender) => {
|
||||
sender.send(db.get_ensembles()).unwrap();
|
||||
}
|
||||
UpdateRecording(recording, sender) => {
|
||||
sender.send(db.update_recording(recording)).unwrap();
|
||||
}
|
||||
DeleteRecording(id, sender) => {
|
||||
sender.send(db.delete_recording(&id)).unwrap();
|
||||
}
|
||||
GetRecordingsForPerson(id, sender) => {
|
||||
sender.send(db.get_recordings_for_person(&id)).unwrap();
|
||||
}
|
||||
GetRecordingsForEnsemble(id, sender) => {
|
||||
sender.send(db.get_recordings_for_ensemble(&id)).unwrap();
|
||||
}
|
||||
GetRecordingsForWork(id, sender) => {
|
||||
sender.send(db.get_recordings_for_work(&id)).unwrap();
|
||||
}
|
||||
RecordingExists(id, sender) => {
|
||||
sender.send(db.recording_exists(&id)).unwrap();
|
||||
}
|
||||
UpdateMedium(medium, sender) => {
|
||||
sender.send(db.update_medium(medium)).unwrap();
|
||||
}
|
||||
GetMedium(id, sender) => {
|
||||
sender.send(db.get_medium(&id)).unwrap();
|
||||
}
|
||||
GetMediumsForPerson(id, sender) => {
|
||||
sender.send(db.get_mediums_for_person(&id)).unwrap();
|
||||
}
|
||||
GetMediumsForEnsemble(id, sender) => {
|
||||
sender.send(db.get_mediums_for_ensemble(&id)).unwrap();
|
||||
}
|
||||
DeleteMedium(id, sender) => {
|
||||
sender.send(db.delete_medium(&id)).unwrap();
|
||||
}
|
||||
GetTrackSets(recording_id, sender) => {
|
||||
sender.send(db.get_track_sets(&recording_id)).unwrap();
|
||||
}
|
||||
Stop(sender) => {
|
||||
sender.send(()).unwrap();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
ready_receiver.await??;
|
||||
Ok(Self { action_sender })
|
||||
}
|
||||
|
||||
/// Update an existing person or insert a new one.
|
||||
pub async fn update_person(&self, person: Person) -> Result<()> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender.send(UpdatePerson(person, sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Get an existing person.
|
||||
pub async fn get_person(&self, id: &str) -> Result<Option<Person>> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender.send(GetPerson(id.to_string(), sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Delete an existing person. This will fail, if there are still other items referencing
|
||||
/// this person.
|
||||
pub async fn delete_person(&self, id: &str) -> Result<()> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender
|
||||
.send(DeletePerson(id.to_string(), sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Get all existing persons.
|
||||
pub async fn get_persons(&self) -> Result<Vec<Person>> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender.send(GetPersons(sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Update an existing instrument or insert a new one.
|
||||
pub async fn update_instrument(&self, instrument: Instrument) -> Result<()> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender
|
||||
.send(UpdateInstrument(instrument, sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Get an existing instrument.
|
||||
pub async fn get_instrument(&self, id: &str) -> Result<Option<Instrument>> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender
|
||||
.send(GetInstrument(id.to_string(), sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Delete an existing instrument. This will fail, if there are still other items referencing
|
||||
/// this instrument.
|
||||
pub async fn delete_instrument(&self, id: &str) -> Result<()> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender
|
||||
.send(DeleteInstrument(id.to_string(), sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Get all existing instruments.
|
||||
pub async fn get_instruments(&self) -> Result<Vec<Instrument>> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender.send(GetInstruments(sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Update an existing work or insert a new one.
|
||||
pub async fn update_work(&self, work: Work) -> Result<()> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender.send(UpdateWork(work, sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Delete an existing work. This will fail, if there are still other items referencing
|
||||
/// this work.
|
||||
pub async fn delete_work(&self, id: &str) -> Result<()> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender
|
||||
.send(DeleteWork(id.to_string(), sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Get information on all existing works by a composer.
|
||||
pub async fn get_works(&self, person_id: &str) -> Result<Vec<Work>> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender
|
||||
.send(GetWorks(person_id.to_string(), sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Update an existing ensemble or insert a new one.
|
||||
pub async fn update_ensemble(&self, ensemble: Ensemble) -> Result<()> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender.send(UpdateEnsemble(ensemble, sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Get an existing ensemble.
|
||||
pub async fn get_ensemble(&self, id: &str) -> Result<Option<Ensemble>> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender
|
||||
.send(GetEnsemble(id.to_string(), sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Delete an existing ensemble. This will fail, if there are still other items referencing
|
||||
/// this ensemble.
|
||||
pub async fn delete_ensemble(&self, id: &str) -> Result<()> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender
|
||||
.send(DeleteEnsemble(id.to_string(), sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Get all existing ensembles.
|
||||
pub async fn get_ensembles(&self) -> Result<Vec<Ensemble>> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender.send(GetEnsembles(sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Update an existing recording or insert a new one.
|
||||
pub async fn update_recording(&self, recording: Recording) -> Result<()> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender
|
||||
.send(UpdateRecording(recording, sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Delete an existing recording.
|
||||
pub async fn delete_recording(&self, id: &str) -> Result<()> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender
|
||||
.send(DeleteRecording(id.to_string(), sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Get information on all recordings in which a person performs.
|
||||
pub async fn get_recordings_for_person(&self, person_id: &str) -> Result<Vec<Recording>> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender
|
||||
.send(GetRecordingsForPerson(person_id.to_string(), sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Get information on all recordings in which an ensemble performs.
|
||||
pub async fn get_recordings_for_ensemble(&self, ensemble_id: &str) -> Result<Vec<Recording>> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender
|
||||
.send(GetRecordingsForEnsemble(ensemble_id.to_string(), sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Get information on all recordings of a work.
|
||||
pub async fn get_recordings_for_work(&self, work_id: &str) -> Result<Vec<Recording>> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender
|
||||
.send(GetRecordingsForWork(work_id.to_string(), sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Check whether a recording exists within the database.
|
||||
pub async fn recording_exists(&self, id: &str) -> Result<bool> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender
|
||||
.send(RecordingExists(id.to_string(), sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Update an existing medium or insert a new one.
|
||||
pub async fn update_medium(&self, medium: Medium) -> Result<()> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender.send(UpdateMedium(medium, sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Delete an existing medium. This will fail, if there are still other
|
||||
/// items referencing this medium.
|
||||
pub async fn delete_medium(&self, id: &str) -> Result<()> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
|
||||
self.action_sender
|
||||
.send(DeleteMedium(id.to_owned(), sender))?;
|
||||
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Get an existing medium.
|
||||
pub async fn get_medium(&self, id: &str) -> Result<Option<Medium>> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender.send(GetMedium(id.to_owned(), sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Get all mediums on which a person performs.
|
||||
pub async fn get_mediums_for_person(&self, id: &str) -> Result<Vec<Medium>> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender.send(GetMediumsForPerson(id.to_owned(), sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Get all mediums on which an ensemble performs.
|
||||
pub async fn get_mediums_for_ensemble(&self, id: &str) -> Result<Vec<Medium>> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender.send(GetMediumsForEnsemble(id.to_owned(), sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Get all track sets for a recording.
|
||||
pub async fn get_track_sets(&self, recording_id: &str) -> Result<Vec<TrackSet>> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender.send(GetTrackSets(recording_id.to_owned(), sender))?;
|
||||
receiver.await?
|
||||
}
|
||||
|
||||
/// Stop the database thread. Any future access to the database will fail.
|
||||
pub async fn stop(&self) -> Result<()> {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
self.action_sender.send(Stop(sender))?;
|
||||
Ok(receiver.await?)
|
||||
}
|
||||
}
|
||||
285
database/src/works.rs
Normal file
285
database/src/works.rs
Normal file
|
|
@ -0,0 +1,285 @@
|
|||
use super::generate_id;
|
||||
use super::schema::{instrumentations, work_parts, work_sections, works};
|
||||
use super::{Database, Error, Instrument, Person, Result};
|
||||
use diesel::prelude::*;
|
||||
use diesel::{Insertable, Queryable};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Table row data for a work.
|
||||
#[derive(Insertable, Queryable, Debug, Clone)]
|
||||
#[table_name = "works"]
|
||||
struct WorkRow {
|
||||
pub id: String,
|
||||
pub composer: String,
|
||||
pub title: String,
|
||||
}
|
||||
|
||||
impl From<Work> for WorkRow {
|
||||
fn from(work: Work) -> Self {
|
||||
WorkRow {
|
||||
id: work.id,
|
||||
composer: work.composer.id,
|
||||
title: work.title,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Definition that a work uses an instrument.
|
||||
#[derive(Insertable, Queryable, Debug, Clone)]
|
||||
#[table_name = "instrumentations"]
|
||||
struct InstrumentationRow {
|
||||
pub id: i64,
|
||||
pub work: String,
|
||||
pub instrument: String,
|
||||
}
|
||||
|
||||
/// Table row data for a work part.
|
||||
#[derive(Insertable, Queryable, Debug, Clone)]
|
||||
#[table_name = "work_parts"]
|
||||
struct WorkPartRow {
|
||||
pub id: i64,
|
||||
pub work: String,
|
||||
pub part_index: i64,
|
||||
pub title: String,
|
||||
}
|
||||
|
||||
/// Table row data for a work section.
|
||||
#[derive(Insertable, Queryable, Debug, Clone)]
|
||||
#[table_name = "work_sections"]
|
||||
struct WorkSectionRow {
|
||||
pub id: i64,
|
||||
pub work: String,
|
||||
pub title: String,
|
||||
pub before_index: i64,
|
||||
}
|
||||
/// A concrete work part that can be recorded.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WorkPart {
|
||||
pub title: String,
|
||||
}
|
||||
|
||||
/// A heading between work parts.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WorkSection {
|
||||
pub title: String,
|
||||
pub before_index: usize,
|
||||
}
|
||||
|
||||
/// A specific work by a composer.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Work {
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub composer: Person,
|
||||
pub instruments: Vec<Instrument>,
|
||||
pub parts: Vec<WorkPart>,
|
||||
pub sections: Vec<WorkSection>,
|
||||
}
|
||||
|
||||
impl Work {
|
||||
/// Initialize a new work with a composer.
|
||||
pub fn new(composer: Person) -> Self {
|
||||
Self {
|
||||
id: generate_id(),
|
||||
title: String::new(),
|
||||
composer,
|
||||
instruments: Vec::new(),
|
||||
parts: Vec::new(),
|
||||
sections: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a string including the composer and title of the work.
|
||||
// TODO: Replace with impl Display.
|
||||
pub fn get_title(&self) -> String {
|
||||
format!("{}: {}", self.composer.name_fl(), self.title)
|
||||
}
|
||||
}
|
||||
|
||||
impl Database {
|
||||
/// Update an existing work or insert a new one.
|
||||
// TODO: Think about also inserting related items.
|
||||
pub fn update_work(&self, work: Work) -> Result<()> {
|
||||
self.defer_foreign_keys()?;
|
||||
|
||||
self.connection.transaction::<(), Error, _>(|| {
|
||||
let work_id = &work.id;
|
||||
self.delete_work(work_id)?;
|
||||
|
||||
// Add associated items from the server, if they don't already exist.
|
||||
|
||||
if self.get_person(&work.composer.id)?.is_none() {
|
||||
self.update_person(work.composer.clone())?;
|
||||
}
|
||||
|
||||
for instrument in &work.instruments {
|
||||
if self.get_instrument(&instrument.id)?.is_none() {
|
||||
self.update_instrument(instrument.clone())?;
|
||||
}
|
||||
}
|
||||
|
||||
// Add the actual work.
|
||||
|
||||
let row: WorkRow = work.clone().into();
|
||||
diesel::insert_into(works::table)
|
||||
.values(row)
|
||||
.execute(&self.connection)?;
|
||||
|
||||
match work {
|
||||
Work {
|
||||
instruments,
|
||||
parts,
|
||||
sections,
|
||||
..
|
||||
} => {
|
||||
for instrument in instruments {
|
||||
let row = InstrumentationRow {
|
||||
id: rand::random(),
|
||||
work: work_id.to_string(),
|
||||
instrument: instrument.id,
|
||||
};
|
||||
|
||||
diesel::insert_into(instrumentations::table)
|
||||
.values(row)
|
||||
.execute(&self.connection)?;
|
||||
}
|
||||
|
||||
for (index, part) in parts.into_iter().enumerate() {
|
||||
let row = WorkPartRow {
|
||||
id: rand::random(),
|
||||
work: work_id.to_string(),
|
||||
part_index: index as i64,
|
||||
title: part.title,
|
||||
};
|
||||
|
||||
diesel::insert_into(work_parts::table)
|
||||
.values(row)
|
||||
.execute(&self.connection)?;
|
||||
}
|
||||
|
||||
for section in sections {
|
||||
let row = WorkSectionRow {
|
||||
id: rand::random(),
|
||||
work: work_id.to_string(),
|
||||
title: section.title,
|
||||
before_index: section.before_index as i64,
|
||||
};
|
||||
|
||||
diesel::insert_into(work_sections::table)
|
||||
.values(row)
|
||||
.execute(&self.connection)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get an existing work.
|
||||
pub fn get_work(&self, id: &str) -> Result<Option<Work>> {
|
||||
let row = works::table
|
||||
.filter(works::id.eq(id))
|
||||
.load::<WorkRow>(&self.connection)?
|
||||
.first()
|
||||
.cloned();
|
||||
|
||||
let work = match row {
|
||||
Some(row) => Some(self.get_work_data(row)?),
|
||||
None => None,
|
||||
};
|
||||
|
||||
Ok(work)
|
||||
}
|
||||
|
||||
/// Retrieve all available information on a work from related tables.
|
||||
fn get_work_data(&self, row: WorkRow) -> Result<Work> {
|
||||
let mut instruments: Vec<Instrument> = Vec::new();
|
||||
|
||||
let instrumentations = instrumentations::table
|
||||
.filter(instrumentations::work.eq(&row.id))
|
||||
.load::<InstrumentationRow>(&self.connection)?;
|
||||
|
||||
for instrumentation in instrumentations {
|
||||
let id = &instrumentation.instrument;
|
||||
instruments.push(
|
||||
self.get_instrument(id)?
|
||||
.ok_or(Error::Other(format!(
|
||||
"Failed to get instrument ({}) for work ({}).",
|
||||
id,
|
||||
row.id,
|
||||
)))?
|
||||
);
|
||||
}
|
||||
|
||||
let mut parts: Vec<WorkPart> = Vec::new();
|
||||
|
||||
let part_rows = work_parts::table
|
||||
.filter(work_parts::work.eq(&row.id))
|
||||
.load::<WorkPartRow>(&self.connection)?;
|
||||
|
||||
for part_row in part_rows {
|
||||
parts.push(WorkPart {
|
||||
title: part_row.title,
|
||||
});
|
||||
}
|
||||
|
||||
let mut sections: Vec<WorkSection> = Vec::new();
|
||||
|
||||
let section_rows = work_sections::table
|
||||
.filter(work_sections::work.eq(&row.id))
|
||||
.load::<WorkSectionRow>(&self.connection)?;
|
||||
|
||||
for section_row in section_rows {
|
||||
sections.push(WorkSection {
|
||||
title: section_row.title,
|
||||
before_index: section_row.before_index as usize,
|
||||
});
|
||||
}
|
||||
|
||||
let person_id = &row.composer;
|
||||
let person = self
|
||||
.get_person(person_id)?
|
||||
.ok_or(Error::Other(format!(
|
||||
"Failed to get person ({}) for work ({}).",
|
||||
person_id,
|
||||
row.id,
|
||||
)))?;
|
||||
|
||||
Ok(Work {
|
||||
id: row.id,
|
||||
composer: person,
|
||||
title: row.title,
|
||||
instruments,
|
||||
parts,
|
||||
sections,
|
||||
})
|
||||
}
|
||||
|
||||
/// 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
|
||||
pub fn delete_work(&self, id: &str) -> Result<()> {
|
||||
diesel::delete(works::table.filter(works::id.eq(id))).execute(&self.connection)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get all existing works by a composer and related information from other tables.
|
||||
pub fn get_works(&self, composer_id: &str) -> Result<Vec<Work>> {
|
||||
let mut works: Vec<Work> = Vec::new();
|
||||
|
||||
let rows = works::table
|
||||
.filter(works::composer.eq(composer_id))
|
||||
.load::<WorkRow>(&self.connection)?;
|
||||
|
||||
for row in rows {
|
||||
works.push(self.get_work_data(row)?);
|
||||
}
|
||||
|
||||
Ok(works)
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue