-
Notifications
You must be signed in to change notification settings - Fork 21
/
database.py
2465 lines (2078 loc) · 86.9 KB
/
database.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
# -*- coding: utf-8 -*-
# Author: Dylan Jones
# Date: 2023-08-13
import logging
import datetime
import secrets
from uuid import uuid4
from pathlib import Path
from typing import Optional, Union
from sqlalchemy import create_engine, or_, event, MetaData, select
from sqlalchemy.orm import Session, Query
from sqlalchemy.exc import NoResultFound
from sqlalchemy.sql.sqltypes import DateTime, String
from ..utils import get_rekordbox_pid, warn_deprecated
from ..config import get_config
from ..anlz import get_anlz_paths, read_anlz_files
from .registry import RekordboxAgentRegistry
from .aux_files import MasterPlaylistXml
from .tables import DjmdContent, PlaylistType
from .smartlist import SmartList
from . import tables
try:
from sqlcipher3 import dbapi2 as sqlite3 # noqa
_sqlcipher_available = True
except ImportError:
import sqlite3
_sqlcipher_available = False
MAX_VERSION = "6.6.5"
logger = logging.getLogger(__name__)
class NoCachedKey(Exception):
pass
def open_rekordbox_database(path=None, key="", unlock=True, sql_driver=None):
"""Opens a connection to the Rekordbox v6 master.db SQLite3 database.
Parameters
----------
path : str or Path, optional
The path of the Rekordbox v6 database file. By default, pyrekordbox
automatically finds the Rekordbox v6 master.db database file.
This parameter is only required for opening other databases or if the
configuration fails.
key : str, optional
The database key. By default, pyrekordbox automatically reads the database
key from the Rekordbox v6 configuration file. This parameter is only required
if the key extraction fails.
unlock: bool, optional
Flag if the database needs to be decrypted. Set to False if you are opening
an unencrypted test database.
sql_driver : Callable, optional
The SQLite driver to used for opening the database. The standard ``sqlite3``
package is used as default driver.
Returns
-------
con : sql_driver.Connection
The opened Rekordbox v6 database connection.
Examples
--------
Open the Rekordbox v6 master.db database:
>>> db = open_rekordbox_database()
Open a copy of the database:
>>> db = open_rekordbox_database("path/to/master_copy.db")
Open a decrypted copy of the database:
>>> db = open_rekordbox_database("path/to/master_unlocked.db", unlock=False)
To use the ``pysqlcipher3`` package as SQLite driver, either import it as
>>> from sqlcipher3 import dbapi2 as sqlite3 # noqa
>>> db = open_rekordbox_database("path/to/master_copy.db")
or supply the package as driver:
>>> from sqlcipher3 import dbapi2 # noqa
>>> db = open_rekordbox_database("path/to/master_copy.db", sql_driver=dbapi2)
"""
warn_deprecated("open_rekordbox_database", remove_in="0.4.0")
rb6_config = get_config("rekordbox6")
if not path:
path = rb6_config["db_path"]
path = Path(path)
if not path.exists():
raise FileNotFoundError(f"File '{path}' does not exist!")
logger.info("Opening %s", path)
# Open database
if sql_driver is None:
# Use default sqlite3 package
# This requires that the 'sqlite3.dll' was replaced by the 'sqlcipher.dll'
sql_driver = sqlite3
con = sql_driver.connect(str(path))
if unlock:
if not key:
try:
key = rb6_config["dp"]
except KeyError:
raise NoCachedKey(
"Could not unlock database: No key found\n"
f"If you are using Rekordbox>{MAX_VERSION} the key can not be "
f"extracted automatically!\n"
"Please use the CLI of pyrekordbox to download the key or "
"use the `key` parameter to manually provide the database key."
)
logger.info("Key: %s", key)
# Unlock database
con.execute(f"PRAGMA key='{key}'")
# Check connection
try:
con.execute("SELECT name FROM sqlite_master WHERE type='table';")
except sqlite3.DatabaseError as e:
msg = f"Opening database failed: '{e}'. Check if the database key is correct!"
raise sqlite3.DatabaseError(msg)
else:
logger.info("Database unlocked!")
return con
def _parse_query_result(query, kwargs):
if "ID" in kwargs or "registry_id" in kwargs:
try:
query = query.one()
except NoResultFound:
return None
return query
class Rekordbox6Database:
"""Rekordbox v6 master.db database handler.
Parameters
----------
path : str or Path, optional
The path of the Rekordbox v6 database file. By default, pyrekordbox
automatically finds the Rekordbox v6 master.db database file.
This parameter is only required for opening other databases or if the
configuration fails.
db_dir: str, optional
The path of the Rekordbox v6 database directory. By default, pyrekordbox
automatically finds the Rekordbox v6 database directory. Usually this is also
the root directory of the analysis files. This parameter is only required for
finding the analysis root directory if you are opening a database, that is
stored somewhere else.
key : str, optional
The database key. By default, pyrekordbox automatically reads the database
key from the Rekordbox v6 configuration file. This parameter is only required
if the key extraction fails.
unlock: bool, optional
Flag if the database needs to be decrypted. Set to False if you are opening
an unencrypted test database.
Attributes
----------
engine : sqlalchemy.engine.Engine
The SQLAlchemy engine instance for the Rekordbox v6 database.
session : sqlalchemy.orm.Session
The SQLAlchemy session instance bound to the engine.
See Also
--------
pyrekordbox.db6.tables: Rekordbox v6 database table definitions
create_rekordbox_engine: Creates the SQLAlchemy engine for the Rekordbox v6 database
Examples
--------
Pyrekordbox automatically finds the Rekordbox v6 master.db database file and
opens it when initializing the object:
>>> db = Rekordbox6Database()
Use the included getters for querying the database:
>>> db.get_content()[0]
<DjmdContent(40110712 Title=NOISE)>
"""
def __init__(self, path=None, db_dir="", key="", unlock=True):
rb6_config = get_config("rekordbox6")
pid = get_rekordbox_pid()
if pid:
logger.warning("Rekordbox is running!")
if not path:
# Get path from the RB config
path = rb6_config.get("db_path", "")
if not path:
pdir = get_config("pioneer", "install_dir")
raise FileNotFoundError(f"No Rekordbox v6 directory found in '{pdir}'")
path = Path(path)
# make sure file exists
if not path.exists():
raise FileNotFoundError(f"File '{path}' does not exist!")
# Open database
if unlock:
if not _sqlcipher_available:
raise ImportError(
"Could not unlock database: 'sqlcipher3' package not found"
)
if not key:
try:
key = rb6_config["dp"]
except KeyError:
raise NoCachedKey(
"Could not unlock database: No key found\n"
f"If you are using Rekordbox>{MAX_VERSION} the key cannot be "
f"extracted automatically!\n"
"Please use the CLI of pyrekordbox to download the key or "
"use the `key` parameter to manually provide it."
)
else:
# Check if key looks like a valid key
if not key.startswith("402fd"):
raise ValueError("The provided database key doesn't look valid!")
logger.info("Key: %s", key)
# Unlock database and create engine
url = f"sqlite+pysqlcipher://:{key}@/{path}?"
engine = create_engine(url, module=sqlite3)
else:
engine = create_engine(f"sqlite:///{path}")
if not db_dir:
db_dir = path.parent
db_dir = Path(db_dir)
if not db_dir.exists():
raise FileNotFoundError(f"Database directory '{db_dir}' does not exist!")
self.engine = engine
self.session: Optional[Session] = None
self.registry = RekordboxAgentRegistry(self)
self._events = dict()
try:
self.playlist_xml = MasterPlaylistXml(db_dir=db_dir)
except FileNotFoundError:
logger.warning(f"No masterPlaylists6.xml found in {db_dir}")
self.playlist_xml = None
self._db_dir = db_dir
self._share_dir = db_dir / "share"
self.open()
@property
def no_autoflush(self):
"""Creates a no-autoflush context."""
return self.session.no_autoflush
@property
def db_directory(self):
return self._db_dir
@property
def share_directory(self):
return self._share_dir
def open(self):
"""Open the database by instantiating a new session using the SQLAchemy engine.
A new session instance is only created if the session was closed previously.
Examples
--------
>>> db = Rekordbox6Database()
>>> db.close()
>>> db.open()
"""
if self.session is None:
self.session = Session(bind=self.engine)
self.registry.clear_buffer()
def close(self):
"""Close the currently active session."""
for key in self._events:
self.unregister_event(key)
self.registry.clear_buffer()
self.session.close()
self.session = None
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def register_event(self, identifier, fn):
"""Registers a session event callback.
Parameters
----------
identifier : str
The identifier of the event, for example 'before_flush', 'after_commit', ...
See the SQLAlchemy documentation for a list of valid event identifiers.
fn : callable
The event callback method.
"""
event.listen(self.session, identifier, fn)
self._events[identifier] = fn
def unregister_event(self, identifier):
"""Removes an existing session event callback.
Parameters
----------
identifier : str
The identifier of the event
"""
fn = self._events[identifier]
event.remove(self.session, identifier, fn)
def query(self, *entities, **kwargs):
"""Creates a new SQL query for the given entities.
Parameters
----------
*entities : Base
The table objects for which the query is created.
**kwargs
Arbitrary keyword arguments used for creating the query.
Returns
-------
query : sqlalchemy.orm.query.Query
The SQLAlchemy ``Query`` object.
Examples
--------
Query the ``DjmdContent`` table
>>> db = Rekordbox6Database()
>>> query = db.query(DjmdContent)
Query the `Title` attribute of the ``DjmdContent`` table
>>> db = Rekordbox6Database()
>>> query = db.query(DjmdContent.Title)
"""
return self.session.query(*entities, **kwargs)
def add(self, instance):
"""Add an element to the Rekordbox database.
Parameters
----------
instance : tables.Base
The table entry to add.
"""
self.session.add(instance)
self.registry.on_create(instance)
def delete(self, instance):
"""Delete an element from the Rekordbox database.
Parameters
----------
instance : tables.Base
The table entry to delte.
"""
self.session.delete(instance)
self.registry.on_delete(instance)
def get_local_usn(self):
"""Returns the local sequence number (update count) of Rekordbox.
Any changes made to the `Djmd...` tables increments the local update count of
Rekordbox. The ``usn`` entry of the changed row is set to the corresponding
update count.
Returns
-------
usn : int
The value of the local update count.
"""
return self.registry.get_local_update_count()
def set_local_usn(self, usn):
"""Sets the local sequence number (update count) of Rekordbox.
Parameters
----------
usn : int or str
The new update sequence number.
"""
self.registry.set_local_update_count(usn)
def increment_local_usn(self, num=1):
"""Increments the local update sequence number (update count) of Rekordbox.
Parameters
----------
num : int, optional
The number of times to increment the update counter. By default, the counter
is incremented by 1.
Returns
-------
usn : int
The value of the incremented local update count.
Examples
--------
>>> db = Rekordbox6Database()
>>> db.get_local_usn()
70500
>>> db.increment_local_usn()
70501
>>> db.get_local_usn()
70501
"""
return self.registry.increment_local_update_count(num)
def autoincrement_usn(self, set_row_usn=True):
"""Auto-increments the local USN for all uncommited changes.
Parameters
----------
set_row_usn : bool, optional
If True, set the ``rb_local_usn`` value of updated or added rows according
to the uncommited update sequence.
Returns
-------
new_usn : int
The new local update sequence number after applying all updates.
Examples
--------
>>> db = Rekordbox6Database()
>>> db.get_local_usn()
70500
>>> content = db.get_content().first()
>>> playlist = db.get_playlist().first()
>>> content.Title = "New Title"
>>> playlist.Name = "New Name"
>>> db.autoincrement_usn(set_row_usn=True)
>>> db.get_local_usn()
70502
"""
return self.registry.autoincrement_local_update_count(set_row_usn)
def flush(self):
"""Flushes the buffer of the SQLAlchemy session instance."""
self.session.flush()
def commit(self, autoinc=True):
"""Commit the changes made to the database.
Parameters
----------
autoinc : bool, optional
If True, auto-increment the local and row USN's before commiting the
changes made to the database.
See Also
--------
autoincrement_usn : Auto-increments the local Rekordbox USN's.
"""
pid = get_rekordbox_pid()
if pid:
raise RuntimeError(
"Rekordbox is running. Please close Rekordbox before commiting changes."
)
if autoinc:
self.registry.autoincrement_local_update_count(set_row_usn=True)
self.session.commit()
self.registry.clear_buffer()
# Update the masterPlaylists6.xml file
if self.playlist_xml is not None:
# Sync the updated_at values of the playlists in the DB and the XML file
for pl in self.get_playlist():
plxml = self.playlist_xml.get(pl.ID)
if plxml is None:
raise ValueError(
f"Playlist {pl.ID} not found in masterPlaylists6.xml! "
"Did you add it manually? "
"Use the create_playlist method instead."
)
ts = plxml["Timestamp"]
diff = pl.updated_at - ts
if abs(diff.total_seconds()) > 1:
logger.debug("Updating updated_at of playlist %s in XML", pl.ID)
self.playlist_xml.update(pl.ID, updated_at=pl.updated_at)
# Save the XML file if it was modified
if self.playlist_xml.modified:
self.playlist_xml.save()
def rollback(self):
"""Rolls back the uncommited changes to the database."""
self.session.rollback()
self.registry.clear_buffer()
# -- Table queries -----------------------------------------------------------------
def get_active_censor(self, **kwargs):
"""Creates a filtered query for the ``DjmdActiveCensor`` table."""
query = self.query(tables.DjmdActiveCensor).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_album(self, **kwargs):
"""Creates a filtered query for the ``DjmdAlbum`` table."""
query = self.query(tables.DjmdAlbum).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_artist(self, **kwargs):
"""Creates a filtered query for the ``DjmdArtist`` table."""
query = self.query(tables.DjmdArtist).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_category(self, **kwargs):
"""Creates a filtered query for the ``DjmdCategory`` table."""
query = self.query(tables.DjmdCategory).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_color(self, **kwargs):
"""Creates a filtered query for the ``DjmdColor`` table."""
query = self.query(tables.DjmdColor).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_content(self, **kwargs):
"""Creates a filtered query for the ``DjmdContent`` table."""
query = self.query(tables.DjmdContent).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
# noinspection PyUnresolvedReferences
def search_content(self, text):
"""Searches the contents of the ``DjmdContent`` table.
The search is case-insensitive and includes the following collumns of the
``DjmdContent`` table:
- `Album`
- `Artist`
- `Commnt`
- `Composer`
- `Genre`
- `Key`
- `OrgArtist`
- `Remixer`
Parameters
----------
text : str
The search text.
Returns
-------
results : list[DjmdContent]
The resulting content elements.
"""
# Search standard columns
query = self.query(tables.DjmdContent).filter(
or_(
DjmdContent.Title.contains(text),
DjmdContent.Commnt.contains(text),
DjmdContent.SearchStr.contains(text),
)
)
results = set(query.all())
# Search artist (Artist, OrgArtist, Composer and Remixer)
artist_attrs = ["Artist", "OrgArtist", "Composer", "Remixer"]
for attr in artist_attrs:
query = self.query(DjmdContent).join(getattr(DjmdContent, attr))
results.update(query.filter(tables.DjmdArtist.Name.contains(text)).all())
# Search album
query = self.query(DjmdContent).join(DjmdContent.Album)
results.update(query.filter(tables.DjmdAlbum.Name.contains(text)).all())
# Search Genre
query = self.query(DjmdContent).join(DjmdContent.Genre)
results.update(query.filter(tables.DjmdGenre.Name.contains(text)).all())
# Search Key
query = self.query(DjmdContent).join(DjmdContent.Key)
results.update(query.filter(tables.DjmdKey.ScaleName.contains(text)).all())
results = list(results)
results.sort(key=lambda x: x.ID)
return results
def get_cue(self, **kwargs):
"""Creates a filtered query for the ``DjmdCue`` table."""
query = self.query(tables.DjmdCue).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_device(self, **kwargs):
"""Creates a filtered query for the ``DjmdDevice`` table."""
query = self.query(tables.DjmdDevice).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_genre(self, **kwargs):
"""Creates a filtered query for the ``DjmdGenre`` table."""
query = self.query(tables.DjmdGenre).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_history(self, **kwargs):
"""Creates a filtered query for the ``DjmdHistory`` table."""
query = self.query(tables.DjmdHistory).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_history_songs(self, **kwargs):
"""Creates a filtered query for the ``DjmdSongHistory`` table."""
query = self.query(tables.DjmdSongHistory).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_hot_cue_banklist(self, **kwargs):
"""Creates a filtered query for the ``DjmdHotCueBanklist`` table."""
query = self.query(tables.DjmdHotCueBanklist).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_hot_cue_banklist_songs(self, **kwargs):
"""Creates a filtered query for the ``DjmdSongHotCueBanklist`` table."""
query = self.query(tables.DjmdSongHotCueBanklist).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_key(self, **kwargs):
"""Creates a filtered query for the ``DjmdKey`` table."""
query = self.query(tables.DjmdKey).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_label(self, **kwargs):
"""Creates a filtered query for the ``DjmdLabel`` table."""
query = self.query(tables.DjmdLabel).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_menu_items(self, **kwargs):
"""Creates a filtered query for the ``DjmdMenuItems`` table."""
query = self.query(tables.DjmdMenuItems).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_mixer_param(self, **kwargs):
"""Creates a filtered query for the ``DjmdMixerParam`` table."""
query = self.query(tables.DjmdMixerParam).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_my_tag(self, **kwargs):
"""Creates a filtered query for the ``DjmdMyTag`` table."""
query = self.query(tables.DjmdMyTag).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_my_tag_songs(self, **kwargs):
"""Creates a filtered query for the ``DjmdSongMyTag`` table."""
query = self.query(tables.DjmdSongMyTag).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_playlist(self, **kwargs):
"""Creates a filtered query for the ``DjmdPlaylist`` table."""
query = self.query(tables.DjmdPlaylist).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_playlist_songs(self, **kwargs):
"""Creates a filtered query for the ``DjmdSongPlaylist`` table."""
query = self.query(tables.DjmdSongPlaylist).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_playlist_contents(self, playlist, *entities) -> Query:
"""Return the contents of a regular or smart playlist.
Parameters
----------
playlist : DjmdPlaylist or int or str
The playlist instance. Can either be a :class:`DjmdPlaylist`
object or a playlist ID.
*entities : Base
The table objects for which the query is created. If no entities
are given, the query will return the :class:`DjmdContent` objects.
Returns
-------
query : sqlalchemy.orm.query.Query
The SQLAlchemy ``Query`` object. The query contains the content instances
or the selected columns if ``entities`` are given.
Examples
--------
Return the content instances in the playlist
>>> db = Rekordbox6Database()
>>> pl = db.get_playlist(Name="My Playlist").one()
>>> db.get_playlist_contents(pl).all()
[<DjmdContent(12345678 Title=Title1)>, <DjmdContent(23456789 Title=Title2)>]
Return only the content IDs
>>> db.get_playlist_contents(pl, DjmdContent.ID).all()
[('12345678',), ('23456789',)]
"""
if isinstance(playlist, (int, str)):
playlist = self.get_playlist(ID=playlist)
if playlist.is_folder:
raise ValueError(f"Playlist {playlist} is a playlist folder.")
if not entities:
entities = [
DjmdContent,
]
if playlist.is_smart_playlist:
smartlist = SmartList()
smartlist.parse(playlist.SmartList)
filter_clause = smartlist.filter_clause()
else:
sub_query = self.query(tables.DjmdSongPlaylist.ContentID).filter(
tables.DjmdSongPlaylist.PlaylistID == playlist.ID
)
filter_clause = DjmdContent.ID.in_(select(sub_query.subquery()))
return self.query(*entities).filter(filter_clause)
def get_property(self, **kwargs):
"""Creates a filtered query for the ``DjmdProperty`` table."""
query = self.query(tables.DjmdProperty).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_related_tracks(self, **kwargs):
"""Creates a filtered query for the ``DjmdRelatedTracks`` table."""
query = self.query(tables.DjmdRelatedTracks).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_related_tracks_songs(self, **kwargs):
"""Creates a filtered query for the ``DjmdSongRelatedTracks`` table."""
query = self.query(tables.DjmdSongRelatedTracks).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_sampler(self, **kwargs):
"""Creates a filtered query for the ``DjmdSampler`` table."""
query = self.query(tables.DjmdSampler).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_sampler_songs(self, **kwargs):
"""Creates a filtered query for the ``DjmdSongSampler`` table."""
query = self.query(tables.DjmdSongSampler).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_tag_list_songs(self, **kwargs):
"""Creates a filtered query for the ``DjmdSongTagList`` table."""
query = self.query(tables.DjmdSongTagList).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_sort(self, **kwargs):
"""Creates a filtered query for the ``DjmdSort`` table."""
query = self.query(tables.DjmdSort).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_agent_registry(self, **kwargs):
"""Creates a filtered query for the ``AgentRegistry`` table."""
query = self.query(tables.AgentRegistry).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_cloud_agent_registry(self, **kwargs):
"""Creates a filtered query for the ``CloudAgentRegistry`` table."""
query = self.query(tables.CloudAgentRegistry).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_content_active_censor(self, **kwargs):
"""Creates a filtered query for the ``ContentActiveCensor`` table."""
query = self.query(tables.ContentActiveCensor).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_content_cue(self, **kwargs):
"""Creates a filtered query for the ``ContentCue`` table."""
query = self.query(tables.ContentCue).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_content_file(self, **kwargs):
"""Creates a filtered query for the ``ContentFile`` table."""
query = self.query(tables.ContentFile).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_hot_cue_banklist_cue(self, **kwargs):
"""Creates a filtered query for the ``HotCueBanklistCue`` table."""
query = self.query(tables.HotCueBanklistCue).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_image_file(self, **kwargs):
"""Creates a filtered query for the ``ImageFile`` table."""
query = self.query(tables.ImageFile).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_setting_file(self, **kwargs):
"""Creates a filtered query for the ``SettingFile`` table."""
query = self.query(tables.SettingFile).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
def get_uuid_map(self, **kwargs):
"""Creates a filtered query for the ``UuidIDMap`` table."""
query = self.query(tables.UuidIDMap).filter_by(**kwargs)
return _parse_query_result(query, kwargs)
# -- Database updates --------------------------------------------------------------
def generate_unused_id(self, table, is_28_bit: bool = True) -> int:
"""Generates an unused ID for the given table."""
max_tries = 1000000
for _ in range(max_tries):
# Generate random ID
buf = secrets.token_bytes(4)
id_ = (buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3] >> 0
if is_28_bit:
id_ = id_ >> 4
if id_ < 100:
continue
# Check if ID is already used
query = self.query(table.ID).filter(table.ID == id_)
used = self.query(query.exists()).scalar()
if not used:
return id_
raise ValueError("Could not generate unused ID")
def add_to_playlist(self, playlist, content, track_no=None):
"""Adds a track to a playlist.
Creates a new :class:`DjmdSongPlaylist` object corresponding to the given
content and adds it to the playlist.
Parameters
----------
playlist : DjmdPlaylist or int or str
The playlist to add the track to. Can either be a :class:`DjmdPlaylist`
object or a playlist ID.
content : DjmdContent or int or str
The content to add to the playlist. Can either be a :class:`DjmdContent`
object or a content ID.
track_no : int, optional
The track number to add the content to. If not specified, the track
will be added to the end of the playlist.
Returns
-------
song: DjmdSongPlaylist
The song playlist object that was created from the content.
Raises
------
ValueError : If the playlist is a folder or smart playlist.
ValueError : If the track number is less than 1 or to large.
Examples
--------
Add a track to the end of a playlist:
>>> db = Rekordbox6Database()
>>> cid = 12345 # Content ID
>>> pid = 56789 # Playlist ID
>>> db.add_to_playlist(pid, cid)
<DjmdSongPlaylist(c803dfde-2236-4659-b3d7-e57221663375)>
Add a track to the beginning of a playlist:
>>> new_song = db.add_to_playlist(pid, cid, track_no=1)
>>> new_song.TrackNo
1
"""
if isinstance(playlist, (int, str)):
playlist = self.get_playlist(ID=playlist)
if isinstance(content, (int, str)):
content = self.get_content(ID=content)
# Check playlist attribute (can't be folder or smart playlist)
if playlist.Attribute != 0:
raise ValueError("Playlist must be a normal playlist")
uuid = str(uuid4())
id_ = str(uuid4())
now = datetime.datetime.now()
nsongs = (
self.query(tables.DjmdSongPlaylist)
.filter_by(PlaylistID=playlist.ID)
.count()
)
if track_no is not None:
insert_at_end = False
track_no = int(track_no)
if track_no < 1:
raise ValueError("Track number must be greater than 0")
if track_no > nsongs + 1:
raise ValueError(
f"Track number too high, parent contains {nsongs} items"
)
else:
insert_at_end = True
track_no = nsongs + 1
cid = content.ID
pid = playlist.ID
logger.info("Adding content with ID=%s to playlist with ID=%s:", cid, pid)
logger.debug("Content ID: %s", cid)
logger.debug("Playlist ID: %s", pid)
logger.debug("ID: %s", id_)
logger.debug("UUID: %s", uuid)
logger.debug("TrackNo: %s", track_no)
moved = list()
if not insert_at_end:
self.registry.disable_tracking()
# Update track numbers higher than the removed track
query = (
self.query(tables.DjmdSongPlaylist)
.filter(
tables.DjmdSongPlaylist.PlaylistID == playlist.ID,
tables.DjmdSongPlaylist.TrackNo >= track_no,
)
.order_by(tables.DjmdSongPlaylist.TrackNo)
)
for song in query:
song.TrackNo += 1
song.updated_at = now
moved.append(song)
self.registry.enable_tracking()
# Add song to playlist
song = tables.DjmdSongPlaylist.create(
ID=id_,
PlaylistID=str(pid),
ContentID=str(cid),
TrackNo=track_no,
UUID=uuid,
created_at=now,
updated_at=now,
)
self.add(song)
if not insert_at_end:
moved.append(song)
self.registry.on_move(moved)
return song
def remove_from_playlist(self, playlist, song):
"""Removes a track from a playlist.
Parameters
----------
playlist : DjmdPlaylist or int or str
The playlist to remove the track from. Can either be a :class:`DjmdPlaylist`
object or a playlist ID.
song : DjmdSongPlaylist or int or str
The song to remove from the playlist. Can either be a
:class:`DjmdSongPlaylist` object or a song ID.
Examples
--------
Remove a track from a playlist:
>>> db = Rekordbox6Database()
>>> pid = 56789
>>> pl = db.get_playlist(ID=pid)
>>> song = pl.Songs[0]
>>> db.remove_from_playlist(pl, song)
"""
if isinstance(playlist, (int, str)):
playlist = self.get_playlist(ID=playlist)
if isinstance(song, (int, str)):
song = self.query(tables.DjmdSongPlaylist).filter_by(ID=song).one()
logger.info(
"Removing song with ID=%s from playlist with ID=%s", song.ID, playlist.ID
)
now = datetime.datetime.now()
# Remove track from playlist
track_no = song.TrackNo
self.delete(song)
self.commit()
# Update track numbers higher than the removed track
query = (
self.query(tables.DjmdSongPlaylist)
.filter(
tables.DjmdSongPlaylist.PlaylistID == playlist.ID,
tables.DjmdSongPlaylist.TrackNo > track_no,
)
.order_by(tables.DjmdSongPlaylist.TrackNo)
)
moved = list()
with self.registry.disabled():
for song in query:
song.TrackNo -= 1
song.updated_at = now