database.cc 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "sql/database.h"
  5. #include <limits.h>
  6. #include <stddef.h>
  7. #include <stdint.h>
  8. #include <string.h>
  9. #include <algorithm>
  10. #include <memory>
  11. #include <tuple>
  12. #include "base/check.h"
  13. #include "base/dcheck_is_on.h"
  14. #include "base/feature_list.h"
  15. #include "base/files/file_path.h"
  16. #include "base/files/file_util.h"
  17. #include "base/format_macros.h"
  18. #include "base/location.h"
  19. #include "base/logging.h"
  20. #include "base/memory/raw_ptr.h"
  21. #include "base/no_destructor.h"
  22. #include "base/notreached.h"
  23. #include "base/numerics/safe_conversions.h"
  24. #include "base/ranges/algorithm.h"
  25. #include "base/sequence_checker.h"
  26. #include "base/strings/strcat.h"
  27. #include "base/strings/string_number_conversions.h"
  28. #include "base/strings/string_piece.h"
  29. #include "base/strings/string_split.h"
  30. #include "base/strings/string_util.h"
  31. #include "base/strings/stringprintf.h"
  32. #include "base/strings/utf_string_conversions.h"
  33. #include "base/synchronization/lock.h"
  34. #include "base/task/single_thread_task_runner.h"
  35. #include "base/threading/scoped_blocking_call.h"
  36. #include "base/trace_event/memory_dump_manager.h"
  37. #include "base/trace_event/trace_event.h"
  38. #include "base/tracing/protos/chrome_track_event.pbzero.h"
  39. #include "base/types/pass_key.h"
  40. #include "build/build_config.h"
  41. #include "sql/database_memory_dump_provider.h"
  42. #include "sql/initialization.h"
  43. #include "sql/meta_table.h"
  44. #include "sql/sql_features.h"
  45. #include "sql/sqlite_result_code.h"
  46. #include "sql/sqlite_result_code_values.h"
  47. #include "sql/statement.h"
  48. #include "sql/vfs_wrapper.h"
  49. #include "third_party/sqlite/sqlite3.h"
  50. namespace sql {
  51. namespace {
  52. bool enable_mmap_by_default_ = true;
  53. // The name of the main database associated with a sqlite3* connection.
  54. //
  55. // SQLite has the ability to ATTACH multiple databases to the same connection.
  56. // As a consequence, some SQLite APIs require the connection-specific database
  57. // name. This is the right name to be passed to such APIs.
  58. static constexpr char kSqliteMainDatabaseName[] = "main";
  59. // Magic path value telling sqlite3_open_v2() to open an in-memory database.
  60. static constexpr char kSqliteOpenInMemoryPath[] = ":memory:";
  61. // Spin for up to a second waiting for the lock to clear when setting
  62. // up the database.
  63. // TODO(shess): Better story on this. http://crbug.com/56559
  64. const int kBusyTimeoutSeconds = 1;
  65. class ScopedBusyTimeout {
  66. public:
  67. explicit ScopedBusyTimeout(sqlite3* db) : db_(db) {}
  68. ~ScopedBusyTimeout() { sqlite3_busy_timeout(db_, 0); }
  69. int SetTimeout(base::TimeDelta timeout) {
  70. DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
  71. return sqlite3_busy_timeout(db_,
  72. static_cast<int>(timeout.InMilliseconds()));
  73. }
  74. private:
  75. raw_ptr<sqlite3> db_;
  76. };
  77. // Helper to "safely" enable writable_schema. No error checking
  78. // because it is reasonable to just forge ahead in case of an error.
  79. // If turning it on fails, then most likely nothing will work, whereas
  80. // if turning it off fails, it only matters if some code attempts to
  81. // continue working with the database and tries to modify the
  82. // sqlite_schema table (none of our code does this).
  83. class ScopedWritableSchema {
  84. public:
  85. explicit ScopedWritableSchema(sqlite3* db) : db_(db) {
  86. sqlite3_exec(db_, "PRAGMA writable_schema=1", nullptr, nullptr, nullptr);
  87. }
  88. ~ScopedWritableSchema() {
  89. sqlite3_exec(db_, "PRAGMA writable_schema=0", nullptr, nullptr, nullptr);
  90. }
  91. private:
  92. raw_ptr<sqlite3> db_;
  93. };
  94. // Raze() helper that uses SQLite's online backup API.
  95. //
  96. // Returns the SQLite error code produced by sqlite3_backup_step(). SQLITE_DONE
  97. // signals success. SQLITE_OK will never be returned.
  98. //
  99. // The implementation is tailored for the Raze() use case. In particular, the
  100. // SQLite API use and and error handling is optimized for 1-page databases.
  101. SqliteResultCode BackupDatabaseForRaze(sqlite3* source_db,
  102. sqlite3* destination_db) {
  103. DCHECK(source_db);
  104. DCHECK(destination_db);
  105. DCHECK_NE(source_db, destination_db);
  106. // https://www.sqlite.org/backup.html has a high-level overview of SQLite's
  107. // backup support. https://www.sqlite.org/c3ref/backup_finish.html describes
  108. // the API.
  109. static constexpr char kMainDatabaseName[] = "main";
  110. sqlite3_backup* backup = sqlite3_backup_init(
  111. destination_db, kMainDatabaseName, source_db, kMainDatabaseName);
  112. if (!backup) {
  113. // sqlite3_backup_init() fails if a transaction is ongoing. In particular,
  114. // SQL statements that return multiple rows keep a read transaction open
  115. // until all the Step() calls are executed.
  116. return ToSqliteResultCode(chrome_sqlite3_extended_errcode(destination_db));
  117. }
  118. constexpr int kUnlimitedPageCount = -1; // Back up entire database.
  119. auto sqlite_result_code =
  120. ToSqliteResultCode(sqlite3_backup_step(backup, kUnlimitedPageCount));
  121. DCHECK_NE(sqlite_result_code, SqliteResultCode::kOk)
  122. << "sqlite3_backup_step() returned SQLITE_OK (instead of SQLITE_DONE) "
  123. << "when asked to back up the entire database";
  124. #if DCHECK_IS_ON()
  125. if (sqlite_result_code == SqliteResultCode::kDone) {
  126. // If successful, exactly one page should have been backed up.
  127. DCHECK_EQ(sqlite3_backup_pagecount(backup), 1)
  128. << __func__ << " was intended to be used with 1-page databases";
  129. }
  130. #endif // DCHECK_IS_ON()
  131. // sqlite3_backup_finish() releases the sqlite3_backup object.
  132. //
  133. // It returns an error code only if the backup encountered a permanent error.
  134. // We use the the sqlite3_backup_step() result instead, because it also tells
  135. // us about temporary errors, like SQLITE_BUSY.
  136. //
  137. // We pass the sqlite3_backup_finish() result code through
  138. // ToSqliteResultCode() to catch codes that should never occur, like
  139. // SQLITE_MISUSE.
  140. std::ignore = ToSqliteResultCode(sqlite3_backup_finish(backup));
  141. return sqlite_result_code;
  142. }
  143. bool ValidAttachmentPoint(base::StringPiece attachment_point) {
  144. // SQLite could handle a much wider character set, with appropriate quoting.
  145. //
  146. // Chrome's constraint is easy to remember, and sufficient for the few
  147. // existing use cases. ATTACH is a discouraged feature, so no new use cases
  148. // are expected.
  149. return base::ranges::all_of(attachment_point,
  150. [](char ch) { return base::IsAsciiLower(ch); });
  151. }
  152. std::string AsUTF8ForSQL(const base::FilePath& path) {
  153. #if BUILDFLAG(IS_WIN)
  154. return base::WideToUTF8(path.value());
  155. #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
  156. return path.value();
  157. #endif
  158. }
  159. } // namespace
  160. // static
  161. Database::ScopedErrorExpecterCallback* Database::current_expecter_cb_ = nullptr;
  162. // static
  163. bool Database::IsExpectedSqliteError(int sqlite_error_code) {
  164. DCHECK_NE(sqlite_error_code, SQLITE_OK)
  165. << __func__ << " received non-error result code";
  166. DCHECK_NE(sqlite_error_code, SQLITE_DONE)
  167. << __func__ << " received non-error result code";
  168. DCHECK_NE(sqlite_error_code, SQLITE_ROW)
  169. << __func__ << " received non-error result code";
  170. if (!current_expecter_cb_)
  171. return false;
  172. return current_expecter_cb_->Run(sqlite_error_code);
  173. }
  174. // static
  175. void Database::SetScopedErrorExpecter(
  176. Database::ScopedErrorExpecterCallback* cb,
  177. base::PassKey<test::ScopedErrorExpecter>) {
  178. CHECK(!current_expecter_cb_);
  179. current_expecter_cb_ = cb;
  180. }
  181. // static
  182. void Database::ResetScopedErrorExpecter(
  183. base::PassKey<test::ScopedErrorExpecter>) {
  184. CHECK(current_expecter_cb_);
  185. current_expecter_cb_ = nullptr;
  186. }
  187. // static
  188. base::FilePath Database::JournalPath(const base::FilePath& db_path) {
  189. return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-journal"));
  190. }
  191. // static
  192. base::FilePath Database::WriteAheadLogPath(const base::FilePath& db_path) {
  193. return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-wal"));
  194. }
  195. // static
  196. base::FilePath Database::SharedMemoryFilePath(const base::FilePath& db_path) {
  197. return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-shm"));
  198. }
  199. Database::StatementRef::StatementRef(Database* database,
  200. sqlite3_stmt* stmt,
  201. bool was_valid)
  202. : database_(database), stmt_(stmt), was_valid_(was_valid) {
  203. DCHECK_EQ(database == nullptr, stmt == nullptr);
  204. if (database)
  205. database_->StatementRefCreated(this);
  206. }
  207. Database::StatementRef::~StatementRef() {
  208. if (database_)
  209. database_->StatementRefDeleted(this);
  210. Close(false);
  211. }
  212. void Database::StatementRef::Close(bool forced) {
  213. if (stmt_) {
  214. // Call to InitScopedBlockingCall() cannot go at the beginning of the
  215. // function because Close() is called unconditionally from destructor to
  216. // clean database_. And if this is inactive statement this won't cause any
  217. // disk access and destructor most probably will be called on thread not
  218. // allowing disk access.
  219. // TODO(paivanof@gmail.com): This should move to the beginning
  220. // of the function. http://crbug.com/136655.
  221. absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
  222. InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
  223. // `stmt_` references memory loaned from the sqlite3 library. Stop
  224. // referencing it from the raw_ptr<> before returning it. This avoids the
  225. // raw_ptr<> becoming dangling.
  226. sqlite3_stmt* statement = stmt_;
  227. stmt_ = nullptr;
  228. // sqlite3_finalize()'s result code is ignored because it reports the same
  229. // error as the most recent sqlite3_step(). The result code is passed
  230. // through ToSqliteResultCode() to catch issues like SQLITE_MISUSE.
  231. std::ignore = ToSqliteResultCode(sqlite3_finalize(statement));
  232. }
  233. database_ = nullptr; // The Database may be getting deleted.
  234. // Forced close is expected to happen from a statement error
  235. // handler. In that case maintain the sense of |was_valid_| which
  236. // previously held for this ref.
  237. was_valid_ = was_valid_ && forced;
  238. }
  239. static_assert(DatabaseOptions::kDefaultPageSize == SQLITE_DEFAULT_PAGE_SIZE,
  240. "DatabaseOptions::kDefaultPageSize must match the value "
  241. "configured into SQLite");
  242. DatabaseDiagnostics::DatabaseDiagnostics() = default;
  243. DatabaseDiagnostics::~DatabaseDiagnostics() = default;
  244. void DatabaseDiagnostics::WriteIntoTrace(
  245. perfetto::TracedProto<TraceProto> context) const {
  246. context->set_reported_sqlite_error_code(reported_sqlite_error_code);
  247. context->set_error_code(error_code);
  248. context->set_last_errno(last_errno);
  249. context->set_sql_statement(sql_statement);
  250. context->set_version(version);
  251. for (const auto& sql : schema_sql_rows) {
  252. context->add_schema_sql_rows(sql);
  253. }
  254. for (const auto& name : schema_other_row_names) {
  255. context->add_schema_other_row_names(name);
  256. }
  257. context->set_has_valid_header(has_valid_header);
  258. context->set_has_valid_schema(has_valid_schema);
  259. }
  260. // DatabaseOptions::explicit_locking needs to be set to false for historical
  261. // reasons.
  262. Database::Database() : Database({.exclusive_locking = false}) {}
  263. Database::Database(DatabaseOptions options)
  264. : options_(options), mmap_disabled_(!enable_mmap_by_default_) {
  265. DCHECK_GE(options.page_size, 512);
  266. DCHECK_LE(options.page_size, 65536);
  267. DCHECK(!(options.page_size & (options.page_size - 1)))
  268. << "page_size must be a power of two";
  269. DCHECK(!options_.mmap_alt_status_discouraged ||
  270. options_.enable_views_discouraged)
  271. << "mmap_alt_status requires views";
  272. // It's valid to construct a database on a sequence and then pass it to a
  273. // different sequence before usage.
  274. DETACH_FROM_SEQUENCE(sequence_checker_);
  275. }
  276. Database::~Database() {
  277. Close();
  278. }
  279. // static
  280. void Database::DisableMmapByDefault() {
  281. enable_mmap_by_default_ = false;
  282. }
  283. bool Database::Open(const base::FilePath& path) {
  284. std::string path_string = AsUTF8ForSQL(path);
  285. TRACE_EVENT1("sql", "Database::Open", "path", path_string);
  286. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  287. DCHECK(!path.empty());
  288. DCHECK_NE(path_string, kSqliteOpenInMemoryPath)
  289. << "Path conflicts with SQLite magic identifier";
  290. return OpenInternal(path_string, OpenMode::kRetryOnPoision);
  291. }
  292. bool Database::OpenInMemory() {
  293. TRACE_EVENT0("sql", "Database::OpenInMemory");
  294. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  295. in_memory_ = true;
  296. return OpenInternal(kSqliteOpenInMemoryPath, OpenMode::kInMemory);
  297. }
  298. bool Database::OpenTemporary(base::PassKey<Recovery>) {
  299. TRACE_EVENT0("sql", "Database::OpenTemporary");
  300. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  301. return OpenInternal(std::string(), OpenMode::kTemporary);
  302. }
  303. void Database::CloseInternal(bool forced) {
  304. TRACE_EVENT0("sql", "Database::CloseInternal");
  305. // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
  306. // will delete the -journal file. For ChromiumOS or other more
  307. // embedded systems, this is probably not appropriate, whereas on
  308. // desktop it might make some sense.
  309. // sqlite3_close() needs all prepared statements to be finalized.
  310. // Release cached statements.
  311. statement_cache_.clear();
  312. // With cached statements released, in-use statements will remain.
  313. // Closing the database while statements are in use is an API
  314. // violation, except for forced close (which happens from within a
  315. // statement's error handler).
  316. DCHECK(forced || open_statements_.empty());
  317. // Deactivate any outstanding statements so sqlite3_close() works.
  318. for (StatementRef* statement_ref : open_statements_)
  319. statement_ref->Close(forced);
  320. open_statements_.clear();
  321. if (db_) {
  322. // Call to InitScopedBlockingCall() cannot go at the beginning of the
  323. // function because Close() must be called from destructor to clean
  324. // statement_cache_, it won't cause any disk access and it most probably
  325. // will happen on thread not allowing disk access.
  326. // TODO(paivanof@gmail.com): This should move to the beginning
  327. // of the function. http://crbug.com/136655.
  328. absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
  329. InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
  330. // Resetting acquires a lock to ensure no dump is happening on the database
  331. // at the same time. Unregister takes ownership of provider and it is safe
  332. // since the db is reset. memory_dump_provider_ could be null if db_ was
  333. // poisoned.
  334. if (memory_dump_provider_) {
  335. memory_dump_provider_->ResetDatabase();
  336. base::trace_event::MemoryDumpManager::GetInstance()
  337. ->UnregisterAndDeleteDumpProviderSoon(
  338. std::move(memory_dump_provider_));
  339. }
  340. auto sqlite_result_code = ToSqliteResultCode(sqlite3_close(db_));
  341. DCHECK_NE(sqlite_result_code, SqliteResultCode::kBusy)
  342. << "sqlite3_close() called while prepared statements are still alive";
  343. DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
  344. << "sqlite3_close() failed in an unexpected way: " << GetErrorMessage();
  345. // The reset must happen after the DCHECKs above. GetErrorMessage() needs a
  346. // valid `db_` value.
  347. db_ = nullptr;
  348. }
  349. }
  350. void Database::Close() {
  351. TRACE_EVENT0("sql", "Database::Close");
  352. // If the database was already closed by RazeAndClose(), then no
  353. // need to close again. Clear the |poisoned_| bit so that incorrect
  354. // API calls are caught.
  355. if (poisoned_) {
  356. poisoned_ = false;
  357. return;
  358. }
  359. CloseInternal(false);
  360. }
  361. void Database::Preload() {
  362. TRACE_EVENT0("sql", "Database::Preload");
  363. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  364. if (!db_) {
  365. DCHECK(poisoned_) << "Cannot preload null db";
  366. return;
  367. }
  368. absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
  369. InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
  370. // Maximum number of bytes that will be prefetched from the database.
  371. //
  372. // This limit is very aggressive. The main trade-off involved is that having
  373. // SQLite block on reading from disk has a high impact on Chrome startup cost
  374. // for the databases that are on the critical path to startup. So, the limit
  375. // must exceed the expected sizes of databases on the critical path.
  376. //
  377. // On Windows 7, base::PreReadFile() falls back to a synchronous read, and
  378. // blocks until the entire file is read into memory. This is a minor factor at
  379. // this point, because Chrome has very limited support for Windows 7.
  380. constexpr int kPreReadSize = 128 * 1024 * 1024; // 128 MB
  381. base::PreReadFile(DbPath(), /*is_executable=*/false, kPreReadSize);
  382. }
  383. // SQLite keeps unused pages associated with a database in a cache. It asks
  384. // the cache for pages by an id, and if the page is present and the database is
  385. // unchanged, it considers the content of the page valid and doesn't read it
  386. // from disk. When memory-mapped I/O is enabled, on read SQLite uses page
  387. // structures created from the memory map data before consulting the cache. On
  388. // write SQLite creates a new in-memory page structure, copies the data from the
  389. // memory map, and later writes it, releasing the updated page back to the
  390. // cache.
  391. //
  392. // This means that in memory-mapped mode, the contents of the cached pages are
  393. // not re-used for reads, but they are re-used for writes if the re-written page
  394. // is still in the cache. The implementation of sqlite3_db_release_memory() as
  395. // of SQLite 3.8.7.4 frees all pages from pcaches associated with the
  396. // database, so it should free these pages.
  397. //
  398. // Unfortunately, the zero page is also freed. That page is never accessed
  399. // using memory-mapped I/O, and the cached copy can be re-used after verifying
  400. // the file change counter on disk. Also, fresh pages from cache receive some
  401. // pager-level initialization before they can be used. Since the information
  402. // involved will immediately be accessed in various ways, it is unclear if the
  403. // additional overhead is material, or just moving processor cache effects
  404. // around.
  405. //
  406. // TODO(shess): It would be better to release the pages immediately when they
  407. // are no longer needed. This would basically happen after SQLite commits a
  408. // transaction. I had implemented a pcache wrapper to do this, but it involved
  409. // layering violations, and it had to be setup before any other sqlite call,
  410. // which was brittle. Also, for large files it would actually make sense to
  411. // maintain the existing pcache behavior for blocks past the memory-mapped
  412. // segment. I think drh would accept a reasonable implementation of the overall
  413. // concept for upstreaming to SQLite core.
  414. //
  415. // TODO(shess): Another possibility would be to set the cache size small, which
  416. // would keep the zero page around, plus some pre-initialized pages, and SQLite
  417. // can manage things. The downside is that updates larger than the cache would
  418. // spill to the journal. That could be compensated by setting cache_spill to
  419. // false. The downside then is that it allows open-ended use of memory for
  420. // large transactions.
  421. void Database::ReleaseCacheMemoryIfNeeded(bool implicit_change_performed) {
  422. TRACE_EVENT0("sql", "Database::ReleaseCacheMemoryIfNeeded");
  423. // The database could have been closed during a transaction as part of error
  424. // recovery.
  425. if (!db_) {
  426. DCHECK(poisoned_) << "Illegal use of Database without a db";
  427. return;
  428. }
  429. // If memory-mapping is not enabled, the page cache helps performance.
  430. if (!mmap_enabled_)
  431. return;
  432. // On caller request, force the change comparison to fail. Done before the
  433. // transaction-nesting test so that the signal can carry to transaction
  434. // commit.
  435. if (implicit_change_performed)
  436. --total_changes_at_last_release_;
  437. // Cached pages may be re-used within the same transaction.
  438. DCHECK_GE(transaction_nesting_, 0);
  439. if (transaction_nesting_)
  440. return;
  441. // If no changes have been made, skip flushing. This allows the first page of
  442. // the database to remain in cache across multiple reads.
  443. const int64_t total_changes = sqlite3_total_changes64(db_);
  444. if (total_changes == total_changes_at_last_release_)
  445. return;
  446. total_changes_at_last_release_ = total_changes;
  447. // Passing the result code through ToSqliteResultCode() to catch issues such
  448. // as SQLITE_MISUSE.
  449. std::ignore = ToSqliteResultCode(sqlite3_db_release_memory(db_));
  450. }
  451. base::FilePath Database::DbPath() const {
  452. if (!is_open())
  453. return base::FilePath();
  454. const char* path = sqlite3_db_filename(db_, "main");
  455. if (!path)
  456. return base::FilePath();
  457. const base::StringPiece db_path(path);
  458. #if BUILDFLAG(IS_WIN)
  459. return base::FilePath(base::UTF8ToWide(db_path));
  460. #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
  461. return base::FilePath(db_path);
  462. #else
  463. NOTREACHED();
  464. return base::FilePath();
  465. #endif
  466. }
  467. std::string Database::CollectErrorInfo(int sqlite_error_code,
  468. Statement* stmt,
  469. DatabaseDiagnostics* diagnostics) const {
  470. TRACE_EVENT0("sql", "Database::CollectErrorInfo");
  471. DCHECK_NE(sqlite_error_code, SQLITE_OK)
  472. << __func__ << " received non-error result code";
  473. DCHECK_NE(sqlite_error_code, SQLITE_DONE)
  474. << __func__ << " received non-error result code";
  475. DCHECK_NE(sqlite_error_code, SQLITE_ROW)
  476. << __func__ << " received non-error result code";
  477. // Buffer for accumulating debugging info about the error. Place
  478. // more-relevant information earlier, in case things overflow the
  479. // fixed-size reporting buffer.
  480. std::string debug_info;
  481. // The error message from the failed operation.
  482. int error_code = GetErrorCode();
  483. base::StringAppendF(&debug_info, "db error: %d/%s\n", error_code,
  484. GetErrorMessage());
  485. if (diagnostics) {
  486. diagnostics->error_code = error_code;
  487. }
  488. // TODO(shess): |error| and |GetErrorCode()| should always be the same, but
  489. // reading code does not entirely convince me. Remove if they turn out to be
  490. // the same.
  491. if (sqlite_error_code != GetErrorCode())
  492. base::StringAppendF(&debug_info, "reported error: %d\n", sqlite_error_code);
  493. // System error information. Interpretation of Windows errors is different
  494. // from posix.
  495. #if BUILDFLAG(IS_WIN)
  496. int last_errno = GetLastErrno();
  497. base::StringAppendF(&debug_info, "LastError: %d\n", last_errno);
  498. if (diagnostics) {
  499. diagnostics->last_errno = last_errno;
  500. }
  501. #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
  502. int last_errno = GetLastErrno();
  503. base::StringAppendF(&debug_info, "errno: %d\n", last_errno);
  504. if (diagnostics) {
  505. diagnostics->last_errno = last_errno;
  506. }
  507. #else
  508. NOTREACHED(); // Add appropriate log info.
  509. #endif
  510. if (stmt) {
  511. std::string sql_string = stmt->GetSQLStatement();
  512. base::StringAppendF(&debug_info, "statement: %s\n", sql_string.c_str());
  513. if (diagnostics) {
  514. diagnostics->sql_statement = sql_string;
  515. }
  516. } else {
  517. base::StringAppendF(&debug_info, "statement: NULL\n");
  518. }
  519. // SQLITE_ERROR often indicates some sort of mismatch between the statement
  520. // and the schema, possibly due to a failed schema migration.
  521. if (sqlite_error_code == SQLITE_ERROR) {
  522. static constexpr char kVersionSql[] =
  523. "SELECT value FROM meta WHERE key='version'";
  524. sqlite3_stmt* sqlite_statement;
  525. // When the number of bytes passed to sqlite3_prepare_v3() includes the null
  526. // terminator, SQLite avoids a buffer copy.
  527. int rc = sqlite3_prepare_v3(db_, kVersionSql, sizeof(kVersionSql),
  528. SQLITE_PREPARE_NO_VTAB, &sqlite_statement,
  529. /* pzTail= */ nullptr);
  530. if (rc == SQLITE_OK) {
  531. rc = sqlite3_step(sqlite_statement);
  532. if (rc == SQLITE_ROW) {
  533. int version = sqlite3_column_int(sqlite_statement, 0);
  534. base::StringAppendF(&debug_info, "version: %d\n", version);
  535. if (diagnostics) {
  536. diagnostics->version = version;
  537. }
  538. } else if (rc == SQLITE_DONE) {
  539. debug_info += "version: none\n";
  540. } else {
  541. base::StringAppendF(&debug_info, "version: error %d\n", rc);
  542. }
  543. sqlite3_finalize(sqlite_statement);
  544. } else {
  545. base::StringAppendF(&debug_info, "version: prepare error %d\n", rc);
  546. }
  547. // Get all the SQL from sqlite_schema.
  548. debug_info += "schema:\n";
  549. static constexpr char kSchemaSql[] =
  550. "SELECT sql FROM sqlite_schema WHERE sql IS NOT NULL ORDER BY ROWID";
  551. rc = sqlite3_prepare_v3(db_, kSchemaSql, sizeof(kSchemaSql),
  552. SQLITE_PREPARE_NO_VTAB, &sqlite_statement,
  553. /* pzTail= */ nullptr);
  554. if (rc == SQLITE_OK) {
  555. while ((rc = sqlite3_step(sqlite_statement)) == SQLITE_ROW) {
  556. std::string text;
  557. base::StringAppendF(&text, "%s",
  558. sqlite3_column_text(sqlite_statement, 0));
  559. debug_info += text + "\n";
  560. if (diagnostics) {
  561. diagnostics->schema_sql_rows.push_back(text);
  562. }
  563. }
  564. if (rc != SQLITE_DONE)
  565. base::StringAppendF(&debug_info, "error %d\n", rc);
  566. sqlite3_finalize(sqlite_statement);
  567. } else {
  568. base::StringAppendF(&debug_info, "prepare error %d\n", rc);
  569. }
  570. // Automatically generated indices have a NULL 'sql' column. For those rows,
  571. // we log the name column instead.
  572. debug_info += "schema rows with only name:\n";
  573. static constexpr char kSchemaOtherRowNamesSql[] =
  574. "SELECT name FROM sqlite_schema WHERE sql IS NULL ORDER BY ROWID";
  575. rc = sqlite3_prepare_v3(db_, kSchemaOtherRowNamesSql,
  576. sizeof(kSchemaOtherRowNamesSql),
  577. SQLITE_PREPARE_NO_VTAB, &sqlite_statement,
  578. /* pzTail= */ nullptr);
  579. if (rc == SQLITE_OK) {
  580. while ((rc = sqlite3_step(sqlite_statement)) == SQLITE_ROW) {
  581. std::string text;
  582. base::StringAppendF(&text, "%s",
  583. sqlite3_column_text(sqlite_statement, 0));
  584. debug_info += text + "\n";
  585. if (diagnostics) {
  586. diagnostics->schema_other_row_names.push_back(text);
  587. }
  588. }
  589. if (rc != SQLITE_DONE)
  590. base::StringAppendF(&debug_info, "error %d\n", rc);
  591. sqlite3_finalize(sqlite_statement);
  592. } else {
  593. base::StringAppendF(&debug_info, "prepare error %d\n", rc);
  594. }
  595. }
  596. return debug_info;
  597. }
  598. // TODO(shess): Since this is only called in an error situation, it might be
  599. // prudent to rewrite in terms of SQLite API calls, and mark the function const.
  600. std::string Database::CollectCorruptionInfo() {
  601. TRACE_EVENT0("sql", "Database::CollectCorruptionInfo");
  602. // If the file cannot be accessed it is unlikely that an integrity check will
  603. // turn up actionable information.
  604. const base::FilePath db_path = DbPath();
  605. int64_t db_size = -1;
  606. if (!base::GetFileSize(db_path, &db_size) || db_size < 0)
  607. return std::string();
  608. // Buffer for accumulating debugging info about the error. Place
  609. // more-relevant information earlier, in case things overflow the
  610. // fixed-size reporting buffer.
  611. std::string debug_info;
  612. base::StringAppendF(&debug_info, "SQLITE_CORRUPT, db size %" PRId64 "\n",
  613. db_size);
  614. // Only check files up to 8M to keep things from blocking too long.
  615. const int64_t kMaxIntegrityCheckSize = 8192 * 1024;
  616. if (db_size > kMaxIntegrityCheckSize) {
  617. debug_info += "integrity_check skipped due to size\n";
  618. } else {
  619. std::vector<std::string> messages;
  620. // TODO(shess): FullIntegrityCheck() splits into a vector while this joins
  621. // into a string. Probably should be refactored.
  622. const base::TimeTicks before = base::TimeTicks::Now();
  623. FullIntegrityCheck(&messages);
  624. base::StringAppendF(
  625. &debug_info, "integrity_check %" PRId64 " ms, %" PRIuS " records:\n",
  626. (base::TimeTicks::Now() - before).InMilliseconds(), messages.size());
  627. // SQLite returns up to 100 messages by default, trim deeper to
  628. // keep close to the 2000-character size limit for dumping.
  629. const size_t kMaxMessages = 20;
  630. for (size_t i = 0; i < kMaxMessages && i < messages.size(); ++i) {
  631. base::StringAppendF(&debug_info, "%s\n", messages[i].c_str());
  632. }
  633. }
  634. return debug_info;
  635. }
  636. bool Database::GetMmapAltStatus(int64_t* status) {
  637. TRACE_EVENT0("sql", "Database::GetMmapAltStatus");
  638. // The [meta] version uses a missing table as a signal for a fresh database.
  639. // That will not work for the view, which would not exist in either a new or
  640. // an existing database. A new database _should_ be only one page long, so
  641. // just don't bother optimizing this case (start at offset 0).
  642. // TODO(shess): Could the [meta] case also get simpler, then?
  643. if (!DoesViewExist("MmapStatus")) {
  644. *status = 0;
  645. return true;
  646. }
  647. const char* kMmapStatusSql = "SELECT * FROM MmapStatus";
  648. Statement s(GetUniqueStatement(kMmapStatusSql));
  649. if (s.Step())
  650. *status = s.ColumnInt64(0);
  651. return s.Succeeded();
  652. }
  653. bool Database::SetMmapAltStatus(int64_t status) {
  654. if (!BeginTransaction())
  655. return false;
  656. // View may not exist on first run.
  657. if (!Execute("DROP VIEW IF EXISTS MmapStatus")) {
  658. RollbackTransaction();
  659. return false;
  660. }
  661. // Views live in the schema, so they cannot be parameterized. For an integer
  662. // value, this construct should be safe from SQL injection, if the value
  663. // becomes more complicated use "SELECT quote(?)" to generate a safe quoted
  664. // value.
  665. const std::string create_view_sql = base::StringPrintf(
  666. "CREATE VIEW MmapStatus (value) AS SELECT %" PRId64, status);
  667. if (!Execute(create_view_sql.c_str())) {
  668. RollbackTransaction();
  669. return false;
  670. }
  671. return CommitTransaction();
  672. }
  673. size_t Database::ComputeMmapSizeForOpen() {
  674. TRACE_EVENT0("sql", "Database::ComputeMmapSizeForOpen");
  675. absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
  676. InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
  677. // How much to map if no errors are found. 50MB encompasses the 99th
  678. // percentile of Chrome databases in the wild, so this should be good.
  679. const size_t kMmapEverything = 256 * 1024 * 1024;
  680. // Progress information is tracked in the [meta] table for databases which use
  681. // sql::MetaTable, otherwise it is tracked in a special view.
  682. // TODO(pwnall): Migrate all databases to using a meta table.
  683. int64_t mmap_ofs = 0;
  684. if (options_.mmap_alt_status_discouraged) {
  685. if (!GetMmapAltStatus(&mmap_ofs))
  686. return 0;
  687. } else {
  688. // If [meta] doesn't exist, yet, it's a new database, assume the best.
  689. // sql::MetaTable::Init() will preload kMmapSuccess.
  690. if (!MetaTable::DoesTableExist(this))
  691. return kMmapEverything;
  692. if (!MetaTable::GetMmapStatus(this, &mmap_ofs))
  693. return 0;
  694. }
  695. // Database read failed in the past, don't memory map.
  696. if (mmap_ofs == MetaTable::kMmapFailure)
  697. return 0;
  698. if (mmap_ofs != MetaTable::kMmapSuccess) {
  699. // Continue reading from previous offset.
  700. DCHECK_GE(mmap_ofs, 0);
  701. // GetSqliteVfsFile() returns null for in-memory and temporary databases.
  702. // This is fine, we don't want to enable memory-mapping in those cases
  703. // anyway.
  704. //
  705. // First, memory-mapping is a no-op for in-memory databases.
  706. //
  707. // Second, temporary databases are only used for corruption recovery, which
  708. // occurs in response to I/O errors. An environment with heightened I/O
  709. // errors translates into a higher risk of mmap-induced Chrome crashes.
  710. sqlite3_int64 db_size = 0;
  711. sqlite3_file* file = GetSqliteVfsFile();
  712. if (!file || file->pMethods->xFileSize(file, &db_size) != SQLITE_OK)
  713. return 0;
  714. // Read more of the database looking for errors. The VFS interface is used
  715. // to assure that the reads are valid for SQLite. |g_reads_allowed| is used
  716. // to limit checking to 20MB per run of Chromium.
  717. //
  718. // Read the data left, or |g_reads_allowed|, whichever is smaller.
  719. // |g_reads_allowed| limits the total amount of I/O to spend verifying data
  720. // in a single Chromium run.
  721. sqlite3_int64 amount = db_size - mmap_ofs;
  722. if (amount < 0)
  723. amount = 0;
  724. if (amount > 0) {
  725. static base::NoDestructor<base::Lock> lock;
  726. base::AutoLock auto_lock(*lock);
  727. static sqlite3_int64 g_reads_allowed = 20 * 1024 * 1024;
  728. if (g_reads_allowed < amount)
  729. amount = g_reads_allowed;
  730. g_reads_allowed -= amount;
  731. }
  732. // |amount| can be <= 0 if |g_reads_allowed| ran out of quota, or if the
  733. // database was truncated after a previous pass.
  734. if (amount <= 0 && mmap_ofs < db_size) {
  735. DCHECK_EQ(0, amount);
  736. } else {
  737. static const int kPageSize = 4096;
  738. char buf[kPageSize];
  739. while (amount > 0) {
  740. int rc = file->pMethods->xRead(file, buf, sizeof(buf), mmap_ofs);
  741. if (rc == SQLITE_OK) {
  742. mmap_ofs += sizeof(buf);
  743. amount -= sizeof(buf);
  744. } else if (rc == SQLITE_IOERR_SHORT_READ) {
  745. // Reached EOF for a database with page size < |kPageSize|.
  746. mmap_ofs = db_size;
  747. break;
  748. } else {
  749. // TODO(shess): Consider calling OnSqliteError().
  750. mmap_ofs = MetaTable::kMmapFailure;
  751. break;
  752. }
  753. }
  754. // Log these events after update to distinguish meta update failure.
  755. if (mmap_ofs >= db_size) {
  756. mmap_ofs = MetaTable::kMmapSuccess;
  757. } else {
  758. DCHECK(mmap_ofs > 0 || mmap_ofs == MetaTable::kMmapFailure);
  759. }
  760. if (options_.mmap_alt_status_discouraged) {
  761. if (!SetMmapAltStatus(mmap_ofs))
  762. return 0;
  763. } else {
  764. if (!MetaTable::SetMmapStatus(this, mmap_ofs))
  765. return 0;
  766. }
  767. }
  768. }
  769. if (mmap_ofs == MetaTable::kMmapFailure)
  770. return 0;
  771. if (mmap_ofs == MetaTable::kMmapSuccess)
  772. return kMmapEverything;
  773. return mmap_ofs;
  774. }
  775. int Database::SqlitePrepareFlags() const {
  776. return options_.enable_virtual_tables_discouraged ? 0
  777. : SQLITE_PREPARE_NO_VTAB;
  778. }
  779. sqlite3_file* Database::GetSqliteVfsFile() {
  780. DCHECK(db_) << "Database not opened";
  781. // sqlite3_file_control() accepts a null pointer to mean the "main" database
  782. // attached to a connection. https://www.sqlite.org/c3ref/file_control.html
  783. constexpr const char* kMainDatabaseName = nullptr;
  784. sqlite3_file* result = nullptr;
  785. auto sqlite_result_code = ToSqliteResultCode(sqlite3_file_control(
  786. db_, kMainDatabaseName, SQLITE_FCNTL_FILE_POINTER, &result));
  787. // SQLITE_FCNTL_FILE_POINTER is handled directly by SQLite, not by the VFS. It
  788. // is only supposed to fail with SQLITE_ERROR if the database name is not
  789. // recognized. However, "main" should always be recognized.
  790. DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
  791. << "sqlite3_file_control(SQLITE_FCNTL_FILE_POINTER) failed";
  792. // SQLite does not return null when called on an in-memory or temporary
  793. // database. Instead, it returns returns a VFS file object with a null
  794. // pMethods member.
  795. DCHECK(result)
  796. << "sqlite3_file_control() succeded but returned a null sqlite3_file*";
  797. if (!result->pMethods) {
  798. // If this assumption fails, sql::Database will still function correctly,
  799. // but will miss some configuration optimizations. The DCHECK is here to
  800. // alert us (via test failures and ASAN canary builds) of such cases.
  801. DCHECK_EQ(DbPath().AsUTF8Unsafe(), "")
  802. << "sqlite3_file_control() returned a sqlite3_file* with null pMethods "
  803. << "in a case when it shouldn't have.";
  804. return nullptr;
  805. }
  806. return result;
  807. }
  808. void Database::TrimMemory() {
  809. TRACE_EVENT0("sql", "Database::TrimMemory");
  810. if (!db_)
  811. return;
  812. // Passing the result code through ToSqliteResultCode() to catch issues such
  813. // as SQLITE_MISUSE.
  814. std::ignore = ToSqliteResultCode(sqlite3_db_release_memory(db_));
  815. // It is tempting to use sqlite3_release_memory() here as well. However, the
  816. // API is documented to be a no-op unless SQLite is built with
  817. // SQLITE_ENABLE_MEMORY_MANAGEMENT. We do not use this option, because it is
  818. // incompatible with per-database page cache pools. Behind the scenes,
  819. // SQLITE_ENABLE_MEMORY_MANAGEMENT causes SQLite to use a global page cache
  820. // pool, and sqlite3_release_memory() releases unused pages from this global
  821. // pool.
  822. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
  823. #error "This method assumes SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined"
  824. #endif // defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
  825. }
  826. // Create an in-memory database with the existing database's page
  827. // size, then backup that database over the existing database.
  828. bool Database::Raze() {
  829. TRACE_EVENT0("sql", "Database::Raze");
  830. absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
  831. InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
  832. if (!db_) {
  833. DCHECK(poisoned_) << "Cannot raze null db";
  834. return false;
  835. }
  836. DCHECK_GE(transaction_nesting_, 0);
  837. if (transaction_nesting_ > 0) {
  838. DLOG(DCHECK) << "Cannot raze within a transaction";
  839. return false;
  840. }
  841. sql::Database null_db(sql::DatabaseOptions{
  842. .exclusive_locking = true,
  843. .page_size = options_.page_size,
  844. .cache_size = 0,
  845. .enable_foreign_keys_discouraged =
  846. options_.enable_foreign_keys_discouraged,
  847. .enable_views_discouraged = options_.enable_views_discouraged,
  848. .enable_virtual_tables_discouraged =
  849. options_.enable_virtual_tables_discouraged,
  850. });
  851. if (!null_db.OpenInMemory()) {
  852. DLOG(DCHECK) << "Unable to open in-memory database.";
  853. return false;
  854. }
  855. #if BUILDFLAG(IS_ANDROID)
  856. // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
  857. // in-memory databases do not respect this define.
  858. // TODO(shess): Figure out a way to set this without using platform
  859. // specific code. AFAICT from sqlite3.c, the only way to do it
  860. // would be to create an actual filesystem database, which is
  861. // unfortunate.
  862. if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
  863. return false;
  864. #endif
  865. // The page size doesn't take effect until a database has pages, and
  866. // at this point the null database has none. Changing the schema
  867. // version will create the first page. This will not affect the
  868. // schema version in the resulting database, as SQLite's backup
  869. // implementation propagates the schema version from the original
  870. // database to the new version of the database, incremented by one
  871. // so that other readers see the schema change and act accordingly.
  872. if (!null_db.Execute("PRAGMA schema_version = 1"))
  873. return false;
  874. // SQLite tracks the expected number of database pages in the first
  875. // page, and if it does not match the total retrieved from a
  876. // filesystem call, treats the database as corrupt. This situation
  877. // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
  878. // used to hint to SQLite to soldier on in that case, specifically
  879. // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
  880. // sqlite3.c lockBtree().]
  881. // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
  882. // page_size" can be used to query such a database.
  883. ScopedWritableSchema writable_schema(db_);
  884. #if BUILDFLAG(IS_WIN)
  885. // On Windows, truncate silently fails when applied to memory-mapped files.
  886. // Disable memory-mapping so that the truncate succeeds. Note that other
  887. // Database connections may have memory-mapped the file, so this may not
  888. // entirely prevent the problem.
  889. // [Source: <https://sqlite.org/mmap.html> plus experiments.]
  890. std::ignore = Execute("PRAGMA mmap_size = 0");
  891. #endif
  892. SqliteResultCode sqlite_result_code = BackupDatabaseForRaze(null_db.db_, db_);
  893. // The destination database was locked.
  894. if (sqlite_result_code == SqliteResultCode::kBusy)
  895. return false;
  896. // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
  897. // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
  898. // isn't even big enough for one page. Either way, reach in and
  899. // truncate it before trying again.
  900. // TODO(shess): Maybe it would be worthwhile to just truncate from
  901. // the get-go?
  902. if (sqlite_result_code == SqliteResultCode::kNotADatabase ||
  903. sqlite_result_code == SqliteResultCode::kIoShortRead) {
  904. sqlite3_file* file = GetSqliteVfsFile();
  905. if (!file || file->pMethods->xTruncate(file, 0) != SQLITE_OK) {
  906. DLOG(DCHECK) << "Failed to truncate file.";
  907. return false;
  908. }
  909. sqlite_result_code = BackupDatabaseForRaze(null_db.db_, db_);
  910. if (sqlite_result_code != SqliteResultCode::kDone)
  911. return false;
  912. }
  913. // Page size of |db_| and |null_db| differ.
  914. if (sqlite_result_code == SqliteResultCode::kReadOnly) {
  915. // Enter TRUNCATE mode to change page size.
  916. // TODO(shuagga@microsoft.com): Need a guarantee here that there is no other
  917. // database connection open.
  918. std::ignore = Execute("PRAGMA journal_mode=TRUNCATE;");
  919. const std::string page_size_sql = base::StrCat(
  920. {"PRAGMA page_size=", base::NumberToString(options_.page_size)});
  921. if (!Execute(page_size_sql.c_str())) {
  922. return false;
  923. }
  924. // Page size isn't changed until the database is vacuumed.
  925. std::ignore = Execute("VACUUM");
  926. // Re-enter WAL mode.
  927. if (UseWALMode()) {
  928. std::ignore = Execute("PRAGMA journal_mode=WAL;");
  929. }
  930. sqlite_result_code = BackupDatabaseForRaze(null_db.db_, db_);
  931. if (sqlite_result_code != SqliteResultCode::kDone)
  932. return false;
  933. }
  934. if (sqlite_result_code != SqliteResultCode::kDone) {
  935. NOTIMPLEMENTED() << "Unhandled sqlite3_backup_step() error: "
  936. << sqlite_result_code;
  937. return false;
  938. }
  939. // Checkpoint to propagate transactions to the database file and empty the WAL
  940. // file.
  941. // The database can still contain old data if the Checkpoint fails so fail the
  942. // Raze.
  943. return CheckpointDatabase();
  944. }
  945. bool Database::RazeAndClose() {
  946. TRACE_EVENT0("sql", "Database::RazeAndClose");
  947. if (!db_) {
  948. DCHECK(poisoned_) << "Cannot raze null db";
  949. return false;
  950. }
  951. // Raze() cannot run in a transaction.
  952. RollbackAllTransactions();
  953. bool result = Raze();
  954. CloseInternal(true);
  955. // Mark the database so that future API calls fail appropriately,
  956. // but don't DCHECK (because after calling this function they are
  957. // expected to fail).
  958. poisoned_ = true;
  959. return result;
  960. }
  961. void Database::Poison() {
  962. TRACE_EVENT0("sql", "Database::Poison");
  963. if (!db_) {
  964. DCHECK(poisoned_) << "Cannot poison null db";
  965. return;
  966. }
  967. RollbackAllTransactions();
  968. CloseInternal(true);
  969. // Mark the database so that future API calls fail appropriately,
  970. // but don't DCHECK (because after calling this function they are
  971. // expected to fail).
  972. poisoned_ = true;
  973. }
  974. // TODO(shess): To the extent possible, figure out the optimal
  975. // ordering for these deletes which will prevent other Database connections
  976. // from seeing odd behavior. For instance, it may be necessary to
  977. // manually lock the main database file in a SQLite-compatible fashion
  978. // (to prevent other processes from opening it), then delete the
  979. // journal files, then delete the main database file. Another option
  980. // might be to lock the main database file and poison the header with
  981. // junk to prevent other processes from opening it successfully (like
  982. // Gears "SQLite poison 3" trick).
  983. //
  984. // static
  985. bool Database::Delete(const base::FilePath& path) {
  986. TRACE_EVENT1("sql", "Database::Delete", "path", path.MaybeAsASCII());
  987. base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
  988. base::BlockingType::MAY_BLOCK);
  989. base::FilePath journal_path = Database::JournalPath(path);
  990. base::FilePath wal_path = Database::WriteAheadLogPath(path);
  991. std::string journal_str = AsUTF8ForSQL(journal_path);
  992. std::string wal_str = AsUTF8ForSQL(wal_path);
  993. std::string path_str = AsUTF8ForSQL(path);
  994. EnsureSqliteInitialized();
  995. sqlite3_vfs* vfs = sqlite3_vfs_find(nullptr);
  996. CHECK(vfs);
  997. CHECK(vfs->xDelete);
  998. CHECK(vfs->xAccess);
  999. // We only work with the VFS implementations listed below. If you're trying to
  1000. // use this code with any other VFS, you're not in a good place.
  1001. CHECK(strncmp(vfs->zName, "unix", 4) == 0 ||
  1002. strncmp(vfs->zName, "win32", 5) == 0 ||
  1003. strcmp(vfs->zName, "storage_service") == 0);
  1004. vfs->xDelete(vfs, journal_str.c_str(), 0);
  1005. vfs->xDelete(vfs, wal_str.c_str(), 0);
  1006. vfs->xDelete(vfs, path_str.c_str(), 0);
  1007. int journal_exists = 0;
  1008. vfs->xAccess(vfs, journal_str.c_str(), SQLITE_ACCESS_EXISTS, &journal_exists);
  1009. int wal_exists = 0;
  1010. vfs->xAccess(vfs, wal_str.c_str(), SQLITE_ACCESS_EXISTS, &wal_exists);
  1011. int path_exists = 0;
  1012. vfs->xAccess(vfs, path_str.c_str(), SQLITE_ACCESS_EXISTS, &path_exists);
  1013. return !journal_exists && !wal_exists && !path_exists;
  1014. }
  1015. bool Database::BeginTransaction() {
  1016. TRACE_EVENT0("sql", "Database::BeginTransaction");
  1017. if (needs_rollback_) {
  1018. DCHECK_GT(transaction_nesting_, 0);
  1019. // When we're going to rollback, fail on this begin and don't actually
  1020. // mark us as entering the nested transaction.
  1021. return false;
  1022. }
  1023. bool success = true;
  1024. DCHECK_GE(transaction_nesting_, 0);
  1025. if (!transaction_nesting_) {
  1026. needs_rollback_ = false;
  1027. Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
  1028. if (!begin.Run())
  1029. return false;
  1030. }
  1031. ++transaction_nesting_;
  1032. return success;
  1033. }
  1034. void Database::RollbackTransaction() {
  1035. TRACE_EVENT0("sql", "Database::RollbackTransaction");
  1036. DCHECK_GE(transaction_nesting_, 0);
  1037. if (!transaction_nesting_) {
  1038. DCHECK(poisoned_) << "Rolling back a nonexistent transaction";
  1039. return;
  1040. }
  1041. DCHECK_GT(transaction_nesting_, 0);
  1042. --transaction_nesting_;
  1043. if (transaction_nesting_ > 0) {
  1044. // Mark the outermost transaction as needing rollback.
  1045. needs_rollback_ = true;
  1046. return;
  1047. }
  1048. DoRollback();
  1049. }
  1050. bool Database::CommitTransaction() {
  1051. TRACE_EVENT0("sql", "Database::CommitTransaction");
  1052. DCHECK_GE(transaction_nesting_, 0);
  1053. if (!transaction_nesting_) {
  1054. DCHECK(poisoned_) << "Committing a nonexistent transaction";
  1055. return false;
  1056. }
  1057. DCHECK_GT(transaction_nesting_, 0);
  1058. --transaction_nesting_;
  1059. if (transaction_nesting_ > 0) {
  1060. // Mark any nested transactions as failing after we've already got one.
  1061. return !needs_rollback_;
  1062. }
  1063. if (needs_rollback_) {
  1064. DoRollback();
  1065. return false;
  1066. }
  1067. Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
  1068. bool succeeded = commit.Run();
  1069. // Release dirty cache pages after the transaction closes.
  1070. ReleaseCacheMemoryIfNeeded(false);
  1071. return succeeded;
  1072. }
  1073. void Database::RollbackAllTransactions() {
  1074. TRACE_EVENT0("sql", "Database::RollbackAllTransactions");
  1075. DCHECK_GE(transaction_nesting_, 0);
  1076. if (transaction_nesting_ > 0) {
  1077. transaction_nesting_ = 0;
  1078. DoRollback();
  1079. }
  1080. }
  1081. bool Database::AttachDatabase(const base::FilePath& other_db_path,
  1082. base::StringPiece attachment_point,
  1083. InternalApiToken) {
  1084. TRACE_EVENT0("sql", "Database::AttachDatabase");
  1085. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  1086. DCHECK(ValidAttachmentPoint(attachment_point));
  1087. Statement statement(GetUniqueStatement("ATTACH ? AS ?"));
  1088. #if OS_WIN
  1089. statement.BindString16(0, base::AsStringPiece16(other_db_path.value()));
  1090. #else
  1091. statement.BindString(0, other_db_path.value());
  1092. #endif
  1093. statement.BindString(1, attachment_point);
  1094. return statement.Run();
  1095. }
  1096. bool Database::DetachDatabase(base::StringPiece attachment_point,
  1097. InternalApiToken) {
  1098. TRACE_EVENT0("sql", "Database::DetachDatabase");
  1099. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  1100. DCHECK(ValidAttachmentPoint(attachment_point));
  1101. Statement statement(GetUniqueStatement("DETACH ?"));
  1102. statement.BindString(0, attachment_point);
  1103. return statement.Run();
  1104. }
  1105. // TODO(crbug.com/1230443): Change this to execute exactly one statement.
  1106. SqliteResultCode Database::ExecuteAndReturnResultCode(const char* sql) {
  1107. TRACE_EVENT0("sql", "Database::ExecuteAndReturnErrorCode");
  1108. DCHECK(sql);
  1109. if (!db_) {
  1110. DCHECK(poisoned_) << "Illegal use of Database without a db";
  1111. return SqliteResultCode::kError;
  1112. }
  1113. absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
  1114. InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
  1115. SqliteResultCode sqlite_result_code = SqliteResultCode::kOk;
  1116. while ((sqlite_result_code == SqliteResultCode::kOk) && *sql) {
  1117. sqlite3_stmt* sqlite_statement;
  1118. const char* leftover_sql;
  1119. sqlite_result_code = ToSqliteResultCode(
  1120. sqlite3_prepare_v3(db_, sql, /* nByte= */ -1, SqlitePrepareFlags(),
  1121. &sqlite_statement, &leftover_sql));
  1122. #if DCHECK_IS_ON()
  1123. // Report SQL compilation errors. On developer machines, the errors are most
  1124. // likely caused by invalid SQL in an under-development feature. In
  1125. // production, SQL compilation errors are caused by database schema
  1126. // corruption.
  1127. //
  1128. // DCHECK would not be appropriate here, because on-disk data is always
  1129. // subject to corruption, so Chrome cannot assume that the database schema
  1130. // will remain intact.
  1131. if (sqlite_result_code == SqliteResultCode::kError) {
  1132. DLOG(ERROR) << "SQL compilation error: " << GetErrorMessage()
  1133. << ". Statement: " << sql;
  1134. }
  1135. #endif // DCHECK_IS_ON()
  1136. // Stop if compiling the SQL statement fails.
  1137. if (sqlite_result_code != SqliteResultCode::kOk) {
  1138. DCHECK_NE(sqlite_result_code, SqliteResultCode::kDone)
  1139. << "sqlite3_prepare_v3() returned unexpected non-error result code";
  1140. DCHECK_NE(sqlite_result_code, SqliteResultCode::kRow)
  1141. << "sqlite3_prepare_v3() returned unexpected non-error result code";
  1142. break;
  1143. }
  1144. sql = leftover_sql;
  1145. // This happens if |sql| originally only contained comments or whitespace.
  1146. // TODO(shess): Audit to see if this can become a DCHECK(). Having
  1147. // extraneous comments and whitespace in the SQL statements increases
  1148. // runtime cost and can easily be shifted out to the C++ layer.
  1149. if (!sqlite_statement)
  1150. continue;
  1151. while (true) {
  1152. sqlite_result_code = ToSqliteResultCode(sqlite3_step(sqlite_statement));
  1153. if (sqlite_result_code != SqliteResultCode::kRow)
  1154. break;
  1155. // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA
  1156. // is the only legitimate case for this. Previously recorded histograms
  1157. // show significant use of this code path.
  1158. }
  1159. // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
  1160. // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
  1161. sqlite_result_code = ToSqliteResultCode(sqlite3_finalize(sqlite_statement));
  1162. DCHECK_NE(sqlite_result_code, SqliteResultCode::kDone)
  1163. << "sqlite3_finalize() returned unexpected non-error result code";
  1164. DCHECK_NE(sqlite_result_code, SqliteResultCode::kRow)
  1165. << "sqlite3_finalize() returned unexpected non-error result code";
  1166. // sqlite3_exec() does this, presumably to avoid spinning the parser for
  1167. // trailing whitespace.
  1168. // TODO(shess): Audit to see if this can become a DCHECK.
  1169. while (base::IsAsciiWhitespace(*sql)) {
  1170. sql++;
  1171. }
  1172. }
  1173. // Most calls to Execute() modify the database. The main exceptions would be
  1174. // calls such as CREATE TABLE IF NOT EXISTS which could modify the database
  1175. // but sometimes don't.
  1176. ReleaseCacheMemoryIfNeeded(true);
  1177. DCHECK_NE(sqlite_result_code, SqliteResultCode::kDone)
  1178. << __func__ << " about to return unexpected non-error result code";
  1179. DCHECK_NE(sqlite_result_code, SqliteResultCode::kRow)
  1180. << __func__ << " about to return unexpected non-error result code";
  1181. return sqlite_result_code;
  1182. }
  1183. bool Database::Execute(const char* sql) {
  1184. TRACE_EVENT1("sql", "Database::Execute", "query", TRACE_STR_COPY(sql));
  1185. if (!db_) {
  1186. DCHECK(poisoned_) << "Illegal use of Database without a db";
  1187. return false;
  1188. }
  1189. SqliteResultCode sqlite_result_code = ExecuteAndReturnResultCode(sql);
  1190. if (sqlite_result_code != SqliteResultCode::kOk)
  1191. OnSqliteError(ToSqliteErrorCode(sqlite_result_code), nullptr, sql);
  1192. return sqlite_result_code == SqliteResultCode::kOk;
  1193. }
  1194. bool Database::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
  1195. TRACE_EVENT0("sql", "Database::ExecuteWithTimeout");
  1196. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  1197. if (!db_) {
  1198. DCHECK(poisoned_) << "Illegal use of Database without a db";
  1199. return false;
  1200. }
  1201. ScopedBusyTimeout busy_timeout(db_);
  1202. busy_timeout.SetTimeout(timeout);
  1203. return Execute(sql);
  1204. }
  1205. bool Database::ExecuteScriptForTesting(const char* sql_script) {
  1206. DCHECK(sql_script);
  1207. if (!db_) {
  1208. DCHECK(poisoned_) << "Illegal use of Database without a db";
  1209. return false;
  1210. }
  1211. absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
  1212. InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
  1213. while (*sql_script) {
  1214. sqlite3_stmt* sqlite_statement;
  1215. auto sqlite_result_code = ToSqliteResultCode(
  1216. sqlite3_prepare_v3(db_, sql_script, /*nByte=*/-1, SqlitePrepareFlags(),
  1217. &sqlite_statement, &sql_script));
  1218. if (sqlite_result_code != SqliteResultCode::kOk)
  1219. return false;
  1220. if (!sqlite_statement) {
  1221. // Trailing comment or whitespace after the last semicolon.
  1222. return true;
  1223. }
  1224. // TODO(pwnall): Investigate restricting ExecuteScriptForTesting() to
  1225. // statements that don't produce any result rows.
  1226. do {
  1227. sqlite_result_code = ToSqliteResultCode(sqlite3_step(sqlite_statement));
  1228. } while (sqlite_result_code == SqliteResultCode::kRow);
  1229. // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
  1230. // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
  1231. sqlite_result_code = ToSqliteResultCode(sqlite3_finalize(sqlite_statement));
  1232. if (sqlite_result_code != SqliteResultCode::kOk)
  1233. return false;
  1234. }
  1235. return true;
  1236. }
  1237. scoped_refptr<Database::StatementRef> Database::GetCachedStatement(
  1238. StatementID id,
  1239. const char* sql) {
  1240. auto it = statement_cache_.find(id);
  1241. if (it != statement_cache_.end()) {
  1242. // Statement is in the cache. It should still be valid. We're the only
  1243. // entity invalidating cached statements, and we remove them from the cache
  1244. // when we do that.
  1245. DCHECK(it->second->is_valid());
  1246. DCHECK_EQ(std::string(sqlite3_sql(it->second->stmt())), std::string(sql))
  1247. << "GetCachedStatement used with same ID but different SQL";
  1248. // Reset the statement so it can be reused.
  1249. //
  1250. // ToSqliteResultCode() is called to ensure that sqlite3_reset() doesn't
  1251. // return a concerning code, such as SQLITE_MISUSE. The processed error code
  1252. // is ignored because sqlite3_reset() returns an error code if the last
  1253. // sqlite3_step() failed, and that error was already reported when we ran
  1254. // sqlite3_step(), via Statement::Run() or Statement::Step().
  1255. std::ignore = ToSqliteResultCode(sqlite3_reset(it->second->stmt()));
  1256. return it->second;
  1257. }
  1258. scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
  1259. if (statement->is_valid()) {
  1260. statement_cache_[id] = statement; // Only cache valid statements.
  1261. DCHECK_EQ(std::string(sqlite3_sql(statement->stmt())), std::string(sql))
  1262. << "Input SQL does not match SQLite's normalized version";
  1263. }
  1264. return statement;
  1265. }
  1266. scoped_refptr<Database::StatementRef> Database::GetUniqueStatement(
  1267. const char* sql) {
  1268. return GetStatementImpl(sql, /*is_readonly=*/false);
  1269. }
  1270. scoped_refptr<Database::StatementRef> Database::GetReadonlyStatement(
  1271. const char* sql) {
  1272. return GetStatementImpl(sql, /*is_readonly=*/true);
  1273. }
  1274. scoped_refptr<Database::StatementRef> Database::GetStatementImpl(
  1275. const char* sql,
  1276. bool is_readonly) {
  1277. DCHECK(sql);
  1278. // Return inactive statement.
  1279. if (!db_)
  1280. return base::MakeRefCounted<StatementRef>(nullptr, nullptr, poisoned_);
  1281. absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
  1282. InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
  1283. #if DCHECK_IS_ON()
  1284. const char* unused_sql = nullptr;
  1285. const char** unused_sql_ptr = &unused_sql;
  1286. #else
  1287. constexpr const char** unused_sql_ptr = nullptr;
  1288. #endif // DCHECK_IS_ON()
  1289. // TODO(pwnall): Cached statements (but not unique statements) should be
  1290. // prepared with prepFlags set to SQLITE_PREPARE_PERSISTENT.
  1291. sqlite3_stmt* sqlite_statement;
  1292. auto sqlite_result_code = ToSqliteResultCode(
  1293. sqlite3_prepare_v3(db_, sql, /* nByte= */ -1, SqlitePrepareFlags(),
  1294. &sqlite_statement, unused_sql_ptr));
  1295. #if DCHECK_IS_ON()
  1296. // Report SQL compilation errors. On developer machines, the errors are most
  1297. // likely caused by invalid SQL in an under-development feature. In
  1298. // production, SQL compilation errors are caused by database schema
  1299. // corruption.
  1300. //
  1301. // DCHECK would not be appropriate here, because on-disk data is always
  1302. // subject to corruption, so Chrome cannot assume that the database schema
  1303. // will remain intact.
  1304. if (sqlite_result_code == SqliteResultCode::kError) {
  1305. DLOG(ERROR) << "SQL compilation error: " << GetErrorMessage()
  1306. << ". Statement: " << sql;
  1307. }
  1308. #endif // DCHECK_IS_ON()
  1309. if (sqlite_result_code != SqliteResultCode::kOk) {
  1310. DCHECK_NE(sqlite_result_code, SqliteResultCode::kDone)
  1311. << "sqlite3_prepare_v3() returned unexpected non-error result code";
  1312. DCHECK_NE(sqlite_result_code, SqliteResultCode::kRow)
  1313. << "sqlite3_prepare_v3() returned unexpected non-error result code";
  1314. OnSqliteError(ToSqliteErrorCode(sqlite_result_code), nullptr, sql);
  1315. return base::MakeRefCounted<StatementRef>(nullptr, nullptr, false);
  1316. }
  1317. // If readonly statement is expected and the statement is not readonly, return
  1318. // an invalid statement and close the created statement.
  1319. if (is_readonly && sqlite3_stmt_readonly(sqlite_statement) == 0) {
  1320. DLOG(ERROR) << "Readonly SQL statement failed readonly test " << sql;
  1321. // Make a `StatementRef` that will close the created statement.
  1322. base::MakeRefCounted<StatementRef>(this, sqlite_statement, true);
  1323. return base::MakeRefCounted<StatementRef>(nullptr, nullptr, false);
  1324. }
  1325. #if DCHECK_IS_ON()
  1326. DCHECK_EQ(unused_sql, sql + strlen(sql))
  1327. << "Unused text: " << std::string(unused_sql) << "\n"
  1328. << "in prepared SQL statement: " << std::string(sql);
  1329. #endif // DCHECK_IS_ON()
  1330. DCHECK(sqlite_statement) << "No SQL statement in string: " << sql;
  1331. return base::MakeRefCounted<StatementRef>(this, sqlite_statement, true);
  1332. }
  1333. std::string Database::GetSchema() {
  1334. // The ORDER BY should not be necessary, but relying on organic
  1335. // order for something like this is questionable.
  1336. static const char kSql[] =
  1337. "SELECT type, name, tbl_name, sql "
  1338. "FROM sqlite_schema ORDER BY 1, 2, 3, 4";
  1339. Statement statement(GetUniqueStatement(kSql));
  1340. std::string schema;
  1341. while (statement.Step()) {
  1342. schema += statement.ColumnString(0);
  1343. schema += '|';
  1344. schema += statement.ColumnString(1);
  1345. schema += '|';
  1346. schema += statement.ColumnString(2);
  1347. schema += '|';
  1348. schema += statement.ColumnString(3);
  1349. schema += '\n';
  1350. }
  1351. return schema;
  1352. }
  1353. bool Database::IsSQLValid(const char* sql) {
  1354. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  1355. absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
  1356. InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
  1357. if (!db_) {
  1358. DCHECK(poisoned_) << "Illegal use of Database without a db";
  1359. return false;
  1360. }
  1361. #if DCHECK_IS_ON()
  1362. const char* unused_sql = nullptr;
  1363. const char** unused_sql_ptr = &unused_sql;
  1364. #else
  1365. constexpr const char** unused_sql_ptr = nullptr;
  1366. #endif // DCHECK_IS_ON()
  1367. sqlite3_stmt* sqlite_statement = nullptr;
  1368. auto sqlite_result_code = ToSqliteResultCode(
  1369. sqlite3_prepare_v3(db_, sql, /* nByte= */ -1, SqlitePrepareFlags(),
  1370. &sqlite_statement, unused_sql_ptr));
  1371. if (sqlite_result_code != SqliteResultCode::kOk)
  1372. return false;
  1373. #if DCHECK_IS_ON()
  1374. DCHECK_EQ(unused_sql, sql + strlen(sql))
  1375. << "Unused text: " << std::string(unused_sql) << "\n"
  1376. << "in SQL statement: " << std::string(sql);
  1377. #endif // DCHECK_IS_ON()
  1378. DCHECK(sqlite_statement) << "No SQL statement in string: " << sql;
  1379. sqlite_result_code = ToSqliteResultCode(sqlite3_finalize(sqlite_statement));
  1380. DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
  1381. << "sqlite3_finalize() failed for valid statement";
  1382. return true;
  1383. }
  1384. bool Database::DoesIndexExist(base::StringPiece index_name) {
  1385. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  1386. return DoesSchemaItemExist(index_name, "index");
  1387. }
  1388. bool Database::DoesTableExist(base::StringPiece table_name) {
  1389. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  1390. return DoesSchemaItemExist(table_name, "table");
  1391. }
  1392. bool Database::DoesViewExist(base::StringPiece view_name) {
  1393. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  1394. return DoesSchemaItemExist(view_name, "view");
  1395. }
  1396. bool Database::DoesSchemaItemExist(base::StringPiece name,
  1397. base::StringPiece type) {
  1398. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  1399. static const char kSql[] =
  1400. "SELECT 1 FROM sqlite_schema WHERE type=? AND name=?";
  1401. Statement statement(GetUniqueStatement(kSql));
  1402. if (!statement.is_valid()) {
  1403. // The database is corrupt.
  1404. return false;
  1405. }
  1406. statement.BindString(0, type);
  1407. statement.BindString(1, name);
  1408. return statement.Step(); // Table exists if any row was returned.
  1409. }
  1410. bool Database::DoesColumnExist(const char* table_name,
  1411. const char* column_name) {
  1412. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  1413. // sqlite3_table_column_metadata uses out-params to return column definition
  1414. // details, such as the column type and whether it allows NULL values. These
  1415. // aren't needed to compute the current method's result, so we pass in nullptr
  1416. // for all the out-params.
  1417. auto sqlite_result_code = ToSqliteResultCode(sqlite3_table_column_metadata(
  1418. db_, "main", table_name, column_name, /* pzDataType= */ nullptr,
  1419. /* pzCollSeq= */ nullptr, /* pNotNull= */ nullptr,
  1420. /* pPrimaryKey= */ nullptr, /* pAutoinc= */ nullptr));
  1421. return sqlite_result_code == SqliteResultCode::kOk;
  1422. }
  1423. int64_t Database::GetLastInsertRowId() const {
  1424. if (!db_) {
  1425. DCHECK(poisoned_) << "Illegal use of Database without a db";
  1426. return 0;
  1427. }
  1428. int64_t last_rowid = sqlite3_last_insert_rowid(db_);
  1429. DCHECK(last_rowid != 0) << "No successful INSERT in a table with ROWID";
  1430. return last_rowid;
  1431. }
  1432. int64_t Database::GetLastChangeCount() {
  1433. if (!db_) {
  1434. DCHECK(poisoned_) << "Illegal use of Database without a db";
  1435. return 0;
  1436. }
  1437. return sqlite3_changes64(db_);
  1438. }
  1439. int Database::GetMemoryUsage() {
  1440. if (!db_) {
  1441. DCHECK(poisoned_) << "Illegal use of Database without a db";
  1442. return 0;
  1443. }
  1444. // The following calls all set the high watermark to zero.
  1445. // See https://www.sqlite.org/c3ref/c_dbstatus_options.html
  1446. int high_watermark = 0;
  1447. int cache_memory = 0, schema_memory = 0, statement_memory = 0;
  1448. auto sqlite_result_code = ToSqliteResultCode(sqlite3_db_status(
  1449. db_, SQLITE_DBSTATUS_CACHE_USED, &cache_memory, &high_watermark,
  1450. /*resetFlg=*/0));
  1451. DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
  1452. << "sqlite3_db_status(SQLITE_DBSTATUS_CACHE_USED) failed";
  1453. #if DCHECK_IS_ON()
  1454. int shared_cache_memory = 0;
  1455. sqlite_result_code = ToSqliteResultCode(
  1456. sqlite3_db_status(db_, SQLITE_DBSTATUS_CACHE_USED_SHARED,
  1457. &shared_cache_memory, &high_watermark, /*resetFlg=*/0));
  1458. DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
  1459. << "sqlite3_db_status(SQLITE_DBSTATUS_CACHE_USED_SHARED) failed";
  1460. DCHECK_EQ(shared_cache_memory, cache_memory)
  1461. << "Memory counting assumes that each database uses a private page cache";
  1462. #endif // DCHECK_IS_ON()
  1463. sqlite_result_code = ToSqliteResultCode(sqlite3_db_status(
  1464. db_, SQLITE_DBSTATUS_SCHEMA_USED, &schema_memory, &high_watermark,
  1465. /*resetFlg=*/0));
  1466. DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
  1467. << "sqlite3_db_status(SQLITE_DBSTATUS_SCHEMA_USED) failed";
  1468. sqlite_result_code = ToSqliteResultCode(sqlite3_db_status(
  1469. db_, SQLITE_DBSTATUS_STMT_USED, &statement_memory, &high_watermark,
  1470. /*resetFlg=*/0));
  1471. DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
  1472. << "sqlite3_db_status(SQLITE_DBSTATUS_STMT_USED) failed";
  1473. return cache_memory + schema_memory + statement_memory;
  1474. }
  1475. int Database::GetErrorCode() const {
  1476. if (!db_)
  1477. return SQLITE_ERROR;
  1478. return sqlite3_extended_errcode(db_);
  1479. }
  1480. int Database::GetLastErrno() const {
  1481. if (!db_)
  1482. return -1;
  1483. int err = 0;
  1484. if (SQLITE_OK != sqlite3_file_control(db_, nullptr, SQLITE_LAST_ERRNO, &err))
  1485. return -2;
  1486. return err;
  1487. }
  1488. const char* Database::GetErrorMessage() const {
  1489. if (!db_)
  1490. return "sql::Database is not opened.";
  1491. return sqlite3_errmsg(db_);
  1492. }
  1493. bool Database::OpenInternal(const std::string& db_file_path,
  1494. Database::OpenMode mode) {
  1495. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  1496. TRACE_EVENT1("sql", "Database::OpenInternal", "path", db_file_path);
  1497. DCHECK(mode != OpenMode::kTemporary || db_file_path.empty())
  1498. << "Temporary databases should be open with an empty file path";
  1499. if (mode == OpenMode::kInMemory) {
  1500. DCHECK_EQ(db_file_path, kSqliteOpenInMemoryPath)
  1501. << "In-memory databases should be open with the magic :memory: path";
  1502. } else {
  1503. DCHECK_NE(db_file_path, kSqliteOpenInMemoryPath)
  1504. << "Database file path conflicts with SQLite magic identifier";
  1505. }
  1506. if (db_) {
  1507. DLOG(DCHECK) << "sql::Database is already open.";
  1508. return false;
  1509. }
  1510. absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
  1511. InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
  1512. EnsureSqliteInitialized();
  1513. // If |poisoned_| is set, it means an error handler called
  1514. // RazeAndClose(). Until regular Close() is called, the caller
  1515. // should be treating the database as open, but is_open() currently
  1516. // only considers the sqlite3 handle's state.
  1517. // TODO(shess): Revise is_open() to consider poisoned_, and review
  1518. // to see if any non-testing code even depends on it.
  1519. DCHECK(!poisoned_) << "sql::Database is already open.";
  1520. poisoned_ = false;
  1521. // Custom memory-mapping VFS which reads pages using regular I/O on first hit.
  1522. sqlite3_vfs* vfs = VFSWrapper();
  1523. const char* vfs_name = (vfs ? vfs->zName : nullptr);
  1524. // The flags are documented at https://www.sqlite.org/c3ref/open.html.
  1525. //
  1526. // Chrome uses SQLITE_OPEN_PRIVATECACHE because SQLite is used by many
  1527. // disparate features with their own databases, and having separate page
  1528. // caches makes it easier to reason about each feature's performance in
  1529. // isolation.
  1530. //
  1531. // SQLITE_OPEN_EXRESCODE enables the full range of SQLite error codes. See
  1532. // https://www.sqlite.org/rescode.html for details.
  1533. int open_flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  1534. SQLITE_OPEN_EXRESCODE | SQLITE_OPEN_PRIVATECACHE;
  1535. auto sqlite_result_code = ToSqliteResultCode(
  1536. sqlite3_open_v2(db_file_path.c_str(), &db_, open_flags, vfs_name));
  1537. if (sqlite_result_code != SqliteResultCode::kOk) {
  1538. OnSqliteError(ToSqliteErrorCode(sqlite_result_code), nullptr,
  1539. "-- sqlite3_open_v2()");
  1540. bool was_poisoned = poisoned_;
  1541. Close();
  1542. if (was_poisoned && mode == OpenMode::kRetryOnPoision)
  1543. return OpenInternal(db_file_path, OpenMode::kNone);
  1544. return false;
  1545. }
  1546. ConfigureSqliteDatabaseObject();
  1547. // If indicated, enable shared mode ("NORMAL") on the database, so it can be
  1548. // opened by multiple processes. This needs to happen before WAL mode is
  1549. // enabled.
  1550. //
  1551. // TODO(crbug.com/1120969): Remove support for non-exclusive mode.
  1552. static_assert(
  1553. SQLITE_DEFAULT_LOCKING_MODE == 1,
  1554. "Chrome assumes SQLite is configured to default to EXCLUSIVE locking");
  1555. if (!options_.exclusive_locking) {
  1556. if (!Execute("PRAGMA locking_mode=NORMAL"))
  1557. return false;
  1558. }
  1559. // The sqlite3_open*() methods only perform I/O on the database file if a hot
  1560. // journal is found. Force SQLite to parse the header and database schema, so
  1561. // we can signal irrecoverable corruption early.
  1562. //
  1563. // sqlite3_table_column_metadata() causes SQLite to parse the database schema.
  1564. // Since the schema is stored inside a table B-tree, parsing the schema
  1565. // implies parsing the database header.
  1566. //
  1567. // sqlite3_table_column_metadata() can be used with a null database name, but
  1568. // that will cause it to search for the table in all databases that are
  1569. // ATTACHed to the connection. While Chrome features (almost) never use
  1570. // ATTACHed databases, we prefer to be explicit here.
  1571. //
  1572. // sqlite3_table_column_metadata() can be used with a null column name, and
  1573. // will report on the existence of the table with the given name. This is
  1574. // sufficient for the purpose of getting SQLite to parse the database schema.
  1575. // See https://www.sqlite.org/c3ref/table_column_metadata.html for details.
  1576. static constexpr char kSqliteSchemaTable[] = "sqlite_schema";
  1577. sqlite_result_code = ToSqliteResultCode(sqlite3_table_column_metadata(
  1578. db_, kSqliteMainDatabaseName, kSqliteSchemaTable, /*zColumnName=*/nullptr,
  1579. /*pzDataType=*/nullptr, /*pzCollSeq=*/nullptr, /*pNotNull=*/nullptr,
  1580. /*pPrimaryKey=*/nullptr, /*pAutoinc=*/nullptr));
  1581. if (sqlite_result_code != SqliteResultCode::kOk) {
  1582. OnSqliteError(ToSqliteErrorCode(sqlite_result_code), nullptr,
  1583. "-- sqlite3_table_column_metadata()");
  1584. // Retry or bail out if the error handler poisoned the handle.
  1585. // TODO(shess): Move this handling to one place (see also sqlite3_open).
  1586. // Possibly a wrapper function?
  1587. if (poisoned_) {
  1588. Close();
  1589. if (mode == OpenMode::kRetryOnPoision)
  1590. return OpenInternal(db_file_path, OpenMode::kNone);
  1591. return false;
  1592. }
  1593. }
  1594. const base::TimeDelta kBusyTimeout = base::Seconds(kBusyTimeoutSeconds);
  1595. // Needs to happen before entering WAL mode. Will only work if this the first
  1596. // time the database is being opened in WAL mode.
  1597. const std::string page_size_sql =
  1598. base::StringPrintf("PRAGMA page_size=%d", options_.page_size);
  1599. std::ignore = ExecuteWithTimeout(page_size_sql.c_str(), kBusyTimeout);
  1600. // http://www.sqlite.org/pragma.html#pragma_journal_mode
  1601. // WAL - Use a write-ahead log instead of a journal file.
  1602. // DELETE (default) - delete -journal file to commit.
  1603. // TRUNCATE - truncate -journal file to commit.
  1604. // PERSIST - zero out header of -journal file to commit.
  1605. // TRUNCATE should be faster than DELETE because it won't need directory
  1606. // changes for each transaction. PERSIST may break the spirit of using
  1607. // secure_delete.
  1608. //
  1609. // Needs to be performed after setting exclusive locking mode. Otherwise can
  1610. // fail if underlying VFS doesn't support shared memory.
  1611. if (UseWALMode()) {
  1612. // Set the synchronous flag to NORMAL. This means that writers don't flush
  1613. // the WAL file after every write. The WAL file is only flushed on a
  1614. // checkpoint. In this case, transcations might lose durability on a power
  1615. // loss (but still durable after an application crash).
  1616. // TODO(shuagga@microsoft.com): Evaluate if this loss of durability is a
  1617. // concern.
  1618. std::ignore = Execute("PRAGMA synchronous=NORMAL");
  1619. // Opening the db in WAL mode can fail (eg if the underlying VFS doesn't
  1620. // support shared memory and we are not in exclusive locking mode).
  1621. //
  1622. // TODO(shuagga@microsoft.com): We should probably catch a failure here.
  1623. std::ignore = Execute("PRAGMA journal_mode=WAL");
  1624. } else {
  1625. std::ignore = Execute("PRAGMA journal_mode=TRUNCATE");
  1626. }
  1627. if (options_.flush_to_media)
  1628. std::ignore = Execute("PRAGMA fullfsync=1");
  1629. if (options_.cache_size != 0) {
  1630. const std::string cache_size_sql = base::StrCat(
  1631. {"PRAGMA cache_size=", base::NumberToString(options_.cache_size)});
  1632. std::ignore = ExecuteWithTimeout(cache_size_sql.c_str(), kBusyTimeout);
  1633. }
  1634. static_assert(SQLITE_SECURE_DELETE == 1,
  1635. "Chrome assumes secure_delete is on by default.");
  1636. // When SQLite needs to grow a database file, it uses a configurable
  1637. // increment. Larger values reduce filesystem fragmentation and mmap()
  1638. // churn, as the database file is grown less often. Smaller values waste
  1639. // less disk space.
  1640. //
  1641. // We currently set different values for small vs large files.
  1642. //
  1643. // TODO(crbug.com/1305778): Replace file size-based heuristic with a
  1644. // DatabaseOptions member. Use the DatabaseOptions value for temporary
  1645. // databases as well.
  1646. sqlite3_file* file = GetSqliteVfsFile();
  1647. // GetSqliteVfsFile() returns null for in-memory and temporary databases. This
  1648. // is fine, because these databases start out empty, so the heuristic below
  1649. // would never set a chunk size on them anyway.
  1650. if (file) {
  1651. sqlite3_int64 db_size = 0;
  1652. sqlite_result_code =
  1653. ToSqliteResultCode(file->pMethods->xFileSize(file, &db_size));
  1654. if (sqlite_result_code == SqliteResultCode::kOk && db_size > 16 * 1024) {
  1655. int chunk_size = 4 * 1024;
  1656. if (db_size > 128 * 1024)
  1657. chunk_size = 32 * 1024;
  1658. sqlite3_file_control(db_, /*zDbName=*/nullptr, SQLITE_FCNTL_CHUNK_SIZE,
  1659. &chunk_size);
  1660. }
  1661. }
  1662. size_t mmap_size = mmap_disabled_ ? 0 : ComputeMmapSizeForOpen();
  1663. // We explicitly issue a "PRGAMA mmap_size=0" to disable memory-mapping. We
  1664. // could skip executing the PRAGMA in that case, and use a static_assert to
  1665. // ensure that SQLITE_DEFAULT_MMAP_SIZE > 0. We didn't choose this alternative
  1666. // because would cost us a bit more logic, and the optimization would apply to
  1667. // edge cases, such as in-memory databases. More details at
  1668. // https://www.sqlite.org/pragma.html#pragma_mmap_size.
  1669. std::string pragma_mmap_size_sql =
  1670. base::StrCat({"PRAGMA mmap_size=", base::NumberToString(mmap_size)});
  1671. std::ignore = Execute(pragma_mmap_size_sql.c_str());
  1672. // Determine if memory-mapping has actually been enabled. The Execute() above
  1673. // can succeed without changing the amount mapped.
  1674. mmap_enabled_ = false;
  1675. {
  1676. Statement pragma_mmap_size(GetUniqueStatement("PRAGMA mmap_size"));
  1677. if (pragma_mmap_size.Step() && pragma_mmap_size.ColumnInt64(0) > 0)
  1678. mmap_enabled_ = true;
  1679. }
  1680. DCHECK(!memory_dump_provider_);
  1681. memory_dump_provider_ =
  1682. std::make_unique<DatabaseMemoryDumpProvider>(db_, histogram_tag_);
  1683. base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
  1684. memory_dump_provider_.get(), "sql::Database", /*task_runner=*/nullptr);
  1685. return true;
  1686. }
  1687. void Database::ConfigureSqliteDatabaseObject() {
  1688. // The use of SQLite's non-standard string quoting is not allowed in Chrome.
  1689. //
  1690. // Allowing double-quoted string literals is now considered a misfeature by
  1691. // SQLite authors. See https://www.sqlite.org/quirks.html#dblquote
  1692. auto sqlite_result_code = ToSqliteResultCode(
  1693. sqlite3_db_config(db_, SQLITE_DBCONFIG_DQS_DDL, 0, nullptr));
  1694. DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
  1695. << "sqlite3_db_config(SQLITE_DBCONFIG_DQS_DDL) should not fail";
  1696. sqlite_result_code = ToSqliteResultCode(
  1697. sqlite3_db_config(db_, SQLITE_DBCONFIG_DQS_DML, 0, nullptr));
  1698. DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
  1699. << "sqlite3_db_config(SQLITE_DBCONFIG_DQS_DML) should not fail";
  1700. sqlite_result_code = ToSqliteResultCode(sqlite3_db_config(
  1701. db_, SQLITE_DBCONFIG_ENABLE_FKEY,
  1702. options_.enable_foreign_keys_discouraged ? 1 : 0, nullptr));
  1703. DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
  1704. << "sqlite3_db_config(SQLITE_DBCONFIG_ENABLE_FKEY) should not fail";
  1705. // The use of triggers is discouraged for Chrome code. Thanks to this
  1706. // configuration change, triggers are not executed. CREATE TRIGGER and DROP
  1707. // TRIGGER still succeed.
  1708. sqlite_result_code = ToSqliteResultCode(
  1709. sqlite3_db_config(db_, SQLITE_DBCONFIG_ENABLE_TRIGGER, 0, nullptr));
  1710. DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
  1711. << "sqlite3_db_config() should not fail";
  1712. sqlite_result_code = ToSqliteResultCode(
  1713. sqlite3_db_config(db_, SQLITE_DBCONFIG_ENABLE_VIEW,
  1714. options_.enable_views_discouraged ? 1 : 0, nullptr));
  1715. DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
  1716. << "sqlite3_db_config() should not fail";
  1717. }
  1718. void Database::DoRollback() {
  1719. TRACE_EVENT0("sql", "Database::DoRollback");
  1720. Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
  1721. rollback.Run();
  1722. // The cache may have been accumulating dirty pages for commit. Note that in
  1723. // some cases sql::Transaction can fire rollback after a database is closed.
  1724. if (is_open())
  1725. ReleaseCacheMemoryIfNeeded(false);
  1726. needs_rollback_ = false;
  1727. }
  1728. void Database::StatementRefCreated(StatementRef* ref) {
  1729. DCHECK(!open_statements_.count(ref))
  1730. << __func__ << " already called with this statement";
  1731. open_statements_.insert(ref);
  1732. }
  1733. void Database::StatementRefDeleted(StatementRef* ref) {
  1734. DCHECK(open_statements_.count(ref))
  1735. << __func__ << " called with non-existing statement";
  1736. open_statements_.erase(ref);
  1737. }
  1738. void Database::set_histogram_tag(const std::string& tag) {
  1739. DCHECK(!is_open());
  1740. histogram_tag_ = tag;
  1741. }
  1742. void Database::OnSqliteError(SqliteErrorCode sqlite_error_code,
  1743. sql::Statement* statement,
  1744. const char* sql_statement) {
  1745. TRACE_EVENT0("sql", "Database::OnSqliteError");
  1746. DCHECK_NE(statement != nullptr, sql_statement != nullptr)
  1747. << __func__ << " should either get a Statement or a raw SQL string";
  1748. // Log errors for developers.
  1749. //
  1750. // This block is wrapped around a DCHECK_IS_ON() check so we don't waste CPU
  1751. // cycles computing the strings that make up the log message in production.
  1752. #if DCHECK_IS_ON()
  1753. std::string logged_statement;
  1754. if (statement) {
  1755. logged_statement = statement->GetSQLStatement();
  1756. } else {
  1757. logged_statement = sql_statement;
  1758. }
  1759. std::string database_id = histogram_tag_;
  1760. if (database_id.empty())
  1761. database_id = DbPath().BaseName().AsUTF8Unsafe();
  1762. // This logging block cannot be a DCHECK, because valid usage of sql::Database
  1763. // can still encounter SQLite errors in production. For example, valid SQL
  1764. // statements can fail when a database is corrupted.
  1765. //
  1766. // This logging block should not use LOG(ERROR) because many features built on
  1767. // top of sql::Database can recover from most errors.
  1768. DVLOG(1) << "SQLite error! This may indicate a programming error!\n"
  1769. << "Database: " << database_id
  1770. << " sqlite_error_code: " << sqlite_error_code
  1771. << " errno: " << GetLastErrno()
  1772. << "\nSQLite error description: " << GetErrorMessage()
  1773. << "\nSQL statement: " << logged_statement;
  1774. #endif // DCHECK_IS_ON()
  1775. // Inform the error expecter that we've encountered the error.
  1776. std::ignore = IsExpectedSqliteError(static_cast<int>(sqlite_error_code));
  1777. if (!error_callback_.is_null()) {
  1778. // Create an additional reference to the state in `error_callback_`, so the
  1779. // state doesn't go away if the callback changes `error_callback_` by
  1780. // calling set_error_callback() or reset_error_callback(). This avoids a
  1781. // subtle source of use-after-frees. See https://crbug.com/254584.
  1782. ErrorCallback error_callback_copy = error_callback_;
  1783. error_callback_copy.Run(static_cast<int>(sqlite_error_code), statement);
  1784. return;
  1785. }
  1786. }
  1787. std::string Database::GetDiagnosticInfo(int sqlite_error_code,
  1788. Statement* statement,
  1789. DatabaseDiagnostics* diagnostics) {
  1790. DCHECK_NE(sqlite_error_code, SQLITE_OK)
  1791. << __func__ << " received non-error result code";
  1792. DCHECK_NE(sqlite_error_code, SQLITE_DONE)
  1793. << __func__ << " received non-error result code";
  1794. DCHECK_NE(sqlite_error_code, SQLITE_ROW)
  1795. << __func__ << " received non-error result code";
  1796. // Prevent reentrant calls to the error callback.
  1797. ErrorCallback original_callback = std::move(error_callback_);
  1798. error_callback_.Reset();
  1799. if (diagnostics) {
  1800. diagnostics->reported_sqlite_error_code = sqlite_error_code;
  1801. }
  1802. // Trim extended error codes.
  1803. const int primary_error_code = sqlite_error_code & 0xff;
  1804. // CollectCorruptionInfo() is implemented in terms of sql::Database,
  1805. // TODO(shess): Rewrite IntegrityCheckHelper() in terms of raw SQLite.
  1806. std::string result =
  1807. (primary_error_code == SQLITE_CORRUPT)
  1808. ? CollectCorruptionInfo()
  1809. : CollectErrorInfo(sqlite_error_code, statement, diagnostics);
  1810. // The following queries must be executed after CollectErrorInfo() above, so
  1811. // if they result in their own errors, they don't interfere with
  1812. // CollectErrorInfo().
  1813. const bool has_valid_header = Execute("PRAGMA auto_vacuum");
  1814. const bool has_valid_schema = Execute("SELECT COUNT(*) FROM sqlite_schema");
  1815. // Restore the original error callback.
  1816. error_callback_ = std::move(original_callback);
  1817. base::StringAppendF(&result, "Has valid header: %s\n",
  1818. (has_valid_header ? "Yes" : "No"));
  1819. base::StringAppendF(&result, "Has valid schema: %s\n",
  1820. (has_valid_schema ? "Yes" : "No"));
  1821. if (diagnostics) {
  1822. diagnostics->has_valid_header = has_valid_header;
  1823. diagnostics->has_valid_schema = has_valid_schema;
  1824. }
  1825. return result;
  1826. }
  1827. bool Database::FullIntegrityCheck(std::vector<std::string>* messages) {
  1828. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  1829. messages->clear();
  1830. // The PRAGMA below has the side effect of setting SQLITE_RecoveryMode, which
  1831. // allows SQLite to process through certain cases of corruption.
  1832. if (!Execute("PRAGMA writable_schema=ON")) {
  1833. // The "PRAGMA integrity_check" statement executed below may return less
  1834. // useful information. However, incomplete information is still better than
  1835. // nothing, so we press on.
  1836. messages->push_back("PRAGMA writable_schema=ON failed");
  1837. }
  1838. // We need to bypass sql::Statement and use raw SQLite C API calls here.
  1839. //
  1840. // "PRAGMA integrity_check" reports SQLITE_CORRUPT when the database is
  1841. // corrupt. Reporting SQLITE_CORRUPT is undesirable in this case, because it
  1842. // causes our sql::Statement infrastructure to call the database error
  1843. // handler, which triggers feature-level error handling. However,
  1844. // FullIntegrityCheck() callers presumably already know that the database is
  1845. // corrupted, and are trying to collect diagnostic information for reporting.
  1846. sqlite3_stmt* statement = nullptr;
  1847. // https://www.sqlite.org/c3ref/prepare.html states that SQLite will perform
  1848. // slightly better if sqlite_prepare_v3() receives a zero-terminated statement
  1849. // string, and a statement size that includes the zero byte. Fortunately,
  1850. // C++'s string literal and sizeof() operator do exactly that.
  1851. constexpr char kIntegrityCheckSql[] = "PRAGMA integrity_check";
  1852. const auto prepare_result_code = ToSqliteResultCode(
  1853. sqlite3_prepare_v3(db_, kIntegrityCheckSql, sizeof(kIntegrityCheckSql),
  1854. SqlitePrepareFlags(), &statement, /*pzTail=*/nullptr));
  1855. if (prepare_result_code != SqliteResultCode::kOk)
  1856. return false;
  1857. // "PRAGMA integrity_check" currently returns multiple lines as a single row.
  1858. //
  1859. // However, since https://www.sqlite.org/pragma.html#pragma_integrity_check
  1860. // states that multiple records may be returned, the code below can handle
  1861. // multiple records, each of which has multiple lines.
  1862. std::vector<std::string> result_lines;
  1863. while (ToSqliteResultCode(sqlite3_step(statement)) ==
  1864. SqliteResultCode::kRow) {
  1865. const uint8_t* row = chrome_sqlite3_column_text(statement, /*iCol=*/0);
  1866. DCHECK(row) << "PRAGMA integrity_check should never return NULL rows";
  1867. const int row_size = sqlite3_column_bytes(statement, /*iCol=*/0);
  1868. base::StringPiece row_string(reinterpret_cast<const char*>(row), row_size);
  1869. const std::vector<base::StringPiece> row_lines = base::SplitStringPiece(
  1870. row_string, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
  1871. for (base::StringPiece row_line : row_lines)
  1872. result_lines.emplace_back(row_line);
  1873. }
  1874. const auto finalize_result_code =
  1875. ToSqliteResultCode(sqlite3_finalize(statement));
  1876. // sqlite3_finalize() may return SQLITE_CORRUPT when the integrity check
  1877. // discovers any problems. We still consider this case a success, as long as
  1878. // the statement produced at least one diagnostic message.
  1879. const bool success = (result_lines.size() > 0) ||
  1880. (finalize_result_code == SqliteResultCode::kOk);
  1881. *messages = std::move(result_lines);
  1882. // Best-effort attempt to undo the "PRAGMA writable_schema=ON" executed above.
  1883. std::ignore = Execute("PRAGMA writable_schema=OFF");
  1884. return success;
  1885. }
  1886. bool Database::ReportMemoryUsage(base::trace_event::ProcessMemoryDump* pmd,
  1887. const std::string& dump_name) {
  1888. return memory_dump_provider_ &&
  1889. memory_dump_provider_->ReportMemoryUsage(pmd, dump_name);
  1890. }
  1891. bool Database::UseWALMode() const {
  1892. #if BUILDFLAG(IS_FUCHSIA)
  1893. // WAL mode is only enabled on Fuchsia for databases with exclusive
  1894. // locking, because this case does not require shared memory support.
  1895. // At the time this was implemented (May 2020), Fuchsia's shared
  1896. // memory support was insufficient for SQLite's needs.
  1897. return options_.wal_mode && options_.exclusive_locking;
  1898. #else
  1899. return options_.wal_mode;
  1900. #endif // BUILDFLAG(IS_FUCHSIA)
  1901. }
  1902. bool Database::CheckpointDatabase() {
  1903. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  1904. absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
  1905. InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
  1906. auto sqlite_result_code = ToSqliteResultCode(sqlite3_wal_checkpoint_v2(
  1907. db_, kSqliteMainDatabaseName, SQLITE_CHECKPOINT_PASSIVE,
  1908. /*pnLog=*/nullptr, /*pnCkpt=*/nullptr));
  1909. return sqlite_result_code == SqliteResultCode::kOk;
  1910. }
  1911. } // namespace sql