-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
SQLiteIDBBackingStore.cpp
2854 lines (2317 loc) · 128 KB
/
SQLiteIDBBackingStore.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) 2016-2021 Apple 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 INC. 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 INC. 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 "SQLiteIDBBackingStore.h"
#include "IDBBindingUtilities.h"
#include "IDBCursorInfo.h"
#include "IDBGetAllRecordsData.h"
#include "IDBGetAllResult.h"
#include "IDBGetRecordData.h"
#include "IDBGetResult.h"
#include "IDBIterateCursorData.h"
#include "IDBKeyData.h"
#include "IDBObjectStoreInfo.h"
#include "IDBSerialization.h"
#include "IDBTransactionInfo.h"
#include "IDBValue.h"
#include "IndexKey.h"
#include "Logging.h"
#include "SQLiteDatabase.h"
#include "SQLiteFileSystem.h"
#include "SQLiteIDBCursor.h"
#include "SQLiteStatement.h"
#include "SQLiteTransaction.h"
#include "ThreadSafeDataBuffer.h"
#include <JavaScriptCore/AuxiliaryBarrierInlines.h>
#include <JavaScriptCore/JSCInlines.h>
#include <JavaScriptCore/StrongInlines.h>
#include <wtf/FileSystem.h>
#include <wtf/NeverDestroyed.h>
#include <wtf/text/StringConcatenateNumbers.h>
#include <wtf/text/StringToIntegerConversion.h>
namespace WebCore {
using namespace JSC;
namespace IDBServer {
constexpr auto objectStoreInfoTableName = "ObjectStoreInfo"_s;
constexpr auto objectStoreInfoTableNameAlternate = "\"ObjectStoreInfo\""_s;
constexpr auto v2ObjectStoreInfoSchema = "CREATE TABLE ObjectStoreInfo (id INTEGER PRIMARY KEY NOT NULL ON CONFLICT FAIL UNIQUE ON CONFLICT FAIL, name TEXT NOT NULL ON CONFLICT FAIL UNIQUE ON CONFLICT FAIL, keyPath BLOB NOT NULL ON CONFLICT FAIL, autoInc INTEGER NOT NULL ON CONFLICT FAIL)"_s;
constexpr auto v1IndexRecordsRecordIndexSchema = "CREATE INDEX IndexRecordsRecordIndex ON IndexRecords (objectStoreID, objectStoreRecordID)"_s;
constexpr auto IndexRecordsIndexSchema = "CREATE INDEX IndexRecordsIndex ON IndexRecords (indexID, key, value)"_s;
// Current version of the metadata schema being used in the metadata database.
static const int currentMetadataVersion = 1;
// The IndexedDatabase spec defines the max key generator value as 2^53.
static const uint64_t maxGeneratorValue = 0x20000000000000;
#define TABLE_SCHEMA_PREFIX "CREATE TABLE "
#define V3_RECORDS_TABLE_SCHEMA_SUFFIX " (objectStoreID INTEGER NOT NULL ON CONFLICT FAIL, key TEXT COLLATE IDBKEY NOT NULL ON CONFLICT FAIL, value NOT NULL ON CONFLICT FAIL, recordID INTEGER PRIMARY KEY)"_s
#define V3_INDEX_RECORDS_TABLE_SCHEMA_SUFFIX " (indexID INTEGER NOT NULL ON CONFLICT FAIL, objectStoreID INTEGER NOT NULL ON CONFLICT FAIL, key TEXT COLLATE IDBKEY NOT NULL ON CONFLICT FAIL, value TEXT COLLATE IDBKEY NOT NULL ON CONFLICT FAIL, objectStoreRecordID INTEGER NOT NULL ON CONFLICT FAIL)"_s;
#define INDEX_INFO_TABLE_SCHEMA_SUFFIX " (id INTEGER NOT NULL ON CONFLICT FAIL, name TEXT NOT NULL ON CONFLICT FAIL, objectStoreID INTEGER NOT NULL ON CONFLICT FAIL, keyPath BLOB NOT NULL ON CONFLICT FAIL, isUnique INTEGER NOT NULL ON CONFLICT FAIL, multiEntry INTEGER NOT NULL ON CONFLICT FAIL)"_s;
#define BLOB_RECORDS_TABLE_SCHEMA_SUFFIX " (objectStoreRow INTEGER NOT NULL ON CONFLICT FAIL, blobURL TEXT NOT NULL ON CONFLICT FAIL)"_s;
#define BLOB_FILES_TABLE_SCHEMA_SUFFIX " (blobURL TEXT NOT NULL ON CONFLICT FAIL UNIQUE ON CONFLICT FAIL, fileName TEXT NOT NULL ON CONFLICT FAIL UNIQUE ON CONFLICT FAIL)"_s;
static int idbKeyCollate(std::span<const uint8_t> aBuffer, std::span<const uint8_t> bBuffer)
{
IDBKeyData a, b;
if (!deserializeIDBKeyData(aBuffer, a)) {
LOG_ERROR("Unable to deserialize key A in collation function.");
// There's no way to indicate an error to SQLite - we have to return a sorting decision.
// We arbitrarily choose "A > B"
return 1;
}
if (!deserializeIDBKeyData(bBuffer, b)) {
LOG_ERROR("Unable to deserialize key B in collation function.");
// There's no way to indicate an error to SQLite - we have to return a sorting decision.
// We arbitrarily choose "A > B"
return 1;
}
return a.compare(b);
}
static const String v1RecordsTableSchema(ASCIILiteral tableName)
{
return makeString("CREATE TABLE "_s, tableName, " (objectStoreID INTEGER NOT NULL ON CONFLICT FAIL, key TEXT COLLATE IDBKEY NOT NULL ON CONFLICT FAIL UNIQUE ON CONFLICT REPLACE, value NOT NULL ON CONFLICT FAIL)"_s);
}
static const String& v1RecordsTableSchema()
{
static NeverDestroyed<String> v1RecordsTableSchemaString(v1RecordsTableSchema("Records"_s));
return v1RecordsTableSchemaString;
}
static const String& v1RecordsTableSchemaAlternate()
{
static NeverDestroyed<String> v1RecordsTableSchemaString(v1RecordsTableSchema("\"Records\""_s));
return v1RecordsTableSchemaString;
}
static const String v2RecordsTableSchema(ASCIILiteral tableName)
{
return makeString("CREATE TABLE "_s, tableName, " (objectStoreID INTEGER NOT NULL ON CONFLICT FAIL, key TEXT COLLATE IDBKEY NOT NULL ON CONFLICT FAIL, value NOT NULL ON CONFLICT FAIL)"_s);
}
static const String& v2RecordsTableSchema()
{
static NeverDestroyed<String> v2RecordsTableSchemaString(v2RecordsTableSchema("Records"_s));
return v2RecordsTableSchemaString;
}
static const String& v2RecordsTableSchemaAlternate()
{
static NeverDestroyed<String> v2RecordsTableSchemaString(v2RecordsTableSchema("\"Records\""_s));
return v2RecordsTableSchemaString;
}
static ASCIILiteral v3RecordsTableSchema()
{
return TABLE_SCHEMA_PREFIX "Records" V3_RECORDS_TABLE_SCHEMA_SUFFIX;
}
static ASCIILiteral v3RecordsTableSchemaAlternate()
{
return TABLE_SCHEMA_PREFIX "\"Records\"" V3_RECORDS_TABLE_SCHEMA_SUFFIX;
}
static ASCIILiteral v3RecordsTableSchemaTemp()
{
return TABLE_SCHEMA_PREFIX "_Temp_Records" V3_RECORDS_TABLE_SCHEMA_SUFFIX;
}
static const String v1IndexRecordsTableSchema(ASCIILiteral tableName)
{
return makeString("CREATE TABLE "_s, tableName, " (indexID INTEGER NOT NULL ON CONFLICT FAIL, objectStoreID INTEGER NOT NULL ON CONFLICT FAIL, key TEXT COLLATE IDBKEY NOT NULL ON CONFLICT FAIL, value NOT NULL ON CONFLICT FAIL)"_s);
}
static const String& v1IndexRecordsTableSchema()
{
static NeverDestroyed<String> v1IndexRecordsTableSchemaString(v1IndexRecordsTableSchema("IndexRecords"_s));
return v1IndexRecordsTableSchemaString;
}
static const String& v1IndexRecordsTableSchemaAlternate()
{
static NeverDestroyed<String> v1IndexRecordsTableSchemaString(v1IndexRecordsTableSchema("\"IndexRecords\""_s));
return v1IndexRecordsTableSchemaString;
}
static const String v2IndexRecordsTableSchema(ASCIILiteral tableName)
{
return makeString("CREATE TABLE "_s, tableName, " (indexID INTEGER NOT NULL ON CONFLICT FAIL, objectStoreID INTEGER NOT NULL ON CONFLICT FAIL, key TEXT COLLATE IDBKEY NOT NULL ON CONFLICT FAIL, value TEXT COLLATE IDBKEY NOT NULL ON CONFLICT FAIL)"_s);
}
static const String& v2IndexRecordsTableSchema()
{
static NeverDestroyed<String> v2IndexRecordsTableSchemaString(v2IndexRecordsTableSchema("IndexRecords"_s));
return v2IndexRecordsTableSchemaString;
}
static const String& v2IndexRecordsTableSchemaAlternate()
{
static NeverDestroyed<String> v2IndexRecordsTableSchemaString(v2IndexRecordsTableSchema("\"IndexRecords\""_s));
return v2IndexRecordsTableSchemaString;
}
static ASCIILiteral v3IndexRecordsTableSchema()
{
return TABLE_SCHEMA_PREFIX "IndexRecords" V3_INDEX_RECORDS_TABLE_SCHEMA_SUFFIX;
}
static ASCIILiteral v3IndexRecordsTableSchemaAlternate()
{
return TABLE_SCHEMA_PREFIX "\"IndexRecords\"" V3_INDEX_RECORDS_TABLE_SCHEMA_SUFFIX;
}
static ASCIILiteral v3IndexRecordsTableSchemaTemp()
{
return TABLE_SCHEMA_PREFIX "_Temp_IndexRecords" V3_INDEX_RECORDS_TABLE_SCHEMA_SUFFIX;
}
static ASCIILiteral blobRecordsTableSchema()
{
return TABLE_SCHEMA_PREFIX "BlobRecords" BLOB_RECORDS_TABLE_SCHEMA_SUFFIX;
}
static ASCIILiteral blobRecordsTableSchemaAlternate()
{
return TABLE_SCHEMA_PREFIX "\"BlobRecords\"" BLOB_RECORDS_TABLE_SCHEMA_SUFFIX;
}
static ASCIILiteral blobFilesTableSchema()
{
return TABLE_SCHEMA_PREFIX "BlobFiles" BLOB_FILES_TABLE_SCHEMA_SUFFIX;
}
static ASCIILiteral blobFilesTableSchemaAlternate()
{
return TABLE_SCHEMA_PREFIX "\"BlobFiles\"" BLOB_FILES_TABLE_SCHEMA_SUFFIX;
}
static String createV1ObjectStoreInfoSchema(ASCIILiteral tableName)
{
return makeString("CREATE TABLE "_s, tableName, " (id INTEGER PRIMARY KEY NOT NULL ON CONFLICT FAIL UNIQUE ON CONFLICT FAIL, name TEXT NOT NULL ON CONFLICT FAIL UNIQUE ON CONFLICT FAIL, keyPath BLOB NOT NULL ON CONFLICT FAIL, autoInc INTEGER NOT NULL ON CONFLICT FAIL, maxIndexID INTEGER NOT NULL ON CONFLICT FAIL)"_s);
}
static String createV2ObjectStoreInfoSchema(ASCIILiteral tableName)
{
return makeString("CREATE TABLE "_s, tableName, " (id INTEGER PRIMARY KEY NOT NULL ON CONFLICT FAIL UNIQUE ON CONFLICT FAIL, name TEXT NOT NULL ON CONFLICT FAIL UNIQUE ON CONFLICT FAIL, keyPath BLOB NOT NULL ON CONFLICT FAIL, autoInc INTEGER NOT NULL ON CONFLICT FAIL)"_s);
}
static ASCIILiteral indexInfoTableSchema()
{
return TABLE_SCHEMA_PREFIX "IndexInfo" INDEX_INFO_TABLE_SCHEMA_SUFFIX;
}
static ASCIILiteral indexInfoTableSchemaTemp()
{
return TABLE_SCHEMA_PREFIX "_Temp_IndexInfo" INDEX_INFO_TABLE_SCHEMA_SUFFIX;
}
SQLiteIDBBackingStore::SQLiteIDBBackingStore(const IDBDatabaseIdentifier& identifier, const String& databaseDirectory)
: m_identifier(identifier)
, m_databaseDirectory(databaseDirectory)
{
}
SQLiteIDBBackingStore::~SQLiteIDBBackingStore()
{
if (m_sqliteDB)
closeSQLiteDB();
}
static IDBError createOrMigrateRecordsTableIfNecessary(SQLiteDatabase& database)
{
String tableStatement = database.tableSQL("Records"_s);
if (tableStatement.isEmpty()) {
if (!database.executeCommand(v3RecordsTableSchema()))
return IDBError { ExceptionCode::UnknownError, makeString("Error creating Records table ("_s, database.lastError(), ") - "_s, span(database.lastErrorMsg())) };
return IDBError { };
}
// If the schema in the backing store is the current schema, we're done.
if (tableStatement == v3RecordsTableSchema() || tableStatement == v3RecordsTableSchemaAlternate())
return IDBError { };
// If the record table is not the current schema then it must be one of the previous schemas.
// If it is not then the database is in an unrecoverable state and this should be considered a fatal error.
if (tableStatement != v1RecordsTableSchema() && tableStatement != v1RecordsTableSchemaAlternate()
&& tableStatement != v2RecordsTableSchema() && tableStatement != v2RecordsTableSchemaAlternate())
RELEASE_ASSERT_NOT_REACHED();
SQLiteTransaction transaction(database);
transaction.begin();
// Create a temporary table with the correct schema and migrate all existing content over.
if (!database.executeCommand(v3RecordsTableSchemaTemp()))
return IDBError { ExceptionCode::UnknownError, makeString("Error creating temporary Records table ("_s, database.lastError(), ") - "_s, span(database.lastErrorMsg())) };
if (!database.executeCommand("INSERT INTO _Temp_Records (objectStoreID, key, value) SELECT objectStoreID, CAST(key AS TEXT), value FROM Records"_s))
return IDBError { ExceptionCode::UnknownError, makeString("Error migrating Records table ("_s, database.lastError(), ") - "_s, span(database.lastErrorMsg())) };
if (!database.executeCommand("DROP TABLE Records"_s))
return IDBError { ExceptionCode::UnknownError, makeString("Error dropping Records table ("_s, database.lastError(), ") - "_s, span(database.lastErrorMsg())) };
if (!database.executeCommand("ALTER TABLE _Temp_Records RENAME TO Records"_s))
return IDBError { ExceptionCode::UnknownError, makeString("Error renaming temporary Records table ("_s, database.lastError(), ") - "_s, span(database.lastErrorMsg())) };
transaction.commit();
return IDBError { };
}
IDBError SQLiteIDBBackingStore::ensureValidBlobTables()
{
ASSERT(m_sqliteDB);
ASSERT(m_sqliteDB->isOpen());
String recordsTableStatement = m_sqliteDB->tableSQL("BlobRecords"_s);
if (recordsTableStatement.isEmpty()) {
if (!m_sqliteDB->executeCommand(blobRecordsTableSchema()))
return IDBError { ExceptionCode::UnknownError, makeString("Error creating BlobRecords table ("_s, m_sqliteDB->lastError(), ") - "_s, span(m_sqliteDB->lastErrorMsg())) };
recordsTableStatement = blobRecordsTableSchema();
}
RELEASE_ASSERT(recordsTableStatement == blobRecordsTableSchema() || recordsTableStatement == blobRecordsTableSchemaAlternate());
String filesTableStatement = m_sqliteDB->tableSQL("BlobFiles"_s);
if (filesTableStatement.isEmpty()) {
if (!m_sqliteDB->executeCommand(blobFilesTableSchema()))
return IDBError { ExceptionCode::UnknownError, makeString("Error creating BlobFiles table ("_s, m_sqliteDB->lastError(), ") - "_s, span(m_sqliteDB->lastErrorMsg())) };
filesTableStatement = blobFilesTableSchema();
}
RELEASE_ASSERT(filesTableStatement == blobFilesTableSchema() || filesTableStatement == blobFilesTableSchemaAlternate());
return IDBError { };
}
IDBError SQLiteIDBBackingStore::ensureValidRecordsTable()
{
ASSERT(m_sqliteDB);
ASSERT(m_sqliteDB->isOpen());
IDBError error = createOrMigrateRecordsTableIfNecessary(*m_sqliteDB);
if (!error.isNull())
return error;
// Whether the updated records table already existed or if it was just created and the data migrated over,
// make sure the uniqueness index exists.
if (!m_sqliteDB->executeCommand("CREATE UNIQUE INDEX IF NOT EXISTS RecordsIndex ON Records (objectStoreID, key);"_s))
error = IDBError { ExceptionCode::UnknownError, makeString("Error creating RecordsIndex on Records table ("_s, m_sqliteDB->lastError(), ") - "_s, span(m_sqliteDB->lastErrorMsg())) };
return error;
}
IDBError SQLiteIDBBackingStore::ensureValidIndexRecordsTable()
{
ASSERT(m_sqliteDB);
ASSERT(m_sqliteDB->isOpen());
String tableStatement = m_sqliteDB->tableSQL("IndexRecords"_s);
if (tableStatement.isEmpty()) {
if (!m_sqliteDB->executeCommand(v3IndexRecordsTableSchema()))
return IDBError { ExceptionCode::UnknownError, makeString("Error creating IndexRecords table ("_s, m_sqliteDB->lastError(), ") - "_s, span(m_sqliteDB->lastErrorMsg())) };
return IDBError { };
}
// If the schema in the backing store is the current schema, we're done.
if (tableStatement == v3IndexRecordsTableSchema() || tableStatement == v3IndexRecordsTableSchemaAlternate())
return IDBError { };
RELEASE_ASSERT(tableStatement == v1IndexRecordsTableSchema() || tableStatement == v1IndexRecordsTableSchemaAlternate() || tableStatement == v2IndexRecordsTableSchema() || tableStatement == v2IndexRecordsTableSchemaAlternate());
SQLiteTransaction transaction(*m_sqliteDB);
transaction.begin();
// Create a temporary table with the correct schema and migrate all existing content over.
if (!m_sqliteDB->executeCommand(v3IndexRecordsTableSchemaTemp()))
return IDBError { ExceptionCode::UnknownError, makeString("Error creating temporary IndexRecords table ("_s, m_sqliteDB->lastError(), ") - "_s, span(m_sqliteDB->lastErrorMsg())) };
if (!m_sqliteDB->executeCommand("INSERT INTO _Temp_IndexRecords SELECT IndexRecords.indexID, IndexRecords.objectStoreID, IndexRecords.key, IndexRecords.value, Records.rowid FROM IndexRecords INNER JOIN Records ON Records.key = IndexRecords.value AND Records.objectStoreID = IndexRecords.objectStoreID"_s))
return IDBError { ExceptionCode::UnknownError, makeString("Error migrating IndexRecords table ("_s, m_sqliteDB->lastError(), ") - "_s, span(m_sqliteDB->lastErrorMsg())) };
if (!m_sqliteDB->executeCommand("DROP TABLE IndexRecords"_s))
return IDBError { ExceptionCode::UnknownError, makeString("Error dropping IndexRecords table ("_s, m_sqliteDB->lastError(), ") - "_s, span(m_sqliteDB->lastErrorMsg())) };
if (!m_sqliteDB->executeCommand("ALTER TABLE _Temp_IndexRecords RENAME TO IndexRecords"_s))
return IDBError { ExceptionCode::UnknownError, makeString("Error renaming temporary IndexRecords table ("_s, m_sqliteDB->lastError(), ") - "_s, span(m_sqliteDB->lastErrorMsg())) };
transaction.commit();
return IDBError { };
}
IDBError SQLiteIDBBackingStore::ensureValidIndexRecordsIndex()
{
ASSERT(m_sqliteDB);
ASSERT(m_sqliteDB->isOpen());
String indexStatement = m_sqliteDB->indexSQL("IndexRecordsIndex"_s);
if (indexStatement == IndexRecordsIndexSchema)
return IDBError { };
if (!m_sqliteDB->executeCommand("DROP INDEX IF EXISTS IndexRecordsIndex"_s))
return IDBError { ExceptionCode::UnknownError, makeString("Error dropping IndexRecordsIndex index ("_s, m_sqliteDB->lastError(), ") - "_s, span(m_sqliteDB->lastErrorMsg())) };
if (!m_sqliteDB->executeCommand(IndexRecordsIndexSchema))
return IDBError { ExceptionCode::UnknownError, makeString("Error creating IndexRecordsIndex index ("_s, m_sqliteDB->lastError(), ") - "_s, span(m_sqliteDB->lastErrorMsg())) };
return IDBError { };
}
IDBError SQLiteIDBBackingStore::ensureValidIndexRecordsRecordIndex()
{
ASSERT(m_sqliteDB);
ASSERT(m_sqliteDB->isOpen());
String indexStatement = m_sqliteDB->indexSQL("IndexRecordsRecordIndex"_s);
if (indexStatement == v1IndexRecordsRecordIndexSchema)
return IDBError { };
if (!m_sqliteDB->executeCommand("DROP INDEX IF EXISTS IndexRecordsRecordIndex"_s))
return IDBError { ExceptionCode::UnknownError, makeString("Error dropping IndexRecordsRecordIndex index ("_s, m_sqliteDB->lastError(), ") - "_s, span(m_sqliteDB->lastErrorMsg())) };
if (!m_sqliteDB->executeCommand(v1IndexRecordsRecordIndexSchema))
return IDBError { ExceptionCode::UnknownError, makeString("Error creating IndexRecordsRecordIndex index ("_s, m_sqliteDB->lastError(), ") - "_s, span(m_sqliteDB->lastErrorMsg())) };
return IDBError { };
}
std::unique_ptr<IDBDatabaseInfo> SQLiteIDBBackingStore::createAndPopulateInitialDatabaseInfo()
{
ASSERT(m_sqliteDB);
ASSERT(m_sqliteDB->isOpen());
if (!m_sqliteDB->executeCommand("CREATE TABLE IDBDatabaseInfo (key TEXT NOT NULL ON CONFLICT FAIL UNIQUE ON CONFLICT REPLACE, value TEXT NOT NULL ON CONFLICT FAIL);"_s)) {
LOG_ERROR("Could not create IDBDatabaseInfo table in database (%i) - %s", m_sqliteDB->lastError(), m_sqliteDB->lastErrorMsg());
closeSQLiteDB();
return nullptr;
}
if (!m_sqliteDB->executeCommand(v2ObjectStoreInfoSchema)) {
LOG_ERROR("Could not create ObjectStoreInfo table in database (%i) - %s", m_sqliteDB->lastError(), m_sqliteDB->lastErrorMsg());
closeSQLiteDB();
return nullptr;
}
if (!m_sqliteDB->executeCommand(indexInfoTableSchema())) {
LOG_ERROR("Could not create IndexInfo table in database (%i) - %s", m_sqliteDB->lastError(), m_sqliteDB->lastErrorMsg());
closeSQLiteDB();
return nullptr;
}
if (!m_sqliteDB->executeCommand("CREATE TABLE KeyGenerators (objectStoreID INTEGER NOT NULL ON CONFLICT FAIL UNIQUE ON CONFLICT REPLACE, currentKey INTEGER NOT NULL ON CONFLICT FAIL);"_s)) {
LOG_ERROR("Could not create KeyGenerators table in database (%i) - %s", m_sqliteDB->lastError(), m_sqliteDB->lastErrorMsg());
closeSQLiteDB();
return nullptr;
}
{
auto sql = m_sqliteDB->prepareStatement("INSERT INTO IDBDatabaseInfo VALUES ('MetadataVersion', ?);"_s);
if (!sql
|| sql->bindInt(1, currentMetadataVersion) != SQLITE_OK
|| sql->step() != SQLITE_DONE) {
LOG_ERROR("Could not insert database metadata version into IDBDatabaseInfo table (%i) - %s", m_sqliteDB->lastError(), m_sqliteDB->lastErrorMsg());
closeSQLiteDB();
return nullptr;
}
}
{
auto sql = m_sqliteDB->prepareStatement("INSERT INTO IDBDatabaseInfo VALUES ('DatabaseName', ?);"_s);
if (!sql
|| sql->bindText(1, m_identifier.databaseName()) != SQLITE_OK
|| sql->step() != SQLITE_DONE) {
LOG_ERROR("Could not insert database name into IDBDatabaseInfo table (%i) - %s", m_sqliteDB->lastError(), m_sqliteDB->lastErrorMsg());
closeSQLiteDB();
return nullptr;
}
}
{
// Database versions are defined to be a uin64_t in the spec but sqlite3 doesn't support native binding of unsigned integers.
// Therefore we'll store the version as a String.
auto sql = m_sqliteDB->prepareStatement("INSERT INTO IDBDatabaseInfo VALUES ('DatabaseVersion', ?);"_s);
if (!sql
|| sql->bindText(1, String::number(0)) != SQLITE_OK
|| sql->step() != SQLITE_DONE) {
LOG_ERROR("Could not insert default version into IDBDatabaseInfo table (%i) - %s", m_sqliteDB->lastError(), m_sqliteDB->lastErrorMsg());
closeSQLiteDB();
return nullptr;
}
}
if (!m_sqliteDB->executeCommand("INSERT INTO IDBDatabaseInfo VALUES ('MaxObjectStoreID', 1);"_s)) {
LOG_ERROR("Could not insert default version into IDBDatabaseInfo table (%i) - %s", m_sqliteDB->lastError(), m_sqliteDB->lastErrorMsg());
closeSQLiteDB();
return nullptr;
}
// This initial database info matches the default values we just put into the metadata database.
return makeUnique<IDBDatabaseInfo>(m_identifier.databaseName(), 0, 0);
}
std::optional<IsSchemaUpgraded> SQLiteIDBBackingStore::ensureValidObjectStoreInfoTable()
{
ASSERT(m_sqliteDB);
ASSERT(m_sqliteDB->isOpen());
String tableStatement = m_sqliteDB->tableSQL("ObjectStoreInfo"_s);
if (tableStatement.isEmpty())
return std::nullopt;
if (tableStatement == v2ObjectStoreInfoSchema || tableStatement == createV2ObjectStoreInfoSchema(objectStoreInfoTableNameAlternate))
return { IsSchemaUpgraded::No };
RELEASE_ASSERT(tableStatement == createV1ObjectStoreInfoSchema(objectStoreInfoTableName) || tableStatement == createV1ObjectStoreInfoSchema(objectStoreInfoTableNameAlternate));
// Drop column maxIndexID from table.
SQLiteTransaction transaction(*m_sqliteDB);
transaction.begin();
if (!m_sqliteDB->executeCommandSlow(createV2ObjectStoreInfoSchema("_Temp_ObjectStoreInfo"_s))) {
LOG_ERROR("Could not create temporary ObjectStoreInfo table in database (%i) - %s", m_sqliteDB->lastError(), m_sqliteDB->lastErrorMsg());
return std::nullopt;
}
if (!m_sqliteDB->executeCommand("INSERT INTO _Temp_ObjectStoreInfo (id, name, keyPath, autoInc) SELECT id, name, keyPath, autoInc FROM ObjectStoreInfo"_s)) {
LOG_ERROR("Could not migrate existing ObjectStoreInfo content (%i) - %s", m_sqliteDB->lastError(), m_sqliteDB->lastErrorMsg());
return std::nullopt;
}
if (!m_sqliteDB->executeCommand("DROP TABLE ObjectStoreInfo"_s)) {
LOG_ERROR("Could not drop existing ObjectStoreInfo table (%i) - %s", m_sqliteDB->lastError(), m_sqliteDB->lastErrorMsg());
return std::nullopt;
}
if (!m_sqliteDB->executeCommand("ALTER TABLE _Temp_ObjectStoreInfo RENAME TO ObjectStoreInfo"_s)) {
LOG_ERROR("Could not rename temporary ObjectStoreInfo table (%i) - %s", m_sqliteDB->lastError(), m_sqliteDB->lastErrorMsg());
return std::nullopt;
}
transaction.commit();
return { IsSchemaUpgraded::Yes };
}
bool SQLiteIDBBackingStore::migrateIndexInfoTableForIDUpdate(const HashMap<std::pair<uint64_t, uint64_t>, uint64_t>& indexIDMap)
{
SQLiteDatabase& database = *m_sqliteDB;
SQLiteTransaction transaction(database);
transaction.begin();
if (!database.executeCommand(indexInfoTableSchemaTemp())) {
LOG_ERROR("Error creating _Temp_IndexInfo table in database (%i) - %s", database.lastError(), database.lastErrorMsg());
return false;
}
{
auto statement = database.prepareStatement("SELECT id, name, objectStoreID, keyPath, isUnique, multiEntry FROM IndexInfo;"_s);
if (!statement) {
LOG_ERROR("Error preparing statement to fetch records from IndexInfo table (%i) - %s", database.lastError(), database.lastErrorMsg());
return false;
}
int result = statement->step();
while (result == SQLITE_ROW) {
uint64_t id = statement->columnInt64(0);
String name = statement->columnText(1);
uint64_t objectStoreID = statement->columnInt64(2);
uint64_t newID = indexIDMap.get({ objectStoreID, id });
auto keyPathBufferSpan = statement->columnBlobAsSpan(3);
bool unique = statement->columnInt(4);
bool multiEntry = statement->columnInt(5);
auto sql = cachedStatement(SQL::CreateTempIndexInfo, "INSERT INTO _Temp_IndexInfo VALUES (?, ?, ?, ?, ?, ?);"_s);
if (!sql
|| sql->bindInt64(1, newID) != SQLITE_OK
|| sql->bindText(2, name) != SQLITE_OK
|| sql->bindInt64(3, objectStoreID) != SQLITE_OK
|| sql->bindBlob(4, keyPathBufferSpan) != SQLITE_OK
|| sql->bindInt(5, unique) != SQLITE_OK
|| sql->bindInt(6, multiEntry) != SQLITE_OK
|| sql->step() != SQLITE_DONE) {
LOG_ERROR("Error adding index '%s' to _Temp_IndexInfo table (%i) - %s", name.utf8().data(), database.lastError(), database.lastErrorMsg());
return false;
}
result = statement->step();
}
if (result != SQLITE_DONE) {
LOG_ERROR("Error fetching indices from IndexInfo table (%i) - %s", database.lastError(), database.lastErrorMsg());
return false;
}
}
if (!database.executeCommand("DROP TABLE IndexInfo"_s)) {
LOG_ERROR("Error dropping existing IndexInfo table (%i) - %s", database.lastError(), database.lastErrorMsg());
return false;
}
if (!database.executeCommand("ALTER TABLE _Temp_IndexInfo RENAME TO IndexInfo"_s)) {
LOG_ERROR("Error renaming _Temp_IndexInfo table (%i) - %s", database.lastError(), database.lastErrorMsg());
return false;
}
transaction.commit();
return true;
}
bool SQLiteIDBBackingStore::migrateIndexRecordsTableForIDUpdate(const HashMap<std::pair<uint64_t, uint64_t>, uint64_t>& indexIDMap)
{
SQLiteDatabase& database = *m_sqliteDB;
SQLiteTransaction transaction(database);
transaction.begin();
if (!database.executeCommand(v3IndexRecordsTableSchemaTemp())) {
LOG_ERROR("Error creating _Temp_IndexRecords table in database (%i) - %s", database.lastError(), database.lastErrorMsg());
return false;
}
{
auto statement = database.prepareStatement("SELECT indexID, objectStoreID, key, value, objectStoreRecordID FROM IndexRecords;"_s);
if (!statement) {
LOG_ERROR("Error preparing statement to fetch records from the IndexRecords table (%i) - %s", database.lastError(), database.lastErrorMsg());
return false;
}
int result = statement->step();
while (result == SQLITE_ROW) {
uint64_t id = statement->columnInt64(0);
uint64_t objectStoreID = statement->columnInt64(1);
uint64_t newID = indexIDMap.get({ objectStoreID, id });
auto keyBufferSpan = statement->columnBlobAsSpan(2);
auto valueBufferSpan = statement->columnBlobAsSpan(3);
uint64_t recordID = statement->columnInt64(4);
auto sql = cachedStatement(SQL::PutTempIndexRecord, "INSERT INTO _Temp_IndexRecords VALUES (?, ?, CAST(? AS TEXT), CAST(? AS TEXT), ?);"_s);
if (!sql
|| sql->bindInt64(1, newID) != SQLITE_OK
|| sql->bindInt64(2, objectStoreID) != SQLITE_OK
|| sql->bindBlob(3, keyBufferSpan) != SQLITE_OK
|| sql->bindBlob(4, valueBufferSpan) != SQLITE_OK
|| sql->bindInt64(5, recordID) != SQLITE_OK
|| sql->step() != SQLITE_DONE) {
LOG_ERROR("Error adding index record to _Temp_IndexRecords table (%i) - %s", database.lastError(), database.lastErrorMsg());
return false;
}
result = statement->step();
}
if (result != SQLITE_DONE) {
LOG_ERROR("Error fetching index record from database on disk (%i) - %s", database.lastError(), database.lastErrorMsg());
return false;
}
}
if (!database.executeCommand("DROP TABLE IndexRecords"_s)) {
LOG_ERROR("Error dropping existing IndexRecords table (%i) - %s", database.lastError(), database.lastErrorMsg());
return false;
}
if (!database.executeCommand("ALTER TABLE _Temp_IndexRecords RENAME TO IndexRecords"_s)) {
LOG_ERROR("Error renaming temporary IndexRecords table (%i) - %s", database.lastError(), database.lastErrorMsg());
return false;
}
transaction.commit();
return true;
}
bool SQLiteIDBBackingStore::removeExistingIndex(uint64_t indexID)
{
SQLiteTransaction transaction(*m_sqliteDB);
transaction.begin();
{
auto sql = cachedStatement(SQL::RemoveIndexInfo, "DELETE FROM IndexInfo WHERE id = ?;"_s);
if (!sql
|| sql->bindInt64(1, indexID) != SQLITE_OK
|| sql->step() != SQLITE_DONE) {
LOG_ERROR("Unable to remove existing index from IndexInfo table (%i) - %s", m_sqliteDB->lastError(), m_sqliteDB->lastErrorMsg());
return false;
}
}
{
auto sql = cachedStatement(SQL::DeleteIndexRecords, "DELETE FROM IndexRecords WHERE indexID = ?;"_s);
if (!sql
|| sql->bindInt64(1, indexID) != SQLITE_OK
|| sql->step() != SQLITE_DONE) {
LOG_ERROR("Unable to remove existing index from IndexRecords table (%i) - %s", m_sqliteDB->lastError(), m_sqliteDB->lastErrorMsg());
return false;
}
}
transaction.commit();
return true;
}
bool SQLiteIDBBackingStore::addExistingIndex(IDBObjectStoreInfo& objectStoreInfo, const IDBIndexInfo& info)
{
SQLiteTransaction transaction(*m_sqliteDB);
transaction.begin();
auto keyPathBlob = serializeIDBKeyPath(info.keyPath());
if (!keyPathBlob) {
LOG_ERROR("Unable to serialize IDBKeyPath to save in database");
return false;
}
{
auto sql = cachedStatement(SQL::CreateIndexInfo, "INSERT INTO IndexInfo VALUES (?, ?, ?, ?, ?, ?);"_s);
if (!sql
|| sql->bindInt64(1, info.identifier()) != SQLITE_OK
|| sql->bindText(2, info.name()) != SQLITE_OK
|| sql->bindInt64(3, info.objectStoreIdentifier()) != SQLITE_OK
|| sql->bindBlob(4, keyPathBlob->span()) != SQLITE_OK
|| sql->bindInt(5, info.unique()) != SQLITE_OK
|| sql->bindInt(6, info.multiEntry()) != SQLITE_OK
|| sql->step() != SQLITE_DONE) {
LOG_ERROR("Could not add index '%s' to IndexInfo table (%i) - %s", info.name().utf8().data(), m_sqliteDB->lastError(), m_sqliteDB->lastErrorMsg());
return false;
}
}
{
auto sql = cachedStatement(SQL::GetObjectStoreRecords, "SELECT key, value, recordID FROM Records WHERE objectStoreID = ?;"_s);
if (!sql
|| sql->bindInt64(1, info.objectStoreIdentifier()) != SQLITE_OK) {
LOG_ERROR("Unable to prepare statement or bind values (%i) - %s", m_sqliteDB->lastError(), m_sqliteDB->lastErrorMsg());
return false;
}
int result = sql->step();
while (result == SQLITE_ROW) {
auto keyBufferSpan = sql->columnBlobAsSpan(0);
IDBKeyData keyData;
if (!deserializeIDBKeyData(keyBufferSpan, keyData)) {
LOG_ERROR("Unable to deserialize key data from database while getting all records");
return false;
}
auto value = ThreadSafeDataBuffer::create(sql->columnBlob(1));
uint64_t recordID = sql->columnInt64(2);
IDBError error = updateOneIndexForAddRecord(objectStoreInfo, info, keyData, value, recordID);
if (!error.isNull())
return false;
result = sql->step();
}
if (result != SQLITE_DONE) {
LOG_ERROR("Error fetching object records from Records table on disk");
return false;
}
}
transaction.commit();
return true;
}
bool SQLiteIDBBackingStore::handleDuplicateIndexIDs(const HashMap<uint64_t, Vector<IDBIndexInfo>>& indexInfoMap, IDBDatabaseInfo& databaseInfo)
{
for (auto& iter : indexInfoMap) {
if (iter.value.size() == 1)
continue;
if (!removeExistingIndex(iter.key))
return false;
for (auto info : iter.value) {
auto objectStoreInfo = databaseInfo.infoForExistingObjectStore(info.objectStoreIdentifier());
ASSERT(objectStoreInfo);
objectStoreInfo->deleteIndex(info.identifier());
// A new index with the same name may already be added.
if (objectStoreInfo->hasIndex(info.name()))
continue;
info.setIdentifier(databaseInfo.generateNextIndexID());
if (!addExistingIndex(*objectStoreInfo, info))
return false;
objectStoreInfo->addExistingIndex(info);
}
}
return true;
}
std::unique_ptr<IDBDatabaseInfo> SQLiteIDBBackingStore::extractExistingDatabaseInfo()
{
ASSERT(m_sqliteDB);
if (!m_sqliteDB->tableExists("IDBDatabaseInfo"_s))
return nullptr;
String databaseName;
{
auto sql = m_sqliteDB->prepareStatement("SELECT value FROM IDBDatabaseInfo WHERE key = 'DatabaseName';"_s);
databaseName = sql->columnText(0);
if (databaseName != m_identifier.databaseName()) {
LOG_ERROR("Database name in the info database ('%s') does not match the expected name ('%s')", databaseName.utf8().data(), m_identifier.databaseName().utf8().data());
return nullptr;
}
}
uint64_t databaseVersion;
{
auto sql = m_sqliteDB->prepareStatement("SELECT value FROM IDBDatabaseInfo WHERE key = 'DatabaseVersion';"_s);
String stringVersion = sql->columnText(0);
auto parsedVersion = parseInteger<uint64_t>(stringVersion);
if (!parsedVersion) {
LOG_ERROR("Database version on disk ('%s') does not cleanly convert to an unsigned 64-bit integer version", stringVersion.utf8().data());
return nullptr;
}
databaseVersion = *parsedVersion;
}
auto databaseInfo = makeUnique<IDBDatabaseInfo>(databaseName, databaseVersion, 0);
auto result = ensureValidObjectStoreInfoTable();
if (!result)
return nullptr;
bool shouldUpdateIndexID = (result.value() == IsSchemaUpgraded::Yes);
{
auto sql = m_sqliteDB->prepareStatement("SELECT id, name, keyPath, autoInc FROM ObjectStoreInfo;"_s);
if (!sql)
return nullptr;
int result = sql->step();
while (result == SQLITE_ROW) {
uint64_t objectStoreID = sql->columnInt64(0);
String objectStoreName = sql->columnText(1);
auto keyPathBufferSpan = sql->columnBlobAsSpan(2);
std::optional<IDBKeyPath> objectStoreKeyPath;
if (!deserializeIDBKeyPath(keyPathBufferSpan, objectStoreKeyPath)) {
LOG_ERROR("Unable to extract key path from database");
return nullptr;
}
bool autoIncrement = sql->columnInt(3);
databaseInfo->addExistingObjectStore({ objectStoreID, objectStoreName, WTFMove(objectStoreKeyPath), autoIncrement });
result = sql->step();
}
if (result != SQLITE_DONE) {
LOG_ERROR("Error fetching object store info from database on disk");
return nullptr;
}
}
uint64_t maxIndexID = 0;
HashMap<std::pair<uint64_t, uint64_t>, uint64_t> indexIDMap;
HashMap<uint64_t, Vector<IDBIndexInfo>> indexInfoMap;
{
auto sql = m_sqliteDB->prepareStatement("SELECT id, name, objectStoreID, keyPath, isUnique, multiEntry FROM IndexInfo;"_s);
if (!sql) {
LOG_ERROR("Unable to prepare statement to fetch records from the IndexInfo table.");
return nullptr;
}
int result = sql->step();
while (result == SQLITE_ROW) {
uint64_t indexID = sql->columnInt64(0);
String indexName = sql->columnText(1);
uint64_t objectStoreID = sql->columnInt64(2);
auto keyPathBufferSpan = sql->columnBlobAsSpan(3);
std::optional<IDBKeyPath> indexKeyPath;
if (!deserializeIDBKeyPath(keyPathBufferSpan, indexKeyPath)) {
LOG_ERROR("Unable to extract key path from database");
return nullptr;
}
if (!indexKeyPath) {
LOG_ERROR("Unable to extract key path from database");
return nullptr;
}
bool unique = sql->columnInt(4);
bool multiEntry = sql->columnInt(5);
auto objectStore = databaseInfo->infoForExistingObjectStore(objectStoreID);
if (!objectStore) {
LOG_ERROR("Found index referring to a non-existant object store");
return nullptr;
}
if (shouldUpdateIndexID) {
indexIDMap.set({ objectStoreID, indexID }, ++maxIndexID);
indexID = maxIndexID;
}
auto indexInfo = IDBIndexInfo { indexID, objectStoreID, indexName, WTFMove(indexKeyPath.value()), unique, multiEntry };
if (!shouldUpdateIndexID) {
auto& indexInfos = indexInfoMap.ensure(indexID, []() -> Vector<IDBIndexInfo> {
return { };
}).iterator->value;
indexInfos.append(indexInfo);
}
objectStore->addExistingIndex(indexInfo);
maxIndexID = maxIndexID < indexID ? indexID : maxIndexID;
result = sql->step();
}
if (result != SQLITE_DONE) {
LOG_ERROR("Error fetching index info from database on disk");
return nullptr;
}
databaseInfo->setMaxIndexID(maxIndexID);
}
if (shouldUpdateIndexID) {
if (!migrateIndexInfoTableForIDUpdate(indexIDMap) || !migrateIndexRecordsTableForIDUpdate(indexIDMap))
return nullptr;
} else {
if (!handleDuplicateIndexIDs(indexInfoMap, *databaseInfo))
return nullptr;
}
return databaseInfo;
}
String SQLiteIDBBackingStore::encodeDatabaseName(const String& databaseName)
{
ASSERT(!databaseName.isNull());
if (databaseName.isEmpty())
return "%00"_s;
return makeStringByReplacingAll(FileSystem::encodeForFileName(databaseName), '.', "%2E"_s);
}
String SQLiteIDBBackingStore::decodeDatabaseName(const String& encodedName)
{
if (encodedName == "%00"_s)
return emptyString();
return FileSystem::decodeFromFilename(makeStringByReplacingAll(encodedName, "%2E"_s, "."_s));
}
String SQLiteIDBBackingStore::fullDatabasePathForDirectory(const String& fullDatabaseDirectory)
{
return FileSystem::pathByAppendingComponent(fullDatabaseDirectory, "IndexedDB.sqlite3"_s);
}
String SQLiteIDBBackingStore::fullDatabasePath() const
{
return fullDatabasePathForDirectory(m_databaseDirectory);
}
std::optional<IDBDatabaseNameAndVersion> SQLiteIDBBackingStore::databaseNameAndVersionFromFile(const String& databasePath)
{
SQLiteDatabase database;
if (!database.open(databasePath)) {
LOG_ERROR("Failed to open SQLite database at path '%s' when getting database name", databasePath.utf8().data());
return std::nullopt;
}
if (!database.tableExists("IDBDatabaseInfo"_s)) {
LOG_ERROR("Could not find IDBDatabaseInfo table and get database name(%i) - %s", database.lastError(), database.lastErrorMsg());
return std::nullopt;
}
auto namesql = database.prepareStatement("SELECT value FROM IDBDatabaseInfo WHERE key = 'DatabaseName';"_s);
if (!namesql) {
LOG_ERROR("Could not prepare statement to get database name(%i) - %s", database.lastError(), database.lastErrorMsg());
return std::nullopt;
}
auto databaseName = namesql->columnText(0);
auto versql = database.prepareStatement("SELECT value FROM IDBDatabaseInfo WHERE key = 'DatabaseVersion';"_s);
String stringVersion = versql ? versql->columnText(0) : String();
auto databaseVersion = parseInteger<uint64_t>(stringVersion);
if (!databaseVersion) {
LOG_ERROR("Database version on disk ('%s') does not cleanly convert to an unsigned 64-bit integer version", stringVersion.utf8().data());
return std::nullopt;
}
return IDBDatabaseNameAndVersion { databaseName, *databaseVersion };
}
IDBError SQLiteIDBBackingStore::getOrEstablishDatabaseInfo(IDBDatabaseInfo& info)
{
LOG(IndexedDB, "SQLiteIDBBackingStore::getOrEstablishDatabaseInfo - database %s", m_identifier.databaseName().utf8().data());
if (m_databaseInfo) {
info = *m_databaseInfo;
return IDBError { };
}
String databasePath = fullDatabasePath();
FileSystem::makeAllDirectories(FileSystem::parentPath(databasePath));
m_sqliteDB = makeUnique<SQLiteDatabase>();
if (!m_sqliteDB->open(databasePath, SQLiteDatabase::OpenMode::ReadWriteCreate, SQLiteDatabase::OpenOptions::CanSuspendWhileLocked)) {
RELEASE_LOG_ERROR(IndexedDB, "%p - SQLiteIDBBackingStore::getOrEstablishDatabaseInfo: Failed to open database at path '%" PUBLIC_LOG_STRING "' (%d) - %" PUBLIC_LOG_STRING, this, databasePath.utf8().data(), m_sqliteDB->lastError(), m_sqliteDB->lastErrorMsg());
closeSQLiteDB();
}
if (!m_sqliteDB)
return IDBError { ExceptionCode::UnknownError, "Unable to open database file on disk"_s };
m_sqliteDB->disableThreadingChecks();
m_sqliteDB->enableAutomaticWALTruncation();
m_sqliteDB->setCollationFunction("IDBKEY"_s, [](int aLength, const void* a, int bLength, const void* b) {
return idbKeyCollate(std::span { static_cast<const uint8_t*>(a), static_cast<size_t>(aLength) }, std::span { static_cast<const uint8_t*>(b), static_cast<size_t>(bLength) });
});
IDBError error = ensureValidRecordsTable();
if (!error.isNull()) {
closeSQLiteDB();
return error;