-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathtrackdao.cpp
2431 lines (2214 loc) · 93.7 KB
/
trackdao.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/trackdao.h"
#include <QChar>
#include <QDir>
#include <QFileInfo>
#include <QThread>
#include <QtDebug>
#ifdef __SQLITE3__
#include <sqlite3.h>
#endif // __SQLITE3__
#include "library/coverart.h"
#include "library/coverartutils.h"
#include "library/dao/analysisdao.h"
#include "library/dao/cuedao.h"
#include "library/dao/libraryhashdao.h"
#include "library/dao/playlistdao.h"
#include "library/library_prefs.h"
#include "library/queryutil.h"
#include "moc_trackdao.cpp"
#include "sources/soundsourceproxy.h"
#include "track/beats.h"
#include "track/globaltrackcache.h"
#include "track/keyfactory.h"
#include "track/keyutils.h"
#include "track/track.h"
#include "util/assert.h"
#include "util/datetime.h"
#include "util/db/fwdsqlquery.h"
#include "util/db/sqlite.h"
#include "util/db/sqlstringformatter.h"
#include "util/db/sqltransaction.h"
#include "util/fileinfo.h"
#include "util/logger.h"
#include "util/math.h"
#include "util/qt.h"
#include "util/timer.h"
namespace {
mixxx::Logger kLogger("TrackDAO");
enum { UndefinedRecordIndex = -2 };
void markTrackLocationsAsDeleted(const QSqlDatabase& database, const QString& directory) {
//qDebug() << "TrackDAO::markTrackLocationsAsDeleted" << QThread::currentThread() << m_database.connectionName();
QSqlQuery query(database);
query.prepare("UPDATE track_locations "
"SET fs_deleted=1 "
"WHERE directory=:directory");
query.bindValue(":directory", directory);
if (!query.exec()) {
LOG_FAILED_QUERY(query)
<< "Couldn't mark tracks in" << directory << "as deleted.";
DEBUG_ASSERT(!"Failed query");
}
}
QString joinTrackIdList(const QSet<TrackId>& trackIds) {
QStringList trackIdList;
trackIdList.reserve(trackIds.size());
for (const auto& trackId : trackIds) {
trackIdList.append(trackId.toString());
}
return trackIdList.join(QChar(','));
}
QString locationPathPrefixFromRootDir(const QDir& rootDir) {
// Appending '/' is required to disambiguate files from parent
// directories, e.g. "a/b.mp3" and "a/b/c.mp3" where "a/b" would
// match both instead of only files in the parent directory "a/b/".
DEBUG_ASSERT(!mixxx::FileInfo(rootDir).location().endsWith('/'));
return mixxx::FileInfo(rootDir).location() + '/';
}
} // anonymous namespace
TrackDAO::TrackDAO(CueDAO& cueDao,
PlaylistDAO& playlistDao,
AnalysisDao& analysisDao,
LibraryHashDAO& libraryHashDao,
UserSettingsPointer pConfig)
: m_cueDao(cueDao),
m_playlistDao(playlistDao),
m_analysisDao(analysisDao),
m_libraryHashDao(libraryHashDao),
m_pConfig(pConfig),
m_trackLocationIdColumn(UndefinedRecordIndex),
m_queryLibraryIdColumn(UndefinedRecordIndex),
m_queryLibraryMixxxDeletedColumn(UndefinedRecordIndex) {
connect(&m_playlistDao,
&PlaylistDAO::tracksRemovedFromPlayedHistory,
this,
[this](const QSet<TrackId>& playedTrackIds) {
if (playedTrackIds.isEmpty()) {
// Nothing to do
return;
}
VERIFY_OR_DEBUG_ASSERT(updatePlayCounterFromPlayedHistory(playedTrackIds)) {
return;
}
});
}
TrackDAO::~TrackDAO() {
qDebug() << "~TrackDAO()";
//clear all leftover Transactions and rollback the db
addTracksFinish(true);
}
void TrackDAO::finish() {
qDebug() << "TrackDAO::finish()";
// clear out played information on exit
// crash prevention: if mixxx crashes, played information will be maintained
qDebug() << "Clearing played information for this session";
QSqlQuery query(m_database);
if (!query.exec("UPDATE library SET played=0 where played>0")) {
// Note: without where, this call updates every row which takes long
LOG_FAILED_QUERY(query)
<< "Error clearing played value";
}
// Do housekeeping on the LibraryHashes/track_locations tables.
qDebug() << "Cleaning LibraryHashes/track_locations tables.";
SqlTransaction transaction(m_database);
const QStringList deletedHashDirs = m_libraryHashDao.getDeletedDirectories();
// Delete any LibraryHashes directories that have been marked as deleted.
m_libraryHashDao.removeDeletedDirectoryHashes();
// And mark the corresponding tracks in track_locations in the deleted
// directories as deleted.
// TODO(XXX) This doesn't handle sub-directories of deleted directories.
for (const auto& dir : deletedHashDirs) {
markTrackLocationsAsDeleted(m_database, dir);
}
transaction.commit();
}
TrackId TrackDAO::getTrackIdByLocation(const QString& location) const {
if (location.isEmpty()) {
return {};
}
QSqlQuery query(m_database);
query.prepare(
"SELECT library.id FROM library "
"INNER JOIN track_locations ON library.location = track_locations.id "
"WHERE track_locations.location=:location");
query.bindValue(":location", location);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
DEBUG_ASSERT(!"Failed query");
return {};
}
if (!query.next()) {
qDebug() << "TrackDAO::getTrackId(): Track location not found in library:" << location;
return {};
}
const auto trackId = TrackId(query.value(query.record().indexOf("id")));
DEBUG_ASSERT(trackId.isValid());
return trackId;
}
QList<TrackId> TrackDAO::resolveTrackIds(
const QList<QUrl>& urls,
ResolveTrackIdFlags flags) {
QStringList pathList;
pathList.reserve(urls.size());
for (const auto& url : urls) {
const QString urlStr = url.isLocalFile() ? url.toLocalFile() : url.toString();
pathList << "(" + SqlStringFormatter::format(m_database, urlStr) + ")";
}
return resolveTrackIds(pathList, flags);
}
QList<TrackId> TrackDAO::resolveTrackIds(
const QList<mixxx::FileInfo>& fileInfos,
ResolveTrackIdFlags flags) {
QStringList pathList;
pathList.reserve(fileInfos.size());
for (const auto& fileInfo : fileInfos) {
pathList << "(" + SqlStringFormatter::format(m_database, fileInfo.location()) + ")";
}
return resolveTrackIds(pathList, flags);
}
QList<TrackId> TrackDAO::resolveTrackIds(
const QStringList& pathList,
ResolveTrackIdFlags flags) {
QList<TrackId> trackIds;
trackIds.reserve(pathList.size());
// Create a temporary database of the paths of all the imported tracks.
QSqlQuery query(m_database);
query.prepare(
"CREATE TEMP TABLE playlist_import "
"(location varchar (512))");
if (!query.exec()) {
LOG_FAILED_QUERY(query);
DEBUG_ASSERT(!"Failed query");
return trackIds;
}
// Add all the track paths temporary to this database.
query.prepare(
"INSERT INTO playlist_import (location) "
"VALUES " + pathList.join(','));
if (!query.exec()) {
LOG_FAILED_QUERY(query);
DEBUG_ASSERT(!"Failed query");
}
if (flags & ResolveTrackIdFlag::AddMissing) {
// Prepare to add tracks to the database.
// This also begins an SQL transaction.
addTracksPrepare();
// Any tracks not already in the database need to be added.
query.prepare("SELECT location FROM playlist_import "
"WHERE NOT EXISTS (SELECT location FROM track_locations "
"WHERE playlist_import.location = track_locations.location)");
if (!query.exec()) {
LOG_FAILED_QUERY(query);
DEBUG_ASSERT(!"Failed query");
}
const int locationColumn = query.record().indexOf("location");
while (query.next()) {
QString location = query.value(locationColumn).toString();
addTracksAddFile(location, true);
}
// Finish adding tracks to the database.
addTracksFinish();
}
query.prepare(
"SELECT library.id FROM playlist_import "
"INNER JOIN track_locations ON playlist_import.location = track_locations.location "
"INNER JOIN library ON library.location = track_locations.id "
// the order by clause enforces the native sorting which is used anyway
// hopefully optimized away. TODO() verify.
"ORDER BY playlist_import.ROWID");
// Old syntax for a shorter but less readable query. TODO() check performance gain
// query.prepare(
// "SELECT library.id FROM playlist_import, "
// "track_locations, library WHERE library.location = track_locations.id "
// "AND playlist_import.location = track_locations.location");
// "ORDER BY playlist_import.ROWID");
if (query.exec()) {
const int idColumn = query.record().indexOf("id");
while (query.next()) {
trackIds.append(TrackId(query.value(idColumn)));
}
DEBUG_ASSERT(trackIds.size() <= pathList.size());
if (trackIds.size() < pathList.size()) {
qDebug() << "TrackDAO::getTrackIds(): Found only"
<< trackIds.size()
<< "of"
<< pathList.size()
<< "tracks in library";
}
} else {
LOG_FAILED_QUERY(query);
}
// Drop the temporary playlist-import table.
query.prepare("DROP TABLE IF EXISTS playlist_import");
if (!query.exec()) {
LOG_FAILED_QUERY(query);
DEBUG_ASSERT(!"Failed query");
}
return trackIds;
}
QSet<QString> TrackDAO::getAllTrackLocations() const {
QSet<QString> locations;
QSqlQuery query(m_database);
query.prepare("SELECT track_locations.location FROM track_locations "
"INNER JOIN library on library.location = track_locations.id");
if (!query.exec()) {
LOG_FAILED_QUERY(query);
DEBUG_ASSERT(!"Failed query");
}
int locationColumn = query.record().indexOf("location");
while (query.next()) {
locations.insert(query.value(locationColumn).toString());
}
return locations;
}
// Some code (eg. drag and drop) needs to just get a track's location, and it's
// not worth retrieving a whole Track.
QString TrackDAO::getTrackLocation(TrackId trackId) const {
qDebug() << "TrackDAO::getTrackLocation"
<< QThread::currentThread() << m_database.connectionName();
QSqlQuery query(m_database);
QString trackLocation = "";
query.prepare("SELECT track_locations.location FROM track_locations "
"INNER JOIN library ON library.location = track_locations.id "
"WHERE library.id=:id");
query.bindValue(":id", trackId.toVariant());
if (!query.exec()) {
LOG_FAILED_QUERY(query);
DEBUG_ASSERT(!"Failed query");
return "";
}
const int locationColumn = query.record().indexOf("location");
while (query.next()) {
trackLocation = query.value(locationColumn).toString();
}
return trackLocation;
}
bool TrackDAO::saveTrack(Track* pTrack) const {
VERIFY_OR_DEBUG_ASSERT(pTrack) {
return false;
}
DEBUG_ASSERT(pTrack->isDirty());
const TrackId trackId = pTrack->getId();
DEBUG_ASSERT(trackId.isValid());
qDebug() << "TrackDAO: Saving track"
<< trackId
<< pTrack->getLocation();
if (!updateTrack(*pTrack)) {
return false;
}
// BaseTrackCache must be informed separately, because the
// track has already been disconnected and TrackDAO does
// not receive any signals that are usually forwarded to
// BaseTrackCache.
pTrack->markClean();
emit mixxx::thisAsNonConst(this)->trackClean(trackId);
return true;
}
void TrackDAO::slotDatabaseTracksChanged(const QSet<TrackId>& changedTrackIds) {
if (!changedTrackIds.isEmpty()) {
emit tracksChanged(changedTrackIds);
}
}
void TrackDAO::slotDatabaseTracksRelocated(const QList<RelocatedTrack>& relocatedTracks) {
QSet<TrackId> removedTrackIds;
QSet<TrackId> changedTrackIds;
for (const auto& relocatedTrack : std::as_const(relocatedTracks)) {
const auto changedTrackId = relocatedTrack.updatedTrackRef().getId();
DEBUG_ASSERT(changedTrackId.isValid());
DEBUG_ASSERT(!removedTrackIds.contains(changedTrackId));
changedTrackIds.insert(changedTrackId);
const auto removedTrackId = relocatedTrack.deletedTrackId();
if (removedTrackId.isValid()) {
DEBUG_ASSERT(!changedTrackIds.contains(removedTrackId));
removedTrackIds.insert(removedTrackId);
}
}
DEBUG_ASSERT(removedTrackIds.size() <= changedTrackIds.size());
DEBUG_ASSERT(!removedTrackIds.intersects(changedTrackIds));
if (!removedTrackIds.isEmpty()) {
emit tracksRemoved(removedTrackIds);
}
if (!changedTrackIds.isEmpty()) {
emit tracksChanged(changedTrackIds);
}
}
void TrackDAO::addTracksPrepare() {
if (m_pQueryLibraryInsert || m_pQueryTrackLocationInsert ||
m_pQueryLibrarySelect || m_pQueryTrackLocationSelect ||
m_pTransaction) {
qDebug() << "TrackDAO::addTracksPrepare: PROGRAMMING ERROR"
<< "old queries have been left open, rolling back.";
// true == do a db rollback
addTracksFinish(true);
}
// Start the transaction
m_pTransaction = std::make_unique<SqlTransaction>(m_database);
m_pQueryTrackLocationInsert = std::make_unique<QSqlQuery>(m_database);
m_pQueryTrackLocationSelect = std::make_unique<QSqlQuery>(m_database);
m_pQueryLibraryInsert = std::make_unique<QSqlQuery>(m_database);
m_pQueryLibraryUpdate = std::make_unique<QSqlQuery>(m_database);
m_pQueryLibrarySelect = std::make_unique<QSqlQuery>(m_database);
m_pQueryTrackLocationInsert->prepare("INSERT INTO track_locations "
"("
"location,directory,filename,filesize,fs_deleted,needs_verification"
") VALUES ("
":location,:directory,:filename,:filesize,:fs_deleted,:needs_verification"
")");
m_pQueryTrackLocationSelect->prepare("SELECT id FROM track_locations WHERE location=:location");
m_pQueryLibraryInsert->prepare(
"INSERT INTO library "
"("
"artist,"
"title,"
"album,"
"album_artist,"
"year,"
"genre,"
"tracknumber,"
"tracktotal,"
"composer,"
"grouping,"
"filetype,"
"location,"
"color,"
"comment,"
"url,"
"rating,"
"key,"
"key_id,"
"cuepoint,"
"bpm,"
"replaygain,"
"replaygain_peak,"
"wavesummaryhex,"
"timesplayed,"
"last_played_at,"
"played,"
"mixxx_deleted,"
"header_parsed,"
"source_synchronized_ms,"
"channels,"
"samplerate,"
"bitrate,"
"duration,"
"beats_version,"
"beats_sub_version,"
"beats,"
"bpm_lock,"
"keys_version,"
"keys_sub_version,"
"keys,"
"coverart_source,"
"coverart_type,"
"coverart_location,"
"coverart_color,"
"coverart_digest,"
"coverart_hash,"
"datetime_added"
") VALUES ("
":artist,"
":title,"
":album,"
":album_artist,"
":year,"
":genre,"
":tracknumber,"
":tracktotal,"
":composer,"
":grouping,"
":filetype,"
":location,"
":color,"
":comment,"
":url,"
":rating,"
":key,"
":key_id,"
":cuepoint,"
":bpm,"
":replaygain,"
":replaygain_peak,"
":wavesummaryhex,"
":timesplayed,"
":last_played_at,"
":played,"
":mixxx_deleted,"
":header_parsed,"
":source_synchronized_ms,"
":channels,"
":samplerate,"
":bitrate,"
":duration,"
":beats_version,"
":beats_sub_version,"
":beats,"
":bpm_lock,"
":keys_version,"
":keys_sub_version,"
":keys,"
":coverart_source,"
":coverart_type,"
":coverart_location,"
":coverart_color,"
":coverart_digest,"
":coverart_hash,"
":datetime_added"
")");
m_pQueryLibraryUpdate->prepare("UPDATE library SET mixxx_deleted = 0 "
"WHERE id=:id");
m_pQueryLibrarySelect->prepare("SELECT location, id, mixxx_deleted from library "
"WHERE location=:location");
}
void TrackDAO::addTracksFinish(bool rollback) {
if (m_pTransaction) {
if (rollback) {
m_pTransaction->rollback();
m_tracksAddedSet.clear();
} else {
m_pTransaction->commit();
}
}
m_pQueryTrackLocationInsert.reset();
m_pQueryTrackLocationSelect.reset();
m_pQueryLibraryInsert.reset();
m_pQueryLibrarySelect.reset();
m_pTransaction.reset();
emit tracksAdded(m_tracksAddedSet);
m_tracksAddedSet.clear();
}
namespace {
bool insertTrackLocation(
QSqlQuery* pTrackLocationInsert,
const mixxx::FileInfo& fileInfo) {
DEBUG_ASSERT(pTrackLocationInsert);
pTrackLocationInsert->bindValue(":location", fileInfo.location());
pTrackLocationInsert->bindValue(":directory", fileInfo.locationPath());
pTrackLocationInsert->bindValue(":filename", fileInfo.fileName());
pTrackLocationInsert->bindValue(":filesize", fileInfo.sizeInBytes());
pTrackLocationInsert->bindValue(":fs_deleted", 0);
pTrackLocationInsert->bindValue(":needs_verification", 0);
if (pTrackLocationInsert->exec()) {
return true;
} else {
LOG_FAILED_QUERY(*pTrackLocationInsert)
<< "Skip inserting duplicate track location" << fileInfo.location();
return false;
}
}
// Bind common values for insert/update
void bindTrackLibraryValues(
QSqlQuery* pTrackLibraryQuery,
const mixxx::TrackRecord& track,
const mixxx::BeatsPointer& pBeats) {
const mixxx::TrackMetadata& trackMetadata = track.getMetadata();
const mixxx::TrackInfo& trackInfo = trackMetadata.getTrackInfo();
const mixxx::AlbumInfo& albumInfo = trackMetadata.getAlbumInfo();
pTrackLibraryQuery->bindValue(":artist", trackInfo.getArtist());
pTrackLibraryQuery->bindValue(":title", trackInfo.getTitle());
pTrackLibraryQuery->bindValue(":album", albumInfo.getTitle());
pTrackLibraryQuery->bindValue(":album_artist", albumInfo.getArtist());
pTrackLibraryQuery->bindValue(":year", trackInfo.getYear());
pTrackLibraryQuery->bindValue(":genre", trackInfo.getGenre());
pTrackLibraryQuery->bindValue(":composer", trackInfo.getComposer());
pTrackLibraryQuery->bindValue(":grouping", trackInfo.getGrouping());
pTrackLibraryQuery->bindValue(":tracknumber", trackInfo.getTrackNumber());
pTrackLibraryQuery->bindValue(":tracktotal", trackInfo.getTrackTotal());
pTrackLibraryQuery->bindValue(":filetype", track.getFileType());
pTrackLibraryQuery->bindValue(":color", mixxx::RgbColor::toQVariant(track.getColor()));
pTrackLibraryQuery->bindValue(":comment", trackInfo.getComment());
pTrackLibraryQuery->bindValue(":url", track.getUrl());
pTrackLibraryQuery->bindValue(":rating", track.getRating());
pTrackLibraryQuery->bindValue(":cuepoint",
track.getMainCuePosition().toEngineSamplePosMaybeInvalid());
pTrackLibraryQuery->bindValue(":bpm_lock", track.getBpmLocked() ? 1 : 0);
pTrackLibraryQuery->bindValue(":replaygain", trackInfo.getReplayGain().getRatio());
pTrackLibraryQuery->bindValue(":replaygain_peak", trackInfo.getReplayGain().getPeak());
pTrackLibraryQuery->bindValue(":channels",
static_cast<uint>(trackMetadata.getStreamInfo().getSignalInfo().getChannelCount()));
pTrackLibraryQuery->bindValue(":samplerate",
static_cast<uint>(trackMetadata.getStreamInfo().getSignalInfo().getSampleRate()));
pTrackLibraryQuery->bindValue(":bitrate",
static_cast<uint>(trackMetadata.getStreamInfo().getBitrate()));
pTrackLibraryQuery->bindValue(":duration",
trackMetadata.getStreamInfo().getDuration().toDoubleSeconds());
pTrackLibraryQuery->bindValue(":header_parsed",
TrackDAO::getTrackHeaderParsedInternal(track) ? 1 : 0);
const QDateTime sourceSynchronizedAt =
track.getSourceSynchronizedAt();
if (sourceSynchronizedAt.isValid()) {
DEBUG_ASSERT(sourceSynchronizedAt.timeSpec() == Qt::UTC);
pTrackLibraryQuery->bindValue(":source_synchronized_ms",
sourceSynchronizedAt.toMSecsSinceEpoch());
} else {
pTrackLibraryQuery->bindValue(":source_synchronized_ms",
QVariant());
}
const PlayCounter& playCounter = track.getPlayCounter();
pTrackLibraryQuery->bindValue(":timesplayed", playCounter.getTimesPlayed());
pTrackLibraryQuery->bindValue(":last_played_at",
mixxx::sqlite::writeGeneratedTimestamp(playCounter.getLastPlayedAt()));
pTrackLibraryQuery->bindValue(":played", playCounter.isPlayed() ? 1 : 0);
const CoverInfoRelative& coverInfo = track.getCoverInfo();
pTrackLibraryQuery->bindValue(":coverart_source", coverInfo.source);
pTrackLibraryQuery->bindValue(":coverart_type", coverInfo.type);
pTrackLibraryQuery->bindValue(":coverart_location", coverInfo.coverLocation);
pTrackLibraryQuery->bindValue(":coverart_color", mixxx::RgbColor::toQVariant(coverInfo.color));
pTrackLibraryQuery->bindValue(":coverart_digest", coverInfo.imageDigest());
pTrackLibraryQuery->bindValue(":coverart_hash", coverInfo.legacyHash());
QByteArray beatsBlob;
QString beatsVersion;
QString beatsSubVersion;
// Fall back on cached BPM
mixxx::Bpm bpm = trackInfo.getBpm();
if (pBeats) {
beatsBlob = pBeats->toByteArray();
beatsVersion = pBeats->getVersion();
beatsSubVersion = pBeats->getSubVersion();
const auto trackEndPosition = mixxx::audio::FramePos{
trackMetadata.getStreamInfo().getDuration().toDoubleSeconds() *
pBeats->getSampleRate()};
bpm = pBeats->getBpmInRange(mixxx::audio::kStartFramePos, trackEndPosition);
}
const double bpmValue = bpm.isValid() ? bpm.value() : mixxx::Bpm::kValueUndefined;
pTrackLibraryQuery->bindValue(":bpm", bpmValue);
pTrackLibraryQuery->bindValue(":beats_version", beatsVersion);
pTrackLibraryQuery->bindValue(":beats_sub_version", beatsSubVersion);
pTrackLibraryQuery->bindValue(":beats", beatsBlob);
const Keys keys = track.getKeys();
QByteArray keysBlob = keys.toByteArray();
QString keysVersion = keys.getVersion();
QString keysSubVersion = keys.getSubVersion();
mixxx::track::io::key::ChromaticKey key = keys.getGlobalKey();
QString keyText = keys.getGlobalKeyText();
pTrackLibraryQuery->bindValue(":keys", keysBlob);
pTrackLibraryQuery->bindValue(":keys_version", keysVersion);
pTrackLibraryQuery->bindValue(":keys_sub_version", keysSubVersion);
pTrackLibraryQuery->bindValue(":key_id", static_cast<int>(key));
pTrackLibraryQuery->bindValue(":key", keyText);
}
bool insertTrackLibrary(
QSqlQuery* pTrackLibraryInsert,
const mixxx::TrackRecord& trackRecord,
const mixxx::BeatsPointer& pBeats,
DbId trackLocationId,
const mixxx::FileInfo& fileInfo,
const QDateTime& trackDateAdded) {
bindTrackLibraryValues(pTrackLibraryInsert, trackRecord, pBeats);
if (!trackRecord.getDateAdded().isNull()) {
qDebug() << "insertTrackLibrary: Track"
<< fileInfo
<< "was added"
<< trackRecord.getDateAdded();
}
pTrackLibraryInsert->bindValue(":datetime_added", trackDateAdded);
// Written only once upon insert
pTrackLibraryInsert->bindValue(":location", trackLocationId.toVariant());
// Column datetime_added is set implicitly
//pTrackLibraryInsert->bindValue(":datetime_added", track.getDateAdded());
pTrackLibraryInsert->bindValue(":mixxx_deleted", 0);
// We no longer store the wavesummary in the library table.
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
pTrackLibraryInsert->bindValue(":wavesummaryhex", QVariant(QMetaType(QMetaType::QByteArray)));
#else
pTrackLibraryInsert->bindValue(":wavesummaryhex", QVariant(QVariant::ByteArray));
#endif
if (!pTrackLibraryInsert->exec()) {
// We failed to insert the track. Maybe it is already in the library
// but marked deleted? Skip this track.
LOG_FAILED_QUERY(*pTrackLibraryInsert)
<< "Failed to insert new track into library:"
<< fileInfo;
DEBUG_ASSERT(!"Failed query");
return false;
}
return true;
}
} // anonymous namespace
TrackId TrackDAO::addTracksAddTrack(const TrackPointer& pTrack, bool unremove) {
DEBUG_ASSERT(pTrack);
const mixxx::FileInfo fileInfo = pTrack->getFileInfo();
if (!(m_pQueryLibraryInsert || m_pQueryTrackLocationInsert ||
m_pQueryLibrarySelect || m_pQueryTrackLocationSelect)) {
qDebug() << "TrackDAO::addTracksAddTrack: needed SqlQuerys have not "
"been prepared. Skipping track"
<< fileInfo.location();
DEBUG_ASSERT("Failed query");
return TrackId();
}
qDebug() << "TrackDAO: Adding track"
<< fileInfo.location();
TrackId trackId;
// Insert the track location into the corresponding table. This will fail
// silently if the location is already in the table because it has a UNIQUE
// constraint.
if (!insertTrackLocation(m_pQueryTrackLocationInsert.get(), fileInfo)) {
DEBUG_ASSERT(pTrack->getDateAdded().isValid());
// Inserting into track_locations failed, so the file already
// exists. Query for its trackLocationId.
m_pQueryTrackLocationSelect->bindValue(":location", fileInfo.location());
if (!m_pQueryTrackLocationSelect->exec()) {
// We can't even select this, something is wrong.
LOG_FAILED_QUERY(*m_pQueryTrackLocationSelect)
<< "Can't find track location ID after failing to insert. Something is wrong.";
return TrackId();
}
if (m_trackLocationIdColumn == UndefinedRecordIndex) {
m_trackLocationIdColumn = m_pQueryTrackLocationSelect->record().indexOf("id");
}
DbId trackLocationId;
while (m_pQueryTrackLocationSelect->next()) {
// This loop body is executed at most once
DEBUG_ASSERT(!trackLocationId.isValid());
trackLocationId = DbId(
m_pQueryTrackLocationSelect->value(m_trackLocationIdColumn));
DEBUG_ASSERT(trackLocationId.isValid());
}
m_pQueryLibrarySelect->bindValue(":location", trackLocationId.toVariant());
if (!m_pQueryLibrarySelect->exec()) {
LOG_FAILED_QUERY(*m_pQueryLibrarySelect)
<< "Failed to query existing track: "
<< fileInfo.location();
return TrackId();
}
if (m_queryLibraryIdColumn == UndefinedRecordIndex) {
QSqlRecord queryLibraryRecord = m_pQueryLibrarySelect->record();
m_queryLibraryIdColumn = queryLibraryRecord.indexOf("id");
m_queryLibraryMixxxDeletedColumn =
queryLibraryRecord.indexOf("mixxx_deleted");
}
while (m_pQueryLibrarySelect->next()) {
// This loop body is executed at most once
DEBUG_ASSERT(!trackId.isValid());
trackId = TrackId(m_pQueryLibrarySelect->value(m_queryLibraryIdColumn));
DEBUG_ASSERT(trackId.isValid());
}
VERIFY_OR_DEBUG_ASSERT(trackId.isValid()) {
return TrackId();
}
pTrack->initId(trackId);
// Track already included in library, but maybe marked as deleted
bool mixxx_deleted = m_pQueryLibrarySelect->value(m_queryLibraryMixxxDeletedColumn).toBool();
if (unremove && mixxx_deleted) {
// Set mixxx_deleted back to 0
m_pQueryLibraryUpdate->bindValue(":id", trackId.toVariant());
if (!m_pQueryLibraryUpdate->exec()) {
LOG_FAILED_QUERY(*m_pQueryLibraryUpdate)
<< "Failed to unremove existing track: "
<< fileInfo.location();
return TrackId();
}
}
// Regardless of whether we unremoved this track or not -- it's
// already in the library and so we need to skip it instead of
// adding it to m_tracksAddedSet.
//
// TODO(XXX) this is a little weird because the track has whatever
// metadata the caller supplied and that metadata may differ from
// what is already in the database. I'm ignoring this corner case.
// rryan 10/2011
// NOTE(uklotzde, 01/2016): It doesn't matter if the track metadata
// has been modified (dirty=true) or not (dirty=false). By not adding
// the track to m_tracksAddedSet we ensure that the track is not
// marked as clean (see below). The library will be updated when
// the last reference to the track is dropped.
} else {
// Inserting succeeded, so just get the last rowid.
const DbId trackLocationId(m_pQueryTrackLocationInsert->lastInsertId());
// Failure of this assert indicates that we were unable to insert the
// track location into the table AND we could not retrieve the id of
// that track location from the same table. "It shouldn't
// happen"... unless I screwed up - Albert :)
VERIFY_OR_DEBUG_ASSERT(trackLocationId.isValid()) {
return TrackId();
}
// Time stamps are stored with timezone UTC in the database
const auto trackDateAdded = QDateTime::currentDateTimeUtc();
const auto trackRecord = pTrack->getRecord();
if (!insertTrackLibrary(
m_pQueryLibraryInsert.get(),
trackRecord,
pTrack->getBeats(),
trackLocationId,
fileInfo,
trackDateAdded)) {
return TrackId();
}
trackId = TrackId(m_pQueryLibraryInsert->lastInsertId());
VERIFY_OR_DEBUG_ASSERT(trackId.isValid()) {
return TrackId();
}
pTrack->initId(trackId);
pTrack->setDateAdded(trackDateAdded);
m_analysisDao.saveTrackAnalyses(
trackId,
pTrack->getWaveform(),
pTrack->getWaveformSummary());
m_cueDao.saveTrackCues(
trackId,
pTrack->getCuePoints());
DEBUG_ASSERT(!m_tracksAddedSet.contains(trackId));
m_tracksAddedSet.insert(trackId);
}
return trackId;
}
TrackPointer TrackDAO::addTracksAddFile(
const mixxx::FileAccess& fileAccess,
bool unremove) {
// Check that track is a supported extension.
// TODO(uklotzde): The following check can be skipped if
// the track is already in the library. A refactoring is
// needed to detect this before calling addTracksAddTrack().
if (!SoundSourceProxy::isFileSupported(fileAccess.info())) {
qWarning() << "TrackDAO::addTracksAddFile:"
<< "Unsupported file type"
<< fileAccess.info().location();
return nullptr;
}
GlobalTrackCacheResolver cacheResolver(fileAccess);
TrackPointer pTrack = cacheResolver.getTrack();
if (!pTrack) {
qWarning() << "TrackDAO::addTracksAddFile:"
<< "File not found"
<< fileAccess.info().location();
return nullptr;
}
const TrackId oldTrackId = pTrack->getId();
if (oldTrackId.isValid()) {
qDebug() << "TrackDAO::addTracksAddFile:"
<< "Track has already been added to the database"
<< oldTrackId;
DEBUG_ASSERT(pTrack->getDateAdded().isValid());
const auto trackLocation = pTrack->getLocation();
// TODO: These duplicates are only detected by chance when
// the other track is currently cached. Instead file aliasing
// must be detected reliably in any situation.
if (fileAccess.info().location() != trackLocation) {
kLogger.warning()
<< "Cannot add track:"
<< "Both the new track at"
<< fileAccess.info().location()
<< "and an existing track at"
<< trackLocation
<< "are referencing the same file"
<< fileAccess.info().canonicalLocation();
return nullptr;
}
return pTrack;
}
// Keep the GlobalTrackCache locked until the id of the Track
// object is known and has been updated in the cache.
// Initially (re-)import the metadata for the newly created track
// from the file.
SoundSourceProxy(pTrack).updateTrackFromSource(
SoundSourceProxy::UpdateTrackFromSourceMode::Once,
SyncTrackMetadataParams::readFromUserSettings(*m_pConfig));
if (!pTrack->checkSourceSynchronized()) {
qWarning() << "TrackDAO::addTracksAddFile:"
<< "Failed to parse track metadata from file"
<< pTrack->getLocation();
// Continue with adding the track to the library, no matter
// if parsing the metadata from file succeeded or failed.
}
const TrackId newTrackId = addTracksAddTrack(pTrack, unremove);
if (!newTrackId.isValid()) {
qWarning() << "TrackDAO::addTracksAddTrack:"
<< "Failed to add track to database"
<< pTrack->getLocation();
// GlobalTrackCache will be unlocked implicitly
return nullptr;
}
// The track object has already been initialized with the
// database id, but the cache is not aware of this yet.
// Re-initializing the track object with the same id again
// from within the cache scope is allowed.
DEBUG_ASSERT(pTrack->getId() == newTrackId);
cacheResolver.initTrackIdAndUnlockCache(newTrackId);
// Only newly inserted tracks must be marked as clean!
// Existing or unremoved tracks have not been added to
// m_tracksAddedSet and will keep their dirty flag unchanged.
if (m_tracksAddedSet.contains(newTrackId)) {
pTrack->markClean();
}
return pTrack;
}
bool TrackDAO::hideTracks(
const QList<TrackId>& trackIds) const {
QStringList idList;
for (const auto& trackId: trackIds) {
idList.append(trackId.toString());
}
FwdSqlQuery query(m_database, QString(
"UPDATE library SET mixxx_deleted=1 WHERE id in (%1)").arg(
idList.join(",")));
return !query.hasError() && query.execPrepared();
}
void TrackDAO::afterHidingTracks(
const QList<TrackId>& trackIds) {
// This signal is received by basetrackcache to remove the tracks from cache
// 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)
emit tracksRemoved(QSet<TrackId>(trackIds.begin(), trackIds.end()));
#else
emit tracksRemoved(QSet<TrackId>::fromList(trackIds));
#endif
}
// If a track has been manually "hidden" from Mixxx's library by the user via
// Mixxx's interface, this lets you add it back. When a track is hidden,
// mixxx_deleted in the DB gets set to 1. This clears that, and makes it show
// up in the library views again.
// This function should get called if you drag-and-drop a file that's been
// "hidden" from Mixxx back into the library view.
bool TrackDAO::unhideTracks(
const QList<TrackId>& trackIds) const {
QStringList idList;
for (const auto& trackId: trackIds) {
idList.append(trackId.toString());
}
FwdSqlQuery query(m_database,
"UPDATE library SET mixxx_deleted=0 "
"WHERE mixxx_deleted!=0 "
"AND id in (" + idList.join(",") + ")");
return !query.hasError() && query.execPrepared();
}
void TrackDAO::afterUnhidingTracks(
const QList<TrackId>& trackIds) {
// 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)
emit tracksAdded(QSet<TrackId>(trackIds.begin(), trackIds.end()));
#else
emit tracksAdded(QSet<TrackId>::fromList(trackIds));
#endif
}
QList<TrackRef> TrackDAO::getAllTrackRefs(const QDir& rootDir) const {
const QString locationPathPrefix = locationPathPrefixFromRootDir(rootDir);
QSqlQuery query(m_database);
query.prepare(
QStringLiteral("SELECT library.id,track_locations.location "
"FROM library INNER JOIN track_locations "
"ON library.location=track_locations.id "
"WHERE "
"INSTR(track_locations.location,:locationPathPrefix)=1"));
query.bindValue(":locationPathPrefix", locationPathPrefix);
if (!query.exec()) {
LOG_FAILED_QUERY(query) << "could not get tracks within directory:" << locationPathPrefix;
DEBUG_ASSERT(!"Failed query");
}
QList<TrackRef> trackRefs;
const int idColumn = query.record().indexOf("id");
const int locationColumn = query.record().indexOf("location");
while (query.next()) {
const auto trackId = TrackId(query.value(idColumn));
const auto fileLocation = query.value(locationColumn).toString();
trackRefs.append(TrackRef::fromFilePath(fileLocation, trackId));
}