-
-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathsqldb.py
2004 lines (1584 loc) · 57.6 KB
/
sqldb.py
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
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from typing import TypedDict, Optional, cast
import sqlalchemy as sql
from sqlalchemy.dialects.sqlite import insert as sqliteinsert
import json
import unicodedata
import math
from datetime import datetime
from threading import Lock
from ..pkg_global.conf import data_dir
from .dbcache import cached_wrapper, cached_wrapper_individual, invalidate_caches, invalidate_entity_cache
from . import exceptions as exc
from . import no_aux_mode
from doreah.logging import log
from doreah.regular import runhourly, runmonthly
##### DB Technical
DBTABLES = {
# name - type - foreign key - kwargs
'_maloja':{
'columns':[
("key", sql.String, {'primary_key':True}),
("value", sql.String, {})
],
'extraargs':(),'extrakwargs':{}
},
'scrobbles':{
'columns':[
("timestamp", sql.Integer, {'primary_key':True}),
("rawscrobble", sql.String, {}),
("origin", sql.String, {}),
("duration", sql.Integer, {}),
("track_id", sql.Integer, sql.ForeignKey('tracks.id'), {}),
("extra", sql.String, {})
],
'extraargs':(),'extrakwargs':{}
},
'tracks':{
'columns':[
("id", sql.Integer, {'primary_key':True}),
("title", sql.String, {}),
("title_normalized", sql.String, {}),
("length", sql.Integer, {}),
("album_id", sql.Integer, sql.ForeignKey('albums.id'), {})
],
'extraargs':(),'extrakwargs':{'sqlite_autoincrement':True}
},
'artists':{
'columns':[
("id", sql.Integer, {'primary_key':True}),
("name", sql.String, {}),
("name_normalized", sql.String, {})
],
'extraargs':(),'extrakwargs':{'sqlite_autoincrement':True}
},
'albums':{
'columns':[
("id", sql.Integer, {'primary_key':True}),
("albtitle", sql.String, {}),
("albtitle_normalized", sql.String, {})
#("albumartist", sql.String, {})
# when an album has no artists, always use 'Various Artists'
],
'extraargs':(),'extrakwargs':{'sqlite_autoincrement':True}
},
'trackartists':{
'columns':[
("id", sql.Integer, {'primary_key':True}),
("artist_id", sql.Integer, sql.ForeignKey('artists.id'), {}),
("track_id", sql.Integer, sql.ForeignKey('tracks.id'), {})
],
'extraargs':(sql.UniqueConstraint('artist_id', 'track_id'),),'extrakwargs':{}
},
'albumartists':{
'columns':[
("id", sql.Integer, {'primary_key':True}),
("artist_id", sql.Integer, sql.ForeignKey('artists.id'), {}),
("album_id", sql.Integer, sql.ForeignKey('albums.id'), {})
],
'extraargs':(sql.UniqueConstraint('artist_id', 'album_id'),),'extrakwargs':{}
},
# 'albumtracks':{
# # tracks can be in multiple albums
# 'columns':[
# ("id", sql.Integer, {'primary_key':True}),
# ("album_id", sql.Integer, sql.ForeignKey('albums.id'), {}),
# ("track_id", sql.Integer, sql.ForeignKey('tracks.id'), {})
# ],
# 'extraargs':(sql.UniqueConstraint('album_id', 'track_id'),),'extrakwargs':{}
# },
'associated_artists':{
'columns':[
("source_artist", sql.Integer, sql.ForeignKey('artists.id'), {}),
("target_artist", sql.Integer, sql.ForeignKey('artists.id'), {})
],
'extraargs':(sql.UniqueConstraint('source_artist', 'target_artist'),),'extrakwargs':{}
}
}
DB = {}
engine = sql.create_engine(f"sqlite:///{data_dir['scrobbles']('malojadb.sqlite')}", echo = False)
meta = sql.MetaData()
# create table definitions
for tablename in DBTABLES:
DB[tablename] = sql.Table(
tablename, meta,
*[sql.Column(colname,*args,**kwargs) for colname,*args,kwargs in DBTABLES[tablename]['columns']],
*DBTABLES[tablename]['extraargs'],
**DBTABLES[tablename]['extrakwargs']
)
# actually create tables for new databases
meta.create_all(engine)
# upgrade old database with new columns
with engine.begin() as conn:
for tablename in DBTABLES:
info = DBTABLES[tablename]
table = DB[tablename]
for colname,datatype,*args,kwargs in info['columns']:
try:
statement = f"ALTER TABLE {tablename} ADD {colname} {datatype().compile()}"
conn.execute(sql.text(statement))
log(f"Column {colname} was added to table {tablename}!")
# TODO figure out how to compile foreign key references!
except sql.exc.OperationalError as e:
pass
# adding a scrobble could consist of multiple write operations that sqlite doesn't
# see as belonging together
SCROBBLE_LOCK = Lock()
# decorator that passes either the provided dbconn, or creates a separate one
# just for this function call
def connection_provider(func):
def wrapper(*args,**kwargs):
if kwargs.get("dbconn") is not None:
return func(*args,**kwargs)
else:
with engine.connect() as connection:
with connection.begin():
kwargs['dbconn'] = connection
return func(*args,**kwargs)
wrapper.__innerfunc__ = func
wrapper.__name__ = f"CONPR_{func.__name__}"
return wrapper
@connection_provider
def get_maloja_info(keys,dbconn=None):
op = DB['_maloja'].select().where(
DB['_maloja'].c.key.in_(keys)
)
result = dbconn.execute(op).all()
info = {}
for row in result:
info[row.key] = row.value
return info
@connection_provider
def set_maloja_info(info,dbconn=None):
for k in info:
op = sqliteinsert(DB['_maloja']).values(
key=k, value=info[k]
).on_conflict_do_update(
index_elements=['key'],
set_={'value':info[k]}
)
dbconn.execute(op)
##### DB <-> Dict translations
## ATTENTION ALL ADVENTURERS
## this is what a scrobble dict will look like from now on
## this is the single canonical source of truth
## stop making different little dicts in every single function
## this is the schema that will definitely 100% stay like this and not
## randomly get changed two versions later
## here we go
#
# {
# "time":int,
# "track":{
# "artists":list,
# "title":string,
# "album":{
# "albumtitle":string,
# "artists":list
# },
# "length":None
# },
# "duration":int,
# "origin":string,
# "extra":{string-keyed mapping for all flags with the scrobble},
# "rawscrobble":{string-keyed mapping of the original scrobble received}
# }
#
# The last two fields are not returned under normal circumstances
class AlbumDict(TypedDict):
albumtitle: str
artists: list[str]
class TrackDict(TypedDict):
artists: list[str]
title: str
album: AlbumDict
length: int | None
class ScrobbleDict(TypedDict):
time: int
track: TrackDict
duration: int
origin: str
extra: Optional[dict]
rawscrobble: Optional[dict]
##### Conversions between DB and dicts
# These should work on whole lists and collect all the references,
# then look them up once and fill them in
### DB -> DICT
def scrobbles_db_to_dict(rows, include_internal=False, dbconn=None) -> list[ScrobbleDict]:
tracks: list[TrackDict] = get_tracks_map(set(row.track_id for row in rows), dbconn=dbconn)
return [
cast(ScrobbleDict, {
**{
"time": row.timestamp,
"track": tracks[row.track_id],
"duration": row.duration,
"origin": row.origin
},
**({
"extra": json.loads(row.extra or '{}'),
"rawscrobble": json.loads(row.rawscrobble or '{}')
} if include_internal else {})
})
for row in rows
]
def scrobble_db_to_dict(row, dbconn=None) -> ScrobbleDict:
return scrobbles_db_to_dict([row], dbconn=dbconn)[0]
def tracks_db_to_dict(rows, dbconn=None) -> list[TrackDict]:
artists = get_artists_of_tracks(set(row.id for row in rows), dbconn=dbconn)
albums = get_albums_map(set(row.album_id for row in rows), dbconn=dbconn)
return [
cast(TrackDict, {
"artists":artists[row.id],
"title":row.title,
"album":albums.get(row.album_id),
"length":row.length
})
for row in rows
]
def track_db_to_dict(row, dbconn=None) -> TrackDict:
return tracks_db_to_dict([row], dbconn=dbconn)[0]
def artists_db_to_dict(rows, dbconn=None) -> list[str]:
return [
row.name
for row in rows
]
def artist_db_to_dict(row, dbconn=None) -> str:
return artists_db_to_dict([row], dbconn=dbconn)[0]
def albums_db_to_dict(rows, dbconn=None) -> list[AlbumDict]:
artists = get_artists_of_albums(set(row.id for row in rows), dbconn=dbconn)
return [
cast(AlbumDict, {
"artists": artists.get(row.id),
"albumtitle": row.albtitle,
})
for row in rows
]
def album_db_to_dict(row, dbconn=None) -> AlbumDict:
return albums_db_to_dict([row], dbconn=dbconn)[0]
### DICT -> DB
# These should return None when no data is in the dict so they can be used for update statements
def scrobble_dict_to_db(info: ScrobbleDict, update_album=False, dbconn=None):
return {
"timestamp": info.get('time'),
"origin": info.get('origin'),
"duration": info.get('duration'),
"track_id": get_track_id(info.get('track'), update_album=update_album, dbconn=dbconn),
"extra": json.dumps(info.get('extra')) if info.get('extra') else None,
"rawscrobble": json.dumps(info.get('rawscrobble')) if info.get('rawscrobble') else None
}
def track_dict_to_db(info: TrackDict, dbconn=None):
return {
"title": info.get('title'),
"title_normalized": normalize_name(info.get('title', '')) or None,
"length": info.get('length')
}
def artist_dict_to_db(info: str, dbconn=None):
return {
"name": info,
"name_normalized": normalize_name(info)
}
def album_dict_to_db(info: AlbumDict, dbconn=None):
return {
"albtitle": info.get('albumtitle'),
"albtitle_normalized": normalize_name(info.get('albumtitle'))
}
##### Actual Database interactions
# TODO: remove all resolve_id args and do that logic outside the caching to improve hit chances
# TODO: maybe also factor out all intitial get entity funcs (some here, some in __init__) and throw exceptions
@connection_provider
def add_scrobble(scrobbledict: ScrobbleDict, update_album=False, dbconn=None):
_, ex, er = add_scrobbles([scrobbledict], update_album=update_album, dbconn=dbconn)
if er > 0:
raise exc.DuplicateTimestamp(existing_scrobble=None, rejected_scrobble=scrobbledict)
# TODO: actually pass existing scrobble
elif ex > 0:
raise exc.DuplicateScrobble(scrobble=scrobbledict)
@connection_provider
def add_scrobbles(scrobbleslist: list[ScrobbleDict], update_album=False, dbconn=None) -> tuple[int, int, int]:
with SCROBBLE_LOCK:
# ops = [
# DB['scrobbles'].insert().values(
# **scrobble_dict_to_db(s,update_album=update_album,dbconn=dbconn)
# ) for s in scrobbleslist
# ]
success, exists, errors = 0, 0, 0
for s in scrobbleslist:
scrobble_entry = scrobble_dict_to_db(s, update_album=update_album, dbconn=dbconn)
try:
dbconn.execute(DB['scrobbles'].insert().values(
**scrobble_entry
))
success += 1
except sql.exc.IntegrityError:
# get existing scrobble
result = dbconn.execute(DB['scrobbles'].select().where(
DB['scrobbles'].c.timestamp == scrobble_entry['timestamp']
)).first()
if result.track_id == scrobble_entry['track_id']:
exists += 1
else:
errors += 1
if errors > 0: log(f"{errors} Scrobbles have not been written to database (duplicate timestamps)!", color='red')
if exists > 0: log(f"{exists} Scrobbles have not been written to database (already exist)", color='orange')
return success, exists, errors
@connection_provider
def delete_scrobble(scrobble_id: int, dbconn=None) -> bool:
with SCROBBLE_LOCK:
op = DB['scrobbles'].delete().where(
DB['scrobbles'].c.timestamp == scrobble_id
)
result = dbconn.execute(op)
return True
@connection_provider
def add_track_to_album(track_id: int, album_id: int, replace=False, dbconn=None) -> bool:
conditions = [
DB['tracks'].c.id == track_id
]
if not replace:
# if we dont want replacement, just update if there is no album yet
conditions.append(
DB['tracks'].c.album_id == None
)
op = DB['tracks'].update().where(
*conditions
).values(
album_id=album_id
)
result = dbconn.execute(op)
invalidate_entity_cache() # because album info has changed
#invalidate_caches() # changing album info of tracks will change album charts
# ARE YOU FOR REAL
# it just took me like 3 hours to figure out that this one line makes the artist page load slow because
# we call this func with every new scrobble that contains album info, even if we end up not changing the album
# of course i was always debugging with the manual scrobble button which just doesnt send any album info
# and because we expel all caches every single time, the artist page then needs to recalculate the weekly charts of
# ALL OF RECORDED HISTORY in order to display top weeks
# lmao
# TODO: figure out something better
return True
@connection_provider
def add_tracks_to_albums(track_to_album_id_dict: dict[int, int], replace=False, dbconn=None) -> bool:
for track_id in track_to_album_id_dict:
add_track_to_album(track_id,track_to_album_id_dict[track_id], replace=replace, dbconn=dbconn)
return True
@connection_provider
def remove_album(*track_ids: list[int], dbconn=None) -> bool:
DB['tracks'].update().where(
DB['tracks'].c.track_id.in_(track_ids)
).values(
album_id=None
)
return True
### these will 'get' the ID of an entity, creating it if necessary
@cached_wrapper
@connection_provider
def get_track_id(trackdict: TrackDict, create_new=True, update_album=False, dbconn=None) -> int | None:
ntitle = normalize_name(trackdict['title'])
artist_ids = [get_artist_id(a, create_new=create_new, dbconn=dbconn) for a in trackdict['artists']]
artist_ids = list(set(artist_ids))
op = DB['tracks'].select().where(
DB['tracks'].c.title_normalized == ntitle
)
result = dbconn.execute(op).all()
for row in result:
# check if the artists are the same
foundtrackartists = []
op = DB['trackartists'].select(
# DB['trackartists'].c.artist_id
).where(
DB['trackartists'].c.track_id == row.id
)
result = dbconn.execute(op).all()
match_artist_ids = [r.artist_id for r in result]
#print("required artists",artist_ids,"this match",match_artist_ids)
if set(artist_ids) == set(match_artist_ids):
#print("ID for",trackdict['title'],"was",row[0])
if trackdict.get('album') and create_new:
# if we don't supply create_new, it means we just want to get info about a track
# which means no need to write album info, even if it was new
# if we havent set update_album, we only want to assign the album in case the track
# has no album yet. this means we also only want to create a potentially new album in that case
album_id = get_album_id(trackdict['album'],create_new=(update_album or not row.album_id),dbconn=dbconn)
add_track_to_album(row.id,album_id,replace=update_album,dbconn=dbconn)
return row.id
if not create_new:
return None
#print("Creating new track")
op = DB['tracks'].insert().values(
**track_dict_to_db(trackdict, dbconn=dbconn)
)
result = dbconn.execute(op)
track_id = result.inserted_primary_key[0]
#print(track_id)
for artist_id in artist_ids:
op = DB['trackartists'].insert().values(
track_id=track_id,
artist_id=artist_id
)
result = dbconn.execute(op)
#print("Created",trackdict['title'],track_id)
if trackdict.get('album'):
add_track_to_album(track_id, get_album_id(trackdict['album'], dbconn=dbconn), dbconn=dbconn)
return track_id
@cached_wrapper
@connection_provider
def get_artist_id(artistname: str, create_new=True, dbconn=None) -> int | None:
nname = normalize_name(artistname)
#print("looking for",nname)
op = DB['artists'].select().where(
DB['artists'].c.name_normalized == nname
)
result = dbconn.execute(op).all()
for row in result:
#print("ID for",artistname,"was",row[0])
return row.id
if not create_new:
return None
op = DB['artists'].insert().values(
name=artistname,
name_normalized=nname
)
result = dbconn.execute(op)
#print("Created",artistname,result.inserted_primary_key)
return result.inserted_primary_key[0]
@cached_wrapper
@connection_provider
def get_album_id(albumdict: AlbumDict, create_new=True, ignore_albumartists=False, dbconn=None) -> int | None:
ntitle = normalize_name(albumdict['albumtitle'])
artist_ids = [get_artist_id(a, dbconn=dbconn) for a in (albumdict.get('artists') or [])]
artist_ids = list(set(artist_ids))
op = DB['albums'].select(
# DB['albums'].c.id
).where(
DB['albums'].c.albtitle_normalized == ntitle
)
result = dbconn.execute(op).all()
for row in result:
if ignore_albumartists:
return row.id
else:
# check if the artists are the same
foundtrackartists = []
op = DB['albumartists'].select(
# DB['albumartists'].c.artist_id
).where(
DB['albumartists'].c.album_id == row.id
)
result = dbconn.execute(op).all()
match_artist_ids = [r.artist_id for r in result]
#print("required artists",artist_ids,"this match",match_artist_ids)
if set(artist_ids) == set(match_artist_ids):
#print("ID for",albumdict['title'],"was",row[0])
return row.id
if not create_new:
return None
op = DB['albums'].insert().values(
**album_dict_to_db(albumdict, dbconn=dbconn)
)
result = dbconn.execute(op)
album_id = result.inserted_primary_key[0]
for artist_id in artist_ids:
op = DB['albumartists'].insert().values(
album_id=album_id,
artist_id=artist_id
)
result = dbconn.execute(op)
#print("Created",trackdict['title'],track_id)
return album_id
### Edit existing
@connection_provider
def edit_scrobble(scrobble_id: int, scrobbleupdatedict: dict, dbconn=None) -> bool:
dbentry = scrobble_dict_to_db(scrobbleupdatedict,dbconn=dbconn)
dbentry = {k: v for k, v in dbentry.items() if v}
print("Updating scrobble", dbentry)
with SCROBBLE_LOCK:
op = DB['scrobbles'].update().where(
DB['scrobbles'].c.timestamp == scrobble_id
).values(
**dbentry
)
dbconn.execute(op)
return True
# edit function only for primary db information (not linked fields)
@connection_provider
def edit_artist(artist_id: int, artistupdatedict: str, dbconn=None) -> bool:
artist = get_artist(artist_id)
changedartist = artistupdatedict # well
dbentry = artist_dict_to_db(artistupdatedict, dbconn=dbconn)
dbentry = {k: v for k, v in dbentry.items() if v}
existing_artist_id = get_artist_id(changedartist, create_new=False, dbconn=dbconn)
if existing_artist_id not in (None, artist_id):
raise exc.ArtistExists(changedartist)
op = DB['artists'].update().where(
DB['artists'].c.id == artist_id
).values(
**dbentry
)
result = dbconn.execute(op)
return True
# edit function only for primary db information (not linked fields)
@connection_provider
def edit_track(track_id: int, trackupdatedict: dict, dbconn=None) -> bool:
track = get_track(track_id, dbconn=dbconn)
changedtrack: TrackDict = {**track, **trackupdatedict}
dbentry = track_dict_to_db(trackupdatedict, dbconn=dbconn)
dbentry = {k: v for k, v in dbentry.items() if v}
existing_track_id = get_track_id(changedtrack, create_new=False, dbconn=dbconn)
if existing_track_id not in (None, track_id):
raise exc.TrackExists(changedtrack)
op = DB['tracks'].update().where(
DB['tracks'].c.id == track_id
).values(
**dbentry
)
result = dbconn.execute(op)
return True
# edit function only for primary db information (not linked fields)
@connection_provider
def edit_album(album_id: int, albumupdatedict: dict, dbconn=None) -> bool:
album = get_album(album_id, dbconn=dbconn)
changedalbum: AlbumDict = {**album, **albumupdatedict}
dbentry = album_dict_to_db(albumupdatedict, dbconn=dbconn)
dbentry = {k: v for k, v in dbentry.items() if v}
existing_album_id = get_album_id(changedalbum, create_new=False, dbconn=dbconn)
if existing_album_id not in (None, album_id):
raise exc.TrackExists(changedalbum)
op = DB['albums'].update().where(
DB['albums'].c.id == album_id
).values(
**dbentry
)
result = dbconn.execute(op)
return True
### Edit associations
@connection_provider
def add_artists_to_tracks(track_ids: list[int], artist_ids: list[int], dbconn=None) -> bool:
op = DB['trackartists'].insert().values([
{'track_id': track_id, 'artist_id': artist_id}
for track_id in track_ids for artist_id in artist_ids
])
result = dbconn.execute(op)
# the resulting tracks could now be duplicates of existing ones
# this also takes care of clean_db
merge_duplicate_tracks(dbconn=dbconn)
return True
@connection_provider
def remove_artists_from_tracks(track_ids: list[int], artist_ids: list[int], dbconn=None) -> bool:
# only tracks that have at least one other artist
subquery = DB['trackartists'].select().where(
~DB['trackartists'].c.artist_id.in_(artist_ids)
).with_only_columns(
DB['trackartists'].c.track_id
).distinct().alias('sub')
op = DB['trackartists'].delete().where(
sql.and_(
DB['trackartists'].c.track_id.in_(track_ids),
DB['trackartists'].c.artist_id.in_(artist_ids),
DB['trackartists'].c.track_id.in_(subquery.select())
)
)
result = dbconn.execute(op)
# the resulting tracks could now be duplicates of existing ones
# this also takes care of clean_db
merge_duplicate_tracks(dbconn=dbconn)
return True
@connection_provider
def add_artists_to_albums(album_ids: list[int], artist_ids: list[int], dbconn=None) -> bool:
op = DB['albumartists'].insert().values([
{'album_id':album_id,'artist_id':artist_id}
for album_id in album_ids for artist_id in artist_ids
])
result = dbconn.execute(op)
# the resulting albums could now be duplicates of existing ones
# this also takes care of clean_db
merge_duplicate_albums(dbconn=dbconn)
return True
@connection_provider
def remove_artists_from_albums(album_ids: list[int], artist_ids: list[int], dbconn=None) -> bool:
# no check here, albums are allowed to have zero artists
op = DB['albumartists'].delete().where(
sql.and_(
DB['albumartists'].c.album_id.in_(album_ids),
DB['albumartists'].c.artist_id.in_(artist_ids)
)
)
result = dbconn.execute(op)
# the resulting albums could now be duplicates of existing ones
# this also takes care of clean_db
merge_duplicate_albums(dbconn=dbconn)
return True
### Merge
@connection_provider
def merge_tracks(target_id: int, source_ids: list[int], dbconn=None) -> bool:
op = DB['scrobbles'].update().where(
DB['scrobbles'].c.track_id.in_(source_ids)
).values(
track_id=target_id
)
result = dbconn.execute(op)
clean_db(dbconn=dbconn)
return True
@connection_provider
def merge_artists(target_id: int, source_ids: list[int], dbconn=None) -> bool:
# some tracks could already have multiple of the to be merged artists
# find literally all tracksartist entries that have any of the artists involved
op = DB['trackartists'].select().where(
DB['trackartists'].c.artist_id.in_(source_ids + [target_id])
)
result = dbconn.execute(op)
track_ids = set(row.track_id for row in result)
# now just delete them all lmao
op = DB['trackartists'].delete().where(
#DB['trackartists'].c.track_id.in_(track_ids),
DB['trackartists'].c.artist_id.in_(source_ids + [target_id]),
)
result = dbconn.execute(op)
# now add back the real new artist
op = DB['trackartists'].insert().values([
{'track_id':track_id,'artist_id':target_id}
for track_id in track_ids
])
result = dbconn.execute(op)
# same for albums
op = DB['albumartists'].select().where(
DB['albumartists'].c.artist_id.in_(source_ids + [target_id])
)
result = dbconn.execute(op)
album_ids = set(row.album_id for row in result)
op = DB['albumartists'].delete().where(
DB['albumartists'].c.artist_id.in_(source_ids + [target_id]),
)
result = dbconn.execute(op)
op = DB['albumartists'].insert().values([
{'album_id':album_id,'artist_id':target_id}
for album_id in album_ids
])
result = dbconn.execute(op)
# tracks_artists = {}
# for row in result:
# tracks_artists.setdefault(row.track_id,[]).append(row.artist_id)
#
# multiple = {k:v for k,v in tracks_artists.items() if len(v) > 1}
#
# print([(get_track(k),[get_artist(a) for a in v]) for k,v in multiple.items()])
#
# op = DB['trackartists'].update().where(
# DB['trackartists'].c.artist_id.in_(source_ids)
# ).values(
# artist_id=target_id
# )
# result = dbconn.execute(op)
# this could have created duplicate tracks and albums
merge_duplicate_tracks(artist_id=target_id, dbconn=dbconn)
merge_duplicate_albums(artist_id=target_id, dbconn=dbconn)
clean_db(dbconn=dbconn)
return True
@connection_provider
def merge_albums(target_id: int, source_ids: list[int], dbconn=None) -> bool:
op = DB['tracks'].update().where(
DB['tracks'].c.album_id.in_(source_ids)
).values(
album_id=target_id
)
result = dbconn.execute(op)
clean_db(dbconn=dbconn)
return True
### Functions that get rows according to parameters
@cached_wrapper
@connection_provider
def get_scrobbles_of_artist(artist,since=None,to=None,resolve_references=True,limit=None,reverse=False,associated=False,dbconn=None):
if since is None: since=0
if to is None: to=now()
if associated:
artist_ids = get_associated_artists(artist,resolve_ids=False,dbconn=dbconn) + [get_artist_id(artist,create_new=False,dbconn=dbconn)]
else:
artist_ids = [get_artist_id(artist,create_new=False,dbconn=dbconn)]
jointable = sql.join(DB['scrobbles'],DB['trackartists'],DB['scrobbles'].c.track_id == DB['trackartists'].c.track_id)
op = jointable.select().where(
DB['scrobbles'].c.timestamp.between(since,to),
DB['trackartists'].c.artist_id.in_(artist_ids)
)
if reverse:
op = op.order_by(sql.desc('timestamp'))
else:
op = op.order_by(sql.asc('timestamp'))
if limit and not associated:
# if we count associated we cant limit here because we remove stuff later!
op = op.limit(limit)
result = dbconn.execute(op).all()
# remove duplicates (multiple associated artists in the song, e.g. Irene & Seulgi being both counted as Red Velvet)
# distinct on doesn't seem to exist in sqlite
if associated:
seen = set()
filtered_result = []
for row in result:
if row.timestamp not in seen:
filtered_result.append(row)
seen.add(row.timestamp)
result = filtered_result
if limit:
result = result[:limit]
if resolve_references:
result = scrobbles_db_to_dict(result,dbconn=dbconn)
#result = [scrobble_db_to_dict(row,resolve_references=resolve_references) for row in result]
return result
@cached_wrapper
@connection_provider
def get_scrobbles_of_track(track,since=None,to=None,resolve_references=True,limit=None,reverse=False,dbconn=None):
if since is None: since=0
if to is None: to=now()
track_id = get_track_id(track,create_new=False,dbconn=dbconn)
op = DB['scrobbles'].select().where(
DB['scrobbles'].c.timestamp<=to,
DB['scrobbles'].c.timestamp>=since,
DB['scrobbles'].c.track_id==track_id
)
if reverse:
op = op.order_by(sql.desc('timestamp'))
else:
op = op.order_by(sql.asc('timestamp'))
if limit:
op = op.limit(limit)
result = dbconn.execute(op).all()
if resolve_references:
result = scrobbles_db_to_dict(result)
#result = [scrobble_db_to_dict(row) for row in result]
return result
@cached_wrapper
@connection_provider
def get_scrobbles_of_album(album,since=None,to=None,resolve_references=True,limit=None,reverse=False,dbconn=None):
if since is None: since=0
if to is None: to=now()
album_id = get_album_id(album,create_new=False,dbconn=dbconn)
jointable = sql.join(DB['scrobbles'],DB['tracks'],DB['scrobbles'].c.track_id == DB['tracks'].c.id)
op = jointable.select().where(
DB['scrobbles'].c.timestamp<=to,
DB['scrobbles'].c.timestamp>=since,
DB['tracks'].c.album_id==album_id
)
if reverse:
op = op.order_by(sql.desc('timestamp'))
else:
op = op.order_by(sql.asc('timestamp'))
if limit:
op = op.limit(limit)
result = dbconn.execute(op).all()
if resolve_references:
result = scrobbles_db_to_dict(result)
#result = [scrobble_db_to_dict(row) for row in result]
return result
@cached_wrapper
@connection_provider
def get_scrobbles(since=None,to=None,resolve_references=True,limit=None,reverse=False,dbconn=None):
if since is None: since=0
if to is None: to=now()
op = DB['scrobbles'].select().where(
DB['scrobbles'].c.timestamp.between(since,to)
)
if reverse:
op = op.order_by(sql.desc('timestamp'))
else:
op = op.order_by(sql.asc('timestamp'))
if limit:
op = op.limit(limit)
result = dbconn.execute(op).all()