File: resourcetable.cpp

package info (click to toggle)
nixnote2 2.0~beta11-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 9,448 kB
  • ctags: 7,058
  • sloc: cpp: 68,338; java: 1,096; sh: 834; makefile: 27
file content (1202 lines) | stat: -rw-r--r-- 36,614 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
/*********************************************************************************
NixNote - An open-source client for the Evernote service.
Copyright (C) 2013 Randy Baumgarte

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
***********************************************************************************/


#include "resourcetable.h"
#include "configstore.h"
#include "notetable.h"
#include "utilities/mimereference.h"
#include "sql/nsqlquery.h"
#include "utilities/noteindexer.h"

#include <QSqlTableModel>

#include <iostream>
#include <fstream>

using namespace std;
extern Global global;

// Default constructor
ResourceTable::ResourceTable(DatabaseConnection *db)
{
    this->db = db;
}



// Given a resource's lid, we give it a new guid.  This can happen
// the first time a record is synchronized
void ResourceTable::updateGuid(qint32 lid, Guid &guid) {
    QLOG_TRACE() << "Entering ResourceTable::updateGuid()";

    db->lockForWrite();
    NSqlQuery query(db);
    query.prepare("Update DataStore set data=:data where key=:key and lid=:lid");
    query.bindValue(":data", guid);
    query.bindValue(":lid", lid);
    query.bindValue(":key", RESOURCE_GUID);
    query.exec();
    query.finish();
    db->unlock();

    QLOG_TRACE() << "Leaving ResourceTable::updateGuid()";
}




// Synchronize a new resource with what is in the database.  We basically
// just delete the old one & give it a new entry
void ResourceTable::sync(Resource &resource) {
    QLOG_TRACE() << "Leaving ResourceTable::sync()";
    sync(0, resource);
    QLOG_TRACE() << "Leaving ResourceTable::sync()";
}



// Synchronize a new resource with what is in the database.  We basically
// just delete the old one & give it a new entry
void ResourceTable::sync(qint32 lid, Resource &resource) {
    QLOG_TRACE() << "Leaving ResourceTable::sync()";

    if (lid > 0) {
        expunge(lid);
        NSqlQuery query(db);
        // Delete the old record
        db->lockForWrite();
        query.prepare("Delete from DataStore where lid=:lid");
        query.bindValue(":lid", lid);
        query.exec();
        query.finish();
        db->unlock();

    } else {
        ConfigStore cs(db);
        lid = cs.incrementLidCounter();
    }

    add(lid, resource, false);

    QLOG_TRACE() << "Leaving ResourceTable::sync()";
}




// Given a resource's GUID, we return the LID
qint32 ResourceTable::getLid(QString noteGuid, QString guid) {

    NSqlQuery query(db);
    NoteTable n(db);
    db->lockForRead();
    qint32 noteLid = n.getLid(noteGuid);
    query.prepare("Select a.lid from DataStore a where a.data=:data and a.key=:key and a.lid = (select distinct b.lid from DataStore b where b.key=:key2 and b.data=:noteLid)");
    query.bindValue(":data", guid);
    query.bindValue(":key", RESOURCE_GUID);
    query.bindValue(":key2", RESOURCE_NOTE_LID);
    query.bindValue(":noteLid", noteLid);
    query.exec();
    qint32 retval = 0;
    if (query.next())
        retval = query.value(0).toInt();
    query.finish();
    db->unlock();
    return retval;
}


// Given a resource's GUID, we return the LID
qint32 ResourceTable::getLid(string noteGuid, string guid) {
    QString nGuid(QString::fromStdString(noteGuid));
    QString rGuid(QString::fromStdString(guid));
    return getLid(nGuid, rGuid);
}


// Get the lid for a resource guid
qint32 ResourceTable::getLid(string resourceGuid) {
    return this->getLid(QString::fromStdString(resourceGuid));
}


// Get the lid for a given resource's guid
qint32 ResourceTable::getLid(QString resourceGuid) {
    NSqlQuery query(db);
    db->lockForRead();
    query.prepare("Select lid from DataStore where key=:key and data=:data");
    query.bindValue(":key", RESOURCE_GUID);
    query.bindValue(":data", resourceGuid);
    query.exec();
    qint32 retval = 0;
    if (query.next())
        retval = query.value(0).toInt();
    query.finish();
    db->unlock();
    return retval;
}


// Get the guid for a given resource lid
QString ResourceTable::getGuid(int lid) {
    NSqlQuery query(db);
    db->lockForRead();
    query.prepare("Select data from DataStore where key=:key and lid=:lid");
    query.bindValue(":key", RESOURCE_GUID);
    query.bindValue(":lid", lid);
    query.exec();
    QString retval = "";
    if (query.next())
        retval = query.value(0).toString();
    query.finish();
    db->unlock();
    return retval;
}

// Return a resource structure given the LID
bool ResourceTable::get(Resource &resource, qint32 lid, bool withBinary) {

    NSqlQuery query(db);
    db->lockForRead();
    query.prepare("Select key, data from DataStore where lid=:lid");
    query.bindValue(":lid", lid);
    query.exec();
    if (query.size() == 0) {
        db->unlock();
        return false;
    }
    while (query.next()) {
        mapResource(query, resource);
    }
    query.finish();
    db->unlock();

    // Now read the binary data from the disk
    if (withBinary) {
        QString mimetype = resource.mime;
        MimeReference ref;
        QString filename;
        ResourceAttributes attributes;
        if (resource.attributes.isSet())
            attributes = resource.attributes;
        if (attributes.fileName.isSet())
            filename = attributes.fileName;
        QString fileExt = ref.getExtensionFromMime(mimetype, filename);
        QFile tfile(global.fileManager.getDbDirPath("/dba/"+QString::number(lid)) +fileExt );
        tfile.open(QIODevice::ReadOnly);
        QByteArray b = tfile.readAll();
        Data d;
        if (resource.data.isSet())
            d = resource.data;
        d.body = b;
        resource.data = d;
        tfile.close();
    }

    return true;
}



// Save a resource's map data.
void ResourceTable::mapResource(NSqlQuery &query, Resource &resource) {
    NoteTable ntable(db);
    Data d, rd, ad;
    ResourceAttributes attributes;
    if (resource.data.isSet())
        d = resource.data;
    if (resource.recognition.isSet())
        rd = resource.recognition;
    if (resource.alternateData.isSet())
        ad = resource.alternateData;
    if (resource.attributes.isSet())
        attributes = resource.attributes;
    qint32 key = query.value(0).toInt();
    switch (key) {
    case (RESOURCE_GUID):
        resource.guid = query.value(1).toString();
        break;
    case (RESOURCE_NOTE_LID):
        resource.noteGuid = ntable.getGuid(query.value(1).toInt());
        break;
    case (RESOURCE_DATA_BODY):
          break;
    case (RESOURCE_DATA_HASH):
        d.bodyHash = QByteArray::fromHex(query.value(1).toByteArray());
        resource.data = d;
        break;
    case (RESOURCE_DATA_SIZE):
        d.size = query.value(1).toInt();
        resource.data = d;
        break;
    case (RESOURCE_MIME):
        resource.mime = query.value(1).toString();
        break;
    case (RESOURCE_ACTIVE):
        resource.active = query.value(1).toBool();
        break;
    case (RESOURCE_HEIGHT):
        resource.height = query.value(1).toString().toInt();
        break;
    case (RESOURCE_WIDTH):
        resource.width = query.value(1).toString().toInt();
        break;
    case (RESOURCE_DURATION):
        resource.duration = query.value(1).toString().toInt();
        break;
    case (RESOURCE_RECOGNITION_BODY):
        rd.body = query.value(1).toByteArray();
        resource.recognition = rd;
        break;
    case (RESOURCE_RECOGNITION_HASH):
        rd.bodyHash = query.value(1).toByteArray();
        resource.recognition = rd;
        break;
    case (RESOURCE_RECOGNITION_SIZE):
        rd.size = query.value(1).toInt();
        resource.recognition = rd;
        break;
    case (RESOURCE_UPDATE_SEQUENCE_NUMBER):
        resource.duration = query.value(1).toString().toInt();
        break;
    case (RESOURCE_ALTERNATE_BODY):
        ad.body = query.value(1).toByteArray();
        resource.alternateData = ad;
        break;
    case (RESOURCE_ALTERNATE_HASH):
        ad.bodyHash = query.value(1).toByteArray();
        resource.alternateData = ad;
        break;
    case (RESOURCE_ALTERNATE_SIZE):
        ad.size = query.value(1).toInt();
        resource.alternateData = ad;
        break;
    case (RESOURCE_SOURCE_URL):
        attributes.sourceURL = query.value(1).toString();
        resource.attributes = attributes;
        break;
    case (RESOURCE_CAMERA_MAKE):
        attributes.cameraMake = query.value(1).toString();
        resource.attributes = attributes;
        break;
    case (RESOURCE_CAMERA_MODEL):
        attributes.cameraModel = query.value(1).toString();
        resource.attributes = attributes;
        break;
    case (RESOURCE_ALTITUDE):
        attributes.altitude = query.value(1).toString().toDouble();
        resource.attributes = attributes;
        break;
    case (RESOURCE_LONGITUDE):
        attributes.longitude = query.value(1).toString().toDouble();
        resource.attributes = attributes;
        break;
    case (RESOURCE_LATITUDE):
        attributes.latitude = query.value(1).toString().toDouble();
        resource.attributes = attributes;
        break;
    case (RESOURCE_RECO_TYPE):
        attributes.recoType = query.value(1).toString();
        resource.attributes = attributes;
        break;
    case (RESOURCE_ATTACHMENT):
        attributes.attachment = query.value(1).toBool();
        resource.attributes = attributes;
        break;
    case (RESOURCE_FILENAME):
        attributes.fileName = query.value(1).toString();
        resource.attributes = attributes;
        break;
    case (RESOURCE_CLIENT_WILL_INDEX):
        attributes.clientWillIndex = query.value(1).toBool();
        resource.attributes = attributes;
        break;
    case (RESOURCE_TIMESTAMP):
        attributes.timestamp = query.value(1).toDouble();
        resource.attributes = attributes;
        break;
    }
}




// Return a resource given the GUID
bool ResourceTable::get(Resource &resource, QString noteGuid, QString guid, bool withBinary) {
    qint32 lid = getLid(noteGuid, guid);
    return get(resource, lid, withBinary);
}



// Return a resource given the GUID as a std::string
bool ResourceTable::get(Resource &resource, string noteGuid, string guid, bool withBinary) {
    qint32 lid = getLid(noteGuid, guid);
    return get(resource, lid, withBinary);
}



// Return if a resource is dirty given its lid
bool ResourceTable::isDirty(qint32 lid) {
    NSqlQuery query(db);
    db->lockForRead();
    query.prepare("Select data from DataStore where key=:key and lid=:lid");
    query.bindValue(":lid", lid);
    query.bindValue(":key", RESOURCE_ISDIRTY);
    query.exec();
    bool retval = false;
    if (query.next())
        retval = query.value(0).toBool();
    query.finish();
    db->unlock();
    return retval;
}


// Determine if a resource is dirty given a guid
bool ResourceTable::isDirty(QString noteGuid, QString guid) {
    qint32 lid = getLid(noteGuid, guid);
    return isDirty(lid);
}


// Determine if a resource is dirty given a guid
bool ResourceTable::isDirty(string noteGuid, string guid) {
    QString g(QString::fromStdString(guid));
    QString ng(QString::fromStdString(noteGuid));
    return isDirty(ng, g);
}


// Does this resource exist?
bool ResourceTable::exists(qint32 lid) {
    NSqlQuery query(db);
    db->lockForRead();
    query.prepare("Select lid from DataStore where key=:key and lid=:lid");
    query.bindValue(":lid", lid);
    query.bindValue(":key", RESOURCE_GUID);
    query.exec();
    bool retval = false;
    if (query.next())
        retval = true;
    query.finish();
    db->unlock();
    return retval;
}


// Determine if a resource exists given a guid
bool ResourceTable::exists(QString noteGuid, QString guid) {
    qint32 lid = getLid(noteGuid, guid);
    return exists(lid);
}


// Determine if a resource exists given a guid
bool ResourceTable::exists(string noteGuid, string guid) {
    qint32 lid = getLid(noteGuid, guid);
    return exists(lid);
}


// Add a resource to the database
qint32 ResourceTable::add(qint32 l, Resource &t, bool isDirty, int noteLid) {
    ConfigStore cs(db);
    qint32 lid = l;
    if (lid <= 0)
        lid = cs.incrementLidCounter();
    else
        expunge(lid);

    NSqlQuery query(db);
    db->lockForWrite();
    query.prepare("Insert into DataStore (lid, key, data) values (:lid, :key, :data)");

    if (t.guid.isSet()) {
        QString guid = t.guid;
        query.bindValue(":lid", lid);
        query.bindValue(":key", RESOURCE_GUID);
        query.bindValue(":data", guid);
        query.exec();
    }

    query.bindValue(":lid", lid);
    query.bindValue(":key", RESOURCE_INDEX_NEEDED);
    query.bindValue(":data", true);
    query.exec();

    if (noteLid <=0) {
        NoteTable noteTable(db);
        noteLid = noteTable.getLid(t.noteGuid);
        if (noteLid <=0) {
            noteLid = noteTable.addStub(t.noteGuid);
        }
    }
    query.bindValue(":lid", lid);
    query.bindValue(":key", RESOURCE_NOTE_LID);
    query.bindValue(":data", noteLid);
    query.exec();

    query.bindValue(":lid", lid);
    query.bindValue(":key", RESOURCE_ISDIRTY);
    query.bindValue(":data", isDirty);
    query.exec();

    if (t.data.isSet()) {
        Data d = t.data;
        if (d.size.isSet()) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", RESOURCE_DATA_SIZE);
            qint32 size = d.size;
            query.bindValue(":data", size);
            query.exec();
        }

        if (d.bodyHash.isSet()) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", RESOURCE_DATA_HASH);
            QByteArray b;
            b.append(d.bodyHash);
            query.bindValue(":data", b.toHex());
            query.exec();
        }

        if (d.body.isSet()) {
            QString mimetype = t.mime;
            QString filename;
            MimeReference ref;
            ResourceAttributes attributes;
            if (t.attributes.isSet())
                attributes = t.attributes;
            if (attributes.fileName.isSet())
                filename = attributes.fileName;
            QString fileExt = ref.getExtensionFromMime(mimetype, filename);
            QFile tfile(global.fileManager.getDbDirPath("/dba/"+QString::number(lid)) +fileExt );
            tfile.open(QIODevice::WriteOnly);
            if (d.size > 0)
                tfile.write(d.body);
            tfile.close();
        }
    }

    if (t.mime.isSet()) {
        query.bindValue(":lid", lid);
        query.bindValue(":key", RESOURCE_MIME);
        QString mime = t.mime;
        query.bindValue(":data", mime);
        query.exec();
    }

    if (t.width.isSet()) {
        qint16 width = t.width;
        query.bindValue(":lid", lid);
        query.bindValue(":key", RESOURCE_WIDTH);
        query.bindValue(":data", width);
        query.exec();
    }

    if (t.height.isSet()) {
        qint16 height = t.height;
        query.bindValue(":lid", lid);
        query.bindValue(":key", RESOURCE_HEIGHT);
        query.bindValue(":data", height);
        query.exec();
    }

    if (t.duration.isSet()) {
        qint16 duration = t.duration;
        query.bindValue(":lid", lid);
        query.bindValue(":key", RESOURCE_DURATION);
        query.bindValue(":data", duration);
        query.exec();
    }

    if (t.active.isSet()) {
        query.bindValue(":lid", lid);
        query.bindValue(":key", RESOURCE_ACTIVE);
        bool active = t.active;
        query.bindValue(":data", active);
        query.exec();
    }

    if (t.recognition.isSet()) {
        Data r = t.recognition;
        if (r.size.isSet()) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", RESOURCE_RECOGNITION_SIZE);
            qint32 size = r.size;
            query.bindValue(":data", size);
            query.exec();
        }

        if (r.bodyHash.isSet()) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", RESOURCE_RECOGNITION_HASH);
            QByteArray b;
            b.append(r.bodyHash);
            query.bindValue(":data", b.toHex());
            query.exec();
        }

        if (r.body.isSet()) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", RESOURCE_RECOGNITION_BODY);
            QByteArray body = r.body;
            query.bindValue(":data", body);
            query.exec();
        }
    }

    if (t.updateSequenceNum.isSet()) {
        qint32 usn =t.updateSequenceNum;
        query.bindValue(":key", RESOURCE_UPDATE_SEQUENCE_NUMBER);
        query.bindValue(":data", usn);
        query.exec();
    }


    if (t.alternateData.isSet()) {
        Data ad = t.alternateData;
        if (ad.size.isSet()) {
            qint32 size = ad.size;
            query.bindValue(":lid", lid);
            query.bindValue(":key", RESOURCE_ALTERNATE_SIZE);
            query.bindValue(":data", size);
            query.exec();
        }

        if (ad.bodyHash.isSet()) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", RESOURCE_ALTERNATE_HASH);
            QByteArray b;
            b.append(ad.bodyHash);
            query.bindValue(":data", b.toHex());
            query.exec();
        }

        if (ad.body.isSet()) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", RESOURCE_ALTERNATE_BODY);
            QByteArray body = ad.body;
            query.bindValue(":data", body);
            query.exec();
        }
    }


    if (t.attributes.isSet()) {
        ResourceAttributes ra = t.attributes;
        if (ra.sourceURL.isSet()) {
            query.bindValue(":lid", lid);
            QString url = ra.sourceURL;
            query.bindValue(":key", RESOURCE_SOURCE_URL);
            query.bindValue(":data", url);
            query.exec();
        }

        if (ra.timestamp.isSet()) {
            qlonglong ts = ra.timestamp;
            query.bindValue(":lid", lid);
            query.bindValue(":key", RESOURCE_TIMESTAMP);
            query.bindValue(":data", ts);
            query.exec();
        }

        if (ra.latitude.isSet()) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", RESOURCE_LATITUDE);
            double lat = ra.latitude;
            query.bindValue(":data", lat);
            query.exec();
        }

        if (ra.longitude.isSet()) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", RESOURCE_LONGITUDE);
            double lon = ra.longitude;
            query.bindValue(":data", lon);
            query.exec();
        }

        if (ra.altitude.isSet()) {
            double alt = ra.altitude;
            query.bindValue(":lid", lid);
            query.bindValue(":key", RESOURCE_ALTITUDE);
            query.bindValue(":data", alt);
            query.exec();
        }

        if (ra.cameraMake.isSet()) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", RESOURCE_CAMERA_MAKE);
            QString cameramake = ra.cameraMake;
            query.bindValue(":data", cameramake);
            query.exec();
        }

        if (ra.cameraModel.isSet()) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", RESOURCE_CAMERA_MODEL);
            QString model = ra.cameraModel;
            query.bindValue(":data", model);
            query.exec();
        }

        if (ra.clientWillIndex.isSet()) {
            bool cwi = ra.clientWillIndex;
            query.bindValue(":lid", lid);
            query.bindValue(":key", RESOURCE_CLIENT_WILL_INDEX);
            query.bindValue(":data", cwi);
            query.exec();
        }

        if (ra.recoType.isSet()) {
            QString reco = ra.recoType;
            query.bindValue(":lid", lid);
            query.bindValue(":key", RESOURCE_RECO_TYPE);
            query.bindValue(":data", reco);
            query.exec();
        }

        if (ra.fileName.isSet()) {
            QString filename = ra.fileName;
            query.bindValue(":lid", lid);
            query.bindValue(":key", RESOURCE_FILENAME);
            query.bindValue(":data", filename);
            query.exec();
        }

        if (ra.attachment.isSet()) {
            bool attachment = ra.attachment;
            query.bindValue(":lid", lid);
            query.bindValue(":key", RESOURCE_ATTACHMENT);
            query.bindValue(":data", attachment);
            query.exec();
        }
    }
    query.finish();
    db->unlock();

    NoteIndexer indexer(db);
    indexer.indexResource(lid);
    return lid;
}


// Get the recognition data for a resource
bool ResourceTable::getResourceRecognition(Resource &resource, qint32 lid) {

    NSqlQuery query(db);
    db->lockForRead();
    query.prepare("Select key, data from DataStore where lid=:lid and (key=:body or key=:size or key=:hash)");
    query.bindValue(":lid", lid);
    query.bindValue(":body", RESOURCE_RECOGNITION_BODY);
    query.bindValue(":size", RESOURCE_RECOGNITION_SIZE);
    query.bindValue(":hash", RESOURCE_RECOGNITION_HASH);

    query.exec();
    if (query.size() == 0)
        return false;
    Data d;
    if (resource.recognition.isSet())
        d = resource.recognition;
    while (query.next()) {
        if (query.value(0).toInt() == RESOURCE_RECOGNITION_HASH) {
            d.bodyHash = query.value(1).toByteArray();
        }
        if (query.value(0).toInt() == RESOURCE_RECOGNITION_SIZE) {
            d.size = query.value(1).toLongLong();
        }
        if (query.value(0).toInt() == RESOURCE_RECOGNITION_BODY) {
            d.body = query.value(1).toByteArray();
        }
    }
    query.finish();
    db->unlock();

    resource.recognition = d;
    return true;
}


// Get a resource for a note by the resource data hash.  This is useful
// when going through a note and finding the resource for that note
qint32 ResourceTable::getLidByHashHex(QString noteGuid, QString hash) {
    NoteTable noteTable(db);
    qint32 notelid = noteTable.getLid(noteGuid);

    NSqlQuery query(db);
    db->lockForRead();
    query.prepare("Select lid from DataStore where data=:lid and key=:key");
    query.bindValue(":lid", notelid);
    query.bindValue(":key", RESOURCE_NOTE_LID);
    query.exec();
    while (query.next()) {
        NSqlQuery query2(db);
        qint32 lid = query.value(0).toInt();
        QByteArray b;
        b.append(hash);
        query2.prepare("Select lid from DataStore where upper(data) like upper(:hash) and key=:key and lid=:lid");
        query2.bindValue(":hash", hash);
        query2.bindValue(":key", RESOURCE_DATA_HASH);
        query2.bindValue(":lid", lid);
        query2.exec();
        if (query2.next()) {
            db->unlock();
            return query2.value(0).toInt();
        } else {
            QLOG_ERROR() << "Resource not found for lid:" << lid << " key:" << RESOURCE_DATA_HASH << " hash:" << hash;
            QLOG_DEBUG() << query2.lastError();
        }
    }
    db->unlock();
    return 0;
}


// Get an ink note's data
bool ResourceTable::getInkNote(QByteArray &value, qint32 lid) {
    QString fileName = global.fileManager.getDbaDirPath()+QString::number(lid)+QString(".png");
    QFile f(fileName);
    f.open(QIODevice::ReadOnly);
    value = f.readAll();
    if (value.size() > 0)
            return true;
    return false;
}


// Set/unset the index needed flag
void ResourceTable::setIndexNeeded(qint32 lid, bool indexNeeded) {
    NSqlQuery query(db);
    db->lockForWrite();
    query.prepare("Delete from DataStore where lid=:lid and key=:key");
    query.bindValue(":lid", lid);
    query.bindValue(":key", RESOURCE_INDEX_NEEDED);
    query.exec();

    if (indexNeeded) {
        query.prepare("Insert into DataStore (lid, key, data) values (:lid, :key, :data)");
        query.bindValue(":lid", lid);
        query.bindValue(":key", RESOURCE_INDEX_NEEDED);
        query.bindValue(":data", indexNeeded);
        query.exec();
    }
    query.finish();

    NoteIndexer indexer(db);
    indexer.indexResource(lid);

    db->unlock();
}


// Get a list of all resources that need indexing
qint32 ResourceTable::getIndexNeeded(QList<qint32> &lids) {
    NSqlQuery query(db);
    lids.clear();
    db->lockForRead();
    query.prepare("Select lid from DataStore where key=:key and data=1");
    query.bindValue(":key", RESOURCE_INDEX_NEEDED);
    query.exec();
    while (query.next()) {
        lids.append(query.value(0).toInt());
    }
    query.finish();
    db->unlock();
    return lids.size();
}



// Get a list of all resource LIDs for a given note
bool ResourceTable::getResourceList(QList<qint32> &resourceList, qint32 noteLid) {

    resourceList.clear();
    db->lockForRead();
    NSqlQuery query(db);
    query.prepare("Select lid from DataStore where key=:key and data=:noteLid");
    query.bindValue(":key", RESOURCE_NOTE_LID);
    query.bindValue(":noteLid", noteLid);
    query.exec();
    while (query.next()) {
        int resLid = query.value(0).toInt();
        resourceList.append(resLid);
    }
    query.finish();
    db->unlock();

    if (resourceList.size() > 0)
        return true;
    else
        return false;
}


// Permanently delete a resource
void ResourceTable::expunge(qint32 lid) {

    if (!this->exists(lid)) {
        return;
    }
    NSqlQuery query(db);
    db->lockForWrite();
    query.prepare("delete from DataStore where lid=:lid");
    query.bindValue(":lid", lid);
    query.exec();
    query.finish();
    db->unlock();

    // Delete the physical files (resource)
    QDir myDir(global.fileManager.getDbaDirPath());
    QString num = QString::number(lid);
    QStringList filter;
    filter.append(num+QString(".*"));
    QStringList list = myDir.entryList(filter, QDir::Files, QDir::NoSort);	// filter resource files
    for (int i=0; i<list.size(); i++) {
        myDir.remove(list[i]);
    }

    // Delete the physical files (thumbnail)
    QDir myTDir(global.fileManager.getThumbnailDirPath());
    list = myTDir.entryList(filter, QDir::Files, QDir::NoSort);	// filter resource files
    for (int i=0; i<list.size(); i++) {
        myTDir.remove(list[i]);
    }
}



// Permanently delete a resource
void ResourceTable::expunge(QString guid) {
    int lid = this->getLid(guid);
    this->expunge(lid);
}


// Permanently delete a resource
void ResourceTable::expungeByNote(qint32 notebookLid) {
    QList<qint32> lids;
    {
        NSqlQuery query(db);
        db->lockForRead();
        query.prepare("Select lid from datastore where data=:data and key=:key");
        query.bindValue(":key", RESOURCE_NOTE_LID);
        query.bindValue(":data", notebookLid);
        query.exec();
        db->unlock();
        while(query.next()) {
            qint32 lid = query.value(0).toInt();
            lids.append(lid);
        }
        query.finish();
    }

    for (int i=0; i<lids.size(); i++) {
        expunge(lids[i]);
    }
}


// Update the existing Resource's hash
void ResourceTable::updateResourceHash(qint32 lid, QByteArray newhash) {
    NSqlQuery query(db);
    db->lockForWrite();
    query.prepare("Update datastore set data=:hash where key=:key and lid=:lid");
    query.bindValue(":hash", newhash.toHex());
    query.bindValue(":key", RESOURCE_DATA_HASH);
    query.bindValue(":lid", lid);
    query.exec();
    query.finish();
    db->unlock();
}






// Get a count of all resources in the database
qint32 ResourceTable::getCount() {
    NSqlQuery query(db);
    db->lockForRead();
    query.prepare("Select count(lid) from DataStore where key=:key;");
    query.bindValue(":key", RESOURCE_GUID);
    query.exec();
    qint32 retval = 0;
    if (query.next())
        retval = query.value(0).toInt();
    query.finish();
    db->unlock();
    return retval;
}


// Get the count of inindexed resources
qint32 ResourceTable::getUnindexedCount() {
    NSqlQuery query(db);
    db->lockForRead();
    query.prepare("Select count(lid) from DataStore where key=:key and data=1");
    query.bindValue(":key", RESOURCE_INDEX_NEEDED);
    query.exec();
    qint32 retval =0;
    if (query.next())
        retval= query.value(0).toInt();
    query.finish();
    db->unlock();
    return retval;
}


// Add a stub resource.  This is a placeholder for a full resource that
// should be added later.
qint32 ResourceTable::addStub(qint32 resLid, qint32 noteLid) {
    NSqlQuery query(db);
    db->lockForWrite();
    query.prepare("Insert into DataStore (lid, key, data) values (:lid, :key, :data)");
    query.bindValue(":lid", resLid);
    query.bindValue(":key", RESOURCE_NOTE_LID);
    query.bindValue(":data", noteLid);
    query.exec();
    query.bindValue(":lid", resLid);
    query.bindValue(":key", RESOURCE_GUID);
    query.bindValue(":data", QString::number(resLid));
    query.exec();
    query.finish();
    db->unlock();
    return resLid;
}

// Get the owning note's LID for a resource.
qint32 ResourceTable::getNoteLid(qint32 resLid) {
    NSqlQuery query(db);
    qint32 retval = 0;
    db->lockForRead();
    query.prepare("Select data from datastore where lid=:lid and key=:key");
    query.bindValue(":lid", resLid);
    query.bindValue(":key", RESOURCE_NOTE_LID);
    query.exec();
    if (query.next()) {
        retval = query.value(0).toInt();
    }
    db->unlock();
    return retval;
}



// Get a resource's HASH data
QByteArray ResourceTable::getDataHash(qint32 lid) {
        NSqlQuery query(db);
        db->lockForRead();
        query.prepare("Select data from datastore where lid=:lid and key=:key");
        query.bindValue(":lid", lid);
        query.bindValue(":key", RESOURCE_DATA_HASH);
        query.exec();
        if (query.next()) {
            db->unlock();
            return QByteArray::fromHex(query.value(0).toByteArray());
        }
        db->unlock();
        return QByteArray();
}


// Mark all note resource as needing reindexed
void ResourceTable::reindexAllResources() {
    NSqlQuery query(db);
    db->lockForWrite();
    query.prepare("delete from datastore where key=:indexKey");
    query.bindValue(":indexKey", RESOURCE_INDEX_NEEDED);
    query.exec();

    query.prepare("insert into datastore (lid, key, data) select lid, :indexKey, 1 from datastore where key=:key;");
    query.bindValue(":indexKey", RESOURCE_INDEX_NEEDED);
    query.bindValue(":key", RESOURCE_GUID);
    query.exec();
    query.finish();
    db->unlock();
}



// Update a resource's owning note.  This is done when merging notes
void ResourceTable::updateNoteLid(qint32 resourceLid, qint32 newNoteLid) {
    NSqlQuery query(db);
    db->lockForWrite();
    query.prepare("Update datastore set data=:newNoteLid where lid=:resourceLid and key=:key");
    query.bindValue(":newNoteLid", newNoteLid);
    query.bindValue(":resourceLid", resourceLid);
    query.bindValue(":key", RESOURCE_NOTE_LID);
    query.exec();
    query.finish();
    db->unlock();
}


// Get a resource's map data
void ResourceTable::getResourceMap(QHash<QString, qint32> &map, QHash< qint32, Resource > &resourceMap, QString guid) {
    NoteTable ntable(db);
    qint32 lid = ntable.getLid(guid);
    this->getResourceMap(map, resourceMap, lid);
}



// Get a resource's map data
void ResourceTable::getResourceMap(QHash<QString, qint32> &map, QHash<qint32, Resource> &resourceMap, string guid) {
    NoteTable ntable(db);
    qint32 lid = ntable.getLid(guid);
    this->getResourceMap(map, resourceMap, lid);
}



// Get a resource's map data
void ResourceTable::getResourceMap(QHash<QString, qint32> &hashMap, QHash<qint32, Resource> &resourceMap, qint32 noteLid) {
    NoteTable ntable(db);
    QString noteGuid = ntable.getGuid(noteLid);
    NSqlQuery query(db);
    qint32 prevLid = -1;
    db->lockForRead();
    query.prepare("Select key, data, lid from datastore where lid in (select lid from datastore where key=:key2 and data=:noteLid) order by lid");
    query.bindValue(":key2", RESOURCE_NOTE_LID);
    query.bindValue(":noteLid", noteLid);
    query.exec();
    hashMap.clear();
    resourceMap.clear();
    Resource *r = NULL;
    QString hash;
    while (query.next()) {
        qint32 lid = query.value(2).toInt();

        // Peek at the next record to see if we are at the end
        // If this is the last result set, we force a save of the
        // record
        if (!query.next()) {
            prevLid = lid;
            lid = -1;
        }
        query.previous();

        // If these don't match, we need to save the current
        // record we are building.
        if (prevLid != lid) {
            if (prevLid > 0) {
                if (hash != "") {
                    hashMap.insert(hash, prevLid);
                    if (r == NULL)
                        r = new Resource();
                    if (!r->noteGuid.isSet()) {
                        r->noteGuid = noteGuid;
                    }
                    resourceMap.insert(prevLid, *r);
                    delete r;
                }
            }
            r = new Resource();
            prevLid = lid;
            hash = "";
        }
        qint32 key = query.value(0).toInt();
        if (key == RESOURCE_DATA_HASH) {
            hash = query.value(1).toString();
        }
        mapResource(query, *r);
    }
    db->unlock();
    query.finish();

    if (r != NULL)
        delete r;
}


// Get all resources for a note
void ResourceTable::getAllResources(QList<Resource> &list, qint32 noteLid, bool fullLoad, bool withBinary) {
    //NoteTable ntable(db);
    //QString noteGuid = ntable.getGuid(noteLid);
    NSqlQuery query(db);
    db->lockForRead();
    QHash<qint32, Resource*> lidMap;
    if (fullLoad){
        query.prepare("Select key, data, lid from datastore where lid in (select lid from datastore where key=:key2 and data=:noteLid) order by lid");
        query.bindValue(":key2", RESOURCE_NOTE_LID);
        query.bindValue(":noteLid", noteLid);
    } else {
        query.prepare("Select key, data, lid from datastore where key=:key and lid in (select lid from datastore where key=:key2 and data=:noteLid) order by lid");
        query.bindValue(":key", RESOURCE_GUID);
        query.bindValue(":key2", RESOURCE_NOTE_LID);
        query.bindValue(":noteLid", noteLid);
    }
    Resource *r = NULL;
    query.exec();
    while (query.next()) {
        qint32 lid = query.value(2).toInt();
        if (!lidMap.contains(lid)) {
            r = new Resource();
            lidMap.insert(lid, r);
        } else {
            r = lidMap[lid];
        }
        mapResource(query, *r);
    }
    query.finish();
    db->unlock();

    // if we need binary data, read it in.  Then add to the list
    QHash<qint32, Resource*>::iterator i;
    list.clear();
    for (i=lidMap.begin(); i!=lidMap.end(); ++i) {
        if (withBinary && fullLoad) {
            Resource *r = i.value();
            qint32 lid = i.key();
            QString mimetype = r->mime;
            MimeReference ref;
            QString filename;
            ResourceAttributes attributes;
            if (r->attributes.isSet())
                attributes = r->attributes;
            if (attributes.fileName.isSet())
                filename = attributes.fileName;
            QString fileExt = ref.getExtensionFromMime(mimetype, filename);
            QFile tfile(global.fileManager.getDbDirPath("/dba/"+QString::number(lid)) +fileExt );
            if (!tfile.open(QIODevice::ReadOnly)) {
                QDir dir(global.fileManager.getDbaDirPath());
                QStringList filterList;
                filterList.append(QString::number(lid)+".*");
                QStringList list= dir.entryList(filterList, QDir::Files);
                if (list.size() > 0) {
                    tfile.setFileName(global.fileManager.getDbaDirPath()+list[0]);
                    tfile.open(QIODevice::ReadOnly);
                }
            }
            QByteArray b = tfile.readAll();
            Data d;
            if (r->data.isSet())
                d = r->data;
            d.body = b;
            r->data = d;
            tfile.close();
        }
        list.append(*i.value());
    }
}