database_unittest.cc 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081
  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 <stddef.h>
  6. #include <stdint.h>
  7. #include <cstdint>
  8. #include "base/bind.h"
  9. #include "base/callback_helpers.h"
  10. #include "base/files/file_util.h"
  11. #include "base/files/scoped_temp_dir.h"
  12. #include "base/logging.h"
  13. #include "base/memory/raw_ptr.h"
  14. #include "base/sequence_checker.h"
  15. #include "base/strings/string_number_conversions.h"
  16. #include "base/test/bind.h"
  17. #include "base/test/gtest_util.h"
  18. #include "base/test/metrics/histogram_tester.h"
  19. #include "base/thread_annotations.h"
  20. #include "base/trace_event/process_memory_dump.h"
  21. #include "build/build_config.h"
  22. #include "sql/database_memory_dump_provider.h"
  23. #include "sql/meta_table.h"
  24. #include "sql/sql_features.h"
  25. #include "sql/statement.h"
  26. #include "sql/test/database_test_peer.h"
  27. #include "sql/test/scoped_error_expecter.h"
  28. #include "sql/test/test_helpers.h"
  29. #include "sql/transaction.h"
  30. #include "testing/gmock/include/gmock/gmock.h"
  31. #include "testing/gtest/include/gtest/gtest.h"
  32. #include "third_party/sqlite/sqlite3.h"
  33. namespace sql {
  34. namespace {
  35. using sql::test::ExecuteWithResult;
  36. // Helper to return the count of items in sqlite_schema. Return -1 in
  37. // case of error.
  38. int SqliteSchemaCount(Database* db) {
  39. const char* kSchemaCount = "SELECT COUNT(*) FROM sqlite_schema";
  40. Statement s(db->GetUniqueStatement(kSchemaCount));
  41. return s.Step() ? s.ColumnInt(0) : -1;
  42. }
  43. // Handle errors by blowing away the database.
  44. void RazeErrorCallback(Database* db,
  45. int expected_error,
  46. int error,
  47. Statement* stmt) {
  48. // Nothing here needs extended errors at this time.
  49. EXPECT_EQ(expected_error, expected_error & 0xff);
  50. EXPECT_EQ(expected_error, error & 0xff);
  51. db->RazeAndClose();
  52. }
  53. #if BUILDFLAG(IS_POSIX)
  54. // Set a umask and restore the old mask on destruction. Cribbed from
  55. // shared_memory_unittest.cc. Used by POSIX-only UserPermission test.
  56. class ScopedUmaskSetter {
  57. public:
  58. explicit ScopedUmaskSetter(mode_t target_mask) {
  59. old_umask_ = umask(target_mask);
  60. }
  61. ~ScopedUmaskSetter() { umask(old_umask_); }
  62. ScopedUmaskSetter(const ScopedUmaskSetter&) = delete;
  63. ScopedUmaskSetter& operator=(const ScopedUmaskSetter&) = delete;
  64. private:
  65. mode_t old_umask_;
  66. };
  67. #endif // BUILDFLAG(IS_POSIX)
  68. } // namespace
  69. // We use the parameter to run all tests with WAL mode on and off.
  70. class SQLDatabaseTest : public testing::Test,
  71. public testing::WithParamInterface<bool> {
  72. public:
  73. enum class OverwriteType {
  74. kTruncate,
  75. kOverwrite,
  76. };
  77. ~SQLDatabaseTest() override = default;
  78. void SetUp() override {
  79. db_ = std::make_unique<Database>(GetDBOptions());
  80. ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
  81. db_path_ = temp_dir_.GetPath().AppendASCII("database_test.sqlite");
  82. ASSERT_TRUE(db_->Open(db_path_));
  83. }
  84. DatabaseOptions GetDBOptions() {
  85. DatabaseOptions options;
  86. options.wal_mode = IsWALEnabled();
  87. // TODO(crbug.com/1120969): Remove after switching to exclusive mode on by
  88. // default.
  89. options.exclusive_locking = false;
  90. #if BUILDFLAG(IS_FUCHSIA) // Exclusive mode needs to be enabled to enter WAL
  91. // mode on Fuchsia
  92. if (IsWALEnabled()) {
  93. options.exclusive_locking = true;
  94. }
  95. #endif // BUILDFLAG(IS_FUCHSIA)
  96. return options;
  97. }
  98. bool IsWALEnabled() { return GetParam(); }
  99. bool TruncateDatabase() {
  100. base::File file(db_path_,
  101. base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
  102. return file.SetLength(0);
  103. }
  104. bool OverwriteDatabaseHeader(OverwriteType type) {
  105. base::File file(db_path_,
  106. base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
  107. if (type == OverwriteType::kTruncate) {
  108. if (!file.SetLength(0))
  109. return false;
  110. }
  111. static constexpr char kText[] = "Now is the winter of our discontent.";
  112. constexpr int kTextBytes = sizeof(kText) - 1;
  113. return file.Write(0, kText, kTextBytes) == kTextBytes;
  114. }
  115. protected:
  116. base::ScopedTempDir temp_dir_;
  117. base::FilePath db_path_;
  118. std::unique_ptr<Database> db_;
  119. };
  120. TEST_P(SQLDatabaseTest, Execute_ValidStatement) {
  121. ASSERT_TRUE(db_->Execute("CREATE TABLE data(contents TEXT)"));
  122. EXPECT_EQ(SQLITE_OK, db_->GetErrorCode());
  123. }
  124. TEST_P(SQLDatabaseTest, Execute_InvalidStatement) {
  125. {
  126. sql::test::ScopedErrorExpecter error_expecter;
  127. error_expecter.ExpectError(SQLITE_ERROR);
  128. EXPECT_FALSE(db_->Execute("CREATE TABLE data("));
  129. EXPECT_TRUE(error_expecter.SawExpectedErrors());
  130. }
  131. EXPECT_EQ(SQLITE_ERROR, db_->GetErrorCode());
  132. }
  133. TEST_P(SQLDatabaseTest, ExecuteScriptForTesting_OneLineValid) {
  134. ASSERT_TRUE(db_->ExecuteScriptForTesting("CREATE TABLE data(contents TEXT)"));
  135. EXPECT_EQ(SQLITE_OK, db_->GetErrorCode());
  136. }
  137. TEST_P(SQLDatabaseTest, ExecuteScriptForTesting_OneLineInvalid) {
  138. ASSERT_FALSE(db_->ExecuteScriptForTesting("CREATE TABLE data("));
  139. EXPECT_EQ(SQLITE_ERROR, db_->GetErrorCode());
  140. }
  141. TEST_P(SQLDatabaseTest, ExecuteScriptForTesting_ExtraContents) {
  142. EXPECT_TRUE(db_->ExecuteScriptForTesting("CREATE TABLE data1(id)"))
  143. << "Minimal statement";
  144. EXPECT_TRUE(db_->ExecuteScriptForTesting("CREATE TABLE data2(id);"))
  145. << "Extra semicolon";
  146. EXPECT_TRUE(db_->ExecuteScriptForTesting("CREATE TABLE data3(id) -- Comment"))
  147. << "Trailing comment";
  148. EXPECT_TRUE(db_->ExecuteScriptForTesting(
  149. "CREATE TABLE data4(id);CREATE TABLE data5(id)"))
  150. << "Extra statement without whitespace";
  151. EXPECT_TRUE(db_->ExecuteScriptForTesting(
  152. "CREATE TABLE data6(id); CREATE TABLE data7(id)"))
  153. << "Extra statement separated by whitespace";
  154. EXPECT_TRUE(db_->ExecuteScriptForTesting("CREATE TABLE data8(id);-- Comment"))
  155. << "Comment without whitespace";
  156. EXPECT_TRUE(
  157. db_->ExecuteScriptForTesting("CREATE TABLE data9(id); -- Comment"))
  158. << "Comment sepatated by whitespace";
  159. }
  160. TEST_P(SQLDatabaseTest, ExecuteScriptForTesting_MultipleValidLines) {
  161. EXPECT_TRUE(db_->ExecuteScriptForTesting(R"(
  162. CREATE TABLE data1(contents TEXT);
  163. CREATE TABLE data2(contents TEXT);
  164. CREATE TABLE data3(contents TEXT);
  165. )"));
  166. EXPECT_EQ(SQLITE_OK, db_->GetErrorCode());
  167. // DoesColumnExist() is implemented directly on top of a SQLite call. The
  168. // other schema functions use sql::Statement infrastructure to query the
  169. // schema table.
  170. EXPECT_TRUE(db_->DoesColumnExist("data1", "contents"));
  171. EXPECT_TRUE(db_->DoesColumnExist("data2", "contents"));
  172. EXPECT_TRUE(db_->DoesColumnExist("data3", "contents"));
  173. }
  174. TEST_P(SQLDatabaseTest, ExecuteScriptForTesting_StopsOnCompileError) {
  175. EXPECT_FALSE(db_->ExecuteScriptForTesting(R"(
  176. CREATE TABLE data1(contents TEXT);
  177. CREATE TABLE data1();
  178. CREATE TABLE data3(contents TEXT);
  179. )"));
  180. EXPECT_EQ(SQLITE_ERROR, db_->GetErrorCode());
  181. EXPECT_TRUE(db_->DoesColumnExist("data1", "contents"));
  182. EXPECT_FALSE(db_->DoesColumnExist("data3", "contents"));
  183. }
  184. TEST_P(SQLDatabaseTest, ExecuteScriptForTesting_StopsOnStepError) {
  185. EXPECT_FALSE(db_->ExecuteScriptForTesting(R"(
  186. CREATE TABLE data1(contents TEXT UNIQUE);
  187. INSERT INTO data1(contents) VALUES('value1');
  188. INSERT INTO data1(contents) VALUES('value1');
  189. CREATE TABLE data3(contents TEXT);
  190. )"));
  191. EXPECT_EQ(SQLITE_CONSTRAINT_UNIQUE, db_->GetErrorCode());
  192. EXPECT_TRUE(db_->DoesColumnExist("data1", "contents"));
  193. EXPECT_FALSE(db_->DoesColumnExist("data3", "contents"));
  194. }
  195. TEST_P(SQLDatabaseTest, CachedStatement) {
  196. StatementID id1 = SQL_FROM_HERE;
  197. StatementID id2 = SQL_FROM_HERE;
  198. static const char kId1Sql[] = "SELECT a FROM foo";
  199. static const char kId2Sql[] = "SELECT b FROM foo";
  200. ASSERT_TRUE(db_->Execute("CREATE TABLE foo (a, b)"));
  201. ASSERT_TRUE(db_->Execute("INSERT INTO foo(a, b) VALUES (12, 13)"));
  202. sqlite3_stmt* raw_id1_statement;
  203. sqlite3_stmt* raw_id2_statement;
  204. {
  205. scoped_refptr<Database::StatementRef> ref_from_id1 =
  206. db_->GetCachedStatement(id1, kId1Sql);
  207. raw_id1_statement = ref_from_id1->stmt();
  208. Statement from_id1(std::move(ref_from_id1));
  209. ASSERT_TRUE(from_id1.is_valid());
  210. ASSERT_TRUE(from_id1.Step());
  211. EXPECT_EQ(12, from_id1.ColumnInt(0));
  212. scoped_refptr<Database::StatementRef> ref_from_id2 =
  213. db_->GetCachedStatement(id2, kId2Sql);
  214. raw_id2_statement = ref_from_id2->stmt();
  215. EXPECT_NE(raw_id1_statement, raw_id2_statement);
  216. Statement from_id2(std::move(ref_from_id2));
  217. ASSERT_TRUE(from_id2.is_valid());
  218. ASSERT_TRUE(from_id2.Step());
  219. EXPECT_EQ(13, from_id2.ColumnInt(0));
  220. }
  221. {
  222. scoped_refptr<Database::StatementRef> ref_from_id1 =
  223. db_->GetCachedStatement(id1, kId1Sql);
  224. EXPECT_EQ(raw_id1_statement, ref_from_id1->stmt())
  225. << "statement was not cached";
  226. Statement from_id1(std::move(ref_from_id1));
  227. ASSERT_TRUE(from_id1.is_valid());
  228. ASSERT_TRUE(from_id1.Step()) << "cached statement was not reset";
  229. EXPECT_EQ(12, from_id1.ColumnInt(0));
  230. scoped_refptr<Database::StatementRef> ref_from_id2 =
  231. db_->GetCachedStatement(id2, kId2Sql);
  232. EXPECT_EQ(raw_id2_statement, ref_from_id2->stmt())
  233. << "statement was not cached";
  234. Statement from_id2(std::move(ref_from_id2));
  235. ASSERT_TRUE(from_id2.is_valid());
  236. ASSERT_TRUE(from_id2.Step()) << "cached statement was not reset";
  237. EXPECT_EQ(13, from_id2.ColumnInt(0));
  238. }
  239. EXPECT_DCHECK_DEATH(db_->GetCachedStatement(id1, kId2Sql))
  240. << "Using a different SQL with the same statement ID should DCHECK";
  241. EXPECT_DCHECK_DEATH(db_->GetCachedStatement(id2, kId1Sql))
  242. << "Using a different SQL with the same statement ID should DCHECK";
  243. }
  244. TEST_P(SQLDatabaseTest, IsSQLValidTest) {
  245. ASSERT_TRUE(db_->Execute("CREATE TABLE foo (a, b)"));
  246. ASSERT_TRUE(db_->IsSQLValid("SELECT a FROM foo"));
  247. ASSERT_FALSE(db_->IsSQLValid("SELECT no_exist FROM foo"));
  248. }
  249. TEST_P(SQLDatabaseTest, DoesTableExist) {
  250. EXPECT_FALSE(db_->DoesTableExist("foo"));
  251. EXPECT_FALSE(db_->DoesTableExist("foo_index"));
  252. ASSERT_TRUE(db_->Execute("CREATE TABLE foo (a, b)"));
  253. ASSERT_TRUE(db_->Execute("CREATE INDEX foo_index ON foo (a)"));
  254. EXPECT_TRUE(db_->DoesTableExist("foo"));
  255. EXPECT_FALSE(db_->DoesTableExist("foo_index"));
  256. // DoesTableExist() is case-sensitive.
  257. EXPECT_FALSE(db_->DoesTableExist("Foo"));
  258. EXPECT_FALSE(db_->DoesTableExist("FOO"));
  259. }
  260. TEST_P(SQLDatabaseTest, DoesIndexExist) {
  261. ASSERT_TRUE(db_->Execute("CREATE TABLE foo (a, b)"));
  262. EXPECT_FALSE(db_->DoesIndexExist("foo"));
  263. EXPECT_FALSE(db_->DoesIndexExist("foo_ubdex"));
  264. ASSERT_TRUE(db_->Execute("CREATE INDEX foo_index ON foo (a)"));
  265. EXPECT_TRUE(db_->DoesIndexExist("foo_index"));
  266. EXPECT_FALSE(db_->DoesIndexExist("foo"));
  267. // DoesIndexExist() is case-sensitive.
  268. EXPECT_FALSE(db_->DoesIndexExist("Foo_index"));
  269. EXPECT_FALSE(db_->DoesIndexExist("Foo_Index"));
  270. EXPECT_FALSE(db_->DoesIndexExist("FOO_INDEX"));
  271. }
  272. TEST_P(SQLDatabaseTest, DoesViewExist) {
  273. EXPECT_FALSE(db_->DoesViewExist("voo"));
  274. ASSERT_TRUE(db_->Execute("CREATE VIEW voo (a) AS SELECT 1"));
  275. EXPECT_FALSE(db_->DoesIndexExist("voo"));
  276. EXPECT_FALSE(db_->DoesTableExist("voo"));
  277. EXPECT_TRUE(db_->DoesViewExist("voo"));
  278. // DoesTableExist() is case-sensitive.
  279. EXPECT_FALSE(db_->DoesViewExist("Voo"));
  280. EXPECT_FALSE(db_->DoesViewExist("VOO"));
  281. }
  282. TEST_P(SQLDatabaseTest, DoesColumnExist) {
  283. ASSERT_TRUE(db_->Execute("CREATE TABLE foo (a, b)"));
  284. EXPECT_FALSE(db_->DoesColumnExist("foo", "bar"));
  285. EXPECT_TRUE(db_->DoesColumnExist("foo", "a"));
  286. ASSERT_FALSE(db_->DoesTableExist("bar"));
  287. EXPECT_FALSE(db_->DoesColumnExist("bar", "b"));
  288. // SQLite resolves table/column names without case sensitivity.
  289. EXPECT_TRUE(db_->DoesColumnExist("FOO", "A"));
  290. EXPECT_TRUE(db_->DoesColumnExist("FOO", "a"));
  291. EXPECT_TRUE(db_->DoesColumnExist("foo", "A"));
  292. }
  293. TEST_P(SQLDatabaseTest, GetLastInsertRowId) {
  294. ASSERT_TRUE(db_->Execute("CREATE TABLE foo (id INTEGER PRIMARY KEY, value)"));
  295. ASSERT_TRUE(db_->Execute("INSERT INTO foo (value) VALUES (12)"));
  296. // Last insert row ID should be valid.
  297. int64_t row = db_->GetLastInsertRowId();
  298. EXPECT_LT(0, row);
  299. // It should be the primary key of the row we just inserted.
  300. Statement s(db_->GetUniqueStatement("SELECT value FROM foo WHERE id=?"));
  301. s.BindInt64(0, row);
  302. ASSERT_TRUE(s.Step());
  303. EXPECT_EQ(12, s.ColumnInt(0));
  304. }
  305. // Test the scoped error expecter by attempting to insert a duplicate
  306. // value into an index.
  307. TEST_P(SQLDatabaseTest, ScopedErrorExpecter) {
  308. const char* kCreateSql = "CREATE TABLE foo (id INTEGER UNIQUE)";
  309. ASSERT_TRUE(db_->Execute(kCreateSql));
  310. ASSERT_TRUE(db_->Execute("INSERT INTO foo (id) VALUES (12)"));
  311. {
  312. sql::test::ScopedErrorExpecter expecter;
  313. expecter.ExpectError(SQLITE_CONSTRAINT);
  314. ASSERT_FALSE(db_->Execute("INSERT INTO foo (id) VALUES (12)"));
  315. ASSERT_TRUE(expecter.SawExpectedErrors());
  316. }
  317. }
  318. TEST_P(SQLDatabaseTest, SchemaIntrospectionUsesErrorExpecter) {
  319. const char* kCreateSql = "CREATE TABLE foo (id INTEGER UNIQUE)";
  320. ASSERT_TRUE(db_->Execute(kCreateSql));
  321. ASSERT_FALSE(db_->DoesTableExist("bar"));
  322. ASSERT_TRUE(db_->DoesTableExist("foo"));
  323. ASSERT_TRUE(db_->DoesColumnExist("foo", "id"));
  324. db_->Close();
  325. // Corrupt the database so that nothing works, including PRAGMAs.
  326. ASSERT_TRUE(sql::test::CorruptSizeInHeader(db_path_));
  327. {
  328. sql::test::ScopedErrorExpecter expecter;
  329. expecter.ExpectError(SQLITE_CORRUPT);
  330. ASSERT_TRUE(db_->Open(db_path_));
  331. ASSERT_FALSE(db_->DoesTableExist("bar"));
  332. ASSERT_FALSE(db_->DoesTableExist("foo"));
  333. ASSERT_FALSE(db_->DoesColumnExist("foo", "id"));
  334. ASSERT_TRUE(expecter.SawExpectedErrors());
  335. }
  336. }
  337. TEST_P(SQLDatabaseTest, SetErrorCallback) {
  338. static constexpr char kCreateSql[] =
  339. "CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)";
  340. ASSERT_TRUE(db_->Execute(kCreateSql));
  341. ASSERT_TRUE(db_->Execute("INSERT INTO rows(id) VALUES(12)"));
  342. bool error_callback_called = false;
  343. int error = SQLITE_OK;
  344. db_->set_error_callback(base::BindLambdaForTesting(
  345. [&](int sqlite_error, sql::Statement* statement) {
  346. error_callback_called = true;
  347. error = sqlite_error;
  348. }));
  349. EXPECT_FALSE(db_->Execute("INSERT INTO rows(id) VALUES(12)"))
  350. << "Inserting a duplicate primary key should have failed";
  351. EXPECT_TRUE(error_callback_called)
  352. << "Execute() should report errors to the database error callback";
  353. EXPECT_EQ(SQLITE_CONSTRAINT_PRIMARYKEY, error)
  354. << "Execute() should report errors to the database error callback";
  355. }
  356. TEST_P(SQLDatabaseTest, SetErrorCallbackDchecksOnExistingCallback) {
  357. db_->set_error_callback(base::DoNothing());
  358. EXPECT_DCHECK_DEATH(db_->set_error_callback(base::DoNothing()))
  359. << "set_error_callback() should DCHECK if error callback already exists";
  360. }
  361. TEST_P(SQLDatabaseTest, ResetErrorCallback) {
  362. static constexpr char kCreateSql[] =
  363. "CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)";
  364. ASSERT_TRUE(db_->Execute(kCreateSql));
  365. ASSERT_TRUE(db_->Execute("INSERT INTO rows(id) VALUES(12)"));
  366. bool error_callback_called = false;
  367. int error = SQLITE_OK;
  368. db_->set_error_callback(
  369. base::BindLambdaForTesting([&](int sqlite_error, Statement* statement) {
  370. error_callback_called = true;
  371. error = sqlite_error;
  372. }));
  373. db_->reset_error_callback();
  374. {
  375. sql::test::ScopedErrorExpecter expecter;
  376. expecter.ExpectError(SQLITE_CONSTRAINT);
  377. EXPECT_FALSE(db_->Execute("INSERT INTO rows(id) VALUES(12)"))
  378. << "Inserting a duplicate primary key should have failed";
  379. EXPECT_TRUE(expecter.SawExpectedErrors())
  380. << "Inserting a duplicate primary key should have failed";
  381. }
  382. EXPECT_FALSE(error_callback_called)
  383. << "Execute() should not report errors after reset_error_callback()";
  384. EXPECT_EQ(SQLITE_OK, error)
  385. << "Execute() should not report errors after reset_error_callback()";
  386. }
  387. // Sets a flag to true/false to track being alive.
  388. class LifeTracker {
  389. public:
  390. explicit LifeTracker(bool* flag_ptr) : flag_ptr_(flag_ptr) {
  391. DCHECK(flag_ptr != nullptr);
  392. DCHECK(!*flag_ptr)
  393. << "LifeTracker's flag should be set to false prior to construction";
  394. *flag_ptr_ = true;
  395. }
  396. LifeTracker(LifeTracker&& rhs) {
  397. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  398. DCHECK_CALLED_ON_VALID_SEQUENCE(rhs.sequence_checker_);
  399. flag_ptr_ = rhs.flag_ptr_;
  400. rhs.flag_ptr_ = nullptr;
  401. }
  402. // base::RepeatingCallback only requires move-construction support.
  403. LifeTracker& operator=(const LifeTracker& rhs) = delete;
  404. ~LifeTracker() {
  405. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  406. if (flag_ptr_)
  407. *flag_ptr_ = false;
  408. }
  409. private:
  410. SEQUENCE_CHECKER(sequence_checker_);
  411. raw_ptr<bool> flag_ptr_ GUARDED_BY_CONTEXT(sequence_checker_);
  412. };
  413. // base::BindRepeating() can curry arguments to be passed by const reference to
  414. // the callback function. If the error callback function calls
  415. // reset_error_callback() and the Database doesn't hang onto the callback while
  416. // running it, the storage for those arguments may be deleted while the callback
  417. // function is executing. This test ensures that the database is hanging onto
  418. // the callback while running it.
  419. TEST_P(SQLDatabaseTest, ErrorCallbackStorageProtectedWhileRun) {
  420. bool is_alive = false;
  421. db_->set_error_callback(base::BindRepeating(
  422. [](Database* db, bool* life_tracker_is_alive,
  423. const LifeTracker& life_tracker, int sqlite_error,
  424. Statement* statement) {
  425. EXPECT_TRUE(*life_tracker_is_alive)
  426. << "The error callback storage should be alive when it is Run()";
  427. db->reset_error_callback();
  428. EXPECT_TRUE(*life_tracker_is_alive)
  429. << "The error storage should remain alive during Run() after "
  430. << "reset_error_callback()";
  431. },
  432. base::Unretained(db_.get()), base::Unretained(&is_alive),
  433. LifeTracker(&is_alive)));
  434. EXPECT_TRUE(is_alive)
  435. << "The error callback storage should be alive after creation";
  436. EXPECT_FALSE(db_->Execute("INSERT INTO rows(id) VALUES(12)"));
  437. EXPECT_FALSE(is_alive)
  438. << "The error callback storage should be released after Run() completes";
  439. }
  440. TEST_P(SQLDatabaseTest, Execute_CompilationError) {
  441. bool error_callback_called = false;
  442. db_->set_error_callback(base::BindLambdaForTesting([&](int error,
  443. sql::Statement*
  444. statement) {
  445. EXPECT_EQ(SQLITE_ERROR, error);
  446. EXPECT_EQ(nullptr, statement);
  447. EXPECT_FALSE(error_callback_called)
  448. << "SQL compilation errors should call the error callback exactly once";
  449. error_callback_called = true;
  450. }));
  451. {
  452. sql::test::ScopedErrorExpecter expecter;
  453. expecter.ExpectError(SQLITE_ERROR);
  454. EXPECT_FALSE(db_->Execute("SELECT missing_column FROM missing_table"));
  455. EXPECT_TRUE(expecter.SawExpectedErrors());
  456. }
  457. EXPECT_TRUE(error_callback_called)
  458. << "SQL compilation errors should call the error callback";
  459. }
  460. TEST_P(SQLDatabaseTest, GetUniqueStatement_CompilationError) {
  461. bool error_callback_called = false;
  462. db_->set_error_callback(base::BindLambdaForTesting([&](int error,
  463. sql::Statement*
  464. statement) {
  465. EXPECT_EQ(SQLITE_ERROR, error);
  466. EXPECT_EQ(nullptr, statement);
  467. EXPECT_FALSE(error_callback_called)
  468. << "SQL compilation errors should call the error callback exactly once";
  469. error_callback_called = true;
  470. }));
  471. {
  472. sql::test::ScopedErrorExpecter expecter;
  473. expecter.ExpectError(SQLITE_ERROR);
  474. sql::Statement statement(
  475. db_->GetUniqueStatement("SELECT missing_column FROM missing_table"));
  476. EXPECT_FALSE(statement.is_valid());
  477. EXPECT_TRUE(expecter.SawExpectedErrors());
  478. }
  479. EXPECT_TRUE(error_callback_called)
  480. << "SQL compilation errors should call the error callback";
  481. }
  482. TEST_P(SQLDatabaseTest, GetCachedStatement_CompilationError) {
  483. bool error_callback_called = false;
  484. db_->set_error_callback(base::BindLambdaForTesting([&](int error,
  485. sql::Statement*
  486. statement) {
  487. EXPECT_EQ(SQLITE_ERROR, error);
  488. EXPECT_EQ(nullptr, statement);
  489. EXPECT_FALSE(error_callback_called)
  490. << "SQL compilation errors should call the error callback exactly once";
  491. error_callback_called = true;
  492. }));
  493. {
  494. sql::test::ScopedErrorExpecter expecter;
  495. expecter.ExpectError(SQLITE_ERROR);
  496. sql::Statement statement(db_->GetCachedStatement(
  497. SQL_FROM_HERE, "SELECT missing_column FROM missing_table"));
  498. EXPECT_FALSE(statement.is_valid());
  499. EXPECT_TRUE(expecter.SawExpectedErrors());
  500. }
  501. EXPECT_TRUE(error_callback_called)
  502. << "SQL compilation errors should call the error callback";
  503. }
  504. TEST_P(SQLDatabaseTest, GetUniqueStatement_ExtraContents) {
  505. sql::Statement minimal(db_->GetUniqueStatement("SELECT 1"));
  506. sql::Statement extra_semicolon(db_->GetUniqueStatement("SELECT 1;"));
  507. // It would be nice to flag trailing comments too, as they cost binary size.
  508. // However, there's no easy way of doing that.
  509. sql::Statement trailing_comment(
  510. db_->GetUniqueStatement("SELECT 1 -- Comment"));
  511. EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("SELECT 1;SELECT 2"))
  512. << "Extra statement without whitespace";
  513. EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("SELECT 1; SELECT 2"))
  514. << "Extra statement separated by whitespace";
  515. EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("SELECT 1;-- Comment"))
  516. << "Comment without whitespace";
  517. EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("SELECT 1; -- Comment"))
  518. << "Comment separated by whitespace";
  519. }
  520. TEST_P(SQLDatabaseTest, GetCachedStatement_ExtraContents) {
  521. sql::Statement minimal(db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1"));
  522. sql::Statement extra_semicolon(
  523. db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1;"));
  524. // It would be nice to flag trailing comments too, as they cost binary size.
  525. // However, there's no easy way of doing that.
  526. sql::Statement trailing_comment(
  527. db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1 -- Comment"));
  528. EXPECT_DCHECK_DEATH(
  529. db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1;SELECT 2"))
  530. << "Extra statement without whitespace";
  531. EXPECT_DCHECK_DEATH(
  532. db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1; SELECT 2"))
  533. << "Extra statement separated by whitespace";
  534. EXPECT_DCHECK_DEATH(
  535. db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1;-- Comment"))
  536. << "Comment without whitespace";
  537. EXPECT_DCHECK_DEATH(
  538. db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1; -- Comment"))
  539. << "Comment separated by whitespace";
  540. }
  541. TEST_P(SQLDatabaseTest, IsSQLValid_ExtraContents) {
  542. EXPECT_TRUE(db_->IsSQLValid("SELECT 1"));
  543. EXPECT_TRUE(db_->IsSQLValid("SELECT 1;"))
  544. << "Trailing semicolons are currently tolerated";
  545. // It would be nice to flag trailing comments too, as they cost binary size.
  546. // However, there's no easy way of doing that.
  547. EXPECT_TRUE(db_->IsSQLValid("SELECT 1 -- Comment"))
  548. << "Trailing comments are currently tolerated";
  549. EXPECT_DCHECK_DEATH(db_->IsSQLValid("SELECT 1;SELECT 2"))
  550. << "Extra statement without whitespace";
  551. EXPECT_DCHECK_DEATH(db_->IsSQLValid("SELECT 1; SELECT 2"))
  552. << "Extra statement separated by whitespace";
  553. EXPECT_DCHECK_DEATH(db_->IsSQLValid("SELECT 1;-- Comment"))
  554. << "Comment without whitespace";
  555. EXPECT_DCHECK_DEATH(db_->IsSQLValid("SELECT 1; -- Comment"))
  556. << "Comment separated by whitespace";
  557. }
  558. TEST_P(SQLDatabaseTest, GetUniqueStatement_NoContents) {
  559. EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("")) << "Empty string";
  560. EXPECT_DCHECK_DEATH(db_->GetUniqueStatement(" ")) << "Space";
  561. EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("\n")) << "Newline";
  562. EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("-- Comment")) << "Comment";
  563. }
  564. TEST_P(SQLDatabaseTest, GetCachedStatement_NoContents) {
  565. EXPECT_DCHECK_DEATH(db_->GetCachedStatement(SQL_FROM_HERE, ""))
  566. << "Empty string";
  567. EXPECT_DCHECK_DEATH(db_->GetCachedStatement(SQL_FROM_HERE, " ")) << "Space";
  568. EXPECT_DCHECK_DEATH(db_->GetCachedStatement(SQL_FROM_HERE, "\n"))
  569. << "Newline";
  570. EXPECT_DCHECK_DEATH(db_->GetCachedStatement(SQL_FROM_HERE, "-- Comment"))
  571. << "Comment";
  572. }
  573. TEST_P(SQLDatabaseTest, GetReadonlyStatement) {
  574. const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
  575. ASSERT_TRUE(db_->Execute(kCreateSql));
  576. ASSERT_TRUE(db_->Execute("INSERT INTO foo (value) VALUES (12)"));
  577. // PRAGMA statements do not change the database file.
  578. {
  579. Statement s(db_->GetReadonlyStatement("PRAGMA analysis_limit"));
  580. ASSERT_TRUE(s.Step());
  581. }
  582. {
  583. Statement s(db_->GetReadonlyStatement("PRAGMA analysis_limit=100"));
  584. ASSERT_TRUE(s.is_valid());
  585. }
  586. // Create and insert statements should fail, while the same queries as unique
  587. // statement succeeds.
  588. {
  589. Statement s(db_->GetReadonlyStatement(
  590. "CREATE TABLE IF NOT EXISTS foo (id INTEGER PRIMARY KEY, value)"));
  591. ASSERT_FALSE(s.is_valid());
  592. Statement s1(db_->GetUniqueStatement(
  593. "CREATE TABLE IF NOT EXISTS foo (id INTEGER PRIMARY KEY, value)"));
  594. ASSERT_TRUE(s1.is_valid());
  595. }
  596. {
  597. Statement s(
  598. db_->GetReadonlyStatement("INSERT INTO foo (value) VALUES (12)"));
  599. ASSERT_FALSE(s.is_valid());
  600. Statement s1(
  601. db_->GetUniqueStatement("INSERT INTO foo (value) VALUES (12)"));
  602. ASSERT_TRUE(s1.is_valid());
  603. }
  604. {
  605. Statement s(
  606. db_->GetReadonlyStatement("CREATE VIRTUAL TABLE bar USING module"));
  607. ASSERT_FALSE(s.is_valid());
  608. Statement s1(
  609. db_->GetUniqueStatement("CREATE VIRTUAL TABLE bar USING module"));
  610. ASSERT_TRUE(s1.is_valid());
  611. }
  612. // Select statement is successful.
  613. {
  614. Statement s(db_->GetReadonlyStatement("SELECT * FROM foo"));
  615. ASSERT_TRUE(s.Step());
  616. EXPECT_EQ(s.ColumnInt(1), 12);
  617. }
  618. }
  619. TEST_P(SQLDatabaseTest, IsSQLValid_NoContents) {
  620. EXPECT_DCHECK_DEATH(db_->IsSQLValid("")) << "Empty string";
  621. EXPECT_DCHECK_DEATH(db_->IsSQLValid(" ")) << "Space";
  622. EXPECT_DCHECK_DEATH(db_->IsSQLValid("\n")) << "Newline";
  623. EXPECT_DCHECK_DEATH(db_->IsSQLValid("-- Comment")) << "Comment";
  624. }
  625. // Test that Database::Raze() results in a database without the
  626. // tables from the original database.
  627. TEST_P(SQLDatabaseTest, Raze) {
  628. const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
  629. ASSERT_TRUE(db_->Execute(kCreateSql));
  630. ASSERT_TRUE(db_->Execute("INSERT INTO foo (value) VALUES (12)"));
  631. int pragma_auto_vacuum = 0;
  632. {
  633. Statement s(db_->GetUniqueStatement("PRAGMA auto_vacuum"));
  634. ASSERT_TRUE(s.Step());
  635. pragma_auto_vacuum = s.ColumnInt(0);
  636. ASSERT_TRUE(pragma_auto_vacuum == 0 || pragma_auto_vacuum == 1);
  637. }
  638. // If auto_vacuum is set, there's an extra page to maintain a freelist.
  639. const int kExpectedPageCount = 2 + pragma_auto_vacuum;
  640. {
  641. Statement s(db_->GetUniqueStatement("PRAGMA page_count"));
  642. ASSERT_TRUE(s.Step());
  643. EXPECT_EQ(kExpectedPageCount, s.ColumnInt(0));
  644. }
  645. {
  646. Statement s(db_->GetUniqueStatement("SELECT * FROM sqlite_schema"));
  647. ASSERT_TRUE(s.Step());
  648. EXPECT_EQ("table", s.ColumnString(0));
  649. EXPECT_EQ("foo", s.ColumnString(1));
  650. EXPECT_EQ("foo", s.ColumnString(2));
  651. // Table "foo" is stored in the last page of the file.
  652. EXPECT_EQ(kExpectedPageCount, s.ColumnInt(3));
  653. EXPECT_EQ(kCreateSql, s.ColumnString(4));
  654. }
  655. ASSERT_TRUE(db_->Raze());
  656. {
  657. Statement s(db_->GetUniqueStatement("PRAGMA page_count"));
  658. ASSERT_TRUE(s.Step());
  659. EXPECT_EQ(1, s.ColumnInt(0));
  660. }
  661. ASSERT_EQ(0, SqliteSchemaCount(db_.get()));
  662. {
  663. Statement s(db_->GetUniqueStatement("PRAGMA auto_vacuum"));
  664. ASSERT_TRUE(s.Step());
  665. // The new database has the same auto_vacuum as a fresh database.
  666. EXPECT_EQ(pragma_auto_vacuum, s.ColumnInt(0));
  667. }
  668. }
  669. TEST_P(SQLDatabaseTest, RazeDuringSelect) {
  670. ASSERT_TRUE(
  671. db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
  672. ASSERT_TRUE(db_->Execute("INSERT INTO rows(id) VALUES(1)"));
  673. ASSERT_TRUE(db_->Execute("INSERT INTO rows(id) VALUES(2)"));
  674. {
  675. // SELECT implicitly creates a transaction while it's executing. This
  676. // implicit transaction will not be caught by Raze()'s checks.
  677. Statement select(db_->GetUniqueStatement("SELECT id FROM rows"));
  678. ASSERT_TRUE(select.Step());
  679. EXPECT_FALSE(db_->Raze()) << "Raze() should fail while SELECT is executing";
  680. }
  681. {
  682. Statement count(db_->GetUniqueStatement("SELECT COUNT(*) FROM rows"));
  683. ASSERT_TRUE(count.Step());
  684. EXPECT_EQ(2, count.ColumnInt(0)) << "Raze() deleted some data";
  685. }
  686. }
  687. // Helper for SQLDatabaseTest.RazePageSize. Creates a fresh db based on
  688. // db_prefix, with the given initial page size, and verifies it against the
  689. // expected size. Then changes to the final page size and razes, verifying that
  690. // the fresh database ends up with the expected final page size.
  691. void TestPageSize(const base::FilePath& db_prefix,
  692. int initial_page_size,
  693. const std::string& expected_initial_page_size,
  694. int final_page_size,
  695. const std::string& expected_final_page_size) {
  696. static const char kCreateSql[] = "CREATE TABLE x (t TEXT)";
  697. static const char kInsertSql1[] = "INSERT INTO x VALUES ('This is a test')";
  698. static const char kInsertSql2[] = "INSERT INTO x VALUES ('That was a test')";
  699. const base::FilePath db_path = db_prefix.InsertBeforeExtensionASCII(
  700. base::NumberToString(initial_page_size));
  701. Database::Delete(db_path);
  702. Database db({.page_size = initial_page_size});
  703. ASSERT_TRUE(db.Open(db_path));
  704. ASSERT_TRUE(db.Execute(kCreateSql));
  705. ASSERT_TRUE(db.Execute(kInsertSql1));
  706. ASSERT_TRUE(db.Execute(kInsertSql2));
  707. ASSERT_EQ(expected_initial_page_size,
  708. ExecuteWithResult(&db, "PRAGMA page_size"));
  709. db.Close();
  710. // Re-open the database while setting a new |options.page_size| in the object.
  711. Database razed_db({.page_size = final_page_size});
  712. ASSERT_TRUE(razed_db.Open(db_path));
  713. // Raze will use the page size set in the connection object, which may not
  714. // match the file's page size.
  715. ASSERT_TRUE(razed_db.Raze());
  716. // SQLite 3.10.2 (at least) has a quirk with the sqlite3_backup() API (used by
  717. // Raze()) which causes the destination database to remember the previous
  718. // page_size, even if the overwriting database changed the page_size. Access
  719. // the actual database to cause the cached value to be updated.
  720. EXPECT_EQ("0",
  721. ExecuteWithResult(&razed_db, "SELECT COUNT(*) FROM sqlite_schema"));
  722. EXPECT_EQ(expected_final_page_size,
  723. ExecuteWithResult(&razed_db, "PRAGMA page_size"));
  724. EXPECT_EQ("1", ExecuteWithResult(&razed_db, "PRAGMA page_count"));
  725. }
  726. // Verify that Recovery maintains the page size, and the virtual table
  727. // works with page sizes other than SQLite's default. Also verify the case
  728. // where the default page size has changed.
  729. TEST_P(SQLDatabaseTest, RazePageSize) {
  730. const std::string default_page_size =
  731. ExecuteWithResult(db_.get(), "PRAGMA page_size");
  732. // Sync uses 32k pages.
  733. EXPECT_NO_FATAL_FAILURE(
  734. TestPageSize(db_path_, 32768, "32768", 32768, "32768"));
  735. // Many clients use 4k pages. This is the SQLite default after 3.12.0.
  736. EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path_, 4096, "4096", 4096, "4096"));
  737. // 1k is the default page size before 3.12.0.
  738. EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path_, 1024, "1024", 1024, "1024"));
  739. EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path_, 2048, "2048", 4096, "4096"));
  740. // Databases with no page size specified should result in the default
  741. // page size. 2k has never been the default page size.
  742. ASSERT_NE("2048", default_page_size);
  743. EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path_, 2048, "2048",
  744. DatabaseOptions::kDefaultPageSize,
  745. default_page_size));
  746. }
  747. // Test that Raze() results are seen in other connections.
  748. TEST_P(SQLDatabaseTest, RazeMultiple) {
  749. const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
  750. ASSERT_TRUE(db_->Execute(kCreateSql));
  751. Database other_db(GetDBOptions());
  752. ASSERT_TRUE(other_db.Open(db_path_));
  753. // Check that the second connection sees the table.
  754. ASSERT_EQ(1, SqliteSchemaCount(&other_db));
  755. ASSERT_TRUE(db_->Raze());
  756. // The second connection sees the updated database.
  757. ASSERT_EQ(0, SqliteSchemaCount(&other_db));
  758. }
  759. TEST_P(SQLDatabaseTest, Raze_OtherConnectionHasWriteLock) {
  760. ASSERT_TRUE(db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY)"));
  761. Database other_db(GetDBOptions());
  762. ASSERT_TRUE(other_db.Open(db_path_));
  763. Transaction other_db_transaction(&other_db);
  764. ASSERT_TRUE(other_db_transaction.Begin());
  765. ASSERT_TRUE(other_db.Execute("INSERT INTO rows(id) VALUES(1)"));
  766. EXPECT_FALSE(db_->Raze())
  767. << "Raze() should fail while another connection has a write lock";
  768. ASSERT_TRUE(other_db_transaction.Commit());
  769. EXPECT_TRUE(db_->Raze())
  770. << "Raze() should succeed after the other connection releases the lock";
  771. }
  772. TEST_P(SQLDatabaseTest, Raze_OtherConnectionHasReadLock) {
  773. ASSERT_TRUE(db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY)"));
  774. ASSERT_TRUE(db_->Execute("INSERT INTO rows(id) VALUES(1)"));
  775. if (IsWALEnabled()) {
  776. // In WAL mode, read transactions in other connections do not block a write
  777. // transaction.
  778. return;
  779. }
  780. Database other_db(GetDBOptions());
  781. ASSERT_TRUE(other_db.Open(db_path_));
  782. Statement select(other_db.GetUniqueStatement("SELECT id FROM rows"));
  783. ASSERT_TRUE(select.Step());
  784. EXPECT_FALSE(db_->Raze())
  785. << "Raze() should fail while another connection has a read lock";
  786. ASSERT_FALSE(select.Step())
  787. << "The SELECT statement should not produce more than one row";
  788. EXPECT_TRUE(db_->Raze())
  789. << "Raze() should succeed after the other connection releases the lock";
  790. }
  791. TEST_P(SQLDatabaseTest, Raze_EmptyDatabaseFile) {
  792. ASSERT_TRUE(
  793. db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
  794. db_->Close();
  795. ASSERT_TRUE(TruncateDatabase());
  796. ASSERT_TRUE(db_->Open(db_path_))
  797. << "Failed to reopen database after truncating";
  798. EXPECT_TRUE(db_->Raze()) << "Raze() failed on an empty file";
  799. EXPECT_TRUE(
  800. db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"))
  801. << "Raze() did not produce a healthy empty database";
  802. }
  803. // Verify that Raze() can handle a file of junk.
  804. // Need exclusive mode off here as there are some subtleties (by design) around
  805. // how the cache is used with it on which causes the test to fail.
  806. TEST_P(SQLDatabaseTest, RazeNOTADB) {
  807. db_->Close();
  808. Database::Delete(db_path_);
  809. ASSERT_FALSE(base::PathExists(db_path_));
  810. ASSERT_TRUE(OverwriteDatabaseHeader(OverwriteType::kTruncate));
  811. ASSERT_TRUE(base::PathExists(db_path_));
  812. // SQLite will successfully open the handle, but fail when running PRAGMA
  813. // statements that access the database.
  814. {
  815. sql::test::ScopedErrorExpecter expecter;
  816. expecter.ExpectError(SQLITE_NOTADB);
  817. EXPECT_TRUE(db_->Open(db_path_));
  818. ASSERT_TRUE(expecter.SawExpectedErrors());
  819. }
  820. EXPECT_TRUE(db_->Raze());
  821. db_->Close();
  822. // Now empty, the open should open an empty database.
  823. EXPECT_TRUE(db_->Open(db_path_));
  824. EXPECT_EQ(0, SqliteSchemaCount(db_.get()));
  825. }
  826. // Verify that Raze() can handle a database overwritten with garbage.
  827. TEST_P(SQLDatabaseTest, RazeNOTADB2) {
  828. const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
  829. ASSERT_TRUE(db_->Execute(kCreateSql));
  830. ASSERT_EQ(1, SqliteSchemaCount(db_.get()));
  831. db_->Close();
  832. ASSERT_TRUE(OverwriteDatabaseHeader(OverwriteType::kOverwrite));
  833. // SQLite will successfully open the handle, but will fail with
  834. // SQLITE_NOTADB on pragma statemenets which attempt to read the
  835. // corrupted header.
  836. {
  837. sql::test::ScopedErrorExpecter expecter;
  838. expecter.ExpectError(SQLITE_NOTADB);
  839. EXPECT_TRUE(db_->Open(db_path_));
  840. ASSERT_TRUE(expecter.SawExpectedErrors());
  841. }
  842. EXPECT_TRUE(db_->Raze());
  843. db_->Close();
  844. // Now empty, the open should succeed with an empty database.
  845. EXPECT_TRUE(db_->Open(db_path_));
  846. EXPECT_EQ(0, SqliteSchemaCount(db_.get()));
  847. }
  848. // Test that a callback from Open() can raze the database. This is
  849. // essential for cases where the Open() can fail entirely, so the
  850. // Raze() cannot happen later. Additionally test that when the
  851. // callback does this during Open(), the open is retried and succeeds.
  852. TEST_P(SQLDatabaseTest, RazeCallbackReopen) {
  853. const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
  854. ASSERT_TRUE(db_->Execute(kCreateSql));
  855. ASSERT_EQ(1, SqliteSchemaCount(db_.get()));
  856. db_->Close();
  857. // Corrupt the database so that nothing works, including PRAGMAs.
  858. ASSERT_TRUE(sql::test::CorruptSizeInHeader(db_path_));
  859. // Open() will succeed, even though the PRAGMA calls within will
  860. // fail with SQLITE_CORRUPT, as will this PRAGMA.
  861. {
  862. sql::test::ScopedErrorExpecter expecter;
  863. expecter.ExpectError(SQLITE_CORRUPT);
  864. ASSERT_TRUE(db_->Open(db_path_));
  865. ASSERT_FALSE(db_->Execute("PRAGMA auto_vacuum"));
  866. db_->Close();
  867. ASSERT_TRUE(expecter.SawExpectedErrors());
  868. }
  869. db_->set_error_callback(
  870. base::BindRepeating(&RazeErrorCallback, db_.get(), SQLITE_CORRUPT));
  871. // When the PRAGMA calls in Open() raise SQLITE_CORRUPT, the error
  872. // callback will call RazeAndClose(). Open() will then fail and be
  873. // retried. The second Open() on the empty database will succeed
  874. // cleanly.
  875. ASSERT_TRUE(db_->Open(db_path_));
  876. ASSERT_TRUE(db_->Execute("PRAGMA auto_vacuum"));
  877. EXPECT_EQ(0, SqliteSchemaCount(db_.get()));
  878. }
  879. TEST_P(SQLDatabaseTest, RazeAndClose_DeletesData) {
  880. ASSERT_TRUE(
  881. db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
  882. ASSERT_TRUE(db_->Execute("INSERT INTO rows(id) VALUES(12)"));
  883. ASSERT_TRUE(db_->RazeAndClose());
  884. // RazeAndClose() actually Poison()s. We need to call Close() in order to
  885. // re-Open(). crbug.com/1311771 tracks renaming RazeAndClose().
  886. db_->Close();
  887. ASSERT_TRUE(db_->Open(db_path_))
  888. << "RazeAndClose() did not produce a healthy database";
  889. EXPECT_TRUE(
  890. db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"))
  891. << "RazeAndClose() did not produce a healthy empty database";
  892. }
  893. TEST_P(SQLDatabaseTest, RazeAndClose_IsOpen) {
  894. ASSERT_TRUE(
  895. db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
  896. ASSERT_TRUE(db_->Execute("INSERT INTO rows(id) VALUES(12)"));
  897. ASSERT_TRUE(db_->RazeAndClose());
  898. EXPECT_FALSE(db_->is_open())
  899. << "RazeAndClose() did not mark the database as closed";
  900. }
  901. TEST_P(SQLDatabaseTest, RazeAndClose_Reopen_NoChanges) {
  902. ASSERT_TRUE(db_->RazeAndClose());
  903. EXPECT_FALSE(
  904. db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"))
  905. << "Execute() should return false after RazeAndClose()";
  906. // RazeAndClose() actually Poison()s. We need to call Close() in order to
  907. // re-Open(). crbug.com/1311771 tracks renaming RazeAndClose().
  908. db_->Close();
  909. ASSERT_TRUE(db_->Open(db_path_))
  910. << "RazeAndClose() did not produce a healthy database";
  911. EXPECT_TRUE(
  912. db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"))
  913. << "Execute() returned false but went through after RazeAndClose()";
  914. }
  915. TEST_P(SQLDatabaseTest, RazeAndClose_OpenTransaction) {
  916. ASSERT_TRUE(
  917. db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
  918. ASSERT_TRUE(db_->Execute("INSERT INTO rows(id) VALUES(12)"));
  919. Transaction transaction(db_.get());
  920. ASSERT_TRUE(transaction.Begin());
  921. ASSERT_TRUE(db_->RazeAndClose());
  922. EXPECT_FALSE(db_->is_open())
  923. << "RazeAndClose() did not mark the database as closed";
  924. EXPECT_FALSE(transaction.Commit())
  925. << "RazeAndClose() did not cancel the transaction";
  926. // RazeAndClose() actually Poison()s. We need to call Close() in order to
  927. // re-Open(). crbug.com/1311771 tracks renaming RazeAndClose().
  928. db_->Close();
  929. ASSERT_TRUE(db_->Open(db_path_));
  930. EXPECT_TRUE(
  931. db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"))
  932. << "RazeAndClose() did not produce a healthy empty database";
  933. }
  934. TEST_P(SQLDatabaseTest, RazeAndClose_Preload_NoCrash) {
  935. db_->Preload();
  936. db_->RazeAndClose();
  937. db_->Preload();
  938. }
  939. TEST_P(SQLDatabaseTest, RazeAndClose_DoesTableExist) {
  940. ASSERT_TRUE(
  941. db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
  942. ASSERT_TRUE(db_->DoesTableExist("rows")) << "Incorrect test setup";
  943. ASSERT_TRUE(db_->RazeAndClose());
  944. EXPECT_FALSE(db_->DoesTableExist("rows"))
  945. << "DoesTableExist() should return false after RazeAndClose()";
  946. }
  947. TEST_P(SQLDatabaseTest, RazeAndClose_IsSQLValid) {
  948. ASSERT_TRUE(db_->IsSQLValid("SELECT 1")) << "Incorrect test setup";
  949. ASSERT_TRUE(db_->RazeAndClose());
  950. EXPECT_FALSE(db_->IsSQLValid("SELECT 1"))
  951. << "IsSQLValid() should return false after RazeAndClose()";
  952. }
  953. TEST_P(SQLDatabaseTest, RazeAndClose_Execute) {
  954. ASSERT_TRUE(db_->Execute("SELECT 1")) << "Incorrect test setup";
  955. ASSERT_TRUE(db_->RazeAndClose());
  956. EXPECT_FALSE(db_->Execute("SELECT 1"))
  957. << "Execute() should return false after RazeAndClose()";
  958. }
  959. TEST_P(SQLDatabaseTest, RazeAndClose_GetUniqueStatement) {
  960. {
  961. Statement select(db_->GetUniqueStatement("SELECT 1"));
  962. ASSERT_TRUE(select.Step()) << "Incorrect test setup";
  963. }
  964. ASSERT_TRUE(db_->RazeAndClose());
  965. {
  966. Statement select(db_->GetUniqueStatement("SELECT 1"));
  967. EXPECT_FALSE(select.Step())
  968. << "GetUniqueStatement() should return an invalid Statement after "
  969. << "RazeAndClose()";
  970. }
  971. }
  972. TEST_P(SQLDatabaseTest, RazeAndClose_GetCachedStatement) {
  973. {
  974. Statement select(db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1"));
  975. ASSERT_TRUE(select.Step()) << "Incorrect test setup";
  976. }
  977. ASSERT_TRUE(db_->RazeAndClose());
  978. {
  979. Statement select(db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1"));
  980. EXPECT_FALSE(select.Step())
  981. << "GetCachedStatement() should return an invalid Statement after "
  982. << "RazeAndClose()";
  983. }
  984. }
  985. TEST_P(SQLDatabaseTest, RazeAndClose_InvalidatesUniqueStatement) {
  986. Statement select(db_->GetUniqueStatement("SELECT 1"));
  987. ASSERT_TRUE(select.is_valid()) << "Incorrect test setup";
  988. ASSERT_TRUE(select.Step()) << "Incorrect test setup";
  989. select.Reset(/*clear_bound_vars=*/true);
  990. ASSERT_TRUE(db_->RazeAndClose());
  991. EXPECT_FALSE(select.is_valid())
  992. << "RazeAndClose() should invalidate live Statements";
  993. EXPECT_FALSE(select.Step())
  994. << "RazeAndClose() should invalidate live Statements";
  995. }
  996. TEST_P(SQLDatabaseTest, RazeAndClose_InvalidatesCachedStatement) {
  997. Statement select(db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1"));
  998. ASSERT_TRUE(select.is_valid()) << "Incorrect test setup";
  999. ASSERT_TRUE(select.Step()) << "Incorrect test setup";
  1000. select.Reset(/*clear_bound_vars=*/true);
  1001. ASSERT_TRUE(db_->RazeAndClose());
  1002. EXPECT_FALSE(select.is_valid())
  1003. << "RazeAndClose() should invalidate live Statements";
  1004. EXPECT_FALSE(select.Step())
  1005. << "RazeAndClose() should invalidate live Statements";
  1006. }
  1007. TEST_P(SQLDatabaseTest, RazeAndClose_TransactionBegin) {
  1008. {
  1009. Transaction transaction(db_.get());
  1010. ASSERT_TRUE(transaction.Begin()) << "Incorrect test setup";
  1011. ASSERT_TRUE(transaction.Commit()) << "Incorrect test setup";
  1012. }
  1013. ASSERT_TRUE(db_->RazeAndClose());
  1014. {
  1015. Transaction transaction(db_.get());
  1016. EXPECT_FALSE(transaction.Begin())
  1017. << "Transaction::Begin() should return false after RazeAndClose()";
  1018. EXPECT_FALSE(transaction.IsActiveForTesting())
  1019. << "RazeAndClose() should block transactions from starting";
  1020. }
  1021. }
  1022. TEST_P(SQLDatabaseTest, Close_IsSQLValid) {
  1023. ASSERT_TRUE(db_->IsSQLValid("SELECT 1")) << "Incorrect test setup";
  1024. db_->Close();
  1025. EXPECT_DCHECK_DEATH_WITH({ std::ignore = db_->IsSQLValid("SELECT 1"); },
  1026. "Illegal use of Database without a db");
  1027. }
  1028. // On Windows, truncate silently fails against a memory-mapped file. One goal
  1029. // of Raze() is to truncate the file to remove blocks which generate I/O errors.
  1030. // Test that Raze() turns off memory mapping so that the file is truncated.
  1031. // [This would not cover the case of multiple connections where one of the other
  1032. // connections is memory-mapped. That is infrequent in Chromium.]
  1033. TEST_P(SQLDatabaseTest, RazeTruncate) {
  1034. // The empty database has 0 or 1 pages. Raze() should leave it with exactly 1
  1035. // page. Not checking directly because auto_vacuum on Android adds a freelist
  1036. // page.
  1037. ASSERT_TRUE(db_->Raze());
  1038. int64_t expected_size;
  1039. ASSERT_TRUE(base::GetFileSize(db_path_, &expected_size));
  1040. ASSERT_GT(expected_size, 0);
  1041. // Cause the database to take a few pages.
  1042. const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
  1043. ASSERT_TRUE(db_->Execute(kCreateSql));
  1044. for (size_t i = 0; i < 24; ++i) {
  1045. ASSERT_TRUE(
  1046. db_->Execute("INSERT INTO foo (value) VALUES (randomblob(1024))"));
  1047. }
  1048. // In WAL mode, writes don't reach the database file until a checkpoint
  1049. // happens.
  1050. ASSERT_TRUE(db_->CheckpointDatabase());
  1051. int64_t db_size;
  1052. ASSERT_TRUE(base::GetFileSize(db_path_, &db_size));
  1053. ASSERT_GT(db_size, expected_size);
  1054. // Make a query covering most of the database file to make sure that the
  1055. // blocks are actually mapped into memory. Empirically, the truncate problem
  1056. // doesn't seem to happen if no blocks are mapped.
  1057. EXPECT_EQ("24576",
  1058. ExecuteWithResult(db_.get(), "SELECT SUM(LENGTH(value)) FROM foo"));
  1059. ASSERT_TRUE(db_->Raze());
  1060. ASSERT_TRUE(base::GetFileSize(db_path_, &db_size));
  1061. ASSERT_EQ(expected_size, db_size);
  1062. }
  1063. #if BUILDFLAG(IS_ANDROID)
  1064. TEST_P(SQLDatabaseTest, SetTempDirForSQL) {
  1065. MetaTable meta_table;
  1066. // Below call needs a temporary directory in sqlite3
  1067. // On Android, it can pass only when the temporary directory is set.
  1068. // Otherwise, sqlite3 doesn't find the correct directory to store
  1069. // temporary files and will report the error 'unable to open
  1070. // database file'.
  1071. ASSERT_TRUE(meta_table.Init(db_.get(), 4, 4));
  1072. }
  1073. #endif // BUILDFLAG(IS_ANDROID)
  1074. TEST_P(SQLDatabaseTest, Delete) {
  1075. EXPECT_TRUE(db_->Execute("CREATE TABLE x (x)"));
  1076. db_->Close();
  1077. base::FilePath journal_path = Database::JournalPath(db_path_);
  1078. base::FilePath wal_path = Database::WriteAheadLogPath(db_path_);
  1079. // Should have both a main database file and a journal file if
  1080. // journal_mode is TRUNCATE. There is no WAL file as it is deleted on Close.
  1081. ASSERT_TRUE(base::PathExists(db_path_));
  1082. if (!IsWALEnabled()) { // TRUNCATE mode
  1083. ASSERT_TRUE(base::PathExists(journal_path));
  1084. }
  1085. Database::Delete(db_path_);
  1086. EXPECT_FALSE(base::PathExists(db_path_));
  1087. EXPECT_FALSE(base::PathExists(journal_path));
  1088. EXPECT_FALSE(base::PathExists(wal_path));
  1089. }
  1090. #if BUILDFLAG(IS_POSIX) // This test operates on POSIX file permissions.
  1091. TEST_P(SQLDatabaseTest, PosixFilePermissions) {
  1092. db_->Close();
  1093. Database::Delete(db_path_);
  1094. ASSERT_FALSE(base::PathExists(db_path_));
  1095. // If the bots all had a restrictive umask setting such that databases are
  1096. // always created with only the owner able to read them, then the code could
  1097. // break without breaking the tests. Temporarily provide a more permissive
  1098. // umask.
  1099. ScopedUmaskSetter permissive_umask(S_IWGRP | S_IWOTH);
  1100. ASSERT_TRUE(db_->Open(db_path_));
  1101. // Cause the journal file to be created. If the default journal_mode is
  1102. // changed back to DELETE, this test will need to be updated.
  1103. EXPECT_TRUE(db_->Execute("CREATE TABLE x (x)"));
  1104. int mode;
  1105. ASSERT_TRUE(base::PathExists(db_path_));
  1106. EXPECT_TRUE(base::GetPosixFilePermissions(db_path_, &mode));
  1107. ASSERT_EQ(mode, 0600);
  1108. if (IsWALEnabled()) { // WAL mode
  1109. // The WAL file is created lazily on first change.
  1110. ASSERT_TRUE(db_->Execute("CREATE TABLE foo (a, b)"));
  1111. base::FilePath wal_path = Database::WriteAheadLogPath(db_path_);
  1112. ASSERT_TRUE(base::PathExists(wal_path));
  1113. EXPECT_TRUE(base::GetPosixFilePermissions(wal_path, &mode));
  1114. ASSERT_EQ(mode, 0600);
  1115. // The shm file doesn't exist in exclusive locking mode.
  1116. if (ExecuteWithResult(db_.get(), "PRAGMA locking_mode") == "normal") {
  1117. base::FilePath shm_path = Database::SharedMemoryFilePath(db_path_);
  1118. ASSERT_TRUE(base::PathExists(shm_path));
  1119. EXPECT_TRUE(base::GetPosixFilePermissions(shm_path, &mode));
  1120. ASSERT_EQ(mode, 0600);
  1121. }
  1122. } else { // Truncate mode
  1123. base::FilePath journal_path = Database::JournalPath(db_path_);
  1124. DLOG(ERROR) << "journal_path: " << journal_path;
  1125. ASSERT_TRUE(base::PathExists(journal_path));
  1126. EXPECT_TRUE(base::GetPosixFilePermissions(journal_path, &mode));
  1127. ASSERT_EQ(mode, 0600);
  1128. }
  1129. }
  1130. #endif // BUILDFLAG(IS_POSIX)
  1131. TEST_P(SQLDatabaseTest, Poison_IsOpen) {
  1132. db_->Poison();
  1133. EXPECT_FALSE(db_->is_open())
  1134. << "Poison() did not mark the database as closed";
  1135. }
  1136. TEST_P(SQLDatabaseTest, Poison_Close_Reopen_NoChanges) {
  1137. db_->Poison();
  1138. EXPECT_FALSE(
  1139. db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"))
  1140. << "Execute() should return false after Poison()";
  1141. db_->Close();
  1142. ASSERT_TRUE(db_->Open(db_path_)) << "Poison() damaged the database";
  1143. EXPECT_TRUE(
  1144. db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"))
  1145. << "Execute() returned false but went through after Poison()";
  1146. }
  1147. TEST_P(SQLDatabaseTest, Poison_Preload_NoCrash) {
  1148. db_->Preload();
  1149. db_->Poison();
  1150. db_->Preload();
  1151. }
  1152. TEST_P(SQLDatabaseTest, Poison_DoesTableExist) {
  1153. ASSERT_TRUE(
  1154. db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
  1155. ASSERT_TRUE(db_->DoesTableExist("rows")) << "Incorrect test setup";
  1156. db_->Poison();
  1157. EXPECT_FALSE(db_->DoesTableExist("rows"))
  1158. << "DoesTableExist() should return false after Poison()";
  1159. }
  1160. TEST_P(SQLDatabaseTest, Poison_IsSQLValid) {
  1161. ASSERT_TRUE(db_->IsSQLValid("SELECT 1")) << "Incorrect test setup";
  1162. db_->Poison();
  1163. EXPECT_FALSE(db_->IsSQLValid("SELECT 1"))
  1164. << "IsSQLValid() should return false after Poison()";
  1165. }
  1166. TEST_P(SQLDatabaseTest, Poison_Execute) {
  1167. ASSERT_TRUE(db_->Execute("SELECT 1")) << "Incorrect test setup";
  1168. db_->Poison();
  1169. EXPECT_FALSE(db_->Execute("SELECT 1"))
  1170. << "Execute() should return false after Poison()";
  1171. }
  1172. TEST_P(SQLDatabaseTest, Poison_GetUniqueStatement) {
  1173. {
  1174. Statement select(db_->GetUniqueStatement("SELECT 1"));
  1175. ASSERT_TRUE(select.Step()) << "Incorrect test setup";
  1176. }
  1177. db_->Poison();
  1178. {
  1179. Statement select(db_->GetUniqueStatement("SELECT 1"));
  1180. EXPECT_FALSE(select.Step())
  1181. << "GetUniqueStatement() should return an invalid Statement after "
  1182. << "Poison()";
  1183. }
  1184. }
  1185. TEST_P(SQLDatabaseTest, Poison_GetCachedStatement) {
  1186. {
  1187. Statement select(db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1"));
  1188. ASSERT_TRUE(select.Step()) << "Incorrect test setup";
  1189. }
  1190. db_->Poison();
  1191. {
  1192. Statement select(db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1"));
  1193. EXPECT_FALSE(select.Step())
  1194. << "GetCachedStatement() should return an invalid Statement after "
  1195. << "Poison()";
  1196. }
  1197. }
  1198. TEST_P(SQLDatabaseTest, Poison_InvalidatesUniqueStatement) {
  1199. Statement select(db_->GetUniqueStatement("SELECT 1"));
  1200. ASSERT_TRUE(select.is_valid()) << "Incorrect test setup";
  1201. ASSERT_TRUE(select.Step()) << "Incorrect test setup";
  1202. select.Reset(/*clear_bound_vars=*/true);
  1203. db_->Poison();
  1204. EXPECT_FALSE(select.is_valid())
  1205. << "Poison() should invalidate live Statements";
  1206. EXPECT_FALSE(select.Step()) << "Poison() should invalidate live Statements";
  1207. }
  1208. TEST_P(SQLDatabaseTest, Poison_InvalidatesCachedStatement) {
  1209. Statement select(db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1"));
  1210. ASSERT_TRUE(select.is_valid()) << "Incorrect test setup";
  1211. ASSERT_TRUE(select.Step()) << "Incorrect test setup";
  1212. select.Reset(/*clear_bound_vars=*/true);
  1213. db_->Poison();
  1214. EXPECT_FALSE(select.is_valid())
  1215. << "Poison() should invalidate live Statements";
  1216. EXPECT_FALSE(select.Step()) << "Poison() should invalidate live Statements";
  1217. }
  1218. TEST_P(SQLDatabaseTest, Poison_TransactionBegin) {
  1219. {
  1220. Transaction transaction(db_.get());
  1221. ASSERT_TRUE(transaction.Begin()) << "Incorrect test setup";
  1222. ASSERT_TRUE(transaction.Commit()) << "Incorrect test setup";
  1223. }
  1224. db_->Poison();
  1225. {
  1226. Transaction transaction(db_.get());
  1227. EXPECT_FALSE(transaction.Begin())
  1228. << "Transaction::Begin() should return false after Poison()";
  1229. EXPECT_FALSE(transaction.IsActiveForTesting())
  1230. << "Poison() should block transactions from starting";
  1231. }
  1232. }
  1233. TEST_P(SQLDatabaseTest, Poison_OpenTransaction) {
  1234. Transaction transaction(db_.get());
  1235. ASSERT_TRUE(transaction.Begin());
  1236. db_->Poison();
  1237. EXPECT_FALSE(transaction.Commit())
  1238. << "Poison() did not cancel the transaction";
  1239. }
  1240. TEST_P(SQLDatabaseTest, AttachDatabase) {
  1241. ASSERT_TRUE(
  1242. db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
  1243. // Create a database to attach to.
  1244. base::FilePath attach_path =
  1245. db_path_.DirName().AppendASCII("attach_database_test.db");
  1246. static constexpr char kAttachmentPoint[] = "other";
  1247. {
  1248. Database other_db;
  1249. ASSERT_TRUE(other_db.Open(attach_path));
  1250. ASSERT_TRUE(
  1251. other_db.Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
  1252. ASSERT_TRUE(other_db.Execute("INSERT INTO rows VALUES(42)"));
  1253. }
  1254. // Cannot see the attached database, yet.
  1255. EXPECT_FALSE(db_->IsSQLValid("SELECT COUNT(*) from other.rows"));
  1256. EXPECT_TRUE(DatabaseTestPeer::AttachDatabase(db_.get(), attach_path,
  1257. kAttachmentPoint));
  1258. EXPECT_TRUE(db_->IsSQLValid("SELECT COUNT(*) from other.rows"));
  1259. // Queries can touch both databases after the ATTACH.
  1260. EXPECT_TRUE(db_->Execute("INSERT INTO rows SELECT id FROM other.rows"));
  1261. {
  1262. Statement select(db_->GetUniqueStatement("SELECT COUNT(*) FROM rows"));
  1263. ASSERT_TRUE(select.Step());
  1264. EXPECT_EQ(1, select.ColumnInt(0));
  1265. }
  1266. EXPECT_TRUE(DatabaseTestPeer::DetachDatabase(db_.get(), kAttachmentPoint));
  1267. EXPECT_FALSE(db_->IsSQLValid("SELECT COUNT(*) from other.rows"));
  1268. }
  1269. TEST_P(SQLDatabaseTest, AttachDatabaseWithOpenTransaction) {
  1270. ASSERT_TRUE(
  1271. db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
  1272. // Create a database to attach to.
  1273. base::FilePath attach_path =
  1274. db_path_.DirName().AppendASCII("attach_database_test.db");
  1275. static constexpr char kAttachmentPoint[] = "other";
  1276. {
  1277. Database other_db;
  1278. ASSERT_TRUE(other_db.Open(attach_path));
  1279. ASSERT_TRUE(
  1280. other_db.Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
  1281. ASSERT_TRUE(other_db.Execute("INSERT INTO rows VALUES(42)"));
  1282. }
  1283. // Cannot see the attached database, yet.
  1284. EXPECT_FALSE(db_->IsSQLValid("SELECT COUNT(*) from other.rows"));
  1285. // Attach succeeds in a transaction.
  1286. Transaction transaction(db_.get());
  1287. EXPECT_TRUE(transaction.Begin());
  1288. EXPECT_TRUE(DatabaseTestPeer::AttachDatabase(db_.get(), attach_path,
  1289. kAttachmentPoint));
  1290. EXPECT_TRUE(db_->IsSQLValid("SELECT COUNT(*) from other.rows"));
  1291. // Queries can touch both databases after the ATTACH.
  1292. EXPECT_TRUE(db_->Execute("INSERT INTO rows SELECT id FROM other.rows"));
  1293. {
  1294. Statement select(db_->GetUniqueStatement("SELECT COUNT(*) FROM rows"));
  1295. ASSERT_TRUE(select.Step());
  1296. EXPECT_EQ(1, select.ColumnInt(0));
  1297. }
  1298. // Detaching the same database fails, database is locked in the transaction.
  1299. {
  1300. sql::test::ScopedErrorExpecter expecter;
  1301. expecter.ExpectError(SQLITE_ERROR);
  1302. EXPECT_FALSE(DatabaseTestPeer::DetachDatabase(db_.get(), kAttachmentPoint));
  1303. ASSERT_TRUE(expecter.SawExpectedErrors());
  1304. }
  1305. EXPECT_TRUE(db_->IsSQLValid("SELECT COUNT(*) from other.rows"));
  1306. // Detach succeeds when the transaction is closed.
  1307. transaction.Rollback();
  1308. EXPECT_TRUE(DatabaseTestPeer::DetachDatabase(db_.get(), kAttachmentPoint));
  1309. EXPECT_FALSE(db_->IsSQLValid("SELECT COUNT(*) from other.rows"));
  1310. }
  1311. TEST_P(SQLDatabaseTest, FullIntegrityCheck) {
  1312. static constexpr char kTableSql[] =
  1313. "CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL, value TEXT NOT NULL)";
  1314. ASSERT_TRUE(db_->Execute(kTableSql));
  1315. ASSERT_TRUE(db_->Execute("CREATE INDEX rows_by_value ON rows(value)"));
  1316. {
  1317. std::vector<std::string> messages;
  1318. EXPECT_TRUE(db_->FullIntegrityCheck(&messages))
  1319. << "FullIntegrityCheck() failed before database was corrupted";
  1320. EXPECT_THAT(messages, testing::ElementsAre("ok"))
  1321. << "FullIntegrityCheck() should report ok before database is corrupted";
  1322. }
  1323. db_->Close();
  1324. ASSERT_TRUE(sql::test::CorruptIndexRootPage(db_path_, "rows_by_value"));
  1325. ASSERT_TRUE(db_->Open(db_path_));
  1326. {
  1327. std::vector<std::string> messages;
  1328. EXPECT_TRUE(db_->FullIntegrityCheck(&messages))
  1329. << "FullIntegrityCheck() failed on corrupted database";
  1330. EXPECT_THAT(messages, testing::Not(testing::ElementsAre("ok")))
  1331. << "FullIntegrityCheck() should not report ok for a corrupted database";
  1332. }
  1333. }
  1334. TEST_P(SQLDatabaseTest, OnMemoryDump) {
  1335. base::trace_event::MemoryDumpArgs args = {
  1336. base::trace_event::MemoryDumpLevelOfDetail::DETAILED};
  1337. base::trace_event::ProcessMemoryDump pmd(args);
  1338. ASSERT_TRUE(db_->memory_dump_provider_->OnMemoryDump(args, &pmd));
  1339. EXPECT_GE(pmd.allocator_dumps().size(), 1u);
  1340. }
  1341. // Test that the functions to collect diagnostic data run to completion, without
  1342. // worrying too much about what they generate (since that will change).
  1343. TEST_P(SQLDatabaseTest, CollectDiagnosticInfo) {
  1344. const std::string corruption_info = db_->CollectCorruptionInfo();
  1345. EXPECT_NE(std::string::npos, corruption_info.find("SQLITE_CORRUPT"));
  1346. EXPECT_NE(std::string::npos, corruption_info.find("integrity_check"));
  1347. // A statement to see in the results.
  1348. const char* kSimpleSql = "SELECT 'mountain'";
  1349. Statement s(db_->GetCachedStatement(SQL_FROM_HERE, kSimpleSql));
  1350. // Error includes the statement.
  1351. {
  1352. DatabaseDiagnostics diagnostics;
  1353. const std::string readonly_info =
  1354. db_->CollectErrorInfo(SQLITE_READONLY, &s, &diagnostics);
  1355. EXPECT_NE(std::string::npos, readonly_info.find(kSimpleSql));
  1356. EXPECT_EQ(diagnostics.sql_statement, kSimpleSql);
  1357. }
  1358. // Some other error doesn't include the statement.
  1359. {
  1360. DatabaseDiagnostics diagnostics;
  1361. const std::string full_info =
  1362. db_->CollectErrorInfo(SQLITE_FULL, nullptr, &diagnostics);
  1363. EXPECT_EQ(std::string::npos, full_info.find(kSimpleSql));
  1364. EXPECT_TRUE(diagnostics.sql_statement.empty());
  1365. }
  1366. // A table to see in the SQLITE_ERROR results.
  1367. EXPECT_TRUE(db_->Execute("CREATE TABLE volcano (x)"));
  1368. // Version info to see in the SQLITE_ERROR results.
  1369. MetaTable meta_table;
  1370. ASSERT_TRUE(meta_table.Init(db_.get(), 4, 4));
  1371. {
  1372. DatabaseDiagnostics diagnostics;
  1373. const std::string error_info =
  1374. db_->CollectErrorInfo(SQLITE_ERROR, &s, &diagnostics);
  1375. EXPECT_NE(std::string::npos, error_info.find(kSimpleSql));
  1376. EXPECT_NE(std::string::npos, error_info.find("volcano"));
  1377. EXPECT_NE(std::string::npos, error_info.find("version: 4"));
  1378. EXPECT_EQ(diagnostics.sql_statement, kSimpleSql);
  1379. EXPECT_EQ(diagnostics.version, 4);
  1380. ASSERT_EQ(diagnostics.schema_sql_rows.size(), 2U);
  1381. EXPECT_EQ(diagnostics.schema_sql_rows[0], "CREATE TABLE volcano (x)");
  1382. EXPECT_EQ(diagnostics.schema_sql_rows[1],
  1383. "CREATE TABLE meta(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY, "
  1384. "value LONGVARCHAR)");
  1385. ASSERT_EQ(diagnostics.schema_other_row_names.size(), 1U);
  1386. EXPECT_EQ(diagnostics.schema_other_row_names[0], "sqlite_autoindex_meta_1");
  1387. }
  1388. }
  1389. // Test that a fresh database has mmap enabled by default, if mmap'ed I/O is
  1390. // enabled by SQLite.
  1391. TEST_P(SQLDatabaseTest, MmapInitiallyEnabled) {
  1392. {
  1393. Statement s(db_->GetUniqueStatement("PRAGMA mmap_size"));
  1394. ASSERT_TRUE(s.Step())
  1395. << "All supported SQLite versions should have mmap support";
  1396. // If mmap I/O is not on, attempt to turn it on. If that succeeds, then
  1397. // Open() should have turned it on. If mmap support is disabled, 0 is
  1398. // returned. If the VFS does not understand SQLITE_FCNTL_MMAP_SIZE (for
  1399. // instance MojoVFS), -1 is returned.
  1400. if (s.ColumnInt(0) <= 0) {
  1401. ASSERT_TRUE(db_->Execute("PRAGMA mmap_size = 1048576"));
  1402. s.Reset(true);
  1403. ASSERT_TRUE(s.Step());
  1404. EXPECT_LE(s.ColumnInt(0), 0);
  1405. }
  1406. }
  1407. // Test that explicit disable prevents mmap'ed I/O.
  1408. db_->Close();
  1409. Database::Delete(db_path_);
  1410. db_->set_mmap_disabled();
  1411. ASSERT_TRUE(db_->Open(db_path_));
  1412. EXPECT_EQ("0", ExecuteWithResult(db_.get(), "PRAGMA mmap_size"));
  1413. }
  1414. // Test whether a fresh database gets mmap enabled when using alternate status
  1415. // storage.
  1416. TEST_P(SQLDatabaseTest, MmapInitiallyEnabledAltStatus) {
  1417. // Re-open fresh database with alt-status flag set.
  1418. db_->Close();
  1419. Database::Delete(db_path_);
  1420. DatabaseOptions options = GetDBOptions();
  1421. options.mmap_alt_status_discouraged = true;
  1422. options.enable_views_discouraged = true;
  1423. db_ = std::make_unique<Database>(options);
  1424. ASSERT_TRUE(db_->Open(db_path_));
  1425. {
  1426. Statement s(db_->GetUniqueStatement("PRAGMA mmap_size"));
  1427. ASSERT_TRUE(s.Step())
  1428. << "All supported SQLite versions should have mmap support";
  1429. // If mmap I/O is not on, attempt to turn it on. If that succeeds, then
  1430. // Open() should have turned it on. If mmap support is disabled, 0 is
  1431. // returned. If the VFS does not understand SQLITE_FCNTL_MMAP_SIZE (for
  1432. // instance MojoVFS), -1 is returned.
  1433. if (s.ColumnInt(0) <= 0) {
  1434. ASSERT_TRUE(db_->Execute("PRAGMA mmap_size = 1048576"));
  1435. s.Reset(true);
  1436. ASSERT_TRUE(s.Step());
  1437. EXPECT_LE(s.ColumnInt(0), 0);
  1438. }
  1439. }
  1440. // Test that explicit disable overrides set_mmap_alt_status().
  1441. db_->Close();
  1442. Database::Delete(db_path_);
  1443. db_->set_mmap_disabled();
  1444. ASSERT_TRUE(db_->Open(db_path_));
  1445. EXPECT_EQ("0", ExecuteWithResult(db_.get(), "PRAGMA mmap_size"));
  1446. }
  1447. TEST_P(SQLDatabaseTest, ComputeMmapSizeForOpen) {
  1448. const size_t kMmapAlot = 25 * 1024 * 1024;
  1449. int64_t mmap_status = MetaTable::kMmapFailure;
  1450. // If there is no meta table (as for a fresh database), assume that everything
  1451. // should be mapped, and the status of the meta table is not affected.
  1452. ASSERT_TRUE(!db_->DoesTableExist("meta"));
  1453. ASSERT_GT(db_->ComputeMmapSizeForOpen(), kMmapAlot);
  1454. ASSERT_TRUE(!db_->DoesTableExist("meta"));
  1455. // When the meta table is first created, it sets up to map everything.
  1456. MetaTable().Init(db_.get(), 1, 1);
  1457. ASSERT_TRUE(db_->DoesTableExist("meta"));
  1458. ASSERT_GT(db_->ComputeMmapSizeForOpen(), kMmapAlot);
  1459. ASSERT_TRUE(MetaTable::GetMmapStatus(db_.get(), &mmap_status));
  1460. ASSERT_EQ(MetaTable::kMmapSuccess, mmap_status);
  1461. // Preload with partial progress of one page. Should map everything.
  1462. ASSERT_TRUE(db_->Execute("REPLACE INTO meta VALUES ('mmap_status', 1)"));
  1463. ASSERT_GT(db_->ComputeMmapSizeForOpen(), kMmapAlot);
  1464. ASSERT_TRUE(MetaTable::GetMmapStatus(db_.get(), &mmap_status));
  1465. ASSERT_EQ(MetaTable::kMmapSuccess, mmap_status);
  1466. // Failure status maps nothing.
  1467. ASSERT_TRUE(db_->Execute("REPLACE INTO meta VALUES ('mmap_status', -2)"));
  1468. ASSERT_EQ(0UL, db_->ComputeMmapSizeForOpen());
  1469. // Re-initializing the meta table does not re-create the key if the table
  1470. // already exists.
  1471. ASSERT_TRUE(db_->Execute("DELETE FROM meta WHERE key = 'mmap_status'"));
  1472. MetaTable().Init(db_.get(), 1, 1);
  1473. ASSERT_EQ(MetaTable::kMmapSuccess, mmap_status);
  1474. ASSERT_TRUE(MetaTable::GetMmapStatus(db_.get(), &mmap_status));
  1475. ASSERT_EQ(0, mmap_status);
  1476. // With no key, map everything and create the key.
  1477. // TODO(shess): This really should be "maps everything after validating it",
  1478. // but that is more complicated to structure.
  1479. ASSERT_GT(db_->ComputeMmapSizeForOpen(), kMmapAlot);
  1480. ASSERT_TRUE(MetaTable::GetMmapStatus(db_.get(), &mmap_status));
  1481. ASSERT_EQ(MetaTable::kMmapSuccess, mmap_status);
  1482. }
  1483. TEST_P(SQLDatabaseTest, ComputeMmapSizeForOpenAltStatus) {
  1484. const size_t kMmapAlot = 25 * 1024 * 1024;
  1485. // At this point, Database still expects a future [meta] table.
  1486. ASSERT_FALSE(db_->DoesTableExist("meta"));
  1487. ASSERT_FALSE(db_->DoesViewExist("MmapStatus"));
  1488. ASSERT_GT(db_->ComputeMmapSizeForOpen(), kMmapAlot);
  1489. ASSERT_FALSE(db_->DoesTableExist("meta"));
  1490. ASSERT_FALSE(db_->DoesViewExist("MmapStatus"));
  1491. // Using alt status, everything should be mapped, with state in the view.
  1492. DatabaseOptions options = GetDBOptions();
  1493. options.mmap_alt_status_discouraged = true;
  1494. options.enable_views_discouraged = true;
  1495. db_ = std::make_unique<Database>(options);
  1496. ASSERT_TRUE(db_->Open(db_path_));
  1497. ASSERT_GT(db_->ComputeMmapSizeForOpen(), kMmapAlot);
  1498. ASSERT_FALSE(db_->DoesTableExist("meta"));
  1499. ASSERT_TRUE(db_->DoesViewExist("MmapStatus"));
  1500. EXPECT_EQ(base::NumberToString(MetaTable::kMmapSuccess),
  1501. ExecuteWithResult(db_.get(), "SELECT * FROM MmapStatus"));
  1502. // Also maps everything when kMmapSuccess is already in the view.
  1503. ASSERT_GT(db_->ComputeMmapSizeForOpen(), kMmapAlot);
  1504. // Preload with partial progress of one page. Should map everything.
  1505. ASSERT_TRUE(db_->Execute("DROP VIEW MmapStatus"));
  1506. ASSERT_TRUE(db_->Execute("CREATE VIEW MmapStatus (value) AS SELECT 1"));
  1507. ASSERT_GT(db_->ComputeMmapSizeForOpen(), kMmapAlot);
  1508. EXPECT_EQ(base::NumberToString(MetaTable::kMmapSuccess),
  1509. ExecuteWithResult(db_.get(), "SELECT * FROM MmapStatus"));
  1510. // Failure status leads to nothing being mapped.
  1511. ASSERT_TRUE(db_->Execute("DROP VIEW MmapStatus"));
  1512. ASSERT_TRUE(db_->Execute("CREATE VIEW MmapStatus (value) AS SELECT -2"));
  1513. ASSERT_EQ(0UL, db_->ComputeMmapSizeForOpen());
  1514. EXPECT_EQ(base::NumberToString(MetaTable::kMmapFailure),
  1515. ExecuteWithResult(db_.get(), "SELECT * FROM MmapStatus"));
  1516. }
  1517. TEST_P(SQLDatabaseTest, GetMemoryUsage) {
  1518. // Databases with mmap enabled may not follow the assumptions below.
  1519. db_->Close();
  1520. db_->set_mmap_disabled();
  1521. ASSERT_TRUE(db_->Open(db_path_));
  1522. int initial_memory = db_->GetMemoryUsage();
  1523. EXPECT_GT(initial_memory, 0)
  1524. << "SQLite should always use some memory for a database";
  1525. ASSERT_TRUE(db_->Execute("CREATE TABLE foo (a, b)"));
  1526. ASSERT_TRUE(db_->Execute("INSERT INTO foo(a, b) VALUES (12, 13)"));
  1527. int post_query_memory = db_->GetMemoryUsage();
  1528. EXPECT_GT(post_query_memory, initial_memory)
  1529. << "Page cache usage should go up after executing queries";
  1530. db_->TrimMemory();
  1531. int post_trim_memory = db_->GetMemoryUsage();
  1532. EXPECT_GT(post_query_memory, post_trim_memory)
  1533. << "Page cache usage should go down after calling TrimMemory()";
  1534. }
  1535. TEST_P(SQLDatabaseTest, DoubleQuotedStringLiteralsDisabledByDefault) {
  1536. ASSERT_TRUE(db_->Execute("CREATE TABLE data(item TEXT NOT NULL);"));
  1537. struct TestCase {
  1538. const char* sql;
  1539. bool is_valid;
  1540. };
  1541. std::vector<TestCase> test_cases = {
  1542. // DML tests.
  1543. {"SELECT item FROM data WHERE item >= 'string literal'", true},
  1544. {"SELECT item FROM data WHERE item >= \"string literal\"", false},
  1545. {"INSERT INTO data(item) VALUES('string literal')", true},
  1546. {"INSERT INTO data(item) VALUES(\"string literal\")", false},
  1547. {"UPDATE data SET item = 'string literal'", true},
  1548. {"UPDATE data SET item = \"string literal\"", false},
  1549. {"DELETE FROM data WHERE item >= 'string literal'", true},
  1550. {"DELETE FROM data WHERE item >= \"string literal\"", false},
  1551. // DDL tests.
  1552. {"CREATE INDEX data_item ON data(item) WHERE item >= 'string literal'",
  1553. true},
  1554. {"CREATE INDEX data_item ON data(item) WHERE item >= \"string literal\"",
  1555. false},
  1556. {"CREATE TABLE data2(item TEXT DEFAULT 'string literal')", true},
  1557. // This should be an invalid DDL statement, due to the double-quoted
  1558. // string literal. However, SQLite currently parses it.
  1559. {"CREATE TABLE data2(item TEXT DEFAULT \"string literal\")", true},
  1560. };
  1561. for (const TestCase& test_case : test_cases) {
  1562. SCOPED_TRACE(test_case.sql);
  1563. EXPECT_EQ(test_case.is_valid, db_->IsSQLValid(test_case.sql));
  1564. }
  1565. }
  1566. TEST_P(SQLDatabaseTest, ForeignKeyEnforcementDisabledByDefault) {
  1567. EXPECT_FALSE(GetDBOptions().enable_foreign_keys_discouraged);
  1568. ASSERT_TRUE(db_->Execute("CREATE TABLE targets(id INTEGER PRIMARY KEY)"));
  1569. // sqlite3_db_config() currently only disables foreign key enforcement. Schema
  1570. // operations on foreign keys are still allowed.
  1571. ASSERT_TRUE(
  1572. db_->Execute("CREATE TABLE refs("
  1573. "id INTEGER PRIMARY KEY,"
  1574. "target_id INTEGER REFERENCES targets(id))"));
  1575. ASSERT_TRUE(db_->Execute("INSERT INTO targets(id) VALUES(42)"));
  1576. ASSERT_TRUE(db_->Execute("INSERT INTO refs(id, target_id) VALUES(42, 42)"));
  1577. EXPECT_TRUE(db_->Execute("DELETE FROM targets WHERE id=42"))
  1578. << "Foreign key enforcement is not disabled";
  1579. }
  1580. TEST_P(SQLDatabaseTest, ForeignKeyEnforcementEnabled) {
  1581. DatabaseOptions options = GetDBOptions();
  1582. options.enable_foreign_keys_discouraged = true;
  1583. db_ = std::make_unique<Database>(options);
  1584. ASSERT_TRUE(db_->Open(db_path_));
  1585. ASSERT_TRUE(db_->Execute("CREATE TABLE targets(id INTEGER PRIMARY KEY)"));
  1586. ASSERT_TRUE(
  1587. db_->Execute("CREATE TABLE refs("
  1588. "id INTEGER PRIMARY KEY,"
  1589. "target_id INTEGER REFERENCES targets(id))"));
  1590. ASSERT_TRUE(db_->Execute("INSERT INTO targets(id) VALUES(42)"));
  1591. ASSERT_TRUE(db_->Execute("INSERT INTO refs(id, target_id) VALUES(42, 42)"));
  1592. {
  1593. sql::test::ScopedErrorExpecter expecter;
  1594. expecter.ExpectError(SQLITE_CONSTRAINT_FOREIGNKEY);
  1595. EXPECT_FALSE(db_->Execute("DELETE FROM targets WHERE id=42"))
  1596. << "Foreign key enforcement is disabled";
  1597. EXPECT_TRUE(expecter.SawExpectedErrors());
  1598. }
  1599. }
  1600. TEST_P(SQLDatabaseTest, TriggersDisabledByDefault) {
  1601. ASSERT_TRUE(db_->Execute("CREATE TABLE data(id INTEGER)"));
  1602. // sqlite3_db_config() currently only disables running triggers. Schema
  1603. // operations on triggers are still allowed.
  1604. EXPECT_TRUE(
  1605. db_->Execute("CREATE TRIGGER trigger AFTER INSERT ON data "
  1606. "BEGIN DELETE FROM data; END"));
  1607. ASSERT_TRUE(db_->Execute("INSERT INTO data(id) VALUES(42)"));
  1608. Statement select(db_->GetUniqueStatement("SELECT id FROM data"));
  1609. EXPECT_TRUE(select.Step())
  1610. << "If the trigger did not run, the table should not be empty.";
  1611. EXPECT_EQ(42, select.ColumnInt64(0));
  1612. // sqlite3_db_config() currently only disables running triggers. Schema
  1613. // operations on triggers are still allowed.
  1614. EXPECT_TRUE(db_->Execute("DROP TRIGGER IF EXISTS trigger"));
  1615. }
  1616. class SQLDatabaseTestExclusiveMode : public testing::Test,
  1617. public testing::WithParamInterface<bool> {
  1618. public:
  1619. ~SQLDatabaseTestExclusiveMode() override = default;
  1620. void SetUp() override {
  1621. db_ = std::make_unique<Database>(GetDBOptions());
  1622. ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
  1623. db_path_ = temp_dir_.GetPath().AppendASCII("recovery_test.sqlite");
  1624. ASSERT_TRUE(db_->Open(db_path_));
  1625. }
  1626. DatabaseOptions GetDBOptions() {
  1627. DatabaseOptions options;
  1628. options.wal_mode = IsWALEnabled();
  1629. options.exclusive_locking = true;
  1630. return options;
  1631. }
  1632. bool IsWALEnabled() { return GetParam(); }
  1633. protected:
  1634. base::ScopedTempDir temp_dir_;
  1635. base::FilePath db_path_;
  1636. std::unique_ptr<Database> db_;
  1637. };
  1638. TEST_P(SQLDatabaseTestExclusiveMode, LockingModeExclusive) {
  1639. EXPECT_EQ(ExecuteWithResult(db_.get(), "PRAGMA locking_mode"), "exclusive");
  1640. }
  1641. TEST_P(SQLDatabaseTest, LockingModeNormal) {
  1642. EXPECT_EQ(ExecuteWithResult(db_.get(), "PRAGMA locking_mode"), "normal");
  1643. }
  1644. TEST_P(SQLDatabaseTest, OpenedInCorrectMode) {
  1645. std::string expected_mode = IsWALEnabled() ? "wal" : "truncate";
  1646. EXPECT_EQ(ExecuteWithResult(db_.get(), "PRAGMA journal_mode"), expected_mode);
  1647. }
  1648. TEST_P(SQLDatabaseTest, CheckpointDatabase) {
  1649. if (!IsWALEnabled())
  1650. return;
  1651. base::FilePath wal_path = Database::WriteAheadLogPath(db_path_);
  1652. int64_t wal_size = 0;
  1653. // WAL file initially empty.
  1654. EXPECT_TRUE(base::PathExists(wal_path));
  1655. base::GetFileSize(wal_path, &wal_size);
  1656. EXPECT_EQ(wal_size, 0);
  1657. ASSERT_TRUE(
  1658. db_->Execute("CREATE TABLE foo (id INTEGER UNIQUE, value INTEGER)"));
  1659. ASSERT_TRUE(db_->Execute("INSERT INTO foo VALUES (1, 1)"));
  1660. ASSERT_TRUE(db_->Execute("INSERT INTO foo VALUES (2, 2)"));
  1661. // Writes reach WAL file but not db file.
  1662. base::GetFileSize(wal_path, &wal_size);
  1663. EXPECT_GT(wal_size, 0);
  1664. int64_t db_size = 0;
  1665. base::GetFileSize(db_path_, &db_size);
  1666. EXPECT_EQ(db_size, db_->page_size());
  1667. // Checkpoint database to immediately propagate writes to DB file.
  1668. EXPECT_TRUE(db_->CheckpointDatabase());
  1669. base::GetFileSize(db_path_, &db_size);
  1670. EXPECT_GT(db_size, db_->page_size());
  1671. EXPECT_EQ(ExecuteWithResult(db_.get(), "SELECT value FROM foo where id=1"),
  1672. "1");
  1673. EXPECT_EQ(ExecuteWithResult(db_.get(), "SELECT value FROM foo where id=2"),
  1674. "2");
  1675. }
  1676. TEST_P(SQLDatabaseTest, OpenFailsAfterCorruptSizeInHeader) {
  1677. // The database file ends up empty if we don't create at least one table.
  1678. ASSERT_TRUE(
  1679. db_->Execute("CREATE TABLE rows(i INTEGER PRIMARY KEY NOT NULL)"));
  1680. db_->Close();
  1681. ASSERT_TRUE(sql::test::CorruptSizeInHeader(db_path_));
  1682. {
  1683. sql::test::ScopedErrorExpecter expecter;
  1684. expecter.ExpectError(SQLITE_CORRUPT);
  1685. ASSERT_TRUE(db_->Open(db_path_));
  1686. EXPECT_TRUE(expecter.SawExpectedErrors());
  1687. }
  1688. }
  1689. TEST_P(SQLDatabaseTest, ExecuteFailsAfterCorruptSizeInHeader) {
  1690. ASSERT_TRUE(
  1691. db_->Execute("CREATE TABLE rows(i INTEGER PRIMARY KEY NOT NULL)"));
  1692. constexpr static char kSelectSql[] = "SELECT * from rows";
  1693. EXPECT_TRUE(db_->Execute(kSelectSql))
  1694. << "The test Execute() statement fails before the header is corrupted";
  1695. db_->Close();
  1696. ASSERT_TRUE(sql::test::CorruptSizeInHeader(db_path_));
  1697. {
  1698. sql::test::ScopedErrorExpecter expecter;
  1699. expecter.ExpectError(SQLITE_CORRUPT);
  1700. ASSERT_TRUE(db_->Open(db_path_));
  1701. EXPECT_TRUE(expecter.SawExpectedErrors())
  1702. << "Database::Open() did not encounter SQLITE_CORRUPT";
  1703. }
  1704. {
  1705. sql::test::ScopedErrorExpecter expecter;
  1706. expecter.ExpectError(SQLITE_CORRUPT);
  1707. EXPECT_FALSE(db_->Execute(kSelectSql));
  1708. EXPECT_TRUE(expecter.SawExpectedErrors())
  1709. << "Database::Execute() did not encounter SQLITE_CORRUPT";
  1710. }
  1711. }
  1712. TEST_P(SQLDatabaseTest, SchemaFailsAfterCorruptSizeInHeader) {
  1713. ASSERT_TRUE(
  1714. db_->Execute("CREATE TABLE rows(i INTEGER PRIMARY KEY NOT NULL)"));
  1715. ASSERT_TRUE(db_->DoesTableExist("rows"))
  1716. << "The test schema check fails before the header is corrupted";
  1717. db_->Close();
  1718. ASSERT_TRUE(sql::test::CorruptSizeInHeader(db_path_));
  1719. {
  1720. sql::test::ScopedErrorExpecter expecter;
  1721. expecter.ExpectError(SQLITE_CORRUPT);
  1722. ASSERT_TRUE(db_->Open(db_path_));
  1723. EXPECT_TRUE(expecter.SawExpectedErrors())
  1724. << "Database::Open() did not encounter SQLITE_CORRUPT";
  1725. }
  1726. {
  1727. sql::test::ScopedErrorExpecter expecter;
  1728. expecter.ExpectError(SQLITE_CORRUPT);
  1729. EXPECT_FALSE(db_->DoesTableExist("rows"));
  1730. EXPECT_TRUE(expecter.SawExpectedErrors())
  1731. << "Database::DoesTableExist() did not encounter SQLITE_CORRUPT";
  1732. }
  1733. }
  1734. TEST(SQLEmptyPathDatabaseTest, EmptyPathTest) {
  1735. Database db;
  1736. EXPECT_TRUE(db.OpenInMemory());
  1737. EXPECT_TRUE(db.is_open());
  1738. EXPECT_TRUE(db.DbPath().empty());
  1739. }
  1740. // WAL mode is currently not supported on Fuchsia.
  1741. #if !BUILDFLAG(IS_FUCHSIA)
  1742. INSTANTIATE_TEST_SUITE_P(JournalMode, SQLDatabaseTest, testing::Bool());
  1743. INSTANTIATE_TEST_SUITE_P(JournalMode,
  1744. SQLDatabaseTestExclusiveMode,
  1745. testing::Bool());
  1746. #else
  1747. INSTANTIATE_TEST_SUITE_P(JournalMode, SQLDatabaseTest, testing::Values(false));
  1748. INSTANTIATE_TEST_SUITE_P(JournalMode,
  1749. SQLDatabaseTestExclusiveMode,
  1750. testing::Values(false));
  1751. #endif
  1752. } // namespace sql