/
IDBBackingStore.cpp
1871 lines (1565 loc) · 70.3 KB
/
IDBBackingStore.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
/*
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "IDBBackingStore.h"
#if ENABLE(INDEXED_DATABASE)
#include "FileSystem.h"
#include "HistogramSupport.h"
#include "IDBFactoryBackendImpl.h"
#include "IDBKey.h"
#include "IDBKeyPath.h"
#include "IDBKeyRange.h"
#include "IDBLevelDBCoding.h"
#include "IDBMetadata.h"
#include "IDBTracing.h"
#include "LevelDBComparator.h"
#include "LevelDBDatabase.h"
#include "LevelDBIterator.h"
#include "LevelDBSlice.h"
#include "LevelDBTransaction.h"
#include "SecurityOrigin.h"
#include "SharedBuffer.h"
#include <wtf/Assertions.h>
namespace WebCore {
using namespace IDBLevelDBCoding;
const int64_t KeyGeneratorInitialNumber = 1; // From the IndexedDB specification.
enum IDBBackingStoreErrorSource {
// 0 - 2 are no longer used.
FindKeyInIndex = 3,
GetIDBDatabaseMetaData,
GetIndexes,
GetKeyGeneratorCurrentNumber,
GetObjectStores,
GetRecord,
KeyExistsInObjectStore,
LoadCurrentRow,
SetupMetadata,
GetPrimaryKeyViaIndex,
KeyExistsInIndex,
VersionExists,
DeleteObjectStore,
SetMaxObjectStoreId,
SetMaxIndexId,
GetNewDatabaseId,
GetNewVersionNumber,
CreateIDBDatabaseMetaData,
DeleteDatabase,
TransactionCommit,
IDBLevelDBBackingStoreInternalErrorMax,
};
static void recordInternalError(const char* type, IDBBackingStoreErrorSource location)
{
String name = String::format("WebCore.IndexedDB.BackingStore.%sError", type);
HistogramSupport::histogramEnumeration(name.utf8().data(), location, IDBLevelDBBackingStoreInternalErrorMax);
}
// Use to signal conditions that usually indicate developer error, but could be caused by data corruption.
// A macro is used instead of an inline function so that the assert and log report the line number.
#define REPORT_ERROR(type, location) \
do { \
LOG_ERROR("IndexedDB %s Error: %s", type, #location); \
ASSERT_NOT_REACHED(); \
recordInternalError(type, location); \
} while (0)
#define INTERNAL_READ_ERROR(location) REPORT_ERROR("Read", location)
#define INTERNAL_CONSISTENCY_ERROR(location) REPORT_ERROR("Consistency", location)
#define INTERNAL_WRITE_ERROR(location) REPORT_ERROR("Write", location)
static void putBool(LevelDBTransaction* transaction, const LevelDBSlice& key, bool value)
{
transaction->put(key, encodeBool(value));
}
template <typename DBOrTransaction>
static bool getInt(DBOrTransaction* db, const LevelDBSlice& key, int64_t& foundInt, bool& found)
{
Vector<char> result;
bool ok = db->safeGet(key, result, found);
if (!ok)
return false;
if (!found)
return true;
foundInt = decodeInt(result.begin(), result.end());
return true;
}
static void putInt(LevelDBTransaction* transaction, const LevelDBSlice& key, int64_t value)
{
ASSERT(value >= 0);
transaction->put(key, encodeInt(value));
}
template <typename DBOrTransaction>
WARN_UNUSED_RETURN static bool getVarInt(DBOrTransaction* db, const LevelDBSlice& key, int64_t& foundInt, bool& found)
{
Vector<char> result;
bool ok = db->safeGet(key, result, found);
if (!ok)
return false;
if (!found)
return true;
found = decodeVarInt(result.begin(), result.end(), foundInt) == result.end();
return true;
}
static void putVarInt(LevelDBTransaction* transaction, const LevelDBSlice& key, int64_t value)
{
transaction->put(key, encodeVarInt(value));
}
template <typename DBOrTransaction>
WARN_UNUSED_RETURN static bool getString(DBOrTransaction* db, const LevelDBSlice& key, String& foundString, bool& found)
{
Vector<char> result;
found = false;
bool ok = db->safeGet(key, result, found);
if (!ok)
return false;
if (!found)
return true;
foundString = decodeString(result.begin(), result.end());
return true;
}
static void putString(LevelDBTransaction* transaction, const LevelDBSlice& key, const String& value)
{
transaction->put(key, encodeString(value));
}
static void putIDBKeyPath(LevelDBTransaction* transaction, const LevelDBSlice& key, const IDBKeyPath& value)
{
transaction->put(key, encodeIDBKeyPath(value));
}
static int compareKeys(const LevelDBSlice& a, const LevelDBSlice& b)
{
return compare(a, b);
}
static int compareIndexKeys(const LevelDBSlice& a, const LevelDBSlice& b)
{
return compare(a, b, true);
}
class Comparator : public LevelDBComparator {
public:
virtual int compare(const LevelDBSlice& a, const LevelDBSlice& b) const { return IDBLevelDBCoding::compare(a, b); }
virtual const char* name() const { return "idb_cmp1"; }
};
// 0 - Initial version.
// 1 - Adds UserIntVersion to DatabaseMetaData.
// 2 - Adds DataVersion to to global metadata.
const int64_t latestKnownSchemaVersion = 2;
WARN_UNUSED_RETURN static bool isSchemaKnown(LevelDBDatabase* db, bool& known)
{
int64_t dbSchemaVersion = 0;
bool found = false;
bool ok = getInt(db, SchemaVersionKey::encode(), dbSchemaVersion, found);
if (!ok)
return false;
if (!found) {
known = true;
return true;
}
if (dbSchemaVersion > latestKnownSchemaVersion) {
known = false;
return true;
}
const uint32_t latestKnownDataVersion = SerializedScriptValue::wireFormatVersion();
int64_t dbDataVersion = 0;
ok = getInt(db, DataVersionKey::encode(), dbDataVersion, found);
if (!ok)
return false;
if (!found) {
known = true;
return true;
}
if (dbDataVersion > latestKnownDataVersion) {
known = false;
return true;
}
known = true;
return true;
}
WARN_UNUSED_RETURN static bool setUpMetadata(LevelDBDatabase* db, const String& origin)
{
const uint32_t latestKnownDataVersion = SerializedScriptValue::wireFormatVersion();
const Vector<char> schemaVersionKey = SchemaVersionKey::encode();
const Vector<char> dataVersionKey = DataVersionKey::encode();
RefPtr<LevelDBTransaction> transaction = LevelDBTransaction::create(db);
int64_t dbSchemaVersion = 0;
int64_t dbDataVersion = 0;
bool found = false;
bool ok = getInt(transaction.get(), schemaVersionKey, dbSchemaVersion, found);
if (!ok) {
INTERNAL_READ_ERROR(SetupMetadata);
return false;
}
if (!found) {
// Initialize new backing store.
dbSchemaVersion = latestKnownSchemaVersion;
putInt(transaction.get(), schemaVersionKey, dbSchemaVersion);
dbDataVersion = latestKnownDataVersion;
putInt(transaction.get(), dataVersionKey, dbDataVersion);
} else {
// Upgrade old backing store.
ASSERT(dbSchemaVersion <= latestKnownSchemaVersion);
if (dbSchemaVersion < 1) {
dbSchemaVersion = 1;
putInt(transaction.get(), schemaVersionKey, dbSchemaVersion);
const Vector<char> startKey = DatabaseNameKey::encodeMinKeyForOrigin(origin);
const Vector<char> stopKey = DatabaseNameKey::encodeStopKeyForOrigin(origin);
OwnPtr<LevelDBIterator> it = db->createIterator();
for (it->seek(startKey); it->isValid() && compareKeys(it->key(), stopKey) < 0; it->next()) {
int64_t databaseId = 0;
found = false;
bool ok = getInt(transaction.get(), it->key(), databaseId, found);
if (!ok) {
INTERNAL_READ_ERROR(SetupMetadata);
return false;
}
if (!found) {
INTERNAL_CONSISTENCY_ERROR(SetupMetadata);
return false;
}
Vector<char> intVersionKey = DatabaseMetaDataKey::encode(databaseId, DatabaseMetaDataKey::UserIntVersion);
putVarInt(transaction.get(), intVersionKey, IDBDatabaseMetadata::DefaultIntVersion);
}
}
if (dbSchemaVersion < 2) {
dbSchemaVersion = 2;
putInt(transaction.get(), schemaVersionKey, dbSchemaVersion);
dbDataVersion = SerializedScriptValue::wireFormatVersion();
putInt(transaction.get(), dataVersionKey, dbDataVersion);
}
}
// All new values will be written using this serialization version.
found = false;
ok = getInt(transaction.get(), dataVersionKey, dbDataVersion, found);
if (!ok) {
INTERNAL_READ_ERROR(SetupMetadata);
return false;
}
if (!found) {
INTERNAL_CONSISTENCY_ERROR(SetupMetadata);
return false;
}
if (dbDataVersion < latestKnownDataVersion) {
dbDataVersion = latestKnownDataVersion;
putInt(transaction.get(), dataVersionKey, dbDataVersion);
}
ASSERT(dbSchemaVersion == latestKnownSchemaVersion);
ASSERT(dbDataVersion == latestKnownDataVersion);
if (!transaction->commit()) {
INTERNAL_WRITE_ERROR(SetupMetadata);
return false;
}
return true;
}
template <typename DBOrTransaction>
WARN_UNUSED_RETURN static bool getMaxObjectStoreId(DBOrTransaction* db, int64_t databaseId, int64_t& maxObjectStoreId)
{
const Vector<char> maxObjectStoreIdKey = DatabaseMetaDataKey::encode(databaseId, DatabaseMetaDataKey::MaxObjectStoreId);
bool ok = getMaxObjectStoreId(db, maxObjectStoreIdKey, maxObjectStoreId);
return ok;
}
template <typename DBOrTransaction>
WARN_UNUSED_RETURN static bool getMaxObjectStoreId(DBOrTransaction* db, const Vector<char>& maxObjectStoreIdKey, int64_t& maxObjectStoreId)
{
maxObjectStoreId = -1;
bool found = false;
bool ok = getInt(db, maxObjectStoreIdKey, maxObjectStoreId, found);
if (!ok)
return false;
if (!found)
maxObjectStoreId = 0;
ASSERT(maxObjectStoreId >= 0);
return true;
}
IDBBackingStore::IDBBackingStore(const String& identifier, IDBFactoryBackendImpl* factory, PassOwnPtr<LevelDBDatabase> db)
: m_identifier(identifier)
, m_factory(factory)
, m_db(db)
{
m_factory->addIDBBackingStore(identifier, this);
}
IDBBackingStore::IDBBackingStore()
{
}
IDBBackingStore::~IDBBackingStore()
{
// Only null in tests.
if (m_factory)
m_factory->removeIDBBackingStore(m_identifier);
// m_db's destructor uses m_comparator. The order of destruction is important.
m_db.clear();
m_comparator.clear();
}
enum IDBLevelDBBackingStoreOpenResult {
IDBLevelDBBackingStoreOpenMemory,
IDBLevelDBBackingStoreOpenSuccess,
IDBLevelDBBackingStoreOpenFailedDirectory,
IDBLevelDBBackingStoreOpenFailedUnknownSchema,
IDBLevelDBBackingStoreOpenCleanupDestroyFailed,
IDBLevelDBBackingStoreOpenCleanupReopenFailed,
IDBLevelDBBackingStoreOpenCleanupReopenSuccess,
IDBLevelDBBackingStoreOpenFailedIOErrCheckingSchema,
IDBLevelDBBackingStoreOpenMax,
};
PassRefPtr<IDBBackingStore> IDBBackingStore::open(SecurityOrigin* securityOrigin, const String& pathBaseArg, const String& fileIdentifier, IDBFactoryBackendImpl* factory)
{
IDB_TRACE("IDBBackingStore::open");
String pathBase = pathBaseArg;
OwnPtr<LevelDBComparator> comparator = adoptPtr(new Comparator());
OwnPtr<LevelDBDatabase> db;
if (pathBase.isEmpty()) {
HistogramSupport::histogramEnumeration("WebCore.IndexedDB.BackingStore.OpenStatus", IDBLevelDBBackingStoreOpenMemory, IDBLevelDBBackingStoreOpenMax);
db = LevelDBDatabase::openInMemory(comparator.get());
} else {
if (!makeAllDirectories(pathBase)) {
LOG_ERROR("Unable to create IndexedDB database path %s", pathBase.utf8().data());
HistogramSupport::histogramEnumeration("WebCore.IndexedDB.BackingStore.OpenStatus", IDBLevelDBBackingStoreOpenFailedDirectory, IDBLevelDBBackingStoreOpenMax);
return PassRefPtr<IDBBackingStore>();
}
String path = pathByAppendingComponent(pathBase, securityOrigin->databaseIdentifier() + ".indexeddb.leveldb");
db = LevelDBDatabase::open(path, comparator.get());
if (db) {
bool known = false;
bool ok = isSchemaKnown(db.get(), known);
if (!ok) {
HistogramSupport::histogramEnumeration("WebCore.IndexedDB.BackingStore.OpenStatus", IDBLevelDBBackingStoreOpenFailedIOErrCheckingSchema, IDBLevelDBBackingStoreOpenMax);
return PassRefPtr<IDBBackingStore>();
}
if (!known) {
LOG_ERROR("IndexedDB backing store had unknown schema, treating it as failure to open");
HistogramSupport::histogramEnumeration("WebCore.IndexedDB.BackingStore.OpenStatus", IDBLevelDBBackingStoreOpenFailedUnknownSchema, IDBLevelDBBackingStoreOpenMax);
db.clear();
}
}
if (db)
HistogramSupport::histogramEnumeration("WebCore.IndexedDB.BackingStore.OpenStatus", IDBLevelDBBackingStoreOpenSuccess, IDBLevelDBBackingStoreOpenMax);
else {
LOG_ERROR("IndexedDB backing store open failed, attempting cleanup");
bool success = LevelDBDatabase::destroy(path);
if (!success) {
LOG_ERROR("IndexedDB backing store cleanup failed");
HistogramSupport::histogramEnumeration("WebCore.IndexedDB.BackingStore.OpenStatus", IDBLevelDBBackingStoreOpenCleanupDestroyFailed, IDBLevelDBBackingStoreOpenMax);
return PassRefPtr<IDBBackingStore>();
}
LOG_ERROR("IndexedDB backing store cleanup succeeded, reopening");
db = LevelDBDatabase::open(path, comparator.get());
if (!db) {
LOG_ERROR("IndexedDB backing store reopen after recovery failed");
HistogramSupport::histogramEnumeration("WebCore.IndexedDB.BackingStore.OpenStatus", IDBLevelDBBackingStoreOpenCleanupReopenFailed, IDBLevelDBBackingStoreOpenMax);
return PassRefPtr<IDBBackingStore>();
}
HistogramSupport::histogramEnumeration("WebCore.IndexedDB.BackingStore.OpenStatus", IDBLevelDBBackingStoreOpenCleanupReopenSuccess, IDBLevelDBBackingStoreOpenMax);
}
}
if (!db)
return PassRefPtr<IDBBackingStore>();
// FIXME: Handle comparator name changes.
RefPtr<IDBBackingStore> backingStore(adoptRef(new IDBBackingStore(fileIdentifier, factory, db.release())));
backingStore->m_comparator = comparator.release();
if (!setUpMetadata(backingStore->m_db.get(), fileIdentifier))
return PassRefPtr<IDBBackingStore>();
return backingStore.release();
}
Vector<String> IDBBackingStore::getDatabaseNames()
{
Vector<String> foundNames;
const Vector<char> startKey = DatabaseNameKey::encodeMinKeyForOrigin(m_identifier);
const Vector<char> stopKey = DatabaseNameKey::encodeStopKeyForOrigin(m_identifier);
ASSERT(foundNames.isEmpty());
OwnPtr<LevelDBIterator> it = m_db->createIterator();
for (it->seek(startKey); it->isValid() && compareKeys(it->key(), stopKey) < 0; it->next()) {
const char* p = it->key().begin();
const char* limit = it->key().end();
DatabaseNameKey databaseNameKey;
p = DatabaseNameKey::decode(p, limit, &databaseNameKey);
ASSERT(p);
foundNames.append(databaseNameKey.databaseName());
}
return foundNames;
}
bool IDBBackingStore::getIDBDatabaseMetaData(const String& name, IDBDatabaseMetadata* metadata, bool& found)
{
const Vector<char> key = DatabaseNameKey::encode(m_identifier, name);
found = false;
bool ok = getInt(m_db.get(), key, metadata->id, found);
if (!ok) {
INTERNAL_READ_ERROR(GetIDBDatabaseMetaData);
return false;
}
if (!found)
return true;
ok = getString(m_db.get(), DatabaseMetaDataKey::encode(metadata->id, DatabaseMetaDataKey::UserVersion), metadata->version, found);
if (!ok) {
INTERNAL_READ_ERROR(GetIDBDatabaseMetaData);
return false;
}
if (!found) {
INTERNAL_CONSISTENCY_ERROR(GetIDBDatabaseMetaData);
return false;
}
ok = getVarInt(m_db.get(), DatabaseMetaDataKey::encode(metadata->id, DatabaseMetaDataKey::UserIntVersion), metadata->intVersion, found);
if (!ok) {
INTERNAL_READ_ERROR(GetIDBDatabaseMetaData);
return false;
}
if (!found) {
INTERNAL_CONSISTENCY_ERROR(GetIDBDatabaseMetaData);
return false;
}
if (metadata->intVersion == IDBDatabaseMetadata::DefaultIntVersion)
metadata->intVersion = IDBDatabaseMetadata::NoIntVersion;
ok = getMaxObjectStoreId(m_db.get(), metadata->id, metadata->maxObjectStoreId);
if (!ok) {
INTERNAL_READ_ERROR(GetIDBDatabaseMetaData);
return false;
}
return true;
}
WARN_UNUSED_RETURN static bool getNewDatabaseId(LevelDBDatabase* db, int64_t& newId)
{
RefPtr<LevelDBTransaction> transaction = LevelDBTransaction::create(db);
newId = -1;
int64_t maxDatabaseId = -1;
bool found = false;
bool ok = getInt(transaction.get(), MaxDatabaseIdKey::encode(), maxDatabaseId, found);
if (!ok) {
INTERNAL_READ_ERROR(GetNewDatabaseId);
return false;
}
if (!found)
maxDatabaseId = 0;
ASSERT(maxDatabaseId >= 0);
int64_t databaseId = maxDatabaseId + 1;
putInt(transaction.get(), MaxDatabaseIdKey::encode(), databaseId);
if (!transaction->commit()) {
INTERNAL_WRITE_ERROR(GetNewDatabaseId);
return false;
}
newId = databaseId;
return true;
}
bool IDBBackingStore::createIDBDatabaseMetaData(const String& name, const String& version, int64_t intVersion, int64_t& rowId)
{
bool ok = getNewDatabaseId(m_db.get(), rowId);
if (!ok)
return false;
ASSERT(rowId >= 0);
if (intVersion == IDBDatabaseMetadata::NoIntVersion)
intVersion = IDBDatabaseMetadata::DefaultIntVersion;
RefPtr<LevelDBTransaction> transaction = LevelDBTransaction::create(m_db.get());
putInt(transaction.get(), DatabaseNameKey::encode(m_identifier, name), rowId);
putString(transaction.get(), DatabaseMetaDataKey::encode(rowId, DatabaseMetaDataKey::UserVersion), version);
putVarInt(transaction.get(), DatabaseMetaDataKey::encode(rowId, DatabaseMetaDataKey::UserIntVersion), intVersion);
if (!transaction->commit()) {
INTERNAL_WRITE_ERROR(CreateIDBDatabaseMetaData);
return false;
}
return true;
}
bool IDBBackingStore::updateIDBDatabaseIntVersion(IDBBackingStore::Transaction* transaction, int64_t rowId, int64_t intVersion)
{
if (intVersion == IDBDatabaseMetadata::NoIntVersion)
intVersion = IDBDatabaseMetadata::DefaultIntVersion;
ASSERT_WITH_MESSAGE(intVersion >= 0, "intVersion was %lld", static_cast<long long>(intVersion));
putVarInt(Transaction::levelDBTransactionFrom(transaction), DatabaseMetaDataKey::encode(rowId, DatabaseMetaDataKey::UserIntVersion), intVersion);
return true;
}
bool IDBBackingStore::updateIDBDatabaseMetaData(IDBBackingStore::Transaction* transaction, int64_t rowId, const String& version)
{
putString(Transaction::levelDBTransactionFrom(transaction), DatabaseMetaDataKey::encode(rowId, DatabaseMetaDataKey::UserVersion), version);
return true;
}
static void deleteRange(LevelDBTransaction* transaction, const Vector<char>& begin, const Vector<char>& end)
{
OwnPtr<LevelDBIterator> it = transaction->createIterator();
for (it->seek(begin); it->isValid() && compareKeys(it->key(), end) < 0; it->next())
transaction->remove(it->key());
}
bool IDBBackingStore::deleteDatabase(const String& name)
{
IDB_TRACE("IDBBackingStore::deleteDatabase");
OwnPtr<LevelDBWriteOnlyTransaction> transaction = LevelDBWriteOnlyTransaction::create(m_db.get());
IDBDatabaseMetadata metadata;
bool success = false;
bool ok = getIDBDatabaseMetaData(name, &metadata, success);
if (!ok)
return false;
if (!success)
return true;
const Vector<char> startKey = DatabaseMetaDataKey::encode(metadata.id, DatabaseMetaDataKey::OriginName);
const Vector<char> stopKey = DatabaseMetaDataKey::encode(metadata.id + 1, DatabaseMetaDataKey::OriginName);
OwnPtr<LevelDBIterator> it = m_db->createIterator();
for (it->seek(startKey); it->isValid() && compareKeys(it->key(), stopKey) < 0; it->next())
transaction->remove(it->key());
const Vector<char> key = DatabaseNameKey::encode(m_identifier, name);
transaction->remove(key);
if (!transaction->commit()) {
INTERNAL_WRITE_ERROR(DeleteDatabase);
return false;
}
return true;
}
static bool checkObjectStoreAndMetaDataType(const LevelDBIterator* it, const Vector<char>& stopKey, int64_t objectStoreId, int64_t metaDataType)
{
if (!it->isValid() || compareKeys(it->key(), stopKey) >= 0)
return false;
ObjectStoreMetaDataKey metaDataKey;
const char* p = ObjectStoreMetaDataKey::decode(it->key().begin(), it->key().end(), &metaDataKey);
ASSERT_UNUSED(p, p);
if (metaDataKey.objectStoreId() != objectStoreId)
return false;
if (metaDataKey.metaDataType() != metaDataType)
return false;
return true;
}
// FIXME: This should do some error handling rather than plowing ahead when bad data is encountered.
void IDBBackingStore::getObjectStores(int64_t databaseId, IDBDatabaseMetadata::ObjectStoreMap* objectStores)
{
IDB_TRACE("IDBBackingStore::getObjectStores");
const Vector<char> startKey = ObjectStoreMetaDataKey::encode(databaseId, 1, 0);
const Vector<char> stopKey = ObjectStoreMetaDataKey::encodeMaxKey(databaseId);
ASSERT(objectStores->isEmpty());
OwnPtr<LevelDBIterator> it = m_db->createIterator();
it->seek(startKey);
while (it->isValid() && compareKeys(it->key(), stopKey) < 0) {
const char* p = it->key().begin();
const char* limit = it->key().end();
ObjectStoreMetaDataKey metaDataKey;
p = ObjectStoreMetaDataKey::decode(p, limit, &metaDataKey);
ASSERT(p);
if (metaDataKey.metaDataType() != ObjectStoreMetaDataKey::Name) {
INTERNAL_CONSISTENCY_ERROR(GetObjectStores);
// Possible stale metadata, but don't fail the load.
it->next();
continue;
}
int64_t objectStoreId = metaDataKey.objectStoreId();
// FIXME: Do this by direct key lookup rather than iteration, to simplify.
String objectStoreName = decodeString(it->value().begin(), it->value().end());
it->next();
if (!checkObjectStoreAndMetaDataType(it.get(), stopKey, objectStoreId, ObjectStoreMetaDataKey::KeyPath)) {
INTERNAL_CONSISTENCY_ERROR(GetObjectStores);
break;
}
IDBKeyPath keyPath = decodeIDBKeyPath(it->value().begin(), it->value().end());
it->next();
if (!checkObjectStoreAndMetaDataType(it.get(), stopKey, objectStoreId, ObjectStoreMetaDataKey::AutoIncrement)) {
INTERNAL_CONSISTENCY_ERROR(GetObjectStores);
break;
}
bool autoIncrement = decodeBool(it->value().begin(), it->value().end());
it->next(); // Is evicatble.
if (!checkObjectStoreAndMetaDataType(it.get(), stopKey, objectStoreId, ObjectStoreMetaDataKey::Evictable)) {
INTERNAL_CONSISTENCY_ERROR(GetObjectStores);
break;
}
it->next(); // Last version.
if (!checkObjectStoreAndMetaDataType(it.get(), stopKey, objectStoreId, ObjectStoreMetaDataKey::LastVersion)) {
INTERNAL_CONSISTENCY_ERROR(GetObjectStores);
break;
}
it->next(); // Maximum index id allocated.
if (!checkObjectStoreAndMetaDataType(it.get(), stopKey, objectStoreId, ObjectStoreMetaDataKey::MaxIndexId)) {
INTERNAL_CONSISTENCY_ERROR(GetObjectStores);
break;
}
int64_t maxIndexId = decodeInt(it->value().begin(), it->value().end());
it->next(); // [optional] has key path (is not null)
if (checkObjectStoreAndMetaDataType(it.get(), stopKey, objectStoreId, ObjectStoreMetaDataKey::HasKeyPath)) {
bool hasKeyPath = decodeBool(it->value().begin(), it->value().end());
// This check accounts for two layers of legacy coding:
// (1) Initially, hasKeyPath was added to distinguish null vs. string.
// (2) Later, null vs. string vs. array was stored in the keyPath itself.
// So this check is only relevant for string-type keyPaths.
if (!hasKeyPath && (keyPath.type() == IDBKeyPath::StringType && !keyPath.string().isEmpty())) {
INTERNAL_CONSISTENCY_ERROR(GetObjectStores);
break;
}
if (!hasKeyPath)
keyPath = IDBKeyPath();
it->next();
}
int64_t keyGeneratorCurrentNumber = -1;
if (checkObjectStoreAndMetaDataType(it.get(), stopKey, objectStoreId, ObjectStoreMetaDataKey::KeyGeneratorCurrentNumber)) {
keyGeneratorCurrentNumber = decodeInt(it->value().begin(), it->value().end());
// FIXME: Return keyGeneratorCurrentNumber, cache in object store, and write lazily to backing store.
// For now, just assert that if it was written it was valid.
ASSERT_UNUSED(keyGeneratorCurrentNumber, keyGeneratorCurrentNumber >= KeyGeneratorInitialNumber);
it->next();
}
IDBObjectStoreMetadata metadata(objectStoreName, objectStoreId, keyPath, autoIncrement, maxIndexId);
getIndexes(databaseId, objectStoreId, &metadata.indexes);
objectStores->set(objectStoreId, metadata);
}
}
WARN_UNUSED_RETURN static bool setMaxObjectStoreId(LevelDBTransaction* transaction, int64_t databaseId, int64_t objectStoreId)
{
const Vector<char> maxObjectStoreIdKey = DatabaseMetaDataKey::encode(databaseId, DatabaseMetaDataKey::MaxObjectStoreId);
int64_t maxObjectStoreId = -1;
bool ok = getMaxObjectStoreId(transaction, maxObjectStoreIdKey, maxObjectStoreId);
if (!ok) {
INTERNAL_READ_ERROR(SetMaxObjectStoreId);
return false;
}
if (objectStoreId <= maxObjectStoreId) {
INTERNAL_CONSISTENCY_ERROR(SetMaxObjectStoreId);
return false;
}
putInt(transaction, maxObjectStoreIdKey, objectStoreId);
return true;
}
bool IDBBackingStore::createObjectStore(IDBBackingStore::Transaction* transaction, int64_t databaseId, int64_t objectStoreId, const String& name, const IDBKeyPath& keyPath, bool autoIncrement)
{
IDB_TRACE("IDBBackingStore::createObjectStore");
LevelDBTransaction* levelDBTransaction = IDBBackingStore::Transaction::levelDBTransactionFrom(transaction);
if (!setMaxObjectStoreId(levelDBTransaction, databaseId, objectStoreId))
return false;
const Vector<char> nameKey = ObjectStoreMetaDataKey::encode(databaseId, objectStoreId, ObjectStoreMetaDataKey::Name);
const Vector<char> keyPathKey = ObjectStoreMetaDataKey::encode(databaseId, objectStoreId, ObjectStoreMetaDataKey::KeyPath);
const Vector<char> autoIncrementKey = ObjectStoreMetaDataKey::encode(databaseId, objectStoreId, ObjectStoreMetaDataKey::AutoIncrement);
const Vector<char> evictableKey = ObjectStoreMetaDataKey::encode(databaseId, objectStoreId, ObjectStoreMetaDataKey::Evictable);
const Vector<char> lastVersionKey = ObjectStoreMetaDataKey::encode(databaseId, objectStoreId, ObjectStoreMetaDataKey::LastVersion);
const Vector<char> maxIndexIdKey = ObjectStoreMetaDataKey::encode(databaseId, objectStoreId, ObjectStoreMetaDataKey::MaxIndexId);
const Vector<char> hasKeyPathKey = ObjectStoreMetaDataKey::encode(databaseId, objectStoreId, ObjectStoreMetaDataKey::HasKeyPath);
const Vector<char> keyGeneratorCurrentNumberKey = ObjectStoreMetaDataKey::encode(databaseId, objectStoreId, ObjectStoreMetaDataKey::KeyGeneratorCurrentNumber);
const Vector<char> namesKey = ObjectStoreNamesKey::encode(databaseId, name);
putString(levelDBTransaction, nameKey, name);
putIDBKeyPath(levelDBTransaction, keyPathKey, keyPath);
putInt(levelDBTransaction, autoIncrementKey, autoIncrement);
putInt(levelDBTransaction, evictableKey, false);
putInt(levelDBTransaction, lastVersionKey, 1);
putInt(levelDBTransaction, maxIndexIdKey, MinimumIndexId);
putBool(levelDBTransaction, hasKeyPathKey, !keyPath.isNull());
putInt(levelDBTransaction, keyGeneratorCurrentNumberKey, KeyGeneratorInitialNumber);
putInt(levelDBTransaction, namesKey, objectStoreId);
return true;
}
bool IDBBackingStore::deleteObjectStore(IDBBackingStore::Transaction* transaction, int64_t databaseId, int64_t objectStoreId)
{
IDB_TRACE("IDBBackingStore::deleteObjectStore");
LevelDBTransaction* levelDBTransaction = IDBBackingStore::Transaction::levelDBTransactionFrom(transaction);
String objectStoreName;
bool found = false;
bool ok = getString(levelDBTransaction, ObjectStoreMetaDataKey::encode(databaseId, objectStoreId, ObjectStoreMetaDataKey::Name), objectStoreName, found);
if (!ok) {
INTERNAL_READ_ERROR(DeleteObjectStore);
return false;
}
if (!found) {
INTERNAL_CONSISTENCY_ERROR(DeleteObjectStore);
return false;
}
deleteRange(levelDBTransaction, ObjectStoreMetaDataKey::encode(databaseId, objectStoreId, 0), ObjectStoreMetaDataKey::encodeMaxKey(databaseId, objectStoreId));
levelDBTransaction->remove(ObjectStoreNamesKey::encode(databaseId, objectStoreName));
deleteRange(levelDBTransaction, IndexFreeListKey::encode(databaseId, objectStoreId, 0), IndexFreeListKey::encodeMaxKey(databaseId, objectStoreId));
deleteRange(levelDBTransaction, IndexMetaDataKey::encode(databaseId, objectStoreId, 0, 0), IndexMetaDataKey::encodeMaxKey(databaseId, objectStoreId));
clearObjectStore(transaction, databaseId, objectStoreId);
return true;
}
bool IDBBackingStore::getRecord(IDBBackingStore::Transaction* transaction, int64_t databaseId, int64_t objectStoreId, const IDBKey& key, Vector<char>& record)
{
IDB_TRACE("IDBBackingStore::getRecord");
LevelDBTransaction* levelDBTransaction = IDBBackingStore::Transaction::levelDBTransactionFrom(transaction);
const Vector<char> leveldbKey = ObjectStoreDataKey::encode(databaseId, objectStoreId, key);
Vector<char> data;
record.clear();
bool found = false;
bool ok = levelDBTransaction->safeGet(leveldbKey, data, found);
if (!ok) {
INTERNAL_READ_ERROR(GetRecord);
return false;
}
if (!found)
return true;
int64_t version;
const char* p = decodeVarInt(data.begin(), data.end(), version);
if (!p) {
INTERNAL_READ_ERROR(GetRecord);
return false;
}
record.appendRange(p, static_cast<const char*>(data.end()));
return true;
}
WARN_UNUSED_RETURN static bool getNewVersionNumber(LevelDBTransaction* transaction, int64_t databaseId, int64_t objectStoreId, int64_t& newVersionNumber)
{
const Vector<char> lastVersionKey = ObjectStoreMetaDataKey::encode(databaseId, objectStoreId, ObjectStoreMetaDataKey::LastVersion);
newVersionNumber = -1;
int64_t lastVersion = -1;
bool found = false;
bool ok = getInt(transaction, lastVersionKey, lastVersion, found);
if (!ok) {
INTERNAL_READ_ERROR(GetNewVersionNumber);
return false;
}
if (!found)
lastVersion = 0;
ASSERT(lastVersion >= 0);
int64_t version = lastVersion + 1;
putInt(transaction, lastVersionKey, version);
ASSERT(version > lastVersion); // FIXME: Think about how we want to handle the overflow scenario.
newVersionNumber = version;
return true;
}
bool IDBBackingStore::putRecord(IDBBackingStore::Transaction* transaction, int64_t databaseId, int64_t objectStoreId, const IDBKey& key, PassRefPtr<SharedBuffer> prpValue, RecordIdentifier* recordIdentifier)
{
IDB_TRACE("IDBBackingStore::putRecord");
ASSERT(key.isValid());
LevelDBTransaction* levelDBTransaction = IDBBackingStore::Transaction::levelDBTransactionFrom(transaction);
int64_t version = -1;
bool ok = getNewVersionNumber(levelDBTransaction, databaseId, objectStoreId, version);
if (!ok)
return false;
ASSERT(version >= 0);
const Vector<char> objectStoredataKey = ObjectStoreDataKey::encode(databaseId, objectStoreId, key);
Vector<char> v;
v.append(encodeVarInt(version));
RefPtr<SharedBuffer> value = prpValue;
ASSERT(value);
v.append(value->data(), value->size());
levelDBTransaction->put(objectStoredataKey, v);
const Vector<char> existsEntryKey = ExistsEntryKey::encode(databaseId, objectStoreId, key);
levelDBTransaction->put(existsEntryKey, encodeInt(version));
recordIdentifier->reset(encodeIDBKey(key), version);
return true;
}
void IDBBackingStore::clearObjectStore(IDBBackingStore::Transaction* transaction, int64_t databaseId, int64_t objectStoreId)
{
IDB_TRACE("IDBBackingStore::clearObjectStore");
LevelDBTransaction* levelDBTransaction = IDBBackingStore::Transaction::levelDBTransactionFrom(transaction);
const Vector<char> startKey = KeyPrefix(databaseId, objectStoreId, 0).encode();
const Vector<char> stopKey = KeyPrefix(databaseId, objectStoreId + 1, 0).encode();
deleteRange(levelDBTransaction, startKey, stopKey);
}
void IDBBackingStore::deleteRecord(IDBBackingStore::Transaction* transaction, int64_t databaseId, int64_t objectStoreId, const RecordIdentifier& recordIdentifier)
{
IDB_TRACE("IDBBackingStore::deleteRecord");
LevelDBTransaction* levelDBTransaction = IDBBackingStore::Transaction::levelDBTransactionFrom(transaction);
const Vector<char> objectStoreDataKey = ObjectStoreDataKey::encode(databaseId, objectStoreId, recordIdentifier.primaryKey());
levelDBTransaction->remove(objectStoreDataKey);
const Vector<char> existsEntryKey = ExistsEntryKey::encode(databaseId, objectStoreId, recordIdentifier.primaryKey());
levelDBTransaction->remove(existsEntryKey);
}
bool IDBBackingStore::getKeyGeneratorCurrentNumber(IDBBackingStore::Transaction* transaction, int64_t databaseId, int64_t objectStoreId, int64_t& keyGeneratorCurrentNumber)
{
LevelDBTransaction* levelDBTransaction = IDBBackingStore::Transaction::levelDBTransactionFrom(transaction);
const Vector<char> keyGeneratorCurrentNumberKey = ObjectStoreMetaDataKey::encode(databaseId, objectStoreId, ObjectStoreMetaDataKey::KeyGeneratorCurrentNumber);
keyGeneratorCurrentNumber = -1;
Vector<char> data;
bool found = false;
bool ok = levelDBTransaction->safeGet(keyGeneratorCurrentNumberKey, data, found);
if (!ok) {
INTERNAL_READ_ERROR(GetKeyGeneratorCurrentNumber);
return false;
}
if (found)
keyGeneratorCurrentNumber = decodeInt(data.begin(), data.end());
else {
// Previously, the key generator state was not stored explicitly but derived from the
// maximum numeric key present in existing data. This violates the spec as the data may
// be cleared but the key generator state must be preserved.
const Vector<char> startKey = ObjectStoreDataKey::encode(databaseId, objectStoreId, minIDBKey());
const Vector<char> stopKey = ObjectStoreDataKey::encode(databaseId, objectStoreId, maxIDBKey());
OwnPtr<LevelDBIterator> it = levelDBTransaction->createIterator();
int64_t maxNumericKey = 0;
for (it->seek(startKey); it->isValid() && compareKeys(it->key(), stopKey) < 0; it->next()) {
const char* p = it->key().begin();
const char* limit = it->key().end();
ObjectStoreDataKey dataKey;
p = ObjectStoreDataKey::decode(p, limit, &dataKey);
ASSERT(p);
if (dataKey.userKey()->type() == IDBKey::NumberType) {
int64_t n = static_cast<int64_t>(dataKey.userKey()->number());
if (n > maxNumericKey)
maxNumericKey = n;
}
}
keyGeneratorCurrentNumber = maxNumericKey + 1;
}
return keyGeneratorCurrentNumber;
}
bool IDBBackingStore::maybeUpdateKeyGeneratorCurrentNumber(IDBBackingStore::Transaction* transaction, int64_t databaseId, int64_t objectStoreId, int64_t newNumber, bool checkCurrent)
{
LevelDBTransaction* levelDBTransaction = IDBBackingStore::Transaction::levelDBTransactionFrom(transaction);
if (checkCurrent) {
int64_t currentNumber;
bool ok = getKeyGeneratorCurrentNumber(transaction, databaseId, objectStoreId, currentNumber);
if (!ok)
return false;
if (newNumber <= currentNumber)
return true;
}
const Vector<char> keyGeneratorCurrentNumberKey = ObjectStoreMetaDataKey::encode(databaseId, objectStoreId, ObjectStoreMetaDataKey::KeyGeneratorCurrentNumber);
putInt(levelDBTransaction, keyGeneratorCurrentNumberKey, newNumber);
return true;
}
bool IDBBackingStore::keyExistsInObjectStore(IDBBackingStore::Transaction* transaction, int64_t databaseId, int64_t objectStoreId, const IDBKey& key, RecordIdentifier* foundRecordIdentifier, bool& found)
{
IDB_TRACE("IDBBackingStore::keyExistsInObjectStore");
found = false;
LevelDBTransaction* levelDBTransaction = IDBBackingStore::Transaction::levelDBTransactionFrom(transaction);
const Vector<char> leveldbKey = ObjectStoreDataKey::encode(databaseId, objectStoreId, key);
Vector<char> data;
bool ok = levelDBTransaction->safeGet(leveldbKey, data, found);
if (!ok) {
INTERNAL_READ_ERROR(KeyExistsInObjectStore);
return false;
}
if (!found)
return true;
int64_t version;
if (!decodeVarInt(data.begin(), data.end(), version))
return false;
foundRecordIdentifier->reset(encodeIDBKey(key), version);
return true;
}
static bool checkIndexAndMetaDataKey(const LevelDBIterator* it, const Vector<char>& stopKey, int64_t indexId, unsigned char metaDataType)
{
if (!it->isValid() || compareKeys(it->key(), stopKey) >= 0)
return false;
IndexMetaDataKey metaDataKey;
const char* p = IndexMetaDataKey::decode(it->key().begin(), it->key().end(), &metaDataKey);
ASSERT_UNUSED(p, p);
if (metaDataKey.indexId() != indexId)
return false;
if (metaDataKey.metaDataType() != metaDataType)
return false;
return true;
}
// FIXME: This should do some error handling rather than plowing ahead when bad data is encountered.
void IDBBackingStore::getIndexes(int64_t databaseId, int64_t objectStoreId, IDBObjectStoreMetadata::IndexMap* indexes)
{
IDB_TRACE("IDBBackingStore::getIndexes");
const Vector<char> startKey = IndexMetaDataKey::encode(databaseId, objectStoreId, 0, 0);