File: shared_storage_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 (2219 lines) | stat: -rw-r--r-- 76,552 bytes parent folder | download | duplicates (3)
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
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/services/storage/shared_storage/shared_storage_database.h"

#include <inttypes.h>

#include <algorithm>
#include <climits>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

#include "base/files/file_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/numerics/checked_math.h"
#include "base/strings/strcat.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/default_clock.h"
#include "base/time/time.h"
#include "base/types/optional_ref.h"
#include "components/services/storage/public/mojom/storage_usage_info.mojom.h"
#include "components/services/storage/shared_storage/shared_storage_database_migrations.h"
#include "components/services/storage/shared_storage/shared_storage_options.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "net/base/schemeful_site.h"
#include "sql/database.h"
#include "sql/error_delegate_util.h"
#include "sql/statement.h"
#include "sql/transaction.h"
#include "storage/browser/quota/special_storage_policy.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/storage_key/storage_key.h"
#include "url/gurl.h"
#include "url/origin.h"

namespace storage {

// Version number of the database.
//
// Version 1 - https://crrev.com/c/3112567
//              * initial commit
//             https://crrev.com/c/3491742
//              * add `budget_mapping` table
// Version 2 - https://crrev.com/c/4029459
//              * add `last_used_time` to `values_mapping`
//              * rename `last_used_time` in `per_origin_mapping` to
//                `creation_time`
// Version 3 - https://crrev.com/c/4463360
//              * store `key` and `value` as BLOB instead of TEXT in order to
//                prevent roundtrip conversion to UTF-8 and back, which is
//                lossy if the original UTF-16 string contains unpaired
//                surrogates
// Version 4 - https://crrev.com/c/4879582
//              * rename `context_origin` column in `budget_mapping` to
//                `context_site`, converting existing data in this column from
//                origins to sites
// Version 5 - https://crrev.com/c/5278559
//              * add `num_bytes` to `per_origin_mapping` to keep track of the
//                total number of bytes stored as key-value pairs, i.e. twice
//                the total number of char16_t's currently stored as `key`s or
//                `value`s for associated `context_origin` in `values_mapping`
// Version 6 - https://crrev.com/c/5325884
//              * remove `length` from `per_origin_mapping`, now that quota
//                enforcement uses `num_bytes` instead

const int SharedStorageDatabase::kCurrentVersionNumber = 6;

// Earliest version which can use a `kCurrentVersionNumber` database
// without failing.
const int SharedStorageDatabase::kCompatibleVersionNumber = 6;

// Latest version of the database that cannot be upgraded to
// `kCurrentVersionNumber` without razing the database.
const int SharedStorageDatabase::kDeprecatedVersionNumber = 0;

namespace {

std::string SerializeOrigin(const url::Origin& origin) {
  DCHECK(!origin.opaque());
  return origin.Serialize();
}

std::string SerializeSite(const net::SchemefulSite& site) {
  DCHECK(!site.opaque());
  return site.Serialize();
}

[[nodiscard]] bool InitSchema(sql::Database& db, sql::MetaTable& meta_table) {
  static constexpr char kValuesMappingSql[] =
      "CREATE TABLE IF NOT EXISTS values_mapping("
      "context_origin TEXT NOT NULL,"
      "key BLOB NOT NULL,"
      "value BLOB NOT NULL,"
      "last_used_time INTEGER NOT NULL,"
      "PRIMARY KEY(context_origin,key)) WITHOUT ROWID";
  if (!db.Execute(kValuesMappingSql))
    return false;

  // Note that `num_bytes` tracks the total number of bytes stored in keys and
  // values for `context_origin` in `values_mapping`, including for any expired
  // by not yet purged entries. The `BytesUsed()` method below returns the byte
  // count for only the unexpired entries.
  static constexpr char kPerOriginMappingSql[] =
      "CREATE TABLE IF NOT EXISTS per_origin_mapping("
      "context_origin TEXT NOT NULL PRIMARY KEY,"
      "creation_time INTEGER NOT NULL,"
      "num_bytes INTEGER NOT NULL) WITHOUT ROWID";
  if (!db.Execute(kPerOriginMappingSql))
    return false;

  static constexpr char kBudgetMappingSql[] =
      "CREATE TABLE IF NOT EXISTS budget_mapping("
      "id INTEGER NOT NULL PRIMARY KEY,"
      "context_site TEXT NOT NULL,"
      "time_stamp INTEGER NOT NULL,"
      "bits_debit REAL NOT NULL)";
  if (!db.Execute(kBudgetMappingSql))
    return false;

  if (meta_table.GetVersionNumber() >= 4) {
    static constexpr char kSiteTimeIndexSql[] =
        "CREATE INDEX IF NOT EXISTS budget_mapping_site_time_stamp_idx "
        "ON budget_mapping(context_site,time_stamp)";
    if (!db.Execute(kSiteTimeIndexSql)) {
      return false;
    }
  }

  if (meta_table.GetVersionNumber() >= 2) {
    static constexpr char kValuesLastUsedTimeIndexSql[] =
        "CREATE INDEX IF NOT EXISTS values_mapping_last_used_time_idx "
        "ON values_mapping(last_used_time)";
    if (!db.Execute(kValuesLastUsedTimeIndexSql))
      return false;

    static constexpr char kCreationTimeIndexSql[] =
        "CREATE INDEX IF NOT EXISTS per_origin_mapping_creation_time_idx "
        "ON per_origin_mapping(creation_time)";
    if (!db.Execute(kCreationTimeIndexSql))
      return false;
  }

  return true;
}

void RecordDataDurationHistogram(base::TimeDelta data_duration) {
  constexpr size_t kExclusiveMax = 61;

  base::UmaHistogramExactLinear(
      "Storage.SharedStorage.OnDataClearedForOrigin.DataDurationInDays",
      data_duration.InDays(),
      /*exclusive_max=*/kExclusiveMax);
}

}  // namespace

SharedStorageDatabase::BatchUpdateResult::BatchUpdateResult(
    OperationResult overall_result,
    std::vector<OperationResult> inner_method_results)
    : overall_result(overall_result),
      inner_method_results(std::move(inner_method_results)) {}

SharedStorageDatabase::BatchUpdateResult::~BatchUpdateResult() = default;

SharedStorageDatabase::BatchUpdateResult::BatchUpdateResult(
    BatchUpdateResult&&) = default;

SharedStorageDatabase::BatchUpdateResult&
SharedStorageDatabase::BatchUpdateResult::operator=(BatchUpdateResult&&) =
    default;

SharedStorageDatabase::GetResult::GetResult() = default;

SharedStorageDatabase::GetResult::GetResult(GetResult&&) = default;

SharedStorageDatabase::GetResult::GetResult(OperationResult result)
    : result(result) {}

SharedStorageDatabase::GetResult::GetResult(std::u16string data,
                                            base::Time last_used_time,
                                            OperationResult result)
    : data(std::move(data)), last_used_time(last_used_time), result(result) {}

SharedStorageDatabase::GetResult::~GetResult() = default;

SharedStorageDatabase::GetResult& SharedStorageDatabase::GetResult::operator=(
    GetResult&&) = default;

SharedStorageDatabase::BudgetResult::BudgetResult(BudgetResult&&) = default;

SharedStorageDatabase::BudgetResult::BudgetResult(double bits,
                                                  OperationResult result)
    : bits(bits), result(result) {}

SharedStorageDatabase::BudgetResult::~BudgetResult() = default;

SharedStorageDatabase::BudgetResult&
SharedStorageDatabase::BudgetResult::operator=(BudgetResult&&) = default;

SharedStorageDatabase::TimeResult::TimeResult() = default;

SharedStorageDatabase::TimeResult::TimeResult(TimeResult&&) = default;

SharedStorageDatabase::TimeResult::TimeResult(OperationResult result)
    : result(result) {}

SharedStorageDatabase::TimeResult::~TimeResult() = default;

SharedStorageDatabase::TimeResult& SharedStorageDatabase::TimeResult::operator=(
    TimeResult&&) = default;

SharedStorageDatabase::MetadataResult::MetadataResult() = default;

SharedStorageDatabase::MetadataResult::MetadataResult(MetadataResult&&) =
    default;

SharedStorageDatabase::MetadataResult::~MetadataResult() = default;

SharedStorageDatabase::MetadataResult&
SharedStorageDatabase::MetadataResult::operator=(MetadataResult&&) = default;

SharedStorageDatabase::EntriesResult::EntriesResult() = default;

SharedStorageDatabase::EntriesResult::EntriesResult(EntriesResult&&) = default;

SharedStorageDatabase::EntriesResult::~EntriesResult() = default;

SharedStorageDatabase::EntriesResult&
SharedStorageDatabase::EntriesResult::operator=(EntriesResult&&) = default;

SharedStorageDatabase::SharedStorageDatabase(
    base::FilePath db_path,
    scoped_refptr<storage::SpecialStoragePolicy> special_storage_policy,
    std::unique_ptr<SharedStorageDatabaseOptions> options)
    : db_(sql::DatabaseOptions()
              .set_preload(true)
              .set_wal_mode(base::FeatureList::IsEnabled(
                  blink::features::kSharedStorageAPIEnableWALForDatabase))
              // Prevent SQLite from trying to use mmap, as SandboxedVfs does
              // not currently support this.
              .set_mmap_enabled(false)
              // We DCHECK that the page size is valid in the constructor for
              // `SharedStorageOptions`.
              .set_page_size(options->max_page_size)
              .set_cache_size(options->max_cache_size),
          /*tag=*/"SharedStorage"),
      db_path_(std::move(db_path)),
      special_storage_policy_(std::move(special_storage_policy)),
      // We DCHECK that these `options` fields are all positive in the
      // constructor for `SharedStorageOptions`.
      max_bytes_per_origin_(int64_t{options->max_bytes_per_origin}),
      max_string_length_(
          static_cast<size_t>(options->max_bytes_per_origin / 2)),
      max_init_tries_(static_cast<size_t>(options->max_init_tries)),
      max_iterator_batch_size_(
          static_cast<size_t>(options->max_iterator_batch_size)),
      bit_budget_(static_cast<double>(options->bit_budget)),
      budget_interval_(options->budget_interval),
      staleness_threshold_(options->staleness_threshold),
      clock_(base::DefaultClock::GetInstance()) {
  DCHECK(!is_filebacked() || db_path_.IsAbsolute());
  db_file_status_ = is_filebacked() ? DBFileStatus::kNotChecked
                                    : DBFileStatus::kNoPreexistingFile;
}

SharedStorageDatabase::~SharedStorageDatabase() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}

bool SharedStorageDatabase::Destroy() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (db_.is_open() && !db_.RazeAndPoison()) {
    return false;
  }

  // The file already doesn't exist.
  if (!is_filebacked())
    return true;

  return sql::Database::Delete(db_path_);
}

void SharedStorageDatabase::TrimMemory() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  db_.TrimMemory();
}

SharedStorageDatabase::GetResult SharedStorageDatabase::Get(
    const url::Origin& context_origin,
    std::u16string_view key) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK_LE(key.size(), max_string_length_);

  if (LazyInit(DBCreationPolicy::kIgnoreIfAbsent) != InitStatus::kSuccess) {
    // We do not return `OperationResult::kInitFailure` if the database doesn't
    // exist, but only if it pre-exists on disk and yet fails to initialize.
    if (db_status_ == InitStatus::kUnattempted)
      return GetResult(OperationResult::kNotFound);
    return GetResult(OperationResult::kInitFailure);
  }

  // In theory, there ought to be at most one entry found. But we make no
  // assumption about the state of the disk. In the rare case that multiple
  // entries are found, we return only the value from the first entry found.
  static constexpr char kSelectSql[] =
      "SELECT value,last_used_time FROM values_mapping "
      "WHERE context_origin=? AND key=? "
      "LIMIT 1";

  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE, kSelectSql));
  std::string origin_str(SerializeOrigin(context_origin));
  statement.BindString(0, origin_str);
  statement.BindBlob(1, std::u16string(key));

  if (statement.Step()) {
    base::Time last_used_time = statement.ColumnTime(1);
    OperationResult op_result =
        (last_used_time >= clock_->Now() - staleness_threshold_)
            ? OperationResult::kSuccess
            : OperationResult::kExpired;
    std::u16string value;
    if (!statement.ColumnBlobAsString16(0, &value)) {
      return GetResult();
    }
    return GetResult(std::move(value), last_used_time, op_result);
  }

  if (!statement.Succeeded())
    return GetResult();

  return GetResult(OperationResult::kNotFound);
}

SharedStorageDatabase::OperationResult SharedStorageDatabase::Set(
    const url::Origin& context_origin,
    std::u16string_view key,
    std::u16string_view value,
    SetBehavior behavior) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(!key.empty());
  DCHECK_LE(key.size(), max_string_length_);
  DCHECK_LE(value.size(), max_string_length_);

  if (LazyInit(DBCreationPolicy::kCreateIfAbsent) != InitStatus::kSuccess)
    return OperationResult::kInitFailure;

  GetResult get_result = Get(context_origin, key);
  if (get_result.result != OperationResult::kSuccess &&
      get_result.result != OperationResult::kNotFound &&
      get_result.result != OperationResult::kExpired) {
    return OperationResult::kSqlError;
  }

  std::string origin_str(SerializeOrigin(context_origin));
  if (get_result.result == OperationResult::kSuccess &&
      behavior == SharedStorageDatabase::SetBehavior::kIgnoreIfPresent) {
    // We re-insert the old key-value pair with an updated `last_used_time`.
    if (!UpdateValuesMapping(origin_str, key, get_result.data,
                             /*previous_value=*/get_result.data)) {
      return OperationResult::kSqlError;
    }
    return OperationResult::kIgnored;
  }

  auto previous_value =
      (get_result.result == OperationResult::kNotFound)
          ? base::optional_ref<const std::u16string>()
          : base::optional_ref<const std::u16string>(get_result.data);

  return InternalSetOrAppend(origin_str, key, value, get_result.result,
                             previous_value);
}

SharedStorageDatabase::OperationResult SharedStorageDatabase::Append(
    const url::Origin& context_origin,
    std::u16string_view key,
    std::u16string_view tail_value) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(!key.empty());
  DCHECK_LE(key.size(), max_string_length_);
  DCHECK_LE(tail_value.size(), max_string_length_);

  if (LazyInit(DBCreationPolicy::kCreateIfAbsent) != InitStatus::kSuccess)
    return OperationResult::kInitFailure;

  GetResult get_result = Get(context_origin, key);
  if (get_result.result != OperationResult::kSuccess &&
      get_result.result != OperationResult::kNotFound &&
      get_result.result != OperationResult::kExpired) {
    return OperationResult::kSqlError;
  }

  std::string origin_str(SerializeOrigin(context_origin));

  if (get_result.result == OperationResult::kSuccess) {
    if (size_t new_size;
        !base::CheckAdd(get_result.data.size(), tail_value.size())
             .AssignIfValid(&new_size) ||
        new_size > max_string_length_) {
      return OperationResult::kInvalidAppend;
    }

    std::u16string new_value = base::StrCat({get_result.data, tail_value});

    return InternalSetOrAppend(origin_str, key, new_value, get_result.result,
                               /*previous_value=*/get_result.data);
  } else if (get_result.result == OperationResult::kExpired) {
    return InternalSetOrAppend(origin_str, key, tail_value, get_result.result,
                               /*previous_value=*/get_result.data);
  } else {
    return InternalSetOrAppend(origin_str, key, tail_value, get_result.result,
                               /*previous_value=*/std::nullopt);
  }
}

SharedStorageDatabase::OperationResult SharedStorageDatabase::Delete(
    const url::Origin& context_origin,
    std::u16string_view key) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK_LE(key.size(), max_string_length_);

  if (LazyInit(DBCreationPolicy::kIgnoreIfAbsent) != InitStatus::kSuccess) {
    // We do not return an error if the database doesn't exist, but only if it
    // pre-exists on disk and yet fails to initialize.
    if (db_status_ == InitStatus::kUnattempted)
      return OperationResult::kSuccess;
    else
      return OperationResult::kInitFailure;
  }

  std::string origin_str(SerializeOrigin(context_origin));
  std::optional<std::u16string> current_value =
      MaybeGetValueFor(origin_str, key);
  if (!current_value) {
    return OperationResult::kSuccess;
  }

  sql::Transaction transaction(&db_);
  if (!transaction.Begin())
    return OperationResult::kSqlError;

  static constexpr char kDeleteSql[] =
      "DELETE FROM values_mapping "
      "WHERE context_origin=? AND key=?";

  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE, kDeleteSql));
  statement.BindString(0, origin_str);
  statement.BindBlob(1, std::u16string(key));

  if (!statement.Run())
    return OperationResult::kSqlError;

  int64_t delta_bytes = -2 * (static_cast<int64_t>(key.size()) +
                              static_cast<int64_t>(current_value->size()));
  if (!UpdateBytes(origin_str,
                   /*delta_bytes=*/delta_bytes)) {
    return OperationResult::kSqlError;
  }

  if (!transaction.Commit())
    return OperationResult::kSqlError;
  return OperationResult::kSuccess;
}

SharedStorageDatabase::OperationResult SharedStorageDatabase::Clear(
    const url::Origin& context_origin,
    DataClearSource source) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (LazyInit(DBCreationPolicy::kIgnoreIfAbsent) != InitStatus::kSuccess) {
    // We do not return an error if the database doesn't exist, but only if it
    // pre-exists on disk and yet fails to initialize.
    if (db_status_ == InitStatus::kUnattempted)
      return OperationResult::kSuccess;
    else
      return OperationResult::kInitFailure;
  }

  if (!Purge(SerializeOrigin(context_origin), source)) {
    return OperationResult::kSqlError;
  }
  return OperationResult::kSuccess;
}

SharedStorageDatabase::BatchUpdateResult SharedStorageDatabase::BatchUpdate(
    const url::Origin& context_origin,
    const std::vector<
        network::mojom::SharedStorageModifierMethodWithOptionsPtr>&
        methods_with_options) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (LazyInit(DBCreationPolicy::kCreateIfAbsent) != InitStatus::kSuccess) {
    return BatchUpdateResult(/*overall_result=*/OperationResult::kInitFailure,
                             /*inner_method_results=*/{});
  }

  sql::Transaction transaction(&db_);
  if (!transaction.Begin()) {
    return BatchUpdateResult(/*overall_result=*/OperationResult::kSqlError,
                             /*inner_method_results=*/{});
  }

  std::vector<OperationResult> results;

  bool inner_method_failed = false;

  for (auto& method_with_options : methods_with_options) {
    network::mojom::SharedStorageModifierMethodPtr& method =
        method_with_options->method;

    switch (method->which()) {
      case network::mojom::SharedStorageModifierMethod::Tag::kSetMethod: {
        network::mojom::SharedStorageSetMethodPtr& set_method =
            method->get_set_method();

        SetBehavior set_behavior = set_method->ignore_if_present
                                       ? SetBehavior::kIgnoreIfPresent
                                       : SetBehavior::kDefault;

        OperationResult result = Set(context_origin, set_method->key,
                                     set_method->value, set_behavior);
        results.push_back(result);

        if (result != OperationResult::kSet &&
            result != OperationResult::kIgnored) {
          inner_method_failed = true;
        }
        break;
      }
      case network::mojom::SharedStorageModifierMethod::Tag::kAppendMethod: {
        network::mojom::SharedStorageAppendMethodPtr& append_method =
            method->get_append_method();

        OperationResult result =
            Append(context_origin, append_method->key, append_method->value);
        results.push_back(result);

        if (result != OperationResult::kSet) {
          inner_method_failed = true;
        }
        break;
      }
      case network::mojom::SharedStorageModifierMethod::Tag::kDeleteMethod: {
        network::mojom::SharedStorageDeleteMethodPtr& delete_method =
            method->get_delete_method();

        OperationResult result = Delete(context_origin, delete_method->key);
        results.push_back(result);

        if (result != OperationResult::kSuccess) {
          inner_method_failed = true;
        }
        break;
      }
      case network::mojom::SharedStorageModifierMethod::Tag::kClearMethod: {
        OperationResult result = Clear(context_origin);
        results.push_back(result);

        if (result != OperationResult::kSuccess) {
          inner_method_failed = true;
        }
        break;
      }
    }

    if (inner_method_failed) {
      break;
    }
  }

  if (inner_method_failed) {
    CHECK(!results.empty());

    OperationResult last_method_result = results.back();
    CHECK_NE(last_method_result, OperationResult::kSuccess);

    return BatchUpdateResult(/*overall_result=*/last_method_result,
                             /*inner_method_results=*/std::move(results));
  }

  CHECK_EQ(results.size(), methods_with_options.size());

  if (!transaction.Commit()) {
    return BatchUpdateResult(/*overall_result=*/OperationResult::kSqlError,
                             /*inner_method_results=*/std::move(results));
  }

  return BatchUpdateResult(/*overall_result=*/OperationResult::kSuccess,
                           /*inner_method_results=*/std::move(results));
}

int64_t SharedStorageDatabase::Length(const url::Origin& context_origin) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (LazyInit(DBCreationPolicy::kIgnoreIfAbsent) != InitStatus::kSuccess) {
    // We do not return -1 (to signifiy an error) if the database doesn't exist,
    // but only if it pre-exists on disk and yet fails to initialize.
    if (db_status_ == InitStatus::kUnattempted)
      return 0L;
    else
      return -1;
  }

  return NumEntriesManualCountExcludeExpired(SerializeOrigin(context_origin));
}

SharedStorageDatabase::OperationResult SharedStorageDatabase::Keys(
    const url::Origin& context_origin,
    mojo::PendingRemote<blink::mojom::SharedStorageEntriesListener>
        pending_listener) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  mojo::Remote<blink::mojom::SharedStorageEntriesListener> keys_listener(
      std::move(pending_listener));

  if (LazyInit(DBCreationPolicy::kIgnoreIfAbsent) != InitStatus::kSuccess) {
    // We do not return an error if the database doesn't exist, but only if it
    // pre-exists on disk and yet fails to initialize.
    if (db_status_ == InitStatus::kUnattempted) {
      keys_listener->DidReadEntries(
          /*success=*/true,
          /*error_message=*/"", /*entries=*/{}, /*has_more_entries=*/false,
          /*total_queued_to_send=*/0);
      return OperationResult::kSuccess;
    } else {
      keys_listener->DidReadEntries(
          /*success=*/false, "SQL database had initialization failure.",
          /*entries=*/{}, /*has_more_entries=*/false,
          /*total_queued_to_send=*/0);
      return OperationResult::kInitFailure;
    }
  }

  std::string origin_str(SerializeOrigin(context_origin));
  int64_t key_count = NumEntriesManualCountExcludeExpired(origin_str);

  if (key_count == -1) {
    keys_listener->DidReadEntries(
        /*success=*/false, "SQL database could not retrieve key count.",
        /*entries=*/{}, /*has_more_entries=*/false, /*total_queued_to_send=*/0);
    return OperationResult::kSqlError;
  }

  if (key_count > INT_MAX) {
    keys_listener->DidReadEntries(
        /*success=*/false, "Unexpectedly found more than INT_MAX keys.",
        /*entries=*/{}, /*has_more_entries=*/false, /*total_queued_to_send=*/0);
    return OperationResult::kTooManyFound;
  }

  if (!key_count) {
    keys_listener->DidReadEntries(
        /*success=*/true,
        /*error_message=*/"", /*entries=*/{}, /*has_more_entries=*/false,
        /*total_queued_to_send=*/0);
    return OperationResult::kSuccess;
  }

  static constexpr char kSelectSql[] =
      "SELECT key FROM values_mapping "
      "WHERE context_origin=? AND last_used_time>=? "
      "ORDER BY key";

  sql::Statement select_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kSelectSql));
  select_statement.BindString(0, origin_str);
  select_statement.BindTime(1, clock_->Now() - staleness_threshold_);

  bool has_more_entries = true;
  std::optional<std::u16string> saved_first_key_for_next_batch;

  while (has_more_entries) {
    has_more_entries = false;
    std::vector<blink::mojom::SharedStorageKeyAndOrValuePtr> keys;

    if (saved_first_key_for_next_batch) {
      keys.push_back(blink::mojom::SharedStorageKeyAndOrValue::New(
          saved_first_key_for_next_batch.value(), u""));
      saved_first_key_for_next_batch.reset();
    }

    bool blob_retrieval_error = false;
    while (select_statement.Step()) {
      std::u16string key;
      if (!select_statement.ColumnBlobAsString16(0, &key)) {
        blob_retrieval_error = true;
        break;
      }
      if (keys.size() < max_iterator_batch_size_) {
        keys.push_back(
            blink::mojom::SharedStorageKeyAndOrValue::New(std::move(key), u""));
      } else {
        // Cache the current key to use as the start of the next batch, as we're
        // already passing through this step and the next iteration of
        // `statement.Step()`, if there is one, during the next iteration of the
        // outer while loop, will give us the subsequent key.
        saved_first_key_for_next_batch = std::move(key);
        has_more_entries = true;
        break;
      }
    }

    if (!select_statement.Succeeded() || blob_retrieval_error) {
      keys_listener->DidReadEntries(
          /*success=*/false,
          "SQL database encountered an error while retrieving keys.",
          /*entries=*/{}, /*has_more_entries=*/false,
          static_cast<int>(key_count));
      return OperationResult::kSqlError;
    }

    keys_listener->DidReadEntries(/*success=*/true, /*error_message=*/"",
                                  std::move(keys), has_more_entries,
                                  static_cast<int>(key_count));
  }

  return OperationResult::kSuccess;
}

SharedStorageDatabase::OperationResult SharedStorageDatabase::Entries(
    const url::Origin& context_origin,
    mojo::PendingRemote<blink::mojom::SharedStorageEntriesListener>
        pending_listener) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  mojo::Remote<blink::mojom::SharedStorageEntriesListener> entries_listener(
      std::move(pending_listener));

  if (LazyInit(DBCreationPolicy::kIgnoreIfAbsent) != InitStatus::kSuccess) {
    // We do not return an error if the database doesn't exist, but only if it
    // pre-exists on disk and yet fails to initialize.
    if (db_status_ == InitStatus::kUnattempted) {
      entries_listener->DidReadEntries(
          /*success=*/true,
          /*error_message=*/"", /*entries=*/{}, /*has_more_entries=*/false,
          /*total_queued_to_send=*/0);
      return OperationResult::kSuccess;
    } else {
      entries_listener->DidReadEntries(
          /*success=*/false, "SQL database had initialization failure.",
          /*entries=*/{}, /*has_more_entries=*/false,
          /*total_queued_to_send=*/0);
      return OperationResult::kInitFailure;
    }
  }

  std::string origin_str(SerializeOrigin(context_origin));
  int64_t entry_count = NumEntriesManualCountExcludeExpired(origin_str);

  if (entry_count == -1) {
    entries_listener->DidReadEntries(
        /*success=*/false, "SQL database could not retrieve entry count.",
        /*entries=*/{}, /*has_more_entries=*/false, /*total_queued_to_send=*/0);
    return OperationResult::kSqlError;
  }

  if (entry_count > INT_MAX) {
    entries_listener->DidReadEntries(
        /*success=*/false, "Unexpectedly found more than INT_MAX entries.",
        /*entries=*/{}, /*has_more_entries=*/false, /*total_queued_to_send=*/0);
    return OperationResult::kTooManyFound;
  }

  if (!entry_count) {
    entries_listener->DidReadEntries(
        /*success=*/true,
        /*error_message=*/"", /*entries=*/{}, /*has_more_entries=*/false,
        /*total_queued_to_send=*/0);
    return OperationResult::kSuccess;
  }

  static constexpr char kSelectSql[] =
      "SELECT key,value FROM values_mapping "
      "WHERE context_origin=? AND last_used_time>=? "
      "ORDER BY key";

  sql::Statement select_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kSelectSql));
  select_statement.BindString(0, origin_str);
  select_statement.BindTime(1, clock_->Now() - staleness_threshold_);

  bool has_more_entries = true;
  std::optional<std::u16string> saved_first_key_for_next_batch;
  std::optional<std::u16string> saved_first_value_for_next_batch;

  while (has_more_entries) {
    has_more_entries = false;
    std::vector<blink::mojom::SharedStorageKeyAndOrValuePtr> entries;

    if (saved_first_key_for_next_batch) {
      DCHECK(saved_first_value_for_next_batch);
      entries.push_back(blink::mojom::SharedStorageKeyAndOrValue::New(
          saved_first_key_for_next_batch.value(),
          saved_first_value_for_next_batch.value()));
      saved_first_key_for_next_batch.reset();
      saved_first_value_for_next_batch.reset();
    }

    bool blob_retrieval_error = false;
    while (select_statement.Step()) {
      std::u16string key;
      if (!select_statement.ColumnBlobAsString16(0, &key)) {
        blob_retrieval_error = true;
        break;
      }
      std::u16string value;
      if (!select_statement.ColumnBlobAsString16(1, &value)) {
        blob_retrieval_error = true;
        break;
      }
      if (entries.size() < max_iterator_batch_size_) {
        entries.push_back(blink::mojom::SharedStorageKeyAndOrValue::New(
            std::move(key), std::move(value)));
      } else {
        // Cache the current key and value to use as the start of the next
        // batch, as we're already passing through this step and the next
        // iteration of `statement.Step()`, if there is one, during the next
        // iteration of the outer while loop, will give us the subsequent
        // key-value pair.
        saved_first_key_for_next_batch = std::move(key);
        saved_first_value_for_next_batch = std::move(value);
        has_more_entries = true;
        break;
      }
    }

    if (!select_statement.Succeeded() || blob_retrieval_error) {
      entries_listener->DidReadEntries(
          /*success=*/false,
          "SQL database encountered an error while retrieving entries.",
          /*entries=*/{}, /*has_more_entries=*/false,
          static_cast<int>(entry_count));
      return OperationResult::kSqlError;
    }

    entries_listener->DidReadEntries(/*success=*/true, /*error_message=*/"",
                                     std::move(entries), has_more_entries,
                                     static_cast<int>(entry_count));
  }

  return OperationResult::kSuccess;
}

int64_t SharedStorageDatabase::BytesUsed(const url::Origin& context_origin) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (LazyInit(DBCreationPolicy::kIgnoreIfAbsent) != InitStatus::kSuccess) {
    // We do not return -1 (to signifiy an error) if the database doesn't exist,
    // but only if it pre-exists on disk and yet fails to initialize.
    if (db_status_ == InitStatus::kUnattempted) {
      return 0L;
    } else {
      return -1;
    }
  }

  return NumBytesUsedManualCountExcludeExpired(SerializeOrigin(context_origin));
}

SharedStorageDatabase::OperationResult
SharedStorageDatabase::PurgeMatchingOrigins(
    StorageKeyPolicyMatcherFunction storage_key_matcher,
    base::Time begin,
    base::Time end,
    bool perform_storage_cleanup) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK_LE(begin, end);

  if (LazyInit(DBCreationPolicy::kIgnoreIfAbsent) != InitStatus::kSuccess) {
    // We do not return an error if the database doesn't exist, but only if it
    // pre-exists on disk and yet fails to initialize.
    if (db_status_ == InitStatus::kUnattempted)
      return OperationResult::kSuccess;
    else
      return OperationResult::kInitFailure;
  }

  static constexpr char kSelectSql[] =
      "SELECT distinct context_origin FROM values_mapping "
      "WHERE last_used_time BETWEEN ? AND ?";
  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE, kSelectSql));
  statement.BindTime(0, begin);
  statement.BindTime(1, end);

  std::vector<std::string> origins;

  while (statement.Step()) {
    origins.push_back(statement.ColumnString(0));
  }

  if (!statement.Succeeded())
    return OperationResult::kSqlError;

  if (origins.empty())
    return OperationResult::kSuccess;

  sql::Transaction transaction(&db_);
  if (!transaction.Begin())
    return OperationResult::kSqlError;

  for (const auto& origin : origins) {
    if (storage_key_matcher &&
        !storage_key_matcher.Run(blink::StorageKey::CreateFirstParty(
                                     url::Origin::Create(GURL(origin))),
                                 special_storage_policy_.get())) {
      continue;
    }

    if (!Purge(origin, DataClearSource::kUI)) {
      return OperationResult::kSqlError;
    }
  }

  if (!transaction.Commit())
    return OperationResult::kSqlError;

  if (perform_storage_cleanup && !Vacuum())
    return OperationResult::kSqlError;

  return OperationResult::kSuccess;
}

SharedStorageDatabase::OperationResult SharedStorageDatabase::PurgeStale() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK_GT(staleness_threshold_, base::TimeDelta());

  if (LazyInit(DBCreationPolicy::kIgnoreIfAbsent) != InitStatus::kSuccess) {
    // We do not return an error if the database doesn't exist, but only if it
    // pre-exists on disk and yet fails to initialize.
    if (db_status_ == InitStatus::kUnattempted)
      return OperationResult::kSuccess;
    else
      return OperationResult::kInitFailure;
  }

  sql::Transaction transaction(&db_);
  if (!transaction.Begin())
    return OperationResult::kSqlError;

  static constexpr char kUpdateNumBytesSql[] =
      "UPDATE per_origin_mapping "
      "SET num_bytes = num_bytes - expired.total_bytes "
      "FROM "
      "  (SELECT context_origin, "
      "  SUM(LENGTH(key) + LENGTH(value)) as total_bytes "
      "  FROM values_mapping WHERE last_used_time<? "
      "  GROUP BY context_origin) "
      "AS expired "
      "WHERE per_origin_mapping.context_origin = expired.context_origin";

  sql::Statement update_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kUpdateNumBytesSql));
  base::Time cutoff_time = clock_->Now() - staleness_threshold_;
  update_statement.BindTime(0, cutoff_time);

  if (!update_statement.Run()) {
    return OperationResult::kSqlError;
  }

  static constexpr char kDeleteEntriesSql[] =
      "DELETE FROM values_mapping WHERE last_used_time<?";
  sql::Statement entries_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kDeleteEntriesSql));
  entries_statement.BindTime(0, cutoff_time);

  // Delete expired entries.
  if (!entries_statement.Run())
    return OperationResult::kSqlError;

  static constexpr char kGetCreationTimeSql[] =
      "SELECT creation_time "
      "FROM per_origin_mapping "
      "WHERE num_bytes<=0";

  sql::Statement creation_time_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kGetCreationTimeSql));

  base::Time now = clock_->Now();

  while (creation_time_statement.Step()) {
    base::Time creation_time = creation_time_statement.ColumnTime(0);
    base::TimeDelta data_duration = now - creation_time;
    RecordDataDurationHistogram(data_duration);
  }

  if (!creation_time_statement.Succeeded()) {
    return OperationResult::kSqlError;
  }

  static constexpr char kDeleteOriginsSql[] =
      "DELETE FROM per_origin_mapping WHERE num_bytes<=0";
  sql::Statement origins_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kDeleteOriginsSql));

  // Delete empty origins.
  if (!origins_statement.Run()) {
    return OperationResult::kSqlError;
  }

  static constexpr char kDeleteWithdrawalsSql[] =
      "DELETE FROM budget_mapping WHERE time_stamp<?";

  sql::Statement withdrawals_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kDeleteWithdrawalsSql));
  withdrawals_statement.BindTime(0, clock_->Now() - budget_interval_);

  // Remove stale budget withdrawals.
  if (!withdrawals_statement.Run())
    return OperationResult::kSqlError;

  if (!transaction.Commit())
    return OperationResult::kSqlError;
  return OperationResult::kSuccess;
}

std::vector<mojom::StorageUsageInfoPtr> SharedStorageDatabase::FetchOrigins() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (LazyInit(DBCreationPolicy::kIgnoreIfAbsent) != InitStatus::kSuccess)
    return {};

  static constexpr char kSelectSql[] =
      "SELECT context_origin,creation_time,num_bytes "
      "FROM per_origin_mapping "
      "ORDER BY context_origin";

  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE, kSelectSql));
  std::vector<mojom::StorageUsageInfoPtr> fetched_origin_infos;

  while (statement.Step()) {
    fetched_origin_infos.emplace_back(mojom::StorageUsageInfo::New(
        blink::StorageKey::CreateFirstParty(
            url::Origin::Create(GURL(statement.ColumnStringView(0)))),
        statement.ColumnInt64(2), statement.ColumnTime(1)));
  }

  if (!statement.Succeeded())
    return {};

  return fetched_origin_infos;
}

SharedStorageDatabase::OperationResult
SharedStorageDatabase::MakeBudgetWithdrawal(
    const net::SchemefulSite& context_site,
    double bits_debit) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK_GT(bits_debit, 0.0);

  if (LazyInit(DBCreationPolicy::kCreateIfAbsent) != InitStatus::kSuccess)
    return OperationResult::kInitFailure;

  static constexpr char kInsertSql[] =
      "INSERT INTO budget_mapping(context_site,time_stamp,bits_debit)"
      "VALUES(?,?,?)";

  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE, kInsertSql));
  statement.BindString(0, SerializeSite(context_site));
  statement.BindTime(1, clock_->Now());
  statement.BindDouble(2, bits_debit);

  if (!statement.Run())
    return OperationResult::kSqlError;
  return OperationResult::kSuccess;
}

SharedStorageDatabase::BudgetResult SharedStorageDatabase::GetRemainingBudget(
    const net::SchemefulSite& context_site) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (LazyInit(DBCreationPolicy::kIgnoreIfAbsent) != InitStatus::kSuccess) {
    // We do not return an error if the database doesn't exist, but only if it
    // pre-exists on disk and yet fails to initialize.
    if (db_status_ == InitStatus::kUnattempted)
      return BudgetResult(bit_budget_, OperationResult::kSuccess);
    else
      return BudgetResult(0.0, OperationResult::kInitFailure);
  }

  static constexpr char kSelectSql[] =
      "SELECT SUM(bits_debit) FROM budget_mapping "
      "WHERE context_site=? AND time_stamp>=?";

  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE, kSelectSql));
  statement.BindString(0, SerializeSite(context_site));
  statement.BindTime(1, clock_->Now() - budget_interval_);

  double total_debits = 0.0;
  if (statement.Step())
    total_debits = statement.ColumnDouble(0);

  if (!statement.Succeeded())
    return BudgetResult(0.0, OperationResult::kSqlError);

  return BudgetResult(bit_budget_ - total_debits, OperationResult::kSuccess);
}

SharedStorageDatabase::TimeResult SharedStorageDatabase::GetCreationTime(
    const url::Origin& context_origin) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (LazyInit(DBCreationPolicy::kIgnoreIfAbsent) != InitStatus::kSuccess) {
    // We do not return an error if the database doesn't exist, but only if it
    // pre-exists on disk and yet fails to initialize.
    if (db_status_ == InitStatus::kUnattempted)
      return TimeResult(OperationResult::kNotFound);
    else
      return TimeResult(OperationResult::kInitFailure);
  }

  TimeResult result;
  int64_t num_bytes = 0L;
  result.result =
      GetOriginInfo(SerializeOrigin(context_origin), &num_bytes, &result.time);

  return result;
}

SharedStorageDatabase::MetadataResult SharedStorageDatabase::GetMetadata(
    const url::Origin& context_origin) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  MetadataResult metadata;

  metadata.length = Length(context_origin);

  metadata.bytes_used = BytesUsed(context_origin);

  TimeResult time_result = GetCreationTime(context_origin);
  metadata.time_result = time_result.result;
  if (time_result.result == OperationResult::kSuccess)
    metadata.creation_time = time_result.time;

  BudgetResult budget_result =
      GetRemainingBudget(net::SchemefulSite(context_origin));
  metadata.budget_result = budget_result.result;
  if (budget_result.result == OperationResult::kSuccess)
    metadata.remaining_budget = budget_result.bits;

  return metadata;
}

SharedStorageDatabase::EntriesResult
SharedStorageDatabase::GetEntriesForDevTools(
    const url::Origin& context_origin) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  EntriesResult entries;

  if (LazyInit(DBCreationPolicy::kIgnoreIfAbsent) != InitStatus::kSuccess) {
    // We do not return an error if the database doesn't exist, but only if it
    // pre-exists on disk and yet fails to initialize.
    if (db_status_ == InitStatus::kUnattempted) {
      entries.result = OperationResult::kSuccess;
      return entries;
    } else {
      entries.result = OperationResult::kInitFailure;
      return entries;
    }
  }

  static constexpr char kSelectSql[] =
      "SELECT key,value FROM values_mapping "
      "WHERE context_origin=? AND last_used_time>=? "
      "ORDER BY key";

  sql::Statement select_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kSelectSql));
  std::string origin_str(SerializeOrigin(context_origin));
  select_statement.BindString(0, origin_str);
  select_statement.BindTime(1, clock_->Now() - staleness_threshold_);

  while (select_statement.Step()) {
    std::u16string key;
    if (!select_statement.ColumnBlobAsString16(0, &key)) {
      key = u"[[DATABASE_ERROR: unable to retrieve key]]";
    }
    std::u16string value;
    if (!select_statement.ColumnBlobAsString16(1, &value)) {
      value = u"[[DATABASE_ERROR: unable to retrieve value]]";
    }
    entries.entries.emplace_back(base::UTF16ToUTF8(key),
                                 base::UTF16ToUTF8(value));
  }

  if (!select_statement.Succeeded())
    return entries;

  entries.result = OperationResult::kSuccess;
  return entries;
}

SharedStorageDatabase::OperationResult
SharedStorageDatabase::ResetBudgetForDevTools(
    const url::Origin& context_origin) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (LazyInit(DBCreationPolicy::kIgnoreIfAbsent) != InitStatus::kSuccess) {
    // We do not return an error if the database doesn't exist, but only if it
    // pre-exists on disk and yet fails to initialize.
    if (db_status_ == InitStatus::kUnattempted) {
      return OperationResult::kSuccess;
    } else {
      return OperationResult::kInitFailure;
    }
  }

  static constexpr char kDeleteSql[] =
      "DELETE FROM budget_mapping WHERE context_site=?";

  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE, kDeleteSql));
  statement.BindString(0, SerializeSite(net::SchemefulSite(context_origin)));

  if (!statement.Run()) {
    return OperationResult::kSqlError;
  }
  return OperationResult::kSuccess;
}

bool SharedStorageDatabase::IsOpenForTesting() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return db_.is_open();
}

SharedStorageDatabase::InitStatus SharedStorageDatabase::DBStatusForTesting()
    const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return db_status_;
}

bool SharedStorageDatabase::OverrideCreationTimeForTesting(
    const url::Origin& context_origin,
    base::Time new_creation_time) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (LazyInit(DBCreationPolicy::kIgnoreIfAbsent) != InitStatus::kSuccess)
    return false;

  std::string origin_str = SerializeOrigin(context_origin);
  int64_t num_bytes = 0L;
  base::Time old_creation_time;
  OperationResult result =
      GetOriginInfo(origin_str, &num_bytes, &old_creation_time);

  if (result != OperationResult::kSuccess &&
      result != OperationResult::kNotFound) {
    return false;
  }

  // Don't override time for non-existent origin.
  if (result == OperationResult::kNotFound)
    return true;

  return UpdatePerOriginMapping(origin_str, new_creation_time, num_bytes,
                                /*origin_exists=*/true);
}

bool SharedStorageDatabase::OverrideLastUsedTimeForTesting(
    const url::Origin& context_origin,
    std::u16string_view key,
    base::Time new_last_used_time) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (LazyInit(DBCreationPolicy::kIgnoreIfAbsent) != InitStatus::kSuccess)
    return false;

  GetResult result = Get(context_origin, key);
  if (result.result != OperationResult::kSuccess &&
      result.result != OperationResult::kNotFound) {
    return false;
  }

  // Don't override time for non-existent key.
  if (result.result == OperationResult::kNotFound)
    return true;

  if (!UpdateValuesMappingWithTime(SerializeOrigin(context_origin), key,
                                   result.data, new_last_used_time,
                                   /*previous_value=*/result.data)) {
    return false;
  }
  return true;
}

void SharedStorageDatabase::OverrideClockForTesting(base::Clock* clock) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(clock);
  clock_ = clock;
}

void SharedStorageDatabase::OverrideSpecialStoragePolicyForTesting(
    scoped_refptr<storage::SpecialStoragePolicy> special_storage_policy) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  special_storage_policy_ = std::move(special_storage_policy);
}

int64_t SharedStorageDatabase::GetNumBudgetEntriesForTesting(
    const net::SchemefulSite& context_site) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (LazyInit(DBCreationPolicy::kIgnoreIfAbsent) != InitStatus::kSuccess) {
    // We do not return an error if the database doesn't exist, but only if it
    // pre-exists on disk and yet fails to initialize.
    if (db_status_ == InitStatus::kUnattempted)
      return 0;
    else
      return -1;
  }

  static constexpr char kSelectSql[] =
      "SELECT COUNT(*) FROM budget_mapping "
      "WHERE context_site=?";

  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE, kSelectSql));
  statement.BindString(0, SerializeSite(context_site));

  if (statement.Step())
    return statement.ColumnInt64(0);

  return -1;
}

int64_t SharedStorageDatabase::GetTotalNumBudgetEntriesForTesting() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (LazyInit(DBCreationPolicy::kIgnoreIfAbsent) != InitStatus::kSuccess) {
    // We do not return an error if the database doesn't exist, but only if it
    // pre-exists on disk and yet fails to initialize.
    if (db_status_ == InitStatus::kUnattempted)
      return 0;
    else
      return -1;
  }

  static constexpr char kSelectSql[] = "SELECT COUNT(*) FROM budget_mapping";

  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE, kSelectSql));

  if (statement.Step())
    return statement.ColumnInt64(0);

  return -1;
}

int64_t SharedStorageDatabase::NumBytesUsedIncludeExpiredForTesting(
    const url::Origin& context_origin) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (LazyInit(DBCreationPolicy::kIgnoreIfAbsent) != InitStatus::kSuccess) {
    // We do not return an error if the database doesn't exist, but only if it
    // pre-exists on disk and yet fails to initialize.
    if (db_status_ == InitStatus::kUnattempted) {
      return 0;
    } else {
      return -1;
    }
  }

  return NumBytesUsedIncludeExpired(SerializeOrigin(context_origin));
}

SharedStorageDatabase::InitStatus SharedStorageDatabase::LazyInit(
    DBCreationPolicy policy) {
  // Early return in case of previous failure, to prevent an unbounded
  // number of re-attempts.
  if (db_status_ != InitStatus::kUnattempted)
    return db_status_;

  if (policy == DBCreationPolicy::kIgnoreIfAbsent && !DBExists())
    return InitStatus::kUnattempted;

  for (size_t i = 0; i < max_init_tries_; ++i) {
    db_status_ = InitImpl();
    if (db_status_ == InitStatus::kSuccess)
      return db_status_;

    meta_table_.Reset();
    db_.Close();
  }

  return db_status_;
}

bool SharedStorageDatabase::OpenImpl() {
  SCOPED_UMA_HISTOGRAM_TIMER("Storage.SharedStorage.Database.Timing.OpenImpl");
  return db_.Open(db_path_);
}

bool SharedStorageDatabase::DBExists() {
  DCHECK_EQ(InitStatus::kUnattempted, db_status_);

  if (db_file_status_ == DBFileStatus::kNoPreexistingFile)
    return false;

  // The in-memory case is included in `DBFileStatus::kNoPreexistingFile`.
  DCHECK(is_filebacked());

  // We do not expect `DBExists()` to be called in the case where
  // `db_file_status_ == DBFileStatus::kPreexistingFile`, as then
  // `db_status_ != InitStatus::kUnattempted`, which would force an early return
  // in `LazyInit()`.
  DCHECK_EQ(DBFileStatus::kNotChecked, db_file_status_);

  if (!OpenImpl()) {
    db_file_status_ = DBFileStatus::kNoPreexistingFile;
    return false;
  }

  static const char kSelectSql[] =
      "SELECT COUNT(*) FROM sqlite_schema WHERE type=?";
  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE, kSelectSql));
  statement.BindCString(0, "table");

  if (!statement.Step() || statement.ColumnInt(0) == 0) {
    db_file_status_ = DBFileStatus::kNoPreexistingFile;
    return false;
  }

  db_file_status_ = DBFileStatus::kPreexistingFile;
  return true;
}

bool SharedStorageDatabase::OpenDatabase() {
  // If this is not the first call to `OpenDatabase()` because we are re-trying
  // initialization, then the error callback will have previously been set.
  db_.reset_error_callback();

  // base::Unretained is safe here because this SharedStorageDatabase owns
  // the sql::Database instance that stores and uses the callback. So,
  // `this` is guaranteed to outlive the callback.
  db_.set_error_callback(base::BindRepeating(
      &SharedStorageDatabase::DatabaseErrorCallback, base::Unretained(this)));

  if (is_filebacked()) {
    if (!db_.is_open() && !OpenImpl()) {
      return false;
    }
  } else {
    if (!db_.OpenInMemory())
      return false;
  }

  return true;
}

void SharedStorageDatabase::DatabaseErrorCallback(int extended_error,
                                                  sql::Statement* stmt) {
  base::UmaHistogramSparse("Storage.SharedStorage.Database.Error",
                           extended_error);

  if (sql::IsErrorCatastrophic(extended_error)) {
    bool success = Destroy();
    base::UmaHistogramBoolean("Storage.SharedStorage.Database.Destruction",
                              success);
    if (!success) {
      DLOG(FATAL) << "Database destruction failed after catastrophic error:\n"
                  << db_.GetErrorMessage();
    }
  }

  // The default handling is to assert on debug and to ignore on release.
  if (!sql::Database::IsExpectedSqliteError(extended_error))
    DLOG(FATAL) << db_.GetErrorMessage();
}

SharedStorageDatabase::InitStatus SharedStorageDatabase::InitImpl() {
  if (!OpenDatabase())
    return InitStatus::kError;

  // Database should now be open.
  DCHECK(db_.is_open());

  // Scope initialization in a transaction so we can't be partially initialized.
  sql::Transaction transaction(&db_);
  if (!transaction.Begin()) {
    LOG(WARNING) << "Shared storage database begin initialization failed.";
    db_.RazeAndPoison();
    return InitStatus::kError;
  }

  // Create the tables.
  if (!meta_table_.Init(&db_, kCurrentVersionNumber,
                        kCompatibleVersionNumber) ||
      !InitSchema(db_, meta_table_)) {
    return InitStatus::kError;
  }

  if (meta_table_.GetCompatibleVersionNumber() > kCurrentVersionNumber) {
    LOG(WARNING) << "Shared storage database is too new.";
    db_.RazeAndPoison();
    return InitStatus::kTooNew;
  }

  int cur_version = meta_table_.GetVersionNumber();

  if (cur_version <= kDeprecatedVersionNumber) {
    LOG(WARNING) << "Shared storage database is too old to be compatible.";
    db_.RazeAndPoison();
    return InitStatus::kTooOld;
  }

  if (cur_version < kCurrentVersionNumber &&
      !UpgradeSharedStorageDatabaseSchema(db_, meta_table_, clock_)) {
    LOG(WARNING) << "Shared storage database upgrade failed.";
    db_.RazeAndPoison();
    return InitStatus::kUpgradeFailed;
  }

  // The initialization is complete.
  if (!transaction.Commit()) {
    LOG(WARNING) << "Shared storage database initialization commit failed.";
    db_.RazeAndPoison();
    return InitStatus::kError;
  }

  LogInitHistograms();
  return InitStatus::kSuccess;
}

bool SharedStorageDatabase::Vacuum() {
  DCHECK_EQ(InitStatus::kSuccess, db_status_);
  DCHECK_EQ(0, db_.transaction_nesting())
      << "Can not have a transaction when vacuuming.";
  return db_.Execute("VACUUM");
}

bool SharedStorageDatabase::Purge(std::string_view context_origin,
                                  DataClearSource source) {
  sql::Transaction transaction(&db_);
  if (!transaction.Begin()) {
    return false;
  }

  static constexpr char kDeleteSql[] =
      "DELETE FROM values_mapping "
      "WHERE context_origin=?";

  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE, kDeleteSql));
  statement.BindString(0, context_origin);

  if (!statement.Run())
    return false;

  if (!DeleteFromPerOriginMapping(context_origin, source)) {
    return false;
  }

  return transaction.Commit();
}

SharedStorageDatabase::OperationResult
SharedStorageDatabase::InternalSetOrAppend(
    std::string_view context_origin,
    std::u16string_view key,
    std::u16string_view value,
    OperationResult result_for_get,
    base::optional_ref<const std::u16string> previous_value) {
  int64_t delta_bytes = 2 * value.size();
  delta_bytes += (result_for_get == OperationResult::kNotFound)
                     ? 2 * key.size()
                     : -2 * static_cast<int64_t>(previous_value->size());

  if (delta_bytes <= 0 ||
      (delta_bytes > 0 &&
       HasCapacityIncludingExpired(context_origin, delta_bytes))) {
    // Either we are decreasing the total number of bytes used by
    // `context_origin`, or else a quick capacity check based on the value in
    // the `num_bytes` column in `per_origin_mapping` for `context_origin` says
    // that there should be enough quota left for the additional bytes. So we go
    // ahead and try to set the value.
    if (!UpdateValuesMapping(context_origin, key, value, previous_value)) {
      return OperationResult::kSqlError;
    }
    return OperationResult::kSet;
  }

  CHECK_GT(delta_bytes, 0);
  if (NumBytesUsedManualCountExcludeExpired(context_origin) + delta_bytes >
      max_bytes_per_origin_) {
    // There is not enough capacity for this delta even after recounting the
    // bytes used manually and excluding any expired entries.
    return OperationResult::kNoCapacity;
  }

  // In theory there will be enough capacity after we purge expired entries in
  // `values_mapping` for `context_origin`.
  if (!ManualPurgeExpiredValues(context_origin)) {
    return OperationResult::kSqlError;
  }

  if (!UpdateValuesMapping(
          context_origin, key, value,
          // If the previous value was expired, it has now been manually
          // purged. So the `UpdateValuesMapping()` call below should see
          // the previous value as nonexistent, i.e. std::nullopt.
          result_for_get == OperationResult::kExpired
              ? base::optional_ref<const std::u16string>()
              : previous_value)) {
    return OperationResult::kSqlError;
  }

  return OperationResult::kSet;
}

int64_t SharedStorageDatabase::NumEntriesManualCountExcludeExpired(
    std::string_view context_origin) {
  static constexpr char kCountSql[] =
      "SELECT COUNT(*) FROM values_mapping "
      "WHERE context_origin=? AND last_used_time>=?";

  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE, kCountSql));
  statement.BindString(0, context_origin);
  statement.BindTime(1, clock_->Now() - staleness_threshold_);

  int64_t length = 0;
  if (statement.Step())
    length = statement.ColumnInt64(0);

  if (!statement.Succeeded())
    return -1;

  return length;
}

int64_t SharedStorageDatabase::NumBytesUsedIncludeExpired(
    std::string_view context_origin) {
  // In theory, there ought to be at most one entry found. But we make no
  // assumption about the state of the disk. In the rare case that multiple
  // entries are found, we return only the `num_bytes` from the first entry
  // found.
  static constexpr char kSelectSql[] =
      "SELECT num_bytes FROM per_origin_mapping "
      "WHERE context_origin=? "
      "LIMIT 1";

  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE, kSelectSql));
  statement.BindString(0, context_origin);

  int64_t num_bytes = 0;
  if (statement.Step()) {
    num_bytes = statement.ColumnInt64(0);
  }

  if (!statement.Succeeded()) {
    return -1;
  }

  return num_bytes;
}

int64_t SharedStorageDatabase::NumBytesUsedManualCountExcludeExpired(
    std::string_view context_origin) {
  static constexpr char kCountSql[] =
      "SELECT SUM(LENGTH(key) + LENGTH(value)) FROM values_mapping "
      "WHERE context_origin=? AND last_used_time>=?";

  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE, kCountSql));
  statement.BindString(0, context_origin);
  statement.BindTime(1, clock_->Now() - staleness_threshold_);

  int64_t num_bytes = 0;
  if (statement.Step()) {
    num_bytes = statement.ColumnInt64(0);
  }

  if (!statement.Succeeded()) {
    return -1;
  }

  return num_bytes;
}

std::optional<std::u16string> SharedStorageDatabase::MaybeGetValueFor(
    std::string_view context_origin,
    std::u16string_view key) {
  static constexpr char kSelectSql[] =
      "SELECT value FROM values_mapping "
      "WHERE context_origin=? AND key=? "
      "LIMIT 1";

  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE, kSelectSql));
  statement.BindString(0, context_origin);
  statement.BindBlob(1, std::u16string(key));

  std::u16string value;
  if (statement.Step() && statement.ColumnBlobAsString16(0, &value)) {
    return value;
  }
  return std::nullopt;
}

SharedStorageDatabase::OperationResult SharedStorageDatabase::GetOriginInfo(
    std::string_view context_origin,
    int64_t* out_num_bytes,
    base::Time* out_creation_time) {
  DCHECK(out_creation_time);
  DCHECK(out_num_bytes);

  // In theory, there ought to be at most one entry found. But we make no
  // assumption about the state of the disk. In the rare case that multiple
  // entries are found, we retrieve only the `length` and `creation_time`
  // from the first entry found.
  static constexpr char kSelectSql[] =
      "SELECT creation_time,num_bytes FROM per_origin_mapping "
      "WHERE context_origin=? "
      "LIMIT 1";

  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE, kSelectSql));
  statement.BindString(0, context_origin);

  if (statement.Step()) {
    *out_creation_time = statement.ColumnTime(0);
    *out_num_bytes = statement.ColumnInt64(1);
    return OperationResult::kSuccess;
  }

  if (!statement.Succeeded())
    return OperationResult::kSqlError;
  return OperationResult::kNotFound;
}

bool SharedStorageDatabase::UpdateBytes(std::string_view context_origin,
                                        int64_t delta_bytes) {
  // No-op if delta is zero.
  if (delta_bytes == 0L) {
    return true;
  }

  int64_t num_bytes = 0L;
  base::Time creation_time;
  OperationResult result =
      GetOriginInfo(context_origin, &num_bytes, &creation_time);

  if (result != OperationResult::kSuccess &&
      result != OperationResult::kNotFound) {
    return false;
  }

  bool origin_exists = true;
  int64_t new_bytes = num_bytes + delta_bytes;
  if (result == OperationResult::kNotFound) {
    // Don't delete or insert anything from/into `per_origin_mapping` for
    // non-existent origin when we would have decreased its byte count if it
    // existed.
    if (new_bytes < 0L) {
      return true;
    }

    // We are creating `context_origin` now.
    creation_time = clock_->Now();
    origin_exists = false;
  }

  return UpdatePerOriginMapping(context_origin, creation_time, new_bytes,
                                origin_exists);
}

bool SharedStorageDatabase::UpdateValuesMappingWithTime(
    std::string_view context_origin,
    std::u16string_view key,
    std::u16string_view value,
    base::Time last_used_time,
    base::optional_ref<const std::u16string> previous_value) {
  sql::Transaction transaction(&db_);
  if (!transaction.Begin()) {
    return false;
  }

  int64_t delta_bytes = 0L;
  if (previous_value) {
    static constexpr char kUpdateSql[] =
        "UPDATE values_mapping SET value=?, last_used_time=? "
        "WHERE context_origin=? AND key=?";

    sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE, kUpdateSql));
    statement.BindBlob(0, std::u16string(value));
    statement.BindTime(1, last_used_time);
    statement.BindString(2, context_origin);
    statement.BindBlob(3, std::u16string(key));

    if (!statement.Run()) {
      return false;
    }

    delta_bytes = 2 * (static_cast<int64_t>(value.size()) -
                       static_cast<int64_t>(previous_value->size()));
    if (!UpdateBytes(context_origin,
                     /*delta_bytes=*/delta_bytes)) {
      return false;
    }

    return transaction.Commit();
  }

  static constexpr char kInsertSql[] =
      "INSERT INTO values_mapping(context_origin,key,value,last_used_time) "
      "VALUES(?,?,?,?)";

  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE, kInsertSql));
  statement.BindString(0, context_origin);
  statement.BindBlob(1, std::u16string(key));
  statement.BindBlob(2, std::u16string(value));
  statement.BindTime(3, last_used_time);

  if (!statement.Run())
    return false;

  delta_bytes = static_cast<int64_t>(2 * (key.size() + value.size()));
  if (!UpdateBytes(context_origin,
                   /*delta_bytes=*/delta_bytes)) {
    return false;
  }

  return transaction.Commit();
}

bool SharedStorageDatabase::UpdateValuesMapping(
    std::string_view context_origin,
    std::u16string_view key,
    std::u16string_view value,
    base::optional_ref<const std::u16string> previous_value) {
  return UpdateValuesMappingWithTime(context_origin, key, value, clock_->Now(),
                                     previous_value);
}

bool SharedStorageDatabase::DeleteFromPerOriginMapping(
    std::string_view context_origin,
    DataClearSource source) {
  if (source != DataClearSource::kSite) {
    // In theory, there ought to be at most one entry found. But we make no
    // assumption about the state of the disk. In the rare case that multiple
    // entries are found, we return only the value from the first entry found.
    static constexpr char kGetCreationTimeSql[] =
        "SELECT creation_time "
        "FROM per_origin_mapping "
        "WHERE context_origin=? "
        "LIMIT 1";

    sql::Statement statement(
        db_.GetCachedStatement(SQL_FROM_HERE, kGetCreationTimeSql));
    statement.BindString(0, context_origin);

    if (statement.Step()) {
      base::Time creation_time = statement.ColumnTime(0);
      base::TimeDelta data_duration = clock_->Now() - creation_time;
      RecordDataDurationHistogram(data_duration);
    }

    if (!statement.Succeeded()) {
      return false;
    }
  }

  static constexpr char kDeleteSql[] =
      "DELETE FROM per_origin_mapping "
      "WHERE context_origin=?";

  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE, kDeleteSql));
  statement.BindString(0, context_origin);

  return statement.Run();
}

bool SharedStorageDatabase::InsertIntoPerOriginMapping(
    std::string_view context_origin,
    base::Time creation_time,
    uint64_t num_bytes) {
  static constexpr char kInsertSql[] =
      "INSERT INTO per_origin_mapping(context_origin,creation_time,num_bytes) "
      "VALUES(?,?,?)";

  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE, kInsertSql));
  statement.BindString(0, context_origin);
  statement.BindTime(1, creation_time);
  statement.BindInt64(2, static_cast<int64_t>(num_bytes));

  return statement.Run();
}

bool SharedStorageDatabase::UpdatePerOriginMapping(
    std::string_view context_origin,
    base::Time creation_time,
    uint64_t num_bytes,
    bool origin_exists) {
  if (num_bytes && origin_exists) {
    static constexpr char kUpdateSql[] =
        "UPDATE per_origin_mapping SET creation_time=?, num_bytes=? "
        "WHERE context_origin=?";
    sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE, kUpdateSql));
    statement.BindTime(0, creation_time);
    statement.BindInt64(1, static_cast<int64_t>(num_bytes));
    statement.BindString(2, context_origin);

    return statement.Run();
  }
  if (num_bytes) {
    return InsertIntoPerOriginMapping(context_origin, creation_time, num_bytes);
  }
  if (origin_exists) {
    return DeleteFromPerOriginMapping(context_origin, DataClearSource::kSite);
  }

  //  Origin does not exist and we are trying to set the `num_bytes` to 0, so
  //  this is a no-op.
  return true;
}

bool SharedStorageDatabase::HasCapacityIncludingExpired(
    std::string_view context_origin,
    int64_t delta_bytes) {
  CHECK_GT(delta_bytes, 0);

  return NumBytesUsedIncludeExpired(context_origin) + delta_bytes <=
         max_bytes_per_origin_;
}

bool SharedStorageDatabase::ManualPurgeExpiredValues(
    std::string_view context_origin) {
  sql::Transaction transaction(&db_);
  if (!transaction.Begin()) {
    return false;
  }

  static constexpr char kDeleteEntriesSql[] =
      "DELETE FROM values_mapping "
      "WHERE context_origin=? AND last_used_time<?";

  sql::Statement delete_entries_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kDeleteEntriesSql));
  delete_entries_statement.BindString(0, context_origin);
  delete_entries_statement.BindTime(1, clock_->Now() - staleness_threshold_);

  // Delete expired entries.
  if (!delete_entries_statement.Run()) {
    return false;
  }

  // Recalculate the `num_bytes` for `context_origin`.
  static constexpr char kSelectSql[] =
      "SELECT SUM(LENGTH(key) + LENGTH(value)) FROM values_mapping "
      "WHERE context_origin=?";

  sql::Statement select_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kSelectSql));
  select_statement.BindString(0, context_origin);

  int64_t num_bytes = 0;
  if (select_statement.Step()) {
    num_bytes = select_statement.ColumnInt64(0);
  }

  if (!select_statement.Succeeded()) {
    return false;
  }

  // There are no entries left for `context_origin`, so remove it from
  // `per_origin_mapping`.
  if (!num_bytes) {
    return DeleteFromPerOriginMapping(context_origin,
                                      DataClearSource::kExpiration) &&
           transaction.Commit();
  }

  // Update the `per_origin_mapping` row for `context_origin`.
  static constexpr char kUpdateSql[] =
      "UPDATE per_origin_mapping SET num_bytes=? WHERE context_origin=?";
  sql::Statement update_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kUpdateSql));
  update_statement.BindInt64(0, static_cast<int64_t>(num_bytes));
  update_statement.BindString(1, context_origin);

  if (!update_statement.Run()) {
    return false;
  }

  return transaction.Commit();
}

void SharedStorageDatabase::LogInitHistograms() {
  base::UmaHistogramBoolean("Storage.SharedStorage.Database.IsFileBacked",
                            is_filebacked());

  if (!is_filebacked()) {
    // The remaining histograms are only defined and recorded for filebacked
    // databases.
    return;
  }

  std::optional<int64_t> file_size = base::GetFileSize(db_path_);
  if (file_size.has_value()) {
    int64_t file_size_kb = file_size.value() / 1024;
    base::UmaHistogramCounts10M(
        "Storage.SharedStorage.Database.FileBacked.FileSize.KB", file_size_kb);

    int64_t file_size_gb = file_size_kb / (1024 * 1024);
    if (file_size_gb) {
      base::UmaHistogramCounts1000(
          "Storage.SharedStorage.Database.FileBacked.FileSize.GB",
          file_size_gb);
    }
  }

  static constexpr char kValueCountSql[] =
      "SELECT COUNT(*) FROM values_mapping";

  sql::Statement value_count_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kValueCountSql));

  if (value_count_statement.Step()) {
    base::UmaHistogramCounts10M(
        "Storage.SharedStorage.Database.FileBacked.NumEntries.Total",
        value_count_statement.ColumnInt64(0));
  }

  static constexpr char kOriginCountSql[] =
      "SELECT COUNT(*) FROM per_origin_mapping";

  sql::Statement origin_count_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kOriginCountSql));

  int64_t origin_count = 0;
  if (origin_count_statement.Step()) {
    origin_count = origin_count_statement.ColumnInt64(0);
    base::UmaHistogramCounts100000(
        "Storage.SharedStorage.Database.FileBacked.NumOrigins", origin_count);
  } else {
    // Skip recording further histograms on `per_origin_mapping` since either
    // it's empty or we've encountered a database error.
    return;
  }

  const int64_t kMedianLimit = 2 - (origin_count % 2);
  const int64_t kMedianOffset = (origin_count - 1) / 2;

  static constexpr char kLengthQuartileSql[] =
      "SELECT AVG(length) "
      "FROM "
      "  (SELECT length "
      "  FROM "
      "    (SELECT context_origin, COUNT(context_origin) AS length "
      "    FROM values_mapping GROUP BY context_origin) "
      "  ORDER BY length LIMIT ? OFFSET ?)";

  sql::Statement length_median_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kLengthQuartileSql));
  length_median_statement.BindInt64(0, kMedianLimit);
  length_median_statement.BindInt64(1, kMedianOffset);

  if (length_median_statement.Step()) {
    base::UmaHistogramCounts100000(
        "Storage.SharedStorage.Database.FileBacked.NumEntries.PerOrigin."
        "Median",
        length_median_statement.ColumnDouble(0));
  }

  static constexpr char kBytesQuartileSql[] =
      "SELECT AVG(num_bytes) "
      "FROM "
      "  (SELECT num_bytes FROM per_origin_mapping "
      "  ORDER BY num_bytes LIMIT ? OFFSET ?)";

  sql::Statement bytes_median_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kBytesQuartileSql));
  bytes_median_statement.BindInt64(0, kMedianLimit);
  bytes_median_statement.BindInt64(1, kMedianOffset);

  if (bytes_median_statement.Step()) {
    base::UmaHistogramCounts10M(
        "Storage.SharedStorage.Database.FileBacked.BytesUsed.PerOrigin."
        "Median",
        bytes_median_statement.ColumnInt64(0));
  }

  const int64_t kQuartileLimit = 2 - (origin_count % 4) / 2;
  const int64_t kQuartileOffset =
      (origin_count > 1) ? (origin_count - 2) / 4 : 0;

  // We use Method 1 from https://en.wikipedia.org/wiki/Quartile to
  // calculate upper and lower quartiles.
  sql::Statement length_q1_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kLengthQuartileSql));
  length_q1_statement.BindInt64(0, kQuartileLimit);
  length_q1_statement.BindInt64(1, kQuartileOffset);

  if (length_q1_statement.Step()) {
    base::UmaHistogramCounts100000(
        "Storage.SharedStorage.Database.FileBacked.NumEntries.PerOrigin.Q1",
        length_q1_statement.ColumnDouble(0));
  }

  // We use Method 1 from https://en.wikipedia.org/wiki/Quartile to
  // calculate upper and lower quartiles.
  sql::Statement bytes_q1_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kBytesQuartileSql));
  bytes_q1_statement.BindInt64(0, kQuartileLimit);
  bytes_q1_statement.BindInt64(1, kQuartileOffset);

  if (bytes_q1_statement.Step()) {
    base::UmaHistogramCounts10M(
        "Storage.SharedStorage.Database.FileBacked.BytesUsed.PerOrigin.Q1",
        bytes_q1_statement.ColumnInt64(0));
  }

  // We use Method 1 from https://en.wikipedia.org/wiki/Quartile to
  // calculate upper and lower quartiles.
  static constexpr char kLengthUpperQuartileSql[] =
      "SELECT AVG(length) "
      "FROM "
      "  (SELECT length "
      "  FROM "
      "    (SELECT context_origin, COUNT(context_origin) AS length "
      "    FROM values_mapping GROUP BY context_origin) "
      "  ORDER BY length DESC LIMIT ? OFFSET ?)";

  sql::Statement length_q3_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kLengthUpperQuartileSql));
  length_q3_statement.BindInt64(0, kQuartileLimit);
  length_q3_statement.BindInt64(1, kQuartileOffset);

  if (length_q3_statement.Step()) {
    base::UmaHistogramCounts100000(
        "Storage.SharedStorage.Database.FileBacked.NumEntries.PerOrigin.Q3",
        length_q3_statement.ColumnDouble(0));
  }

  // We use Method 1 from https://en.wikipedia.org/wiki/Quartile to
  // calculate upper and lower quartiles.
  static constexpr char kBytesUpperQuartileSql[] =
      "SELECT AVG(num_bytes) "
      "FROM "
      "  (SELECT num_bytes FROM per_origin_mapping "
      "  ORDER BY num_bytes DESC LIMIT ? OFFSET ?)";

  sql::Statement bytes_q3_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kBytesUpperQuartileSql));
  bytes_q3_statement.BindInt64(0, kQuartileLimit);
  bytes_q3_statement.BindInt64(1, kQuartileOffset);

  if (bytes_q3_statement.Step()) {
    base::UmaHistogramCounts10M(
        "Storage.SharedStorage.Database.FileBacked.BytesUsed.PerOrigin.Q3",
        bytes_q3_statement.ColumnInt64(0));
  }

  static constexpr char kLengthMinSql[] =
      "SELECT MIN(length) "
      "FROM "
      "  (SELECT context_origin, COUNT(context_origin) AS length "
      "  FROM values_mapping GROUP BY context_origin) ";

  sql::Statement length_min_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kLengthMinSql));

  if (length_min_statement.Step()) {
    base::UmaHistogramCounts100000(
        "Storage.SharedStorage.Database.FileBacked.NumEntries.PerOrigin."
        "Min",
        length_min_statement.ColumnInt64(0));
  }

  static constexpr char kBytesMinSql[] =
      "SELECT MIN(num_bytes) FROM per_origin_mapping";

  sql::Statement bytes_min_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kBytesMinSql));

  if (bytes_min_statement.Step()) {
    base::UmaHistogramCounts10M(
        "Storage.SharedStorage.Database.FileBacked.BytesUsed.PerOrigin."
        "Min",
        bytes_min_statement.ColumnInt64(0));
  }

  static constexpr char kLengthMaxSql[] =
      "SELECT MAX(length) "
      "FROM "
      "  (SELECT context_origin, COUNT(context_origin) AS length "
      "  FROM values_mapping GROUP BY context_origin)";

  sql::Statement length_max_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kLengthMaxSql));

  if (length_max_statement.Step()) {
    base::UmaHistogramCounts100000(
        "Storage.SharedStorage.Database.FileBacked.NumEntries.PerOrigin."
        "Max",
        length_max_statement.ColumnInt64(0));
  }

  static constexpr char kBytesMaxSql[] =
      "SELECT MAX(num_bytes) FROM per_origin_mapping";

  sql::Statement bytes_max_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kBytesMaxSql));

  if (bytes_max_statement.Step()) {
    base::UmaHistogramCounts10M(
        "Storage.SharedStorage.Database.FileBacked.BytesUsed.PerOrigin."
        "Max",
        bytes_max_statement.ColumnInt64(0));
  }

  static constexpr char kBytesSumSql[] =
      "SELECT SUM(num_bytes) FROM per_origin_mapping";

  sql::Statement bytes_sum_statement(
      db_.GetCachedStatement(SQL_FROM_HERE, kBytesSumSql));

  if (bytes_sum_statement.Step()) {
    base::UmaHistogramCounts10M(
        "Storage.SharedStorage.Database.FileBacked.BytesUsed.Total.KB",
        bytes_sum_statement.ColumnInt64(0) / 1024);
  }
}

}  // namespace storage