File: sqlite_backend_impl.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (146 lines) | stat: -rw-r--r-- 5,224 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
// Copyright 2025 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/persistent_cache/sqlite/sqlite_backend_impl.h"

#include <memory>
#include <utility>

#include "base/check_op.h"
#include "base/containers/span.h"
#include "base/trace_event/base_tracing.h"
#include "components/persistent_cache/sqlite/sqlite_entry_impl.h"
#include "components/persistent_cache/sqlite/vfs/sandboxed_file.h"
#include "components/persistent_cache/sqlite/vfs/sqlite_sandboxed_vfs.h"
#include "sql/database.h"
#include "sql/statement.h"

namespace {

constexpr const char kSqliteHistogramTag[] = "PersistentCache";

}  // namespace

namespace persistent_cache {

// static
SqliteVfsFileSet SqliteBackendImpl::GetVfsFileSetFromParams(
    BackendParams backend_params) {
  CHECK_EQ(backend_params.type, BackendType::kSqlite);

  using AccessRights = SandboxedFile::AccessRights;
  SandboxedFile db_file = SandboxedFile(std::move(backend_params.db_file),
                                        backend_params.db_file_is_writable
                                            ? AccessRights::kReadWrite
                                            : AccessRights::kReadOnly);
  SandboxedFile journal_file = SandboxedFile(
      std::move(backend_params.journal_file),
      backend_params.journal_file_is_writable ? AccessRights::kReadWrite
                                              : AccessRights::kReadOnly);

  return SqliteVfsFileSet(std::move(db_file), std::move(journal_file));
}

SqliteBackendImpl::SqliteBackendImpl(BackendParams backend_params)
    : SqliteBackendImpl(GetVfsFileSetFromParams(std::move(backend_params))) {}

SqliteBackendImpl::SqliteBackendImpl(SqliteVfsFileSet vfs_file_set)
    : database_path_(vfs_file_set.GetDbVirtualFilePath()),
      db_(sql::DatabaseOptions()
              .set_vfs_name_discouraged(
                  SqliteSandboxedVfsDelegate::kSqliteVfsName)
              // Prevent SQLite from trying to use mmap, as SandboxedVfs does
              // not currently support this.
              .set_mmap_enabled(false),
          kSqliteHistogramTag),
      unregister_runner_(
          SqliteSandboxedVfsDelegate::GetInstance()->RegisterSandboxedFiles(
              std::move(vfs_file_set))) {}

SqliteBackendImpl::~SqliteBackendImpl() = default;

bool SqliteBackendImpl::Initialize() {
  CHECK(!initialized_);
  TRACE_EVENT0("persistent_cache", "initialize");

  if (!db_.Open(database_path_)) {
    TRACE_EVENT_INSTANT1("persistent_cache", "open_failed",
                         TRACE_EVENT_SCOPE_THREAD, "error_code",
                         db_.GetErrorCode());
    return false;
  }

  if (!db_.Execute(
          "CREATE TABLE IF NOT EXISTS entries(key TEXT PRIMARY KEY UNIQUE NOT "
          "NULL, content BLOB NOT NULL, input_signature INTEGER, "
          "write_timestamp INTEGER)")) {
    TRACE_EVENT_INSTANT1("persistent_cache", "create_failed",
                         TRACE_EVENT_SCOPE_THREAD, "error_code",
                         db_.GetErrorCode());
    return false;
  }

  initialized_ = true;
  return true;
}

std::unique_ptr<Entry> SqliteBackendImpl::Find(std::string_view key) {
  CHECK(initialized_);
  CHECK_GT(key.length(), 0ull);
  TRACE_EVENT0("persistent_cache", "Find");

  sql::Statement stm = sql::Statement(
      db_.GetCachedStatement(SQL_FROM_HERE,
                             "SELECT content, input_signature, write_timestamp "
                             "FROM entries WHERE key = ?"));
  stm.BindString(0, key);

  DCHECK(stm.is_valid());
  if (!stm.Step()) {
    const int error_code = db_.GetErrorCode();
    // If the last error code is SQLITE_DONE then `Step()` failed because the
    // row was not found which is not a reportable error.
    if (error_code != SQLITE_DONE) {
      TRACE_EVENT_INSTANT1("persistent_cache", "find_failed",
                           TRACE_EVENT_SCOPE_THREAD, "error_code", error_code);
    }
    return nullptr;
  }

  EntryMetadata metadata;
  metadata.input_signature = stm.ColumnInt64(1);
  metadata.write_timestamp = stm.ColumnInt64(2);

  return SqliteEntryImpl::MakeUnique(Passkey(), stm.ColumnString(0), metadata);
}

void SqliteBackendImpl::Insert(std::string_view key,
                               base::span<const uint8_t> content,
                               EntryMetadata metadata) {
  CHECK(initialized_);
  CHECK_GT(key.length(), 0ull);
  TRACE_EVENT0("persistent_cache", "insert");

  CHECK_EQ(metadata.write_timestamp, 0)
      << "Write timestamp is generated by SQLite so it should not be specified "
         "manually";

  sql::Statement stm(db_.GetCachedStatement(
      SQL_FROM_HERE,
      "REPLACE INTO entries (key, content, input_signature, write_timestamp) "
      "VALUES (?, ?, ?, CURRENT_TIMESTAMP)"));

  stm.BindString(0, key);
  stm.BindString(1, base::as_string_view(content));
  stm.BindInt64(2, metadata.input_signature);

  DCHECK(stm.is_valid());
  if (!stm.Run()) {
    TRACE_EVENT_INSTANT1("persistent_cache", "insert_failed",
                         TRACE_EVENT_SCOPE_THREAD, "error_code",
                         db_.GetErrorCode());
  }
}

}  // namespace persistent_cache