File: quota_database.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1360 lines) | stat: -rw-r--r-- 45,831 bytes parent folder | download | duplicates (5)
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
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "storage/browser/quota/quota_database.h"

#include <stddef.h>
#include <stdint.h>

#include <memory>
#include <tuple>
#include <vector>

#include "base/auto_reset.h"
#include "base/containers/contains.h"
#include "base/dcheck_is_on.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/metrics/histogram_functions.h"
#include "base/sequence_checker.h"
#include "base/time/clock.h"
#include "components/services/storage/public/cpp/buckets/constants.h"
#include "components/services/storage/public/cpp/quota_error_or.h"
#include "sql/database.h"
#include "sql/error_delegate_util.h"
#include "sql/meta_table.h"
#include "sql/recovery.h"
#include "sql/statement.h"
#include "sql/transaction.h"
#include "storage/browser/quota/quota_database_migrations.h"
#include "storage/browser/quota/quota_features.h"
#include "storage/browser/quota/quota_internals.mojom.h"
#include "storage/browser/quota/special_storage_policy.h"
#include "url/gurl.h"

using ::blink::StorageKey;

namespace storage {
namespace {

static const int kDaysInTenYears = 10 * 365;

// Version number of the database schema.
//
// We support migrating the database schema from versions that are at most 2
// years old. Older versions are unsupported, and will cause the database to get
// razed.
//
// Version 1 - 2011-03-17 - http://crrev.com/78521 (unsupported)
// Version 2 - 2011-04-25 - http://crrev.com/82847 (unsupported)
// Version 3 - 2011-07-08 - http://crrev.com/91835 (unsupported)
// Version 4 - 2011-10-17 - http://crrev.com/105822 (unsupported)
// Version 5 - 2015-10-19 - https://crrev.com/354932 (unsupported)
// Version 6 - 2021-04-27 - https://crrev.com/c/2757450 (unsupported)
// Version 7 - 2021-05-20 - https://crrev.com/c/2910136
// Version 8 - 2021-09-01 - https://crrev.com/c/3119831
// Version 9 - 2022-05-13 - https://crrev.com/c/3601253
// Version 10 - 2023-04-10 - https://crrev.com/c/4412082
//
// TODO(crbug.com/40211051): Remove field `type` and all rows that are not of
// `type` 0 (Temporary) with the next migration. All other types have been
// deprecated and no data is associated with any other type. Therefore they
// should be removed. Until this is done, queries without 'WHERE type=0' might
// return buckets of other types so this should always be included until this is
// complete.
const int kQuotaDatabaseCurrentSchemaVersion = 10;
const int kQuotaDatabaseCompatibleVersion = 10;

// Definitions for database schema.
const char kBucketTable[] = "buckets";

// Flag to ensure that all existing data for storage keys have been
// registered into the buckets table. Introduced 2022-05 (crrev.com/c/3594211).
const char kBucketsTableBootstrapped[] = "IsBucketsBootstrapped";

// Flag to not repeat MediaLicenseDatabase cleanup in all the bucket
// directories. Introduced 2025-01 (crrev.com/c/6088694).
const char kMediaLicenseDatabaseRemoved[] = "IsMediaLicenseDatabaseRemoved";

const int kCommitIntervalMs = 30000;

const base::Clock* g_clock_for_testing = nullptr;

void RecordDatabaseResetHistogram(const DatabaseResetReason reason) {
  base::UmaHistogramEnumeration("Quota.QuotaDatabaseReset", reason);
}

// SQL statement fragment for inserting fields into the buckets table.
#define BUCKETS_FIELDS_INSERTER                                               \
  " (storage_key, host, type, name, use_count, last_accessed, last_modified," \
  " expiration, quota, persistent, durability) "                              \
  " VALUES (?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?) "

void BindBucketInitParamsToInsertStatement(const BucketInitParams& params,
                                           int use_count,
                                           const base::Time& last_accessed,
                                           const base::Time& last_modified,
                                           sql::Statement& statement) {
  statement.BindString(0, params.storage_key.Serialize());
  statement.BindString(1, params.storage_key.origin().host());
  statement.BindString(2, params.name);
  statement.BindInt(3, use_count);
  statement.BindTime(4, last_accessed);
  statement.BindTime(5, last_modified);
  statement.BindTime(6, params.expiration);
  statement.BindInt64(7, params.quota);
  statement.BindBool(8, params.persistent.value_or(false));
  int durability = static_cast<int>(
      params.durability.value_or(blink::mojom::BucketDurability::kRelaxed));
  statement.BindInt(9, durability);
}

// Fields to be retrieved from the database and stored in a
// `BucketTableEntryPtr`.
#define BUCKET_TABLE_ENTRY_FIELDS_SELECTOR \
  "id, storage_key, type, name, use_count, last_accessed, last_modified "

mojom::BucketTableEntryPtr BucketTableEntryFromSqlStatement(
    sql::Statement& statement) {
  // Should only ever return type Temporary. All other types are deprecated.
  CHECK_EQ(statement.ColumnInt(2), 0);

  mojom::BucketTableEntryPtr entry = mojom::BucketTableEntry::New();
  entry->bucket_id = statement.ColumnInt64(0);
  entry->storage_key = statement.ColumnString(1);
  entry->name = statement.ColumnString(3);
  entry->use_count = statement.ColumnInt(4);
  entry->last_accessed = statement.ColumnTime(5);
  entry->last_modified = statement.ColumnTime(6);
  return entry;
}

// Fields to be retrieved from the database and stored in a `BucketInfo`.
#define BUCKET_INFO_FIELDS_SELECTOR \
  " id, storage_key, type, name, expiration, quota, persistent, durability "

QuotaErrorOr<BucketInfo> BucketInfoFromSqlStatement(sql::Statement& statement) {
  if (!statement.Step()) {
    return base::unexpected(statement.Succeeded() ? QuotaError::kNotFound
                                                  : QuotaError::kDatabaseError);
  }

  std::optional<StorageKey> storage_key =
      StorageKey::Deserialize(statement.ColumnStringView(1));
  if (!storage_key.has_value()) {
    return base::unexpected(QuotaError::kStorageKeyError);
  }

  // Should only ever return type Temporary. All other types are deprecated.
  CHECK_EQ(statement.ColumnInt(2), 0);
  BucketInfo bucket_info(
      BucketId(statement.ColumnInt64(0)), storage_key.value(),
      statement.ColumnString(3), statement.ColumnTime(4),
      statement.ColumnInt64(5), statement.ColumnBool(6),
      static_cast<blink::mojom::BucketDurability>(statement.ColumnInt(7)));
  // Ignore the durability saved in the database for default buckets, which
  // changed from strict by default to relaxed by default in M124.
  if (bucket_info.is_default()) {
    bucket_info.durability = blink::mojom::BucketDurability::kRelaxed;
  }
  return bucket_info;
}

std::set<BucketInfo> BucketInfosFromSqlStatement(sql::Statement& statement) {
  std::set<BucketInfo> result;
  QuotaErrorOr<BucketInfo> bucket;
  while ((bucket = BucketInfoFromSqlStatement(statement)).has_value()) {
    result.insert(bucket.value());
  }

  return result;
}

}  // anonymous namespace

const QuotaDatabase::TableSchema QuotaDatabase::kTables[] = {
    {kBucketTable,
     "(id INTEGER PRIMARY KEY AUTOINCREMENT,"
     " storage_key TEXT NOT NULL,"
     " host TEXT NOT NULL,"
     " type INTEGER NOT NULL,"
     " name TEXT NOT NULL,"
     " use_count INTEGER NOT NULL,"
     " last_accessed INTEGER NOT NULL,"
     " last_modified INTEGER NOT NULL,"
     " expiration INTEGER NOT NULL,"
     " quota INTEGER NOT NULL,"
     " persistent INTEGER NOT NULL,"
     " durability INTEGER NOT NULL)"
     " STRICT"}};
const size_t QuotaDatabase::kTableCount = std::size(QuotaDatabase::kTables);

// static
const QuotaDatabase::IndexSchema QuotaDatabase::kIndexes[] = {
    {"buckets_by_storage_key", kBucketTable, "(storage_key, type, name)", true},
    {"buckets_by_host", kBucketTable, "(host, type)", false},
    {"buckets_by_last_accessed", kBucketTable, "(type, last_accessed)", false},
    {"buckets_by_last_modified", kBucketTable, "(type, last_modified)", false},
    {"buckets_by_expiration", kBucketTable, "(expiration)", false},
};
const size_t QuotaDatabase::kIndexCount = std::size(QuotaDatabase::kIndexes);

// QuotaDatabase ------------------------------------------------------------
QuotaDatabase::QuotaDatabase(const base::FilePath& profile_path)
    : storage_directory_(
          profile_path.empty()
              ? nullptr
              : std::make_unique<StorageDirectory>(profile_path)),
      db_file_path_(
          profile_path.empty()
              ? base::FilePath()
              : storage_directory_->path().AppendASCII(kDatabaseName)),
      legacy_db_file_path_(profile_path.empty()
                               ? base::FilePath()
                               : profile_path.AppendASCII(kDatabaseName)) {
  DETACH_FROM_SEQUENCE(sequence_checker_);
}

QuotaDatabase::~QuotaDatabase() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (db_) {
    db_->reset_error_callback();
    db_->CommitTransactionDeprecated();
  }
}

constexpr char QuotaDatabase::kDatabaseName[];

QuotaErrorOr<BucketInfo> QuotaDatabase::UpdateOrCreateBucket(
    const BucketInitParams& params,
    int max_bucket_count) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  sqlite_error_code_ = 0;
  QuotaErrorOr<BucketInfo> bucket_result =
      GetBucket(params.storage_key, params.name);

  if (!bucket_result.has_value()) {
    if (bucket_result.error() == QuotaError::kNotFound) {
      bucket_result = CreateBucketInternal(params, max_bucket_count);
    }
    if (!bucket_result.has_value()) {
      bucket_result.error().sqlite_error = sqlite_error_code_;
    }
    return bucket_result;
  }

  // Don't bother updating anything if the bucket is expired.
  if (!bucket_result->expiration.is_null() &&
      (bucket_result->expiration <= GetNow())) {
    return bucket_result;
  }

  // Update the parameters that can be changed.
  if (!params.expiration.is_null() &&
      (params.expiration != bucket_result->expiration)) {
    DCHECK(!bucket_result->is_default());
    bucket_result =
        UpdateBucketExpiration(bucket_result->id, params.expiration);
    DCHECK(bucket_result.has_value());
  }

  if (params.persistent && (*params.persistent != bucket_result->persistent)) {
    DCHECK(!bucket_result->is_default());
    bucket_result =
        UpdateBucketPersistence(bucket_result->id, *params.persistent);
    DCHECK(bucket_result.has_value());
  }

  return bucket_result;
}

QuotaErrorOr<BucketInfo> QuotaDatabase::CreateBucketForTesting(
    const StorageKey& storage_key,
    const std::string& bucket_name) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  BucketInitParams params(storage_key, bucket_name);
  return CreateBucketInternal(params);
}

QuotaErrorOr<BucketInfo> QuotaDatabase::GetBucket(
    const StorageKey& storage_key,
    const std::string& bucket_name) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  QuotaError open_error = EnsureOpened();
  if (open_error != QuotaError::kNone) {
    return base::unexpected(open_error);
  }

  static constexpr char kSql[] =
      // clang-format off
      "SELECT " BUCKET_INFO_FIELDS_SELECTOR
        "FROM buckets "
        "WHERE storage_key = ? AND type = 0 AND name = ?";
  // clang-format on
  last_operation_ = "GetBucket";
  sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
  statement.BindString(0, storage_key.Serialize());
  statement.BindString(1, bucket_name);

  return BucketInfoFromSqlStatement(statement);
}

QuotaErrorOr<BucketInfo> QuotaDatabase::UpdateBucketExpiration(
    BucketId bucket,
    const base::Time& expiration) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  QuotaError open_error = EnsureOpened();
  if (open_error != QuotaError::kNone) {
    return base::unexpected(open_error);
  }

  static constexpr char kSql[] =
      // clang-format off
      "UPDATE buckets "
        "SET expiration = ? "
        "WHERE id = ? "
        "RETURNING " BUCKET_INFO_FIELDS_SELECTOR;
  // clang-format on
  last_operation_ = "UpdateBucketExpiration";
  sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
  statement.BindTime(0, expiration);
  statement.BindInt64(1, bucket.value());
  ScheduleCommit();

  return BucketInfoFromSqlStatement(statement);
}

QuotaErrorOr<BucketInfo> QuotaDatabase::UpdateBucketPersistence(
    BucketId bucket,
    bool persistent) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  QuotaError open_error = EnsureOpened();
  if (open_error != QuotaError::kNone) {
    return base::unexpected(open_error);
  }

  static constexpr char kSql[] =
      // clang-format off
      "UPDATE buckets "
        "SET persistent = ? "
        "WHERE id = ? "
        "RETURNING " BUCKET_INFO_FIELDS_SELECTOR;
  // clang-format on
  last_operation_ = "UpdateBucketPersistence";
  sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
  statement.BindBool(0, persistent);
  statement.BindInt64(1, bucket.value());
  ScheduleCommit();

  return BucketInfoFromSqlStatement(statement);
}

QuotaErrorOr<BucketInfo> QuotaDatabase::GetBucketById(BucketId bucket_id) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  QuotaError open_error = EnsureOpened();
  if (open_error != QuotaError::kNone) {
    return base::unexpected(open_error);
  }

  static constexpr char kSql[] =
      // clang-format off
      "SELECT " BUCKET_INFO_FIELDS_SELECTOR
        "FROM buckets "
        "WHERE id = ?";
  // clang-format on
  last_operation_ = "GetBucketById";
  sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
  statement.BindInt64(0, bucket_id.value());

  return BucketInfoFromSqlStatement(statement);
}

QuotaErrorOr<std::set<BucketInfo>> QuotaDatabase::GetAllBuckets() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  QuotaError open_error = EnsureOpened();
  if (open_error != QuotaError::kNone) {
    return base::unexpected(open_error);
  }

  static constexpr char kSql[] =
      // clang-format off
      "SELECT " BUCKET_INFO_FIELDS_SELECTOR
        "FROM buckets "
        "WHERE type = 0";
  // clang-format on
  last_operation_ = "GetBucketsForType";
  sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));

  return BucketInfosFromSqlStatement(statement);
}

QuotaErrorOr<std::set<BucketInfo>> QuotaDatabase::GetBucketsForHost(
    const std::string& host) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  QuotaError open_error = EnsureOpened();
  if (open_error != QuotaError::kNone) {
    return base::unexpected(open_error);
  }

  static constexpr char kSql[] =
      // clang-format off
      "SELECT " BUCKET_INFO_FIELDS_SELECTOR
        "FROM buckets "
        "WHERE host = ? AND type = 0";
  // clang-format on
  last_operation_ = "GetBucketsForHost";
  sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
  statement.BindString(0, host);

  return BucketInfosFromSqlStatement(statement);
}

QuotaErrorOr<std::set<BucketInfo>> QuotaDatabase::GetBucketsForStorageKey(
    const StorageKey& storage_key) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  QuotaError open_error = EnsureOpened();
  if (open_error != QuotaError::kNone) {
    return base::unexpected(open_error);
  }

  static constexpr char kSql[] =
      // clang-format off
      "SELECT " BUCKET_INFO_FIELDS_SELECTOR
        "FROM buckets "
        "WHERE storage_key = ? AND type = 0";
  // clang-format on
  last_operation_ = "GetBucketsForStorageKey";
  sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
  statement.BindString(0, storage_key.Serialize());

  return BucketInfosFromSqlStatement(statement);
}

QuotaError QuotaDatabase::SetStorageKeyLastAccessTime(
    const StorageKey& storage_key,
    base::Time last_accessed) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  QuotaError open_error = EnsureOpened();
  if (open_error != QuotaError::kNone) {
    return open_error;
  }

  // clang-format off
  static constexpr char kSqlReadLastAccessed[] =
      "SELECT last_accessed FROM buckets "
        "WHERE storage_key = ? AND type = 0 AND name = ?";
  // clang-format on
  last_operation_ = "ReadStorageKeyLastAccessTime";
  sql::Statement statement_read(
      db_->GetCachedStatement(SQL_FROM_HERE, kSqlReadLastAccessed));
  statement_read.BindString(0, storage_key.Serialize());
  statement_read.BindString(1, kDefaultBucketName);

  if (statement_read.Step()) {
    base::Time earlier_last_accessed = statement_read.ColumnTime(0);
    // We want to record the delta in days between the last_accessed field value
    // and the new value so we better understand how often old quota buckets are
    // loaded for new use.
    if (!earlier_last_accessed.is_null() &&
        last_accessed > earlier_last_accessed) {
      int days_since_last_accessed =
          (last_accessed - earlier_last_accessed).InDays();
      if (days_since_last_accessed > 400) {
        base::UmaHistogramCustomCounts("Quota.DaysSinceLastAccessed400DaysGT",
                                       days_since_last_accessed, 401,
                                       kDaysInTenYears, 100);
      } else {
        base::UmaHistogramCustomCounts("Quota.DaysSinceLastAccessed400DaysLTE",
                                       days_since_last_accessed, 1, 400, 100);
      }
    }
  }

  // clang-format off
  static constexpr char kSqlSetLastAccessed[] =
      "UPDATE buckets "
        "SET use_count = use_count + 1, last_accessed = ? "
        "WHERE storage_key = ? AND type = 0 AND name = ?";
  // clang-format on
  last_operation_ = "SetStorageKeyLastAccessTime";
  sql::Statement statement_set(
      db_->GetCachedStatement(SQL_FROM_HERE, kSqlSetLastAccessed));
  statement_set.BindTime(0, last_accessed);
  statement_set.BindString(1, storage_key.Serialize());
  statement_set.BindString(2, kDefaultBucketName);

  if (!statement_set.Run()) {
    return QuotaError::kDatabaseError;
  }

  ScheduleCommit();
  return QuotaError::kNone;
}

QuotaError QuotaDatabase::SetBucketLastAccessTime(BucketId bucket_id,
                                                  base::Time last_accessed) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(!bucket_id.is_null());
  QuotaError open_error = EnsureOpened();
  if (open_error != QuotaError::kNone) {
    return open_error;
  }

  // clang-format off
  static constexpr char kSql[] =
      "UPDATE buckets "
        "SET use_count = use_count + 1, last_accessed = ? "
        "WHERE id = ?";
  // clang-format on
  last_operation_ = "SetBucketLastAccessTime";
  sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
  statement.BindTime(0, last_accessed);
  statement.BindInt64(1, bucket_id.value());

  if (!statement.Run()) {
    return QuotaError::kDatabaseError;
  }

  ScheduleCommit();
  return QuotaError::kNone;
}

QuotaError QuotaDatabase::SetBucketLastModifiedTime(BucketId bucket_id,
                                                    base::Time last_modified) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(!bucket_id.is_null());
  QuotaError open_error = EnsureOpened();
  if (open_error != QuotaError::kNone) {
    return open_error;
  }

  static constexpr char kSql[] =
      "UPDATE buckets SET last_modified = ? WHERE id = ?";
  last_operation_ = "SetBucketLastModifiedTime";
  sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
  statement.BindTime(0, last_modified);
  statement.BindInt64(1, bucket_id.value());

  if (!statement.Run()) {
    return QuotaError::kDatabaseError;
  }

  ScheduleCommit();
  return QuotaError::kNone;
}

QuotaError QuotaDatabase::RegisterInitialStorageKeyInfo(
    std::set<StorageKey> storage_keys) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  QuotaError open_error = EnsureOpened();
  if (open_error != QuotaError::kNone) {
    return open_error;
  }

  for (const auto& storage_key : storage_keys) {
    static constexpr char kSql[] =
        "INSERT OR IGNORE INTO buckets" BUCKETS_FIELDS_INSERTER;
    last_operation_ = "BootstrapDefaultBucket";
    sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
    BucketInitParams init_params =
        BucketInitParams::ForDefaultBucket(storage_key);
    BindBucketInitParamsToInsertStatement(init_params, /*use_count=*/0,
                                          /*last_accessed=*/base::Time(),
                                          /*last_modified=*/base::Time(),
                                          statement);

    if (!statement.Run()) {
      return QuotaError::kDatabaseError;
    }
  }
  ScheduleCommit();
  return QuotaError::kNone;
}

QuotaErrorOr<mojom::BucketTableEntryPtr> QuotaDatabase::GetBucketInfoForTest(
    BucketId bucket_id) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(!bucket_id.is_null());
  QuotaError open_error = EnsureOpened();
  if (open_error != QuotaError::kNone) {
    return base::unexpected(open_error);
  }

  static constexpr char kSql[] =
      // clang-format off
      "SELECT " BUCKET_TABLE_ENTRY_FIELDS_SELECTOR
        "FROM buckets "
        "WHERE id = ?";
  // clang-format on
  sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
  statement.BindInt64(0, bucket_id.value());

  if (!statement.Step()) {
    return base::unexpected(statement.Succeeded() ? QuotaError::kNotFound
                                                  : QuotaError::kDatabaseError);
  }

  std::optional<StorageKey> storage_key =
      StorageKey::Deserialize(statement.ColumnStringView(1));
  if (!storage_key.has_value()) {
    return base::unexpected(QuotaError::kStorageKeyError);
  }

  mojom::BucketTableEntryPtr entry =
      BucketTableEntryFromSqlStatement(statement);
  return entry;
}

QuotaErrorOr<mojom::BucketTableEntryPtr> QuotaDatabase::DeleteBucketData(
    const BucketLocator& bucket) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  QuotaError open_error = EnsureOpened();
  if (open_error != QuotaError::kNone) {
    return base::unexpected(open_error);
  }

  // Doom bucket directory first so data is no longer accessible, even if
  // directory deletion fails. `storage_directory_` may be nullptr for
  // in-memory only.
  if (storage_directory_ && !storage_directory_->DoomBucket(bucket)) {
    return base::unexpected(QuotaError::kFileOperationError);
  }

  static constexpr char kSql[] =
      "DELETE FROM buckets WHERE id = ? "
      "RETURNING " BUCKET_TABLE_ENTRY_FIELDS_SELECTOR;
  last_operation_ = "DeleteBucket";
  sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
  statement.BindInt64(0, bucket.id.value());

  if (!statement.Step()) {
    return base::unexpected(QuotaError::kDatabaseError);
  }

  // Scheduling this commit introduces the chance of inconsistencies
  // between the buckets table and data stored on disk in the file system.
  // If there is a crash or a battery failure before the transaction is
  // committed, the bucket directory may be deleted from the file system,
  // while an entry still may exist in the database.
  //
  // While this is not ideal, this does not introduce any new edge case.
  // We should check that bucket IDs have existing associated directories,
  // because database corruption could result in invalid bucket IDs.
  // TODO(crbug.com/40832940): For handling inconsistencies between the db and
  // the file system.
  ScheduleCommit();

  if (storage_directory_) {
    storage_directory_->ClearDoomedBuckets();
  }

  return BucketTableEntryFromSqlStatement(statement);
}

QuotaErrorOr<std::set<BucketLocator>> QuotaDatabase::GetBucketsForEviction(
    int64_t target_usage,
    const std::map<BucketLocator, int64_t>& usage_map,
    const std::set<BucketId>& bucket_exceptions,
    SpecialStoragePolicy* special_storage_policy) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  QuotaError open_error = EnsureOpened();
  if (open_error != QuotaError::kNone) {
    return base::unexpected(open_error);
  }

  std::set<BucketLocator> buckets_to_evict;

  // clang-format off
  static constexpr char kSql[] =
      "SELECT id, storage_key, name FROM buckets "
        "WHERE type = 0 AND persistent = 0 "
        "ORDER BY last_accessed";
  // clang-format on
  last_operation_ = "GetBucketsForEviction";

  sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));

  // The total space used by all buckets marked for eviction.
  int64_t total_usage = 0;

  while (statement.Step()) {
    std::optional<StorageKey> read_storage_key =
        StorageKey::Deserialize(statement.ColumnStringView(1));
    if (!read_storage_key.has_value()) {
      // TODO(estade): this row needs to be deleted.
      continue;
    }

    BucketId read_bucket_id = BucketId(statement.ColumnInt64(0));
    if (base::Contains(bucket_exceptions, read_bucket_id)) {
      continue;
    }

    // Only the default bucket is persisted by `navigator.storage.persist()`.
    const bool is_default = statement.ColumnStringView(2) == kDefaultBucketName;
    const GURL read_gurl = read_storage_key->origin().GetURL();
    if (is_default && special_storage_policy &&
        (special_storage_policy->IsStorageDurable(read_gurl) ||
         special_storage_policy->IsStorageUnlimited(read_gurl))) {
      continue;
    }

    BucketLocator locator(read_bucket_id, std::move(read_storage_key).value(),
                          is_default);
    const auto& bucket_usage = usage_map.find(locator);
    total_usage += (bucket_usage == usage_map.end()) ? 1 : bucket_usage->second;
    buckets_to_evict.insert(locator);
    if (total_usage >= target_usage) {
      break;
    }
  }
  if (buckets_to_evict.empty()) {
    return base::unexpected(QuotaError::kNotFound);
  }
  return buckets_to_evict;
}

QuotaErrorOr<std::set<StorageKey>> QuotaDatabase::GetAllStorageKeys() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  QuotaError open_error = EnsureOpened();
  if (open_error != QuotaError::kNone) {
    return base::unexpected(open_error);
  }

  static constexpr char kSql[] =
      "SELECT DISTINCT storage_key FROM buckets WHERE type = 0";
  last_operation_ = "GetStorageKeys";

  sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));

  std::set<StorageKey> storage_keys;
  while (statement.Step()) {
    std::optional<StorageKey> read_storage_key =
        StorageKey::Deserialize(statement.ColumnStringView(0));
    if (!read_storage_key.has_value()) {
      continue;
    }
    storage_keys.insert(read_storage_key.value());
  }
  return storage_keys;
}

QuotaErrorOr<std::set<BucketLocator>> QuotaDatabase::GetBucketsModifiedBetween(
    base::Time begin,
    base::Time end) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  QuotaError open_error = EnsureOpened();
  if (open_error != QuotaError::kNone) {
    return base::unexpected(open_error);
  }

  DCHECK(!begin.is_max());
  DCHECK(end != base::Time());
  // clang-format off
  static constexpr char kSql[] =
      "SELECT id, storage_key, name FROM buckets "
        "WHERE type = 0 AND last_modified >= ? AND last_modified < ?";
  // clang-format on
  last_operation_ = "GetBucketsModifiedBetween";

  sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
  statement.BindTime(0, begin);
  statement.BindTime(1, end);

  std::set<BucketLocator> buckets;
  while (statement.Step()) {
    std::optional<StorageKey> read_storage_key =
        StorageKey::Deserialize(statement.ColumnStringView(1));
    if (!read_storage_key.has_value()) {
      continue;
    }
    buckets.emplace(BucketId(statement.ColumnInt64(0)),
                    read_storage_key.value(),
                    statement.ColumnStringView(2) == kDefaultBucketName);
  }
  return buckets;
}

QuotaErrorOr<std::set<BucketInfo>> QuotaDatabase::GetExpiredBuckets(
    SpecialStoragePolicy* special_storage_policy) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  QuotaError open_error = EnsureOpened();
  if (open_error != QuotaError::kNone) {
    return base::unexpected(open_error);
  }

  // We only clear stale/orphan buckets once after a delay since startup. If we
  // have already done so, or should not do so yet, then we just want to clear
  // expired buckets here and not do the full query.
  if (already_evicted_stale_storage_ ||
      GetNow() < evict_stale_buckets_after_) {
    // clang-format off
    static constexpr char kSqlExpired[] =
        "SELECT " BUCKET_INFO_FIELDS_SELECTOR
          "FROM buckets "
          "WHERE expiration > 0 AND expiration < ?";
    // clang-format on
    last_operation_ = "GetExpired";

    sql::Statement statement(
        db_->GetCachedStatement(SQL_FROM_HERE, kSqlExpired));
    statement.BindTime(0, GetNow());
    return BucketInfosFromSqlStatement(statement);
  }

  already_evicted_stale_storage_ = true;
  // clang-format off
  static constexpr char kSqlExpiredAndStaleAndOrphan[] =
      "SELECT " BUCKET_INFO_FIELDS_SELECTOR
        "FROM buckets "
        "WHERE (expiration > 0 AND expiration < ?) OR "
        "      (type = 0 AND persistent = 0 AND "
        "       last_accessed < ? AND last_modified < ?) OR "
        "      (storage_key REGEXP '.*\\^(1|4).*' AND "
        "       last_accessed < ? AND last_modified < ?)";
  // clang-format on
  last_operation_ = "GetExpiredAndOrphanAndStale";

  sql::Statement statement(
      db_->GetCachedStatement(SQL_FROM_HERE, kSqlExpiredAndStaleAndOrphan));
  base::Time expiration_cutoff = GetNow();
  statement.BindTime(0, expiration_cutoff);
  base::Time stale_cutoff = GetNow() - base::Days(400);
  statement.BindTime(1, stale_cutoff);
  statement.BindTime(2, stale_cutoff);
  base::Time orphan_cutoff = GetNow() - base::Days(1);
  statement.BindTime(3, orphan_cutoff);
  statement.BindTime(4, orphan_cutoff);

  // Filter and count returned buckets.
  QuotaErrorOr<BucketInfo> bucket;
  std::set<BucketInfo> expired_buckets;
  uint64_t stale_buckets_found = 0;
  uint64_t orphan_buckets_found = 0;
  while ((bucket = BucketInfoFromSqlStatement(statement)).has_value()) {
    // Only the default bucket is persisted by `navigator.storage.persist()`.
    const GURL read_gurl = bucket->storage_key.origin().GetURL();
    if (bucket->is_default() && special_storage_policy &&
        (special_storage_policy->IsStorageDurable(read_gurl) ||
         special_storage_policy->IsStorageUnlimited(read_gurl))) {
      continue;
    }
    if (bucket->storage_key.nonce() ||
        bucket->storage_key.top_level_site().opaque()) {
      orphan_buckets_found++;
    } else if (bucket->expiration.is_null() ||
               bucket->expiration > expiration_cutoff) {
      stale_buckets_found++;
    }
    expired_buckets.insert(*bucket);
  }
  base::UmaHistogramCounts100000("Quota.StaleBucketCount", stale_buckets_found);
  base::UmaHistogramCounts100000("Quota.OrphanBucketCount",
                                 orphan_buckets_found);
  return expired_buckets;
}

bool QuotaDatabase::IsBootstrapped() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (EnsureOpened() != QuotaError::kNone) {
    return false;
  }

  int flag = 0;
  return meta_table_->GetValue(kBucketsTableBootstrapped, &flag) && flag;
}

QuotaError QuotaDatabase::SetIsBootstrapped(bool bootstrap_flag) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  QuotaError open_error = EnsureOpened();
  if (open_error != QuotaError::kNone) {
    return open_error;
  }

  return meta_table_->SetValue(kBucketsTableBootstrapped, bootstrap_flag)
             ? QuotaError::kNone
             : QuotaError::kDatabaseError;
}

bool QuotaDatabase::IsMediaLicenseDatabaseRemoved() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (EnsureOpened() != QuotaError::kNone) {
    return false;
  }

  int flag = 0;
  return meta_table_->GetValue(kMediaLicenseDatabaseRemoved, &flag) && flag;
}

QuotaError QuotaDatabase::SetIsMediaLicenseDatabaseRemoved(bool removed_flag) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  QuotaError open_error = EnsureOpened();
  if (open_error != QuotaError::kNone) {
    return open_error;
  }

  return meta_table_->SetValue(kMediaLicenseDatabaseRemoved, removed_flag)
             ? QuotaError::kNone
             : QuotaError::kDatabaseError;
}

bool QuotaDatabase::RecoverOrRaze(int error_code) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  std::ignore = sql::Recovery::RecoverIfPossible(
      db_.get(), error_code,
      sql::Recovery::Strategy::kRecoverWithMetaVersionOrRaze);

  db_.reset();
  EnsureOpened();
  return db_ && db_->is_open();
}

QuotaError QuotaDatabase::CorruptForTesting(
    base::OnceCallback<void(const base::FilePath&)> corrupter) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (db_) {
    // Commit the long-running transaction.
    db_->CommitTransactionDeprecated();
    db_->Close();
  }

  std::move(corrupter).Run(db_file_path_);

  if (!db_) {
    return QuotaError::kDatabaseError;
  }
  if (!OpenDatabase()) {
    return QuotaError::kDatabaseError;
  }

  // Begin a long-running transaction. This matches EnsureOpen().
  if (!db_->BeginTransactionDeprecated()) {
    return QuotaError::kDatabaseError;
  }
  return QuotaError::kNone;
}

void QuotaDatabase::SetDisabledForTesting(bool disable) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  is_disabled_ = disable;
}

// static
base::Time QuotaDatabase::GetNow() {
  return g_clock_for_testing ? g_clock_for_testing->Now() : base::Time::Now();
}

// static
void QuotaDatabase::SetClockForTesting(const base::Clock* clock) {
  g_clock_for_testing = clock;
}

void QuotaDatabase::SetAlreadyEvictedStaleStorageForTesting(
    bool already_evicted_stale_storage) {
  already_evicted_stale_storage_ = already_evicted_stale_storage;
}

void QuotaDatabase::CommitNow() {
  Commit();
}

void QuotaDatabase::Commit() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (!db_) {
    return;
  }

  if (timer_.IsRunning()) {
    timer_.Stop();
  }

  last_operation_ = "Commit";
  DCHECK_EQ(1, db_->transaction_nesting());
  db_->CommitTransactionDeprecated();
  DCHECK_EQ(0, db_->transaction_nesting());
  db_->BeginTransactionDeprecated();
  DCHECK_EQ(1, db_->transaction_nesting());
}

void QuotaDatabase::ScheduleCommit() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (timer_.IsRunning()) {
    return;
  }
  timer_.Start(FROM_HERE, base::Milliseconds(kCommitIntervalMs), this,
               &QuotaDatabase::Commit);
}

QuotaError QuotaDatabase::EnsureOpened() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (db_) {
    return QuotaError::kNone;
  }

  // If we tried and failed once, don't try again in the same session
  // to avoid creating an incoherent mess on disk.
  if (is_disabled_) {
    return QuotaError::kDatabaseError;
  }

  db_ = std::make_unique<sql::Database>(
      sql::DatabaseOptions()
          .set_preload(true)
          // The quota database is a critical storage component. If it's
          // corrupted, all client-side storage APIs fail, because they don't
          // know where their data is stored.
          .set_flush_to_media(true),
      sql::Database::Tag("Quota"));
  meta_table_ = std::make_unique<sql::MetaTable>();

  db_->set_error_callback(base::BindRepeating(&QuotaDatabase::OnSqliteError,
                                              base::Unretained(this)));

  // Migrate an existing database from the old path.
  if (!db_file_path_.empty() && !MoveLegacyDatabase()) {
    if (ResetStorage()) {
      // ResetStorage() has succeeded and database is already open.
      return QuotaError::kNone;
    }
    is_disabled_ = true;
    db_.reset();
    meta_table_.reset();
    return QuotaError::kDatabaseError;
  }

  if (!OpenDatabase() || !EnsureDatabaseVersion()) {
    LOG(ERROR) << "Could not open the quota database, resetting.";
    if (!db_file_path_.empty() && ResetStorage()) {
      // ResetStorage() has succeeded and database is already open.
      return QuotaError::kNone;
    }
    LOG(ERROR) << "Failed to reset the quota database.";
    is_disabled_ = true;
    db_.reset();
    meta_table_.reset();
    return QuotaError::kDatabaseError;
  }

  // Start a long-running transaction.
  DCHECK_EQ(0, db_->transaction_nesting());
  db_->BeginTransactionDeprecated();

  return QuotaError::kNone;
}

void QuotaDatabase::OnSqliteError(int sqlite_error_code,
                                  sql::Statement* statement) {
  // This check is here to DCHECK the error code in a place that gives a
  // useful stack trace.
  sql::IsErrorCatastrophic(sqlite_error_code);
  sqlite_error_code_ = sqlite_error_code;

  // Don't log UMA twice if the same operation manages to cause more than one
  // error (this can happen in particular when opening a database).
  if (last_operation_) {
    sql::UmaHistogramSqliteResult(
        std::string("Quota.DatabaseSpecificError.") + *last_operation_,
        sqlite_error_code);
    last_operation_.reset();
  }

  if (db_error_callback_) {
    db_error_callback_.Run(sqlite_error_code);
  }
}

bool QuotaDatabase::MoveLegacyDatabase() {
  // Migration was added on 04/2022 (https://crrev.com/c/3513545).
  // Cleanup after enough time has passed.
  if (base::PathExists(db_file_path_) ||
      !base::PathExists(legacy_db_file_path_)) {
    return true;
  }

  if (!base::CreateDirectory(db_file_path_.DirName()) ||
      !base::CopyFile(legacy_db_file_path_, db_file_path_)) {
    sql::Database::Delete(db_file_path_);
    return false;
  }

  base::FilePath legacy_journal_path =
      sql::Database::JournalPath(legacy_db_file_path_);
  if (base::PathExists(legacy_journal_path) &&
      !base::CopyFile(legacy_journal_path,
                      sql::Database::JournalPath(db_file_path_))) {
    sql::Database::Delete(db_file_path_);
    return false;
  }

  sql::Database::Delete(legacy_db_file_path_);
  return true;
}

bool QuotaDatabase::OpenDatabase() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  last_operation_ = "Open";

  // Open in memory database.
  if (db_file_path_.empty()) {
    if (db_->OpenInMemory()) {
      return true;
    }
    RecordDatabaseResetHistogram(DatabaseResetReason::kOpenInMemoryDatabase);
    return false;
  }

  if (!base::CreateDirectory(db_file_path_.DirName())) {
    RecordDatabaseResetHistogram(DatabaseResetReason::kCreateDirectory);
    return false;
  }

  if (!db_->Open(db_file_path_)) {
    RecordDatabaseResetHistogram(DatabaseResetReason::kOpenDatabase);
    return false;
  }

  return true;
}

bool QuotaDatabase::EnsureDatabaseVersion() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (!sql::MetaTable::DoesTableExist(db_.get())) {
    if (CreateSchema()) {
      return true;
    }
    RecordDatabaseResetHistogram(DatabaseResetReason::kCreateSchema);
    return false;
  }

  if (!meta_table_->Init(db_.get(), kQuotaDatabaseCurrentSchemaVersion,
                         kQuotaDatabaseCompatibleVersion)) {
    RecordDatabaseResetHistogram(DatabaseResetReason::kInitMetaTable);
    return false;
  }

  if (meta_table_->GetCompatibleVersionNumber() >
      kQuotaDatabaseCurrentSchemaVersion) {
    RecordDatabaseResetHistogram(DatabaseResetReason::kDatabaseVersionTooNew);
    LOG(WARNING) << "Quota database is too new.";
    return false;
  }

  if (meta_table_->GetVersionNumber() < kQuotaDatabaseCurrentSchemaVersion) {
    if (!QuotaDatabaseMigrations::UpgradeSchema(*this)) {
      RecordDatabaseResetHistogram(DatabaseResetReason::kDatabaseMigration);
      return false;
    }
  }

#if DCHECK_IS_ON()
  DCHECK(sql::MetaTable::DoesTableExist(db_.get()));
  for (const TableSchema& table : kTables) {
    DCHECK(db_->DoesTableExist(table.table_name));
  }
#endif

  return true;
}

bool QuotaDatabase::CreateSchema() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // TODO(kinuko): Factor out the common code to create databases.
  sql::Transaction transaction(db_.get());
  if (!transaction.Begin()) {
    return false;
  }

  if (!meta_table_->Init(db_.get(), kQuotaDatabaseCurrentSchemaVersion,
                         kQuotaDatabaseCompatibleVersion)) {
    return false;
  }

  for (const TableSchema& table : kTables) {
    if (!CreateTable(table)) {
      return false;
    }
  }

  for (const IndexSchema& index : kIndexes) {
    if (!CreateIndex(index)) {
      return false;
    }
  }

  return transaction.Commit();
}

bool QuotaDatabase::CreateTable(const TableSchema& table) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  last_operation_ = "CreateTable";
  std::string sql("CREATE TABLE ");
  sql += table.table_name;
  sql += table.columns;
  if (!db_->Execute(sql)) {
    VLOG(1) << "Failed to execute " << sql;
    return false;
  }
  return true;
}

bool QuotaDatabase::CreateIndex(const IndexSchema& index) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  std::string sql;
  if (index.unique) {
    sql += "CREATE UNIQUE INDEX ";
  } else {
    sql += "CREATE INDEX ";
  }
  sql += index.index_name;
  sql += " ON ";
  sql += index.table_name;
  sql += index.columns;
  if (!db_->Execute(sql)) {
    VLOG(1) << "Failed to execute " << sql;
    return false;
  }
  return true;
}

bool QuotaDatabase::ResetStorage() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(!db_file_path_.empty());
  DCHECK(storage_directory_);
  DCHECK(!db_ || !db_->transaction_nesting());
  VLOG(1) << "Deleting existing quota data and starting over.";

  meta_table_.reset();
  db_.reset();

  sql::Database::Delete(legacy_db_file_path_);
  sql::Database::Delete(db_file_path_);

  // Explicit file deletion to try and get consistent deletion across platforms.
  base::DeleteFile(legacy_db_file_path_);
  base::DeleteFile(db_file_path_);
  base::DeleteFile(sql::Database::JournalPath(legacy_db_file_path_));
  base::DeleteFile(sql::Database::JournalPath(db_file_path_));

  storage_directory_->Doom();
  storage_directory_->ClearDoomed();

  // So we can't go recursive.
  if (is_recreating_) {
    return false;
  }

  base::AutoReset<bool> auto_reset(&is_recreating_, true);
  return EnsureOpened() == QuotaError::kNone;
}

QuotaError QuotaDatabase::DumpBucketTable(const BucketTableCallback& callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  QuotaError open_error = EnsureOpened();
  if (open_error != QuotaError::kNone) {
    return open_error;
  }

  static constexpr char kSql[] =
      // clang-format off
      "SELECT " BUCKET_TABLE_ENTRY_FIELDS_SELECTOR
        "FROM buckets "
        "WHERE type = 0 ";
  // clang-format on
  sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));

  while (statement.Step()) {
    std::optional<StorageKey> storage_key =
        StorageKey::Deserialize(statement.ColumnStringView(1));
    if (!storage_key.has_value()) {
      continue;
    }

    auto entry = BucketTableEntryFromSqlStatement(statement);

    if (!callback.Run(std::move(entry))) {
      return QuotaError::kNone;
    }
  }
  return statement.Succeeded() ? QuotaError::kNone : QuotaError::kDatabaseError;
}

QuotaErrorOr<BucketInfo> QuotaDatabase::CreateBucketInternal(
    const BucketInitParams& params,
    int max_bucket_count) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  // TODO(crbug.com/40182349): Add DCHECKs for input validation.
  QuotaError open_error = EnsureOpened();
  if (open_error != QuotaError::kNone) {
    return base::unexpected(open_error);
  }

  // First verify this won't exceed the max bucket count if one is given.
  if (max_bucket_count > 0) {
    DCHECK_NE(params.name, kDefaultBucketName);
    // Note that technically we should be filtering out default buckets when
    // counting existing buckets so that the max count only applies to
    // non-default buckets. However the precise bucket count is not that
    // important and we don't want to perform a lot of string comparisons.
    static constexpr char kSql[] =
        // clang-format off
        "SELECT count(*) "
          "FROM buckets "
          "WHERE storage_key = ? AND type = 0";
    // clang-format on
    last_operation_ = "CountBuckets";
    sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
    statement.BindString(0, params.storage_key.Serialize());

    if (!statement.Step()) {
      return base::unexpected(QuotaError::kDatabaseError);
    }

    const int64_t current_bucket_count = statement.ColumnInt64(0);
    if (current_bucket_count >= max_bucket_count) {
      return base::unexpected(QuotaError::kQuotaExceeded);
    }

    base::UmaHistogramCounts100000("Storage.Buckets.BucketCount",
                                   current_bucket_count + 1);
  }

  static constexpr char kSql[] =
      // clang-format off
      "INSERT INTO buckets " BUCKETS_FIELDS_INSERTER
        " RETURNING " BUCKET_INFO_FIELDS_SELECTOR;
  // clang-format on
  last_operation_ = "CreateBucket";

  const base::Time now = GetNow();
  sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
  BindBucketInitParamsToInsertStatement(params,
                                        /*use_count=*/0,
                                        /*last_accessed=*/now,
                                        /*last_modified=*/now, statement);
  QuotaErrorOr<BucketInfo> result = BucketInfoFromSqlStatement(statement);

  if (result.has_value()) {
    CHECK(!statement.Step());
    // Commit immediately so that we persist the bucket metadata to disk before
    // we inform other services / web apps (via the Buckets API) that we did so.
    // Once informed, that promise should persist across power failures.
    Commit();
  }

  return result;
}

void QuotaDatabase::SetDbErrorCallback(
    const base::RepeatingCallback<void(int)>& db_error_callback) {
  db_error_callback_ = db_error_callback;
}

}  // namespace storage