-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
playlistdao.cpp
1302 lines (1124 loc) · 44.7 KB
/
playlistdao.cpp
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
#include "library/dao/playlistdao.h"
#include <QRandomGenerator>
#include <QtDebug>
#include <QtSql>
#include "library/autodj/autodjprocessor.h"
#include "library/queryutil.h"
#include "library/trackcollection.h"
#include "moc_playlistdao.cpp"
#include "track/track.h"
#include "util/db/dbconnection.h"
#include "util/db/fwdsqlquery.h"
#include "util/math.h"
PlaylistDAO::PlaylistDAO()
: m_pAutoDJProcessor(nullptr) {
}
void PlaylistDAO::initialize(const QSqlDatabase& database) {
DAO::initialize(database);
populatePlaylistMembershipCache();
}
void PlaylistDAO::populatePlaylistMembershipCache() {
// Minor optimization: reserve space in m_playlistsTrackIsIn.
QSqlQuery query(m_database);
query.prepare(QStringLiteral("SELECT COUNT(*) from " PLAYLIST_TRACKS_TABLE));
if (query.exec() && query.next()) {
m_playlistsTrackIsIn.reserve(query.value(0).toInt());
} else {
LOG_FAILED_QUERY(query);
}
// now fetch all Tracks from all playlists and insert them into the hashmap
query.prepare(QStringLiteral(
"SELECT track_id, playlist_id from " PLAYLIST_TRACKS_TABLE));
if (!query.exec()) {
LOG_FAILED_QUERY(query);
}
const int trackIdColumn = query.record().indexOf(PLAYLISTTRACKSTABLE_TRACKID);
const int playlistIdColumn = query.record().indexOf(PLAYLISTTRACKSTABLE_PLAYLISTID);
while (query.next()) {
m_playlistsTrackIsIn.insert(TrackId(query.value(trackIdColumn)),
query.value(playlistIdColumn).toInt());
}
}
int PlaylistDAO::createPlaylist(const QString& name, const HiddenType hidden) {
//qDebug() << "PlaylistDAO::createPlaylist"
// << QThread::currentThread()
// << m_database.connectionName();
// Start the transaction
ScopedTransaction transaction(m_database);
// Find out the highest position for the existing playlists so we know what
// position this playlist should have.
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"SELECT max(position) as posmax FROM Playlists"));
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return kInvalidPlaylistId;
}
//Get the id of the last playlist.
int position = 0;
if (query.next()) {
position = query.value(query.record().indexOf("posmax")).toInt();
position++; // Append after the last playlist.
}
//qDebug() << "Inserting playlist" << name << "at position" << position;
query.prepare(QStringLiteral(
"INSERT INTO Playlists (name, position, hidden, date_created, date_modified) "
"VALUES (:name, :position, :hidden, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"));
query.bindValue(":name", name);
query.bindValue(":position", position);
query.bindValue(":hidden", static_cast<int>(hidden));
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return kInvalidPlaylistId;
}
int playlistId = query.lastInsertId().toInt();
// Commit the transaction
transaction.commit();
emit added(playlistId);
return playlistId;
}
int PlaylistDAO::createUniquePlaylist(QString* pName, const HiddenType hidden) {
int playlistId = getPlaylistIdFromName(*pName);
int i = 1;
if (playlistId != kInvalidPlaylistId) {
// Calculate a unique name
*pName += "(%1)";
while (playlistId != kInvalidPlaylistId) {
i++;
playlistId = getPlaylistIdFromName(pName->arg(i));
}
*pName = pName->arg(i);
}
return createPlaylist(*pName, hidden);
}
QString PlaylistDAO::getPlaylistName(const int playlistId) const {
//qDebug() << "PlaylistDAO::getPlaylistName" << QThread::currentThread() << m_database.connectionName();
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"SELECT name FROM Playlists WHERE id= :id"));
query.bindValue(":id", playlistId);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return "";
}
// Get the name field
QString name = "";
const int nameColumn = query.record().indexOf("name");
if (query.next()) {
name = query.value(nameColumn).toString();
}
return name;
}
QList<TrackId> PlaylistDAO::getTrackIds(const int playlistId) const {
QList<TrackId> trackIds;
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"SELECT DISTINCT track_id FROM PlaylistTracks "
"WHERE playlist_id = :id"));
query.bindValue(":id", playlistId);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return trackIds;
}
const int trackIdColumn = query.record().indexOf("track_id");
while (query.next()) {
trackIds.append(TrackId(query.value(trackIdColumn)));
}
return trackIds;
}
int PlaylistDAO::getPlaylistIdFromName(const QString& name) const {
//qDebug() << "PlaylistDAO::getPlaylistIdFromName" << QThread::currentThread() << m_database.connectionName();
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"SELECT id FROM Playlists WHERE name = :name"));
query.bindValue(":name", name);
if (query.exec()) {
if (query.next()) {
return query.value(query.record().indexOf("id")).toInt();
}
} else {
LOG_FAILED_QUERY(query);
}
return kInvalidPlaylistId;
}
void PlaylistDAO::deletePlaylist(const int playlistId) {
//qDebug() << "PlaylistDAO::deletePlaylist" << QThread::currentThread() << m_database.connectionName();
ScopedTransaction transaction(m_database);
QSet<TrackId> playedTrackIds;
if (getHiddenType(playlistId) == PLHT_SET_LOG) {
const QList<TrackId> trackIds = getTrackIds(playlistId);
// TODO: QSet<T>::fromList(const QList<T>&) is deprecated and should be
// replaced with QSet<T>(list.begin(), list.end()).
// However, the proposed alternative has just been introduced in Qt
// 5.14. Until the minimum required Qt version of Mixxx is increased,
// we need a version check here
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
playedTrackIds = QSet<TrackId>(trackIds.constBegin(), trackIds.constEnd());
#else
playedTrackIds = QSet<TrackId>::fromList(trackIds);
#endif
}
// Get the playlist id for this
QSqlQuery query(m_database);
// Delete the row in the Playlists table.
query.prepare(QStringLiteral(
"DELETE FROM Playlists WHERE id= :id"));
query.bindValue(":id", playlistId);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return;
}
// Delete the tracks in this playlist from the PlaylistTracks table.
query.prepare(QStringLiteral(
"DELETE FROM PlaylistTracks WHERE playlist_id = :id"));
query.bindValue(":id", playlistId);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return;
}
transaction.commit();
//TODO: Crap, we need to shuffle the positions of all the playlists?
for (QMultiHash<TrackId, int>::iterator it = m_playlistsTrackIsIn.begin();
it != m_playlistsTrackIsIn.end();) {
if (it.value() == playlistId) {
it = m_playlistsTrackIsIn.erase(it);
} else {
++it;
}
}
emit deleted(playlistId);
if (!playedTrackIds.isEmpty()) {
emit tracksRemovedFromPlayedHistory(playedTrackIds);
}
}
bool PlaylistDAO::deletePlaylists(const QStringList& idStringList) {
if (idStringList.isEmpty()) {
return false;
}
const QString idString = idStringList.join(",");
qInfo() << "Deleting" << idStringList.size() << "playlists";
// delete tracks assigned to these playlists
auto deleteTracks = FwdSqlQuery(m_database,
QString("DELETE FROM PlaylistTracks WHERE playlist_id IN (%1)")
.arg(idString));
if (!deleteTracks.execPrepared()) {
return false;
}
// delete the playlists
auto deletePlaylists = FwdSqlQuery(m_database,
QString("DELETE FROM Playlists WHERE id IN (%1)").arg(idString));
if (!deletePlaylists.execPrepared()) {
return false;
}
emit deleted(kInvalidPlaylistId);
return true;
}
bool PlaylistDAO::deleteUnlockedPlaylists(QStringList&& idStringList) {
if (idStringList.isEmpty()) {
return false;
}
idStringList.removeDuplicates();
const QString idString = idStringList.join(",");
QSqlQuery query(m_database);
// select locked playlists
query.prepare(QStringLiteral(
"SELECT id FROM Playlists WHERE id IN (%1) AND locked = 1")
.arg(idString));
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return false;
}
// remove locked playlists from list
while (query.next()) {
idStringList.removeOne(query.value(0).toString());
}
return deletePlaylists(idStringList);
}
bool PlaylistDAO::deleteAllUnlockedPlaylistsWithFewerTracks(
PlaylistDAO::HiddenType type, int minNumberOfTracks) {
VERIFY_OR_DEBUG_ASSERT(minNumberOfTracks > 0) {
return false; // nothing to do, probably unintended invocation
}
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"SELECT id FROM Playlists "
"WHERE (SELECT count(playlist_id) FROM PlaylistTracks WHERE "
"Playlists.ID = PlaylistTracks.playlist_id) < :length AND "
"Playlists.hidden = :hidden AND Playlists.locked = 0"));
query.bindValue(":hidden", static_cast<int>(type));
query.bindValue(":length", minNumberOfTracks);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return false;
}
QStringList idStringList;
while (query.next()) {
idStringList.append(query.value(0).toString());
}
qInfo() << "Prepared deletion of" << idStringList.size() << "playlists of type" << type
<< "that contain fewer than" << minNumberOfTracks << "tracks";
return deletePlaylists(idStringList);
}
void PlaylistDAO::renamePlaylist(const int playlistId, const QString& newName) {
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"UPDATE Playlists SET name = :name WHERE id = :id"));
query.bindValue(":name", newName);
query.bindValue(":id", playlistId);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return;
}
emit renamed(playlistId, newName);
}
bool PlaylistDAO::setPlaylistLocked(const int playlistId, const bool locked) {
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"UPDATE Playlists SET locked = :lock WHERE id = :id"));
// SQLite3 doesn't support boolean value. Using integer instead.
int lock = locked ? 1 : 0;
query.bindValue(":lock", lock);
query.bindValue(":id", playlistId);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return false;
}
emit lockChanged(QSet<int>{playlistId});
return true;
}
int PlaylistDAO::setPlaylistsLocked(const QSet<int>& playlistIds, const bool lock) {
if (playlistIds.isEmpty()) {
return 0;
}
if (lock) {
qInfo() << "Locking" << playlistIds.size() << "playlists";
} else {
qInfo() << "Unlocking" << playlistIds.size() << "playlists";
}
QString idsString;
for (int id : playlistIds) {
idsString += QString::number(id) + ',';
}
// strip the last comma
idsString.chop(1);
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"UPDATE Playlists SET locked = :lock WHERE id IN (%1)")
.arg(idsString));
// SQLite3 doesn't support boolean value. Using integer instead.
int iLock = lock ? 1 : 0;
query.bindValue(":lock", iLock);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return -1;
}
emit lockChanged(playlistIds);
return playlistIds.size();
}
bool PlaylistDAO::isPlaylistLocked(const int playlistId) const {
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"SELECT locked FROM Playlists WHERE id = :id"));
query.bindValue(":id", playlistId);
if (query.exec()) {
if (query.next()) {
int lockValue = query.value(0).toInt();
return lockValue == 1;
}
} else {
LOG_FAILED_QUERY(query);
}
return false;
}
bool PlaylistDAO::removeTracksFromPlaylist(int playlistId, int startIndex) {
// Retain the first track if it is loaded in a deck
ScopedTransaction transaction(m_database);
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"DELETE FROM PlaylistTracks "
"WHERE playlist_id=:id AND position>=:pos"));
query.bindValue(":id", playlistId);
query.bindValue(":pos", startIndex);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return false;
}
transaction.commit();
emit tracksChanged(QSet<int>{playlistId});
return true;
}
bool PlaylistDAO::appendTracksToPlaylist(const QList<TrackId>& trackIds, const int playlistId) {
// qDebug() << "PlaylistDAO::appendTracksToPlaylist"
// << QThread::currentThread() << m_database.connectionName();
// Start the transaction
ScopedTransaction transaction(m_database);
int position = getMaxPosition(playlistId);
// Append after the last song. If no songs or a failed query then 0 becomes 1.
++position;
//Insert the song into the PlaylistTracks table
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"INSERT INTO PlaylistTracks (playlist_id, track_id, position, pl_datetime_added)"
"VALUES (:playlist_id, :track_id, :position, CURRENT_TIMESTAMP)"));
query.bindValue(":playlist_id", playlistId);
int insertPosition = position;
for (const auto& trackId : trackIds) {
query.bindValue(":track_id", trackId.toVariant());
query.bindValue(":position", insertPosition++);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return false;
}
}
// Commit the transaction
transaction.commit();
insertPosition = position;
for (const auto& trackId : trackIds) {
m_playlistsTrackIsIn.insert(trackId, playlistId);
// TODO(XXX) don't emit if the track didn't add successfully.
emit trackAdded(playlistId, trackId, insertPosition++);
}
emit tracksChanged(QSet<int>{playlistId});
return true;
}
bool PlaylistDAO::appendTrackToPlaylist(TrackId trackId, const int playlistId) {
QList<TrackId> trackIds;
trackIds.append(trackId);
return appendTracksToPlaylist(trackIds, playlistId);
}
/** Find out how many playlists exist. */
unsigned int PlaylistDAO::playlistCount() const {
// qDebug() << "PlaylistDAO::playlistCount" << QThread::currentThread() << m_database.connectionName();
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"SELECT count(*) as count FROM Playlists"));
if (!query.exec()) {
LOG_FAILED_QUERY(query);
}
int numRecords = 0;
if (query.next()) {
numRecords = query.value(query.record().indexOf("count")).toInt();
}
return numRecords;
}
QList<QPair<int, QString>> PlaylistDAO::getPlaylists(const HiddenType hidden) const {
//qDebug() << "PlaylistDAO::getPlaylists(hidden =" << hidden
// << QThread::currentThread() << m_database.connectionName();
QSqlQuery query(m_database);
query.prepare(
mixxx::DbConnection::collateLexicographically(
QString("SELECT id, name FROM Playlists "
"WHERE hidden = %1 "
"ORDER BY name")
.arg(hidden)));
QList<QPair<int, QString>> playlists;
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return playlists;
}
while (query.next()) {
const int id = query.value(0).toInt();
const QString name = query.value(1).toString();
playlists.append(qMakePair(id, name));
}
return playlists;
}
int PlaylistDAO::getPlaylistId(const int index) const {
//qDebug() << "PlaylistDAO::getPlaylistId"
// << QThread::currentThread() << m_database.connectionName();
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"SELECT id FROM Playlists"));
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return kInvalidPlaylistId;
}
int currentRow = 0;
while (query.next()) {
if (currentRow++ == index) {
int id = query.value(0).toInt();
return id;
}
}
return kInvalidPlaylistId;
}
PlaylistDAO::HiddenType PlaylistDAO::getHiddenType(const int playlistId) const {
// qDebug() << "PlaylistDAO::getHiddenType"
// << QThread::currentThread() << m_database.connectionName();
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"SELECT hidden FROM Playlists WHERE id = :id"));
query.bindValue(":id", playlistId);
if (query.exec()) {
if (query.next()) {
return static_cast<HiddenType>(query.value(0).toInt());
}
} else {
LOG_FAILED_QUERY(query);
}
qDebug() << "PlaylistDAO::getHiddenType returns PLHT_UNKNOWN for playlistId "
<< playlistId;
return PLHT_UNKNOWN;
}
bool PlaylistDAO::isHidden(const int playlistId) const {
// qDebug() << "PlaylistDAO::isHidden"
// << QThread::currentThread() << m_database.connectionName();
HiddenType ht = getHiddenType(playlistId);
if (ht == PLHT_NOT_HIDDEN) {
return false;
}
return true;
}
void PlaylistDAO::removeHiddenTracks(const int playlistId) {
ScopedTransaction transaction(m_database);
// This query deletes all tracks marked as deleted and all
// phantom track_ids with no match in the library table
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"SELECT p1.position FROM PlaylistTracks AS p1 "
"WHERE p1.id NOT IN ("
"SELECT p2.id FROM PlaylistTracks AS p2 "
"INNER JOIN library ON library.id=p2.track_id "
"WHERE p2.playlist_id=p1.playlist_id "
"AND library.mixxx_deleted=0) "
"AND p1.playlist_id=:id"));
query.bindValue(":id", playlistId);
query.setForwardOnly(true);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return;
}
while (query.next()) {
int position = query.value(query.record().indexOf("position")).toInt();
removeTracksFromPlaylistInner(playlistId, position);
}
transaction.commit();
emit tracksChanged(QSet<int>{playlistId});
}
void PlaylistDAO::removeTracksFromPlaylistById(int playlistId, TrackId trackId) {
ScopedTransaction transaction(m_database);
removeTracksFromPlaylistByIdInner(playlistId, trackId);
transaction.commit();
emit tracksChanged(QSet<int>{playlistId});
}
void PlaylistDAO::removeTracksFromPlaylistByIdInner(int playlistId, TrackId trackId) {
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"SELECT position FROM PlaylistTracks "
"WHERE playlist_id=:id AND track_id=:track_id"));
query.bindValue(":id", playlistId);
query.bindValue(":track_id", trackId.toVariant());
query.setForwardOnly(true);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return;
}
while (query.next()) {
int position = query.value(query.record().indexOf("position")).toInt();
removeTracksFromPlaylistInner(playlistId, position);
}
}
void PlaylistDAO::removeTrackFromPlaylist(int playlistId, int position) {
// qDebug() << "PlaylistDAO::removeTrackFromPlaylist"
// << QThread::currentThread() << m_database.connectionName();
ScopedTransaction transaction(m_database);
removeTracksFromPlaylistInner(playlistId, position);
transaction.commit();
emit tracksChanged(QSet<int>{playlistId});
}
void PlaylistDAO::removeTracksFromPlaylist(int playlistId, const QList<int>& positions) {
// get positions in reversed order
auto sortedPositons = positions;
std::sort(sortedPositons.begin(), sortedPositons.end(), std::greater<int>());
//qDebug() << "PlaylistDAO::removeTrackFromPlaylist"
// << QThread::currentThread() << m_database.connectionName();
ScopedTransaction transaction(m_database);
for (const auto position : qAsConst(sortedPositons)) {
removeTracksFromPlaylistInner(playlistId, position);
}
transaction.commit();
emit tracksChanged(QSet<int>{playlistId});
}
void PlaylistDAO::removeTracksFromPlaylistInner(int playlistId, int position) {
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"SELECT track_id FROM PlaylistTracks "
"WHERE playlist_id=:id AND position=:position"));
query.bindValue(":id", playlistId);
query.bindValue(":position", position);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return;
}
if (!query.next()) {
qDebug() << "removeTrackFromPlaylist no track exists at position:"
<< position << "in playlist:" << playlistId;
return;
}
TrackId trackId(query.value(query.record().indexOf("track_id")));
// Delete the track from the playlist.
query.prepare(QStringLiteral(
"DELETE FROM PlaylistTracks "
"WHERE playlist_id=:id AND position=:position"));
query.bindValue(":id", playlistId);
query.bindValue(":position", position);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return;
}
query.prepare(QStringLiteral(
"UPDATE PlaylistTracks SET position=position-1 "
"WHERE position>=:position AND playlist_id=:id"));
query.bindValue(":id", playlistId);
query.bindValue(":position", position);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
}
m_playlistsTrackIsIn.remove(trackId, playlistId);
emit trackRemoved(playlistId, trackId, position);
if (getHiddenType(playlistId) == PLHT_SET_LOG) {
emit tracksRemovedFromPlayedHistory({trackId});
}
}
bool PlaylistDAO::insertTrackIntoPlaylist(TrackId trackId, const int playlistId, int position) {
if (playlistId < 0 || !trackId.isValid() || position < 0) {
return false;
}
ScopedTransaction transaction(m_database);
int max_position = getMaxPosition(playlistId) + 1;
if (position > max_position) {
position = max_position;
}
// Move all the tracks in the playlist up by one
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"UPDATE PlaylistTracks SET position=position+1 "
"WHERE position>=:position AND playlist_id=:id"));
query.bindValue(":id", playlistId);
query.bindValue(":position", position);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return false;
}
//Insert the song into the PlaylistTracks table
query.prepare(QStringLiteral(
"INSERT INTO PlaylistTracks (playlist_id, track_id, position, pl_datetime_added)"
"VALUES (:playlist_id, :track_id, :position, CURRENT_TIMESTAMP)"));
query.bindValue(":playlist_id", playlistId);
query.bindValue(":track_id", trackId.toVariant());
query.bindValue(":position", position);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return false;
}
transaction.commit();
m_playlistsTrackIsIn.insert(trackId, playlistId);
emit trackAdded(playlistId, trackId, position);
emit tracksChanged(QSet<int>{playlistId});
return true;
}
int PlaylistDAO::insertTracksIntoPlaylist(const QList<TrackId>& trackIds,
const int playlistId,
int position) {
if (playlistId < 0 || position < 0) {
return 0;
}
int tracksAdded = 0;
ScopedTransaction transaction(m_database);
int max_position = getMaxPosition(playlistId) + 1;
if (position > max_position) {
position = max_position;
}
QSqlQuery insertQuery(m_database);
insertQuery.prepare(QStringLiteral(
"INSERT INTO PlaylistTracks (playlist_id, track_id, position)"
"VALUES (:playlist_id, :track_id, :position)"));
QSqlQuery query(m_database);
int insertPositon = position;
for (const auto& trackId : trackIds) {
if (!trackId.isValid()) {
continue;
}
// Move all tracks in playlist up by 1.
// TODO(XXX) We could do this in one query before the for loop.
query.prepare(QStringLiteral(
"UPDATE PlaylistTracks SET position=position+1 "
"WHERE position>=:position AND "
"playlist_id=:id"));
query.bindValue(":id", playlistId);
query.bindValue(":position", insertPositon);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
continue;
}
// Insert the track at the given position
insertQuery.bindValue(":playlist_id", playlistId);
insertQuery.bindValue(":track_id", trackId.toVariant());
insertQuery.bindValue(":position", insertPositon);
if (!insertQuery.exec()) {
LOG_FAILED_QUERY(insertQuery);
continue;
}
// Increment the insert position for the track.
++insertPositon;
++tracksAdded;
}
transaction.commit();
insertPositon = position;
for (const auto& trackId : trackIds) {
m_playlistsTrackIsIn.insert(trackId, playlistId);
// TODO(XXX) The position is wrong if any track failed to insert.
emit trackAdded(playlistId, trackId, insertPositon++);
}
emit tracksChanged(QSet<int>{playlistId});
return tracksAdded;
}
void PlaylistDAO::addPlaylistToAutoDJQueue(const int playlistId, AutoDJSendLoc loc) {
//qDebug() << "Adding tracks from playlist " << playlistId << " to the Auto-DJ Queue";
// Query the PlaylistTracks database to locate tracks in the selected
// playlist. Tracks are automatically sorted by position.
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"SELECT track_id FROM PlaylistTracks "
"WHERE playlist_id = :plid ORDER BY position ASC"));
query.bindValue(":plid", playlistId);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return;
}
// Loop through the tracks, adding them to the Auto-DJ Queue. Start at
// position 2 because position 1 was already loaded to the deck.
QList<TrackId> trackIds;
while (query.next()) {
trackIds.append(TrackId(query.value(0)));
}
addTracksToAutoDJQueue(trackIds, loc);
}
int PlaylistDAO::getPreviousPlaylist(const int currentPlaylistId, HiddenType hidden) const {
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"SELECT max(id) as id FROM Playlists "
"WHERE id < :id AND hidden = :hidden"));
query.bindValue(":id", currentPlaylistId);
query.bindValue(":hidden", hidden);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return kInvalidPlaylistId;
}
if (query.next()) {
return query.value(query.record().indexOf("id")).toInt();
}
return kInvalidPlaylistId;
}
int PlaylistDAO::getNextPlaylist(const int currentPlaylistId, HiddenType hidden) const {
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"SELECT max(id) as id FROM Playlists "
"WHERE id > :id AND hidden = :hidden"));
query.bindValue(":id", currentPlaylistId);
query.bindValue(":hidden", hidden);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return kInvalidPlaylistId;
}
if (query.next()) {
return query.value(query.record().indexOf("id")).toInt();
}
return kInvalidPlaylistId;
}
bool PlaylistDAO::copyPlaylistTracks(const int sourcePlaylistID, const int targetPlaylistID) {
// Start the transaction
ScopedTransaction transaction(m_database);
// Copy the new tracks after the last track in the target playlist.
int positionOffset = getMaxPosition(targetPlaylistID);
// Copy the tracks from one playlist to another, adjusting the position of
// each copied track, and preserving the date/time added.
// INSERT INTO PlaylistTracks (playlist_id, track_id, position, pl_datetime_added) SELECT :target_plid, track_id, position + :position_offset, pl_datetime_added FROM PlaylistTracks WHERE playlist_id = :source_plid;
QSqlQuery query(m_database);
query.prepare(
QStringLiteral(
"INSERT INTO " PLAYLIST_TRACKS_TABLE
" (%1, %2, %3, %4) SELECT :target_plid, %2, "
"%3 + :position_offset, %4 FROM " PLAYLIST_TRACKS_TABLE
" WHERE %1 = :source_plid")
.arg(
PLAYLISTTRACKSTABLE_PLAYLISTID,
PLAYLISTTRACKSTABLE_TRACKID,
PLAYLISTTRACKSTABLE_POSITION,
PLAYLISTTRACKSTABLE_DATETIMEADDED));
query.bindValue(":position_offset", positionOffset);
query.bindValue(":source_plid", sourcePlaylistID);
query.bindValue(":target_plid", targetPlaylistID);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return false;
}
// Query each added track and its new position.
// SELECT track_id, position FROM PlaylistTracks WHERE playlist_id = :target_plid AND position > :position_offset;
query.prepare(
QStringLiteral(
"SELECT %2, %3 FROM " PLAYLIST_TRACKS_TABLE
" WHERE %1 = :target_plid AND %3 > :position_offset")
.arg(
PLAYLISTTRACKSTABLE_PLAYLISTID,
PLAYLISTTRACKSTABLE_TRACKID,
PLAYLISTTRACKSTABLE_POSITION));
query.bindValue(":target_plid", targetPlaylistID);
query.bindValue(":position_offset", positionOffset);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return false;
}
// Commit the transaction
transaction.commit();
// Let subscribers know about each added track.
while (query.next()) {
TrackId copiedTrackId(query.value(0));
int copiedPosition = query.value(1).toInt();
m_playlistsTrackIsIn.insert(copiedTrackId, targetPlaylistID);
emit trackAdded(targetPlaylistID, copiedTrackId, copiedPosition);
}
emit tracksChanged(QSet<int>{targetPlaylistID});
return true;
}
int PlaylistDAO::getMaxPosition(const int playlistId) const {
// Find out the highest position existing in the playlist so we know what
// position this track should have.
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"SELECT max(position) as position FROM PlaylistTracks "
"WHERE playlist_id = :id"));
query.bindValue(":id", playlistId);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
}
// Get the position of the highest track in the playlist.
int position = 0;
if (query.next()) {
position = query.value(query.record().indexOf("position")).toInt();
}
return position;
}
void PlaylistDAO::removeTracksFromPlaylists(const QList<TrackId>& trackIds) {
// copy the hash, because there is no guarantee that "it" is valid after remove
QMultiHash<TrackId, int> playlistsTrackIsInCopy = m_playlistsTrackIsIn;
QSet<int> playlistIds;
ScopedTransaction transaction(m_database);
for (const auto& trackId : trackIds) {
for (auto it = playlistsTrackIsInCopy.constBegin();
it != playlistsTrackIsInCopy.constEnd();
++it) {
if (it.key() == trackId) {
const auto playlistId = it.value();
// keep tracks in history playlists
if (getHiddenType(playlistId) == PlaylistDAO::PLHT_SET_LOG) {
continue;
}
removeTracksFromPlaylistByIdInner(playlistId, trackId);
playlistIds.insert(playlistId);
}
}
}
transaction.commit();
emit tracksChanged(playlistIds);
}
int PlaylistDAO::tracksInPlaylist(const int playlistId) const {
QSqlQuery query(m_database);
query.prepare(QStringLiteral(
"SELECT COUNT(id) AS count FROM PlaylistTracks "
"WHERE playlist_id = :playlist_id"));
query.bindValue(":playlist_id", playlistId);
if (!query.exec()) {
LOG_FAILED_QUERY(query) << "Couldn't get the number of tracks in playlist"
<< playlistId;
return -1;
}
int count = -1;
const int countColumn = query.record().indexOf("count");
while (query.next()) {
count = query.value(countColumn).toInt();
}
return count;
}
void PlaylistDAO::moveTrack(const int playlistId, const int oldPosition, const int newPosition) {
ScopedTransaction transaction(m_database);
QSqlQuery query(m_database);
// Algorithm for code below
// Case 1: destination < source (newPositon < oldPosition)
// 1) Set position = -1 where pos=source -- Gives that track a dummy index to keep stuff simple.
// 2) Decrement position where pos >= dest AND pos < source
// 3) Set position = dest where pos=-1 -- Move track from dummy pos to final destination.
// Case 2: destination > source (newPos > oldPos)
// 1) Set position=-1 where pos=source -- Give track a dummy index again.
// 2) Decrement position where pos > source AND pos <= dest
// 3) Set position=dest where pos=-1 -- Move that track from dummy pos to final destination