mecomp-storage 0.7.2

This library is responsible for storing and retrieving data about a user's music library to and from an embedded surrealdb database.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
//! CRUD operations for the artist table
use std::{
    collections::{HashMap, HashSet},
    time::Duration,
};

use surrealdb::{Connection, Surreal};
use surrealqlx::surrql;
use tracing::instrument;

use crate::{
    db::{
        queries::{
            artist::{
                add_album, add_album_to_artists, add_song, read_albums, read_by_name,
                read_by_names, read_songs, remove_song,
            },
            generic::{read_many, read_rand},
        },
        schemas::{
            album::{Album, AlbumId},
            artist::{Artist, ArtistBrief, ArtistChangeSet, ArtistId, TABLE_NAME},
            song::{Song, SongId},
        },
    },
    errors::StorageResult,
};
use one_or_many::OneOrMany;

impl Artist {
    #[instrument]
    pub async fn create<C: Connection>(
        db: &Surreal<C>,
        artist: Self,
    ) -> StorageResult<Option<Self>> {
        Ok(db.create(artist.id.clone()).content(artist).await?)
    }

    #[instrument]
    pub async fn create_many<C: Connection>(
        db: &Surreal<C>,
        artists: Vec<Self>,
    ) -> StorageResult<Vec<Self>> {
        Ok(db.insert(TABLE_NAME).content(artists).await?)
    }

    #[instrument]
    pub async fn read_or_create_by_name<C: Connection>(
        db: &Surreal<C>,
        name: &str,
    ) -> StorageResult<Option<Self>> {
        if let Ok(Some(artist)) = Self::read_by_name(db, name).await {
            Ok(Some(artist))
        } else {
            let artist = Self {
                id: Self::generate_id(),
                name: name.into(),
                song_count: 0,
                album_count: 0,
                runtime: Duration::from_secs(0),
            };
            Self::create(db, artist).await
        }
    }

    #[instrument]
    pub async fn read_or_create_by_names<C: Connection>(
        db: &Surreal<C>,
        names: OneOrMany<String>,
    ) -> StorageResult<Vec<Self>> {
        let mut artists = Vec::with_capacity(names.len());
        for name in &names {
            if let Some(artist) = Self::read_or_create_by_name(db, name).await? {
                artists.push(artist);
            }
        }
        Ok(artists)
    }

    /// Read or create multiple artists by their names in bulk.
    /// This is much more efficient than calling `read_or_create_by_name` repeatedly.
    ///
    /// Returns a `HashMap` mapping artist names to Artist objects.
    #[instrument]
    pub async fn bulk_read_or_create_by_names<C: Connection>(
        db: &Surreal<C>,
        names: HashSet<String>,
    ) -> StorageResult<HashMap<String, ArtistId>> {
        // Query which artists already exist
        let existing: Vec<Self> = db
            .query(surrql!("SELECT * FROM artist WHERE name IN $names"))
            .bind(("names", names.clone()))
            .await?
            .take(0)?;

        let mut result: HashMap<String, ArtistId> =
            existing.into_iter().map(|a| (a.name, a.id)).collect();

        // Find missing artists
        let missing: Vec<Self> = names
            .into_iter()
            .filter(|name| !result.contains_key(name))
            .map(|name| Self {
                id: Self::generate_id(),
                name,
                song_count: 0,
                album_count: 0,
                runtime: Duration::from_secs(0),
            })
            .collect();

        if !missing.is_empty() {
            let created = Self::create_many(db, missing).await?;

            for artist in created {
                result.insert(artist.name, artist.id);
            }
        }

        Ok(result)
    }

    #[instrument]
    pub async fn read_by_name<C: Connection>(
        db: &Surreal<C>,
        name: &str,
    ) -> StorageResult<Option<Self>> {
        Ok(db
            .query(read_by_name())
            .bind(("name", name.to_string()))
            .await?
            .take(0)?)
    }

    #[instrument]
    pub async fn read_by_names<C: Connection>(
        db: &Surreal<C>,
        names: Vec<String>,
    ) -> StorageResult<Vec<Self>> {
        // select artists records whose `name` field is in $names
        Ok(db
            .query(read_by_names())
            .bind(("names", names))
            .await?
            .take(0)?)
    }

    #[instrument]
    pub async fn read_all<C: Connection>(db: &Surreal<C>) -> StorageResult<Vec<Self>> {
        Ok(db.select(TABLE_NAME).await?)
    }

    #[instrument]
    pub async fn read_all_brief<C: Connection>(db: &Surreal<C>) -> StorageResult<Vec<ArtistBrief>> {
        Ok(db
            .query(surrql!(
                "SELECT type::fields($fields) FROM type::table($table)"
            ))
            .bind(("fields", Self::BRIEF_FIELDS))
            .bind(("table", TABLE_NAME))
            .await?
            .take(0)?)
    }

    #[instrument]
    pub async fn read<C: Connection>(db: &Surreal<C>, id: ArtistId) -> StorageResult<Option<Self>> {
        Ok(db.select(id).await?)
    }

    #[instrument]
    pub async fn read_one_or_many<C: Connection>(
        db: &Surreal<C>,
        ids: OneOrMany<ArtistId>,
    ) -> StorageResult<OneOrMany<Self>> {
        match ids {
            OneOrMany::One(id) => Ok(Self::read(db, *id).await?.into()),
            OneOrMany::Many(ids) => Self::read_many(db, ids).await.map(std::convert::Into::into),
            OneOrMany::None => Ok(OneOrMany::None),
        }
    }

    #[instrument]
    pub async fn read_many<C: Connection>(
        db: &Surreal<C>,
        ids: Vec<ArtistId>,
    ) -> StorageResult<Vec<Self>> {
        Ok(db.query(read_many()).bind(("ids", ids)).await?.take(0)?)
    }

    #[instrument]
    pub async fn read_rand<C: Connection>(
        db: &Surreal<C>,
        limit: usize,
    ) -> StorageResult<Vec<ArtistBrief>> {
        Ok(db
            .query(read_rand())
            .bind(("fields", Self::BRIEF_FIELDS))
            .bind(("table", TABLE_NAME))
            .bind(("limit", limit))
            .await?
            .take(0)?)
    }

    #[instrument]
    pub async fn search<C: Connection>(
        db: &Surreal<C>,
        query: &str,
        limit: usize,
    ) -> StorageResult<Vec<ArtistBrief>> {
        Ok(db
            .query(surrql!("SELECT type::fields($fields),relevance FROM artist WHERE name @@ $query ORDER BY relevance DESC LIMIT $limit"))
            .bind(("fields", Self::BRIEF_FIELDS))
            .bind(("query", query.to_string()))
            .bind(("limit", limit))
            .await?
            .take(0)?)
    }

    #[instrument]
    pub async fn update<C: Connection>(
        db: &Surreal<C>,
        id: ArtistId,
        changes: ArtistChangeSet,
    ) -> StorageResult<Option<Self>> {
        Ok(db.update(id).merge(changes).await?)
    }

    #[instrument]
    pub async fn delete<C: Connection>(
        db: &Surreal<C>,
        id: ArtistId,
    ) -> StorageResult<Option<Self>> {
        Ok(db.delete(id).await?)
    }

    #[instrument]
    pub async fn read_albums<C: Connection>(
        db: &Surreal<C>,
        id: ArtistId,
    ) -> StorageResult<Vec<Album>> {
        Ok(db.query(read_albums()).bind(("id", id)).await?.take(0)?)
    }

    #[instrument]
    pub async fn add_album<C: Connection>(
        db: &Surreal<C>,
        id: ArtistId,
        album_id: AlbumId,
    ) -> StorageResult<()> {
        db
            // relate this artist to the album
            .query(add_album())
            // relate this artist to the songs in the album
            // .query("RELATE $id->artist_to_song->(SELECT ->album_to_song<-album FROM $album)")
            .bind(("id", id))
            .bind(("album", album_id))
            .await?;
        Ok(())
    }

    #[instrument]
    pub async fn add_album_to_artists<C: Connection>(
        db: &Surreal<C>,
        ids: Vec<ArtistId>,
        album_id: AlbumId,
    ) -> StorageResult<()> {
        db
            // relate this artist to the album
            .query(add_album_to_artists())
            .bind(("ids", ids))
            .bind(("album", album_id))
            .await?;
        Ok(())
    }

    #[instrument]
    pub async fn add_song<C: Connection>(
        db: &Surreal<C>,
        id: ArtistId,
        song: SongId,
    ) -> StorageResult<()> {
        db
            // relate this artist to this song
            .query(add_song())
            .bind(("id", id))
            .bind(("song", song))
            .await?;
        Ok(())
    }

    #[instrument]
    /// removes a song from an artist's list of songs
    pub async fn remove_song<C: Connection>(
        db: &Surreal<C>,
        id: ArtistId,
        song_id: SongId,
    ) -> StorageResult<()> {
        db.query(remove_song())
            .bind(("artist", id))
            .bind(("song", song_id))
            .await?;
        Ok(())
    }

    #[instrument]
    /// gets all the songs associated with an artist, either directly or through an album
    pub async fn read_songs<C: Connection>(
        db: &Surreal<C>,
        id: ArtistId,
    ) -> StorageResult<Vec<Song>> {
        Ok(db.query(read_songs()).bind(("artist", id)).await?.take(0)?)
    }

    /// Deletes all orphaned artists from the database
    ///
    /// An orphaned artist is an artist that has no associated songs
    /// or albums
    #[instrument]
    pub async fn delete_orphaned<C: Connection>(db: &Surreal<C>) -> StorageResult<Vec<Self>> {
        Ok(db
            .query(surrql!(
                "DELETE FROM artist WHERE type::int(song_count) = 0 RETURN BEFORE"
            ))
            .await?
            .take(0)?)
    }
}

#[cfg(test)]
mod tests {
    use std::{path::PathBuf, time::Duration};

    use super::*;
    use crate::test_utils::init_test_database;

    use anyhow::{Result, anyhow};
    use pretty_assertions::assert_eq;

    fn create_artist() -> Artist {
        Artist {
            id: Artist::generate_id(),
            name: "Test Artist".into(),
            runtime: Duration::from_secs(0),
            album_count: 0,
            song_count: 0,
        }
    }

    #[tokio::test]
    async fn test_create() -> Result<()> {
        let db = init_test_database().await?;
        let artist = create_artist();

        let created = Artist::create(&db, artist.clone()).await?;
        assert_eq!(Some(artist), created);
        Ok(())
    }

    #[tokio::test]
    async fn test_read() -> Result<()> {
        let db = init_test_database().await?;
        let artist = create_artist();

        let created = Artist::create(&db, artist.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create artist"))?;

        let read = Artist::read(&db, artist.id.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to read artist"))?;
        assert_eq!(artist, read);
        assert_eq!(read, created);
        Ok(())
    }

    #[tokio::test]
    async fn test_read_one_or_many() -> Result<()> {
        let db = init_test_database().await?;
        let artist = create_artist();
        let mut artist2 = create_artist();
        artist2.name = "Test Artist 2".to_string();

        // test None
        let read = Artist::read_one_or_many(&db, OneOrMany::None).await?;
        assert_eq!(read, OneOrMany::None);

        // test One
        let created = Artist::create(&db, artist.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create artist"))?;
        let read = Artist::read_one_or_many(&db, artist.id.clone().into()).await?;
        assert_eq!(read, created.clone().into());

        // test Many
        let created2 = Artist::create(&db, artist2.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create artist"))?;
        let read = Artist::read_one_or_many(
            &db,
            OneOrMany::Many(vec![artist.id.clone(), artist2.id.clone()]),
        )
        .await?;
        assert_eq!(read, OneOrMany::Many(vec![created, created2]));

        Ok(())
    }

    #[tokio::test]
    async fn test_read_many() -> Result<()> {
        let db = init_test_database().await?;
        let artist = create_artist();
        let mut artist2 = create_artist();
        artist2.name = "Test Artist 2".to_string();

        let created = Artist::create(&db, artist.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create artist"))?;
        let created2 = Artist::create(&db, artist2.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create artist"))?;

        let read = Artist::read_many(&db, vec![artist.id.clone(), artist2.id.clone()]).await?;
        assert_eq!(read, vec![created, created2]);
        Ok(())
    }

    #[tokio::test]
    async fn test_read_rand() -> Result<()> {
        let db = init_test_database().await?;
        let artist1 = create_artist();
        let mut artist2 = create_artist();
        artist2.name = "Another Test Artist".to_string();

        let artist1 = Artist::create(&db, artist1.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create artist"))?
            .into();
        let artist2 = Artist::create(&db, artist2.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create artist"))?
            .into();

        // n = # records
        let read = Artist::read_rand(&db, 2).await?;
        assert_eq!(read.len(), 2);
        assert!(read.contains(&artist1) && read.contains(&artist2));
        // n > # records
        let read = Artist::read_rand(&db, 3).await?;
        assert_eq!(read.len(), 2);
        assert!(read.contains(&artist1) && read.contains(&artist2));
        // n < # records
        let read = Artist::read_rand(&db, 1).await?;
        assert_eq!(read.len(), 1);
        assert!(read.contains(&artist1) || read.contains(&artist2));
        // n == 0
        let read = Artist::read_rand(&db, 0).await?;
        assert_eq!(read.len(), 0);

        Ok(())
    }

    #[tokio::test]
    async fn test_search() -> Result<()> {
        let db = init_test_database().await?;
        let mut artist1 = create_artist();
        artist1.name = "Foo Bar".into();
        let mut artist2 = create_artist();
        artist2.name = "Foo".into();

        Artist::create(&db, artist1.clone()).await?;
        Artist::create(&db, artist2.clone()).await?;

        let found = Artist::search(&db, "foo", 2).await?;
        assert_eq!(found.len(), 2);
        assert!(found.contains(&artist1.clone().into()));
        assert!(found.contains(&artist2.into()));

        let found = Artist::search(&db, "bar", 1).await?;
        assert_eq!(found.len(), 1);
        assert_eq!(found, vec![artist1.into()]);
        Ok(())
    }

    #[tokio::test]
    async fn test_update() -> Result<()> {
        let db = init_test_database().await?;
        let artist = create_artist();

        let _ = Artist::create(&db, artist.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create artist"))?;

        let changes = ArtistChangeSet {
            name: Some("New Name".to_string()),
        };

        let updated = Artist::update(&db, artist.id.clone(), changes).await?;
        let read = Artist::read(&db, artist.id.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to read artist"))?;

        assert_eq!(read.name, "New Name".to_string());
        assert_eq!(Some(read), updated);
        Ok(())
    }

    #[tokio::test]
    async fn test_delete() -> Result<()> {
        let db = init_test_database().await?;
        let artist = create_artist();

        let _ = Artist::create(&db, artist.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create artist"))?;

        let deleted = Artist::delete(&db, artist.id.clone()).await?;
        let read = Artist::read(&db, artist.id.clone()).await?;

        assert_eq!(deleted, Some(artist));
        assert_eq!(read, None);
        Ok(())
    }

    #[tokio::test]
    async fn test_read_by_name() -> Result<()> {
        let db = init_test_database().await?;
        let album = create_artist();

        let _ = Artist::create(&db, album.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create artist"))?;

        let read = Artist::read_by_name(&db, "Test Artist").await?;
        assert_eq!(read, Some(album));
        Ok(())
    }

    #[tokio::test]
    /// read path tested in `test_read_by_name`, so we only need to test the create path
    async fn test_read_or_create_by_name() -> Result<()> {
        let db = init_test_database().await?;

        let created = Artist::read_or_create_by_name(&db, "Test Artist")
            .await?
            .ok_or_else(|| anyhow!("Failed to create artist"))?;

        let read = Artist::read_by_name(&db, "Test Artist").await?;
        assert_eq!(read, Some(created));
        Ok(())
    }

    #[tokio::test]
    async fn test_read_by_names() -> Result<()> {
        let db = init_test_database().await?;
        let album = create_artist();
        let mut album2 = create_artist();
        album2.name = "Test Artist 2".into();

        let _ = Artist::create(&db, album.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create artist"))?;
        let _ = Artist::create(&db, album2.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create artist"))?;

        let read =
            Artist::read_by_names(&db, vec!["Test Artist".into(), "Test Artist 2".into()]).await?;

        assert_eq!(read.len(), 2);

        if read[0].name == album.name {
            assert_eq!(read[0], album);
            assert_eq!(read[1], album2);
        } else {
            assert_eq!(read[1], album);
            assert_eq!(read[0], album2);
        }

        Ok(())
    }

    #[tokio::test]
    /// read path tested in `test_read_by_names`, so we only need to test the create path
    async fn test_read_or_create_by_names() -> Result<()> {
        let db = init_test_database().await?;

        let created = Artist::read_or_create_by_names(
            &db,
            OneOrMany::Many(vec!["Test Artist".into(), "Test Artist 2".into()]),
        )
        .await?;

        let read =
            Artist::read_by_names(&db, vec!["Test Artist".into(), "Test Artist 2".into()]).await?;

        assert_eq!(read.len(), 2);

        assert_eq!(read, created);
        Ok(())
    }

    #[tokio::test]
    async fn test_read_all() -> Result<()> {
        let db = init_test_database().await?;
        let artist = create_artist();

        let artist = Artist::create(&db, artist)
            .await?
            .ok_or_else(|| anyhow!("Failed to create artist"))?;

        let read = Artist::read_all(&db).await?;
        assert!(!read.is_empty());
        assert_eq!(read, vec![artist.clone()]);

        let read = Artist::read_all_brief(&db).await?;
        assert!(!read.is_empty());
        assert_eq!(read, vec![artist.into()]);
        Ok(())
    }

    #[tokio::test]
    async fn test_read_albums() -> Result<()> {
        let db = init_test_database().await?;
        let artist = create_artist();
        let album = Album {
            id: Album::generate_id(),
            title: "Test Album".into(),
            artist: artist.name.clone().into(),
            song_count: 4,
            runtime: Duration::from_secs(8),
            release: None,
            discs: 1,
            genre: OneOrMany::None,
        };

        let _ = Artist::create(&db, artist.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create artist"))?;
        let _ = Album::create(&db, album.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create album"))?;

        for i in 0..album.song_count {
            let song = Song {
                id: Song::generate_id(),
                title: format!("Test Song {i}"),
                artist: artist.name.clone().into(),
                album: album.title.clone(),
                runtime: Duration::from_secs(2),
                track: Some(i as u32 + 1),
                disc: Some(1),
                genre: OneOrMany::None,
                album_artist: artist.name.clone().into(),
                release_year: None,
                extension: "mp3".into(),
                path: PathBuf::from(format!("song{i}.mp3")),
            };
            let _ = Song::create(&db, song.clone())
                .await?
                .ok_or_else(|| anyhow!("Failed to create song"))?;
            Album::add_song(&db, album.id.clone(), song.id.clone()).await?;
        }

        Artist::add_album(&db, artist.id.clone(), album.id.clone()).await?;

        let read = Artist::read_albums(&db, artist.id.clone()).await?;
        assert_eq!(read.len(), 1);
        assert_eq!(read[0], album);
        Ok(())
    }

    #[tokio::test]
    async fn test_add_album() -> Result<()> {
        let db = init_test_database().await?;
        let artist = create_artist();
        let album = Album {
            id: Album::generate_id(),
            title: "Test Album".into(),
            artist: artist.name.clone().into(),
            song_count: 0,
            runtime: Duration::from_secs(0),
            release: None,
            discs: 1,
            genre: OneOrMany::None,
        };
        let song = Song {
            id: Song::generate_id(),
            title: "Test Song".into(),
            artist: artist.name.clone().into(),
            album: "Test Album".into(),
            runtime: Duration::from_secs(5),
            track: Some(1),
            disc: Some(1),
            genre: OneOrMany::None,
            album_artist: artist.name.clone().into(),
            release_year: None,
            extension: "mp3".into(),
            path: PathBuf::from("song.mp3"),
        };

        let _ = Artist::create(&db, artist.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create artist"))?;
        let _ = Album::create(&db, album.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create album"))?;
        let _ = Song::create(&db, song.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create song"))?;

        Album::add_song(&db, album.id.clone(), song.id.clone()).await?;
        Artist::add_album(&db, artist.id.clone(), album.id.clone()).await?;

        let read = Artist::read(&db, artist.id.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to read artist"))?;

        assert_eq!(read.album_count, 1);
        assert_eq!(read.runtime, song.runtime);
        assert_eq!(read.song_count, 1);

        Ok(())
    }

    #[tokio::test]
    async fn test_add_album_to_artists() -> Result<()> {
        let db = init_test_database().await?;
        let artist = create_artist();
        let mut artist2 = create_artist();
        artist2.name = "Test Artist 2".into();
        let album = Album {
            id: Album::generate_id(),
            title: "Test Album".into(),
            artist: OneOrMany::Many(vec![artist.name.clone(), artist2.name.clone()]),
            song_count: 0,
            runtime: Duration::from_secs(0),
            release: None,
            discs: 1,
            genre: OneOrMany::None,
        };
        let song = Song {
            id: Song::generate_id(),
            title: "Test Song".to_string(),
            artist: artist.name.clone().into(),
            album: "Test Album ".to_string(),
            runtime: Duration::from_secs(5),
            track: Some(1),
            disc: Some(1),
            genre: OneOrMany::None,
            album_artist: artist.name.clone().into(),
            release_year: None,
            extension: "mp3".into(),
            path: PathBuf::from("song.mp3"),
        };

        let _ = Artist::create(&db, artist.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create artist"))?;
        let _ = Artist::create(&db, artist2.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create artist"))?;
        let _ = Album::create(&db, album.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create album"))?;
        let _ = Song::create(&db, song.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create song"))?;

        Album::add_song(&db, album.id.clone(), song.id.clone()).await?;
        Artist::add_album_to_artists(
            &db,
            vec![artist.id.clone(), artist2.id.clone()],
            album.id.clone(),
        )
        .await?;
        Artist::add_song(&db, artist.id.clone(), song.id.clone()).await?;

        let read = Artist::read_many(&db, vec![artist.id.clone(), artist2.id.clone()]).await?;

        for artist in read {
            assert_eq!(artist.album_count, 1);
            assert_eq!(artist.runtime, song.runtime);
            assert_eq!(artist.song_count, 1);
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_add_songs() -> Result<()> {
        let db = init_test_database().await?;
        let artist = create_artist();
        let song = Song {
            id: Song::generate_id(),
            title: "Test Song".into(),
            artist: artist.name.clone().into(),
            album: "Test Album".into(),
            runtime: Duration::from_secs(5),
            track: Some(1),
            disc: Some(1),
            genre: OneOrMany::None,
            album_artist: artist.name.clone().into(),
            release_year: None,
            extension: "mp3".into(),
            path: PathBuf::from("song.mp3"),
        };

        let artist = Artist::create(&db, artist)
            .await?
            .ok_or_else(|| anyhow!("Failed to create artist"))?;
        let song = Song::create(&db, song)
            .await?
            .ok_or_else(|| anyhow!("Failed to create song"))?;

        Artist::add_song(&db, artist.id.clone(), song.id.clone()).await?;

        let read = Artist::read(&db, artist.id.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to read artist"))?;

        assert_eq!(read.song_count, 1);
        assert_eq!(read.runtime, song.runtime);

        Ok(())
    }

    #[tokio::test]
    async fn test_remove_songs() -> Result<()> {
        let db = init_test_database().await?;
        let artist = create_artist();
        let song = Song {
            id: Song::generate_id(),
            title: "Test Song".into(),
            artist: artist.name.clone().into(),
            album: "Test Album".into(),
            runtime: Duration::from_secs(5),
            track: Some(1),
            disc: Some(1),
            genre: OneOrMany::None,
            album_artist: artist.name.clone().into(),
            release_year: None,
            extension: "mp3".into(),
            path: PathBuf::from("song.mp3"),
        };

        let artist = Artist::create(&db, artist.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create artist"))?;
        let song = Song::create(&db, song.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create song"))?;

        Artist::add_song(&db, artist.id.clone(), song.id.clone()).await?;
        let read = Artist::read(&db, artist.id.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to read artist"))?;
        assert_eq!(read.song_count, 1);
        assert_eq!(read.runtime, song.runtime);

        Artist::remove_song(&db, artist.id.clone(), song.id.clone()).await?;
        let read = Artist::read(&db, artist.id.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to read artist"))?;
        assert_eq!(read.runtime, Duration::from_secs(0));
        assert_eq!(read.song_count, 0);

        Ok(())
    }

    #[tokio::test]
    async fn test_read_songs() -> Result<()> {
        let db = init_test_database().await?;
        let artist = create_artist();
        let album = Album {
            id: Album::generate_id(),
            title: "Test Album".into(),
            artist: artist.name.clone().into(),
            song_count: 4,
            runtime: Duration::from_secs(5),
            release: None,
            discs: 1,
            genre: OneOrMany::None,
        };
        // in an album by the artist
        let song1 = Song {
            id: Song::generate_id(),
            title: "Test Song 1".into(),
            artist: artist.name.clone().into(),
            album: "Test Album".into(),
            runtime: Duration::from_secs(5),
            track: Some(1),
            disc: Some(1),
            genre: OneOrMany::None,
            album_artist: artist.name.clone().into(),
            release_year: None,
            extension: "mp3".into(),
            path: PathBuf::from("song.mp3"),
        };
        // directly by the artist
        let song2 = Song {
            id: Song::generate_id(),
            title: "Test Song 2".into(),
            artist: artist.name.clone().into(),
            album: "Test Album".into(),
            runtime: Duration::from_secs(5),
            track: Some(2),
            disc: Some(1),
            genre: OneOrMany::None,
            album_artist: artist.name.clone().into(),
            release_year: None,
            extension: "mp3".into(),
            path: PathBuf::from("song_2.mp3"),
        };
        // both
        let song3 = Song {
            id: Song::generate_id(),
            title: "Test Song 3".into(),
            artist: artist.name.clone().into(),
            album: "Test Album".into(),
            runtime: Duration::from_secs(5),
            track: Some(3),
            disc: Some(1),
            genre: OneOrMany::None,
            album_artist: artist.name.clone().into(),
            release_year: None,
            extension: "mp3".into(),
            path: PathBuf::from("song_3.mp3"),
        };

        let _ = Artist::create(&db, artist.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create artist"))?;
        let _ = Album::create(&db, album.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create album"))?;
        let _ = Song::create(&db, song1.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create song"))?;
        let _ = Song::create(&db, song2.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create song"))?;
        let _ = Song::create(&db, song3.clone())
            .await?
            .ok_or_else(|| anyhow!("Failed to create song"))?;

        for song in [&song1, &song3] {
            Album::add_song(&db, album.id.clone(), song.id.clone()).await?;
        }

        Artist::add_album(&db, artist.id.clone(), album.id.clone()).await?;

        for song in [&song2, &song3] {
            Artist::add_song(&db, artist.id.clone(), song.id.clone()).await?;
        }

        let mut read = Artist::read_songs(&db, artist.id.clone()).await?;

        // we want to check that all the songs are there, but the order will be arbitrary.
        // so we'll just sort them by title and compare that way
        read.sort_by(|a, b| a.title.cmp(&b.title));
        assert_eq!(vec![song1, song2, song3], read);
        Ok(())
    }
}