1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "sql/database.h"
11 #include "base/containers/contains.h"
12 #include "base/files/file.h"
13 #include "base/files/file_util.h"
14 #include "base/files/scoped_temp_dir.h"
15 #include "base/functional/bind.h"
16 #include "base/functional/callback_helpers.h"
17 #include "base/logging.h"
18 #include "base/memory/raw_ptr.h"
19 #include "base/sequence_checker.h"
20 #include "base/strings/strcat.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/test/bind.h"
23 #include "base/test/gtest_util.h"
24 #include "base/test/metrics/histogram_tester.h"
25 #include "base/thread_annotations.h"
26 #include "base/trace_event/process_memory_dump.h"
27 #include "build/build_config.h"
28 #include "sql/database_memory_dump_provider.h"
29 #include "sql/meta_table.h"
30 #include "sql/sql_features.h"
31 #include "sql/statement.h"
32 #include "sql/test/database_test_peer.h"
33 #include "sql/test/scoped_error_expecter.h"
34 #include "sql/test/test_helpers.h"
35 #include "sql/transaction.h"
36 #include "testing/gmock/include/gmock/gmock.h"
37 #include "testing/gtest/include/gtest/gtest.h"
38 #include "third_party/sqlite/sqlite3.h"
44 using sql::test::ExecuteWithResult;
46 // Helper to return the count of items in sqlite_schema. Return -1 in
48 int SqliteSchemaCount(Database* db) {
49 const char* kSchemaCount = "SELECT COUNT(*) FROM sqlite_schema";
50 Statement s(db->GetUniqueStatement(kSchemaCount));
51 return s.Step() ? s.ColumnInt(0) : -1;
54 // Handle errors by blowing away the database.
55 void RazeErrorCallback(Database* db,
59 // Nothing here needs extended errors at this time.
60 EXPECT_EQ(expected_error, expected_error & 0xff);
61 EXPECT_EQ(expected_error, error & 0xff);
65 #if BUILDFLAG(IS_POSIX)
66 // Set a umask and restore the old mask on destruction. Cribbed from
67 // shared_memory_unittest.cc. Used by POSIX-only UserPermission test.
68 class ScopedUmaskSetter {
70 explicit ScopedUmaskSetter(mode_t target_mask) {
71 old_umask_ = umask(target_mask);
73 ~ScopedUmaskSetter() { umask(old_umask_); }
75 ScopedUmaskSetter(const ScopedUmaskSetter&) = delete;
76 ScopedUmaskSetter& operator=(const ScopedUmaskSetter&) = delete;
81 #endif // BUILDFLAG(IS_POSIX)
85 // We use the parameter to run all tests with WAL mode on and off.
86 class SQLDatabaseTest : public testing::Test,
87 public testing::WithParamInterface<bool> {
89 enum class OverwriteType {
94 ~SQLDatabaseTest() override = default;
96 void SetUp() override {
97 db_ = std::make_unique<Database>(GetDBOptions());
98 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
99 db_path_ = temp_dir_.GetPath().AppendASCII("database_test.sqlite");
100 ASSERT_TRUE(db_->Open(db_path_));
103 DatabaseOptions GetDBOptions() {
104 DatabaseOptions options;
105 options.wal_mode = IsWALEnabled();
106 // TODO(crbug.com/1120969): Remove after switching to exclusive mode on by
108 options.exclusive_locking = false;
109 #if BUILDFLAG(IS_FUCHSIA) // Exclusive mode needs to be enabled to enter WAL
111 if (IsWALEnabled()) {
112 options.exclusive_locking = true;
114 #endif // BUILDFLAG(IS_FUCHSIA)
118 bool IsWALEnabled() { return GetParam(); }
120 bool TruncateDatabase() {
121 base::File file(db_path_,
122 base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
123 return file.SetLength(0);
126 bool OverwriteDatabaseHeader(OverwriteType type) {
127 base::File file(db_path_,
128 base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
129 if (type == OverwriteType::kTruncate) {
130 if (!file.SetLength(0))
134 static constexpr char kText[] = "Now is the winter of our discontent.";
135 constexpr int kTextBytes = sizeof(kText) - 1;
136 return file.Write(0, kText, kTextBytes) == kTextBytes;
140 base::ScopedTempDir temp_dir_;
141 base::FilePath db_path_;
142 std::unique_ptr<Database> db_;
145 TEST_P(SQLDatabaseTest, Execute_ValidStatement) {
146 ASSERT_TRUE(db_->Execute("CREATE TABLE data(contents TEXT)"));
147 EXPECT_EQ(SQLITE_OK, db_->GetErrorCode());
150 TEST_P(SQLDatabaseTest, Execute_InvalidStatement) {
152 sql::test::ScopedErrorExpecter error_expecter;
153 error_expecter.ExpectError(SQLITE_ERROR);
154 EXPECT_FALSE(db_->Execute("CREATE TABLE data("));
155 EXPECT_TRUE(error_expecter.SawExpectedErrors());
157 EXPECT_EQ(SQLITE_ERROR, db_->GetErrorCode());
160 TEST_P(SQLDatabaseTest, ExecuteScriptForTesting_OneLineValid) {
161 ASSERT_TRUE(db_->ExecuteScriptForTesting("CREATE TABLE data(contents TEXT)"));
162 EXPECT_EQ(SQLITE_OK, db_->GetErrorCode());
165 TEST_P(SQLDatabaseTest, ExecuteScriptForTesting_OneLineInvalid) {
166 ASSERT_FALSE(db_->ExecuteScriptForTesting("CREATE TABLE data("));
167 EXPECT_EQ(SQLITE_ERROR, db_->GetErrorCode());
170 TEST_P(SQLDatabaseTest, ExecuteScriptForTesting_ExtraContents) {
171 EXPECT_TRUE(db_->ExecuteScriptForTesting("CREATE TABLE data1(id)"))
172 << "Minimal statement";
173 EXPECT_TRUE(db_->ExecuteScriptForTesting("CREATE TABLE data2(id);"))
174 << "Extra semicolon";
175 EXPECT_TRUE(db_->ExecuteScriptForTesting("CREATE TABLE data3(id) -- Comment"))
176 << "Trailing comment";
178 EXPECT_TRUE(db_->ExecuteScriptForTesting(
179 "CREATE TABLE data4(id);CREATE TABLE data5(id)"))
180 << "Extra statement without whitespace";
181 EXPECT_TRUE(db_->ExecuteScriptForTesting(
182 "CREATE TABLE data6(id); CREATE TABLE data7(id)"))
183 << "Extra statement separated by whitespace";
185 EXPECT_TRUE(db_->ExecuteScriptForTesting("CREATE TABLE data8(id);-- Comment"))
186 << "Comment without whitespace";
188 db_->ExecuteScriptForTesting("CREATE TABLE data9(id); -- Comment"))
189 << "Comment sepatated by whitespace";
192 TEST_P(SQLDatabaseTest, ExecuteScriptForTesting_MultipleValidLines) {
193 EXPECT_TRUE(db_->ExecuteScriptForTesting(R"(
194 CREATE TABLE data1(contents TEXT);
195 CREATE TABLE data2(contents TEXT);
196 CREATE TABLE data3(contents TEXT);
198 EXPECT_EQ(SQLITE_OK, db_->GetErrorCode());
200 // DoesColumnExist() is implemented directly on top of a SQLite call. The
201 // other schema functions use sql::Statement infrastructure to query the
203 EXPECT_TRUE(db_->DoesColumnExist("data1", "contents"));
204 EXPECT_TRUE(db_->DoesColumnExist("data2", "contents"));
205 EXPECT_TRUE(db_->DoesColumnExist("data3", "contents"));
208 TEST_P(SQLDatabaseTest, ExecuteScriptForTesting_StopsOnCompileError) {
209 EXPECT_FALSE(db_->ExecuteScriptForTesting(R"(
210 CREATE TABLE data1(contents TEXT);
211 CREATE TABLE data1();
212 CREATE TABLE data3(contents TEXT);
214 EXPECT_EQ(SQLITE_ERROR, db_->GetErrorCode());
216 EXPECT_TRUE(db_->DoesColumnExist("data1", "contents"));
217 EXPECT_FALSE(db_->DoesColumnExist("data3", "contents"));
220 TEST_P(SQLDatabaseTest, ExecuteScriptForTesting_StopsOnStepError) {
221 EXPECT_FALSE(db_->ExecuteScriptForTesting(R"(
222 CREATE TABLE data1(contents TEXT UNIQUE);
223 INSERT INTO data1(contents) VALUES('value1');
224 INSERT INTO data1(contents) VALUES('value1');
225 CREATE TABLE data3(contents TEXT);
227 EXPECT_EQ(SQLITE_CONSTRAINT_UNIQUE, db_->GetErrorCode());
229 EXPECT_TRUE(db_->DoesColumnExist("data1", "contents"));
230 EXPECT_FALSE(db_->DoesColumnExist("data3", "contents"));
233 TEST_P(SQLDatabaseTest, CachedStatement) {
234 StatementID id1 = SQL_FROM_HERE;
235 StatementID id2 = SQL_FROM_HERE;
236 static const char kId1Sql[] = "SELECT a FROM foo";
237 static const char kId2Sql[] = "SELECT b FROM foo";
239 ASSERT_TRUE(db_->Execute("CREATE TABLE foo (a, b)"));
240 ASSERT_TRUE(db_->Execute("INSERT INTO foo(a, b) VALUES (12, 13)"));
242 sqlite3_stmt* raw_id1_statement;
243 sqlite3_stmt* raw_id2_statement;
245 scoped_refptr<Database::StatementRef> ref_from_id1 =
246 db_->GetCachedStatement(id1, kId1Sql);
247 raw_id1_statement = ref_from_id1->stmt();
249 Statement from_id1(std::move(ref_from_id1));
250 ASSERT_TRUE(from_id1.is_valid());
251 ASSERT_TRUE(from_id1.Step());
252 EXPECT_EQ(12, from_id1.ColumnInt(0));
254 scoped_refptr<Database::StatementRef> ref_from_id2 =
255 db_->GetCachedStatement(id2, kId2Sql);
256 raw_id2_statement = ref_from_id2->stmt();
257 EXPECT_NE(raw_id1_statement, raw_id2_statement);
259 Statement from_id2(std::move(ref_from_id2));
260 ASSERT_TRUE(from_id2.is_valid());
261 ASSERT_TRUE(from_id2.Step());
262 EXPECT_EQ(13, from_id2.ColumnInt(0));
266 scoped_refptr<Database::StatementRef> ref_from_id1 =
267 db_->GetCachedStatement(id1, kId1Sql);
268 EXPECT_EQ(raw_id1_statement, ref_from_id1->stmt())
269 << "statement was not cached";
271 Statement from_id1(std::move(ref_from_id1));
272 ASSERT_TRUE(from_id1.is_valid());
273 ASSERT_TRUE(from_id1.Step()) << "cached statement was not reset";
274 EXPECT_EQ(12, from_id1.ColumnInt(0));
276 scoped_refptr<Database::StatementRef> ref_from_id2 =
277 db_->GetCachedStatement(id2, kId2Sql);
278 EXPECT_EQ(raw_id2_statement, ref_from_id2->stmt())
279 << "statement was not cached";
281 Statement from_id2(std::move(ref_from_id2));
282 ASSERT_TRUE(from_id2.is_valid());
283 ASSERT_TRUE(from_id2.Step()) << "cached statement was not reset";
284 EXPECT_EQ(13, from_id2.ColumnInt(0));
287 EXPECT_DCHECK_DEATH(db_->GetCachedStatement(id1, kId2Sql))
288 << "Using a different SQL with the same statement ID should DCHECK";
289 EXPECT_DCHECK_DEATH(db_->GetCachedStatement(id2, kId1Sql))
290 << "Using a different SQL with the same statement ID should DCHECK";
293 TEST_P(SQLDatabaseTest, IsSQLValidTest) {
294 ASSERT_TRUE(db_->Execute("CREATE TABLE foo (a, b)"));
295 ASSERT_TRUE(db_->IsSQLValid("SELECT a FROM foo"));
296 ASSERT_FALSE(db_->IsSQLValid("SELECT no_exist FROM foo"));
299 TEST_P(SQLDatabaseTest, DoesTableExist) {
300 EXPECT_FALSE(db_->DoesTableExist("foo"));
301 EXPECT_FALSE(db_->DoesTableExist("foo_index"));
303 ASSERT_TRUE(db_->Execute("CREATE TABLE foo (a, b)"));
304 ASSERT_TRUE(db_->Execute("CREATE INDEX foo_index ON foo (a)"));
305 EXPECT_TRUE(db_->DoesTableExist("foo"));
306 EXPECT_FALSE(db_->DoesTableExist("foo_index"));
308 // DoesTableExist() is case-sensitive.
309 EXPECT_FALSE(db_->DoesTableExist("Foo"));
310 EXPECT_FALSE(db_->DoesTableExist("FOO"));
313 TEST_P(SQLDatabaseTest, DoesIndexExist) {
314 ASSERT_TRUE(db_->Execute("CREATE TABLE foo (a, b)"));
315 EXPECT_FALSE(db_->DoesIndexExist("foo"));
316 EXPECT_FALSE(db_->DoesIndexExist("foo_ubdex"));
318 ASSERT_TRUE(db_->Execute("CREATE INDEX foo_index ON foo (a)"));
319 EXPECT_TRUE(db_->DoesIndexExist("foo_index"));
320 EXPECT_FALSE(db_->DoesIndexExist("foo"));
322 // DoesIndexExist() is case-sensitive.
323 EXPECT_FALSE(db_->DoesIndexExist("Foo_index"));
324 EXPECT_FALSE(db_->DoesIndexExist("Foo_Index"));
325 EXPECT_FALSE(db_->DoesIndexExist("FOO_INDEX"));
328 TEST_P(SQLDatabaseTest, DoesViewExist) {
329 EXPECT_FALSE(db_->DoesViewExist("voo"));
330 ASSERT_TRUE(db_->Execute("CREATE VIEW voo (a) AS SELECT 1"));
331 EXPECT_FALSE(db_->DoesIndexExist("voo"));
332 EXPECT_FALSE(db_->DoesTableExist("voo"));
333 EXPECT_TRUE(db_->DoesViewExist("voo"));
335 // DoesTableExist() is case-sensitive.
336 EXPECT_FALSE(db_->DoesViewExist("Voo"));
337 EXPECT_FALSE(db_->DoesViewExist("VOO"));
340 TEST_P(SQLDatabaseTest, DoesColumnExist) {
341 ASSERT_TRUE(db_->Execute("CREATE TABLE foo (a, b)"));
343 EXPECT_FALSE(db_->DoesColumnExist("foo", "bar"));
344 EXPECT_TRUE(db_->DoesColumnExist("foo", "a"));
346 ASSERT_FALSE(db_->DoesTableExist("bar"));
347 EXPECT_FALSE(db_->DoesColumnExist("bar", "b"));
349 // SQLite resolves table/column names without case sensitivity.
350 EXPECT_TRUE(db_->DoesColumnExist("FOO", "A"));
351 EXPECT_TRUE(db_->DoesColumnExist("FOO", "a"));
352 EXPECT_TRUE(db_->DoesColumnExist("foo", "A"));
355 TEST_P(SQLDatabaseTest, GetLastInsertRowId) {
356 ASSERT_TRUE(db_->Execute("CREATE TABLE foo (id INTEGER PRIMARY KEY, value)"));
358 ASSERT_TRUE(db_->Execute("INSERT INTO foo (value) VALUES (12)"));
360 // Last insert row ID should be valid.
361 int64_t row = db_->GetLastInsertRowId();
364 // It should be the primary key of the row we just inserted.
365 Statement s(db_->GetUniqueStatement("SELECT value FROM foo WHERE id=?"));
367 ASSERT_TRUE(s.Step());
368 EXPECT_EQ(12, s.ColumnInt(0));
371 // Test the scoped error expecter by attempting to insert a duplicate
372 // value into an index.
373 TEST_P(SQLDatabaseTest, ScopedErrorExpecter) {
374 const char* kCreateSql = "CREATE TABLE foo (id INTEGER UNIQUE)";
375 ASSERT_TRUE(db_->Execute(kCreateSql));
376 ASSERT_TRUE(db_->Execute("INSERT INTO foo (id) VALUES (12)"));
379 sql::test::ScopedErrorExpecter expecter;
380 expecter.ExpectError(SQLITE_CONSTRAINT);
381 ASSERT_FALSE(db_->Execute("INSERT INTO foo (id) VALUES (12)"));
382 ASSERT_TRUE(expecter.SawExpectedErrors());
386 TEST_P(SQLDatabaseTest, SchemaIntrospectionUsesErrorExpecter) {
387 const char* kCreateSql = "CREATE TABLE foo (id INTEGER UNIQUE)";
388 ASSERT_TRUE(db_->Execute(kCreateSql));
389 ASSERT_FALSE(db_->DoesTableExist("bar"));
390 ASSERT_TRUE(db_->DoesTableExist("foo"));
391 ASSERT_TRUE(db_->DoesColumnExist("foo", "id"));
394 // Corrupt the database so that nothing works, including PRAGMAs.
395 ASSERT_TRUE(sql::test::CorruptSizeInHeader(db_path_));
398 sql::test::ScopedErrorExpecter expecter;
399 expecter.ExpectError(SQLITE_CORRUPT);
400 ASSERT_TRUE(db_->Open(db_path_));
401 ASSERT_FALSE(db_->DoesTableExist("bar"));
402 ASSERT_FALSE(db_->DoesTableExist("foo"));
403 ASSERT_FALSE(db_->DoesColumnExist("foo", "id"));
404 ASSERT_TRUE(expecter.SawExpectedErrors());
408 TEST_P(SQLDatabaseTest, SetErrorCallback) {
409 static constexpr char kCreateSql[] =
410 "CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)";
411 ASSERT_TRUE(db_->Execute(kCreateSql));
412 ASSERT_TRUE(db_->Execute("INSERT INTO rows(id) VALUES(12)"));
414 bool error_callback_called = false;
415 int error = SQLITE_OK;
416 db_->set_error_callback(base::BindLambdaForTesting(
417 [&](int sqlite_error, sql::Statement* statement) {
418 error_callback_called = true;
419 error = sqlite_error;
421 EXPECT_FALSE(db_->Execute("INSERT INTO rows(id) VALUES(12)"))
422 << "Inserting a duplicate primary key should have failed";
423 EXPECT_TRUE(error_callback_called)
424 << "Execute() should report errors to the database error callback";
425 EXPECT_EQ(SQLITE_CONSTRAINT_PRIMARYKEY, error)
426 << "Execute() should report errors to the database error callback";
429 TEST_P(SQLDatabaseTest, SetErrorCallbackDchecksOnExistingCallback) {
430 db_->set_error_callback(base::DoNothing());
431 EXPECT_DCHECK_DEATH(db_->set_error_callback(base::DoNothing()))
432 << "set_error_callback() should DCHECK if error callback already exists";
435 TEST_P(SQLDatabaseTest, ResetErrorCallback) {
436 static constexpr char kCreateSql[] =
437 "CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)";
438 ASSERT_TRUE(db_->Execute(kCreateSql));
439 ASSERT_TRUE(db_->Execute("INSERT INTO rows(id) VALUES(12)"));
441 bool error_callback_called = false;
442 int error = SQLITE_OK;
443 db_->set_error_callback(
444 base::BindLambdaForTesting([&](int sqlite_error, Statement* statement) {
445 error_callback_called = true;
446 error = sqlite_error;
448 db_->reset_error_callback();
451 sql::test::ScopedErrorExpecter expecter;
452 expecter.ExpectError(SQLITE_CONSTRAINT);
453 EXPECT_FALSE(db_->Execute("INSERT INTO rows(id) VALUES(12)"))
454 << "Inserting a duplicate primary key should have failed";
455 EXPECT_TRUE(expecter.SawExpectedErrors())
456 << "Inserting a duplicate primary key should have failed";
458 EXPECT_FALSE(error_callback_called)
459 << "Execute() should not report errors after reset_error_callback()";
460 EXPECT_EQ(SQLITE_OK, error)
461 << "Execute() should not report errors after reset_error_callback()";
464 // Sets a flag to true/false to track being alive.
467 explicit LifeTracker(bool* flag_ptr) : flag_ptr_(flag_ptr) {
468 DCHECK(flag_ptr != nullptr);
470 << "LifeTracker's flag should be set to false prior to construction";
474 LifeTracker(LifeTracker&& rhs) {
475 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
476 DCHECK_CALLED_ON_VALID_SEQUENCE(rhs.sequence_checker_);
477 flag_ptr_ = rhs.flag_ptr_;
478 rhs.flag_ptr_ = nullptr;
481 // base::RepeatingCallback only requires move-construction support.
482 LifeTracker& operator=(const LifeTracker& rhs) = delete;
485 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
491 SEQUENCE_CHECKER(sequence_checker_);
492 raw_ptr<bool> flag_ptr_ GUARDED_BY_CONTEXT(sequence_checker_);
495 // base::BindRepeating() can curry arguments to be passed by const reference to
496 // the callback function. If the error callback function calls
497 // reset_error_callback() and the Database doesn't hang onto the callback while
498 // running it, the storage for those arguments may be deleted while the callback
499 // function is executing. This test ensures that the database is hanging onto
500 // the callback while running it.
501 TEST_P(SQLDatabaseTest, ErrorCallbackStorageProtectedWhileRun) {
502 bool is_alive = false;
503 db_->set_error_callback(base::BindRepeating(
504 [](Database* db, bool* life_tracker_is_alive,
505 const LifeTracker& life_tracker, int sqlite_error,
506 Statement* statement) {
507 EXPECT_TRUE(*life_tracker_is_alive)
508 << "The error callback storage should be alive when it is Run()";
509 db->reset_error_callback();
510 EXPECT_TRUE(*life_tracker_is_alive)
511 << "The error storage should remain alive during Run() after "
512 << "reset_error_callback()";
514 base::Unretained(db_.get()), base::Unretained(&is_alive),
515 LifeTracker(&is_alive)));
517 EXPECT_TRUE(is_alive)
518 << "The error callback storage should be alive after creation";
519 EXPECT_FALSE(db_->Execute("INSERT INTO rows(id) VALUES(12)"));
520 EXPECT_FALSE(is_alive)
521 << "The error callback storage should be released after Run() completes";
524 TEST_P(SQLDatabaseTest, Execute_CompilationError) {
525 bool error_callback_called = false;
526 db_->set_error_callback(base::BindLambdaForTesting([&](int error,
529 EXPECT_EQ(SQLITE_ERROR, error);
530 EXPECT_EQ(nullptr, statement);
531 EXPECT_FALSE(error_callback_called)
532 << "SQL compilation errors should call the error callback exactly once";
533 error_callback_called = true;
537 sql::test::ScopedErrorExpecter expecter;
538 expecter.ExpectError(SQLITE_ERROR);
539 EXPECT_FALSE(db_->Execute("SELECT missing_column FROM missing_table"));
540 EXPECT_TRUE(expecter.SawExpectedErrors());
543 EXPECT_TRUE(error_callback_called)
544 << "SQL compilation errors should call the error callback";
547 TEST_P(SQLDatabaseTest, GetUniqueStatement_CompilationError) {
548 bool error_callback_called = false;
549 db_->set_error_callback(base::BindLambdaForTesting([&](int error,
552 EXPECT_EQ(SQLITE_ERROR, error);
553 EXPECT_EQ(nullptr, statement);
554 EXPECT_FALSE(error_callback_called)
555 << "SQL compilation errors should call the error callback exactly once";
556 error_callback_called = true;
560 sql::test::ScopedErrorExpecter expecter;
561 expecter.ExpectError(SQLITE_ERROR);
562 sql::Statement statement(
563 db_->GetUniqueStatement("SELECT missing_column FROM missing_table"));
564 EXPECT_FALSE(statement.is_valid());
565 EXPECT_TRUE(expecter.SawExpectedErrors());
568 EXPECT_TRUE(error_callback_called)
569 << "SQL compilation errors should call the error callback";
572 TEST_P(SQLDatabaseTest, GetCachedStatement_CompilationError) {
573 bool error_callback_called = false;
574 db_->set_error_callback(base::BindLambdaForTesting([&](int error,
577 EXPECT_EQ(SQLITE_ERROR, error);
578 EXPECT_EQ(nullptr, statement);
579 EXPECT_FALSE(error_callback_called)
580 << "SQL compilation errors should call the error callback exactly once";
581 error_callback_called = true;
585 sql::test::ScopedErrorExpecter expecter;
586 expecter.ExpectError(SQLITE_ERROR);
587 sql::Statement statement(db_->GetCachedStatement(
588 SQL_FROM_HERE, "SELECT missing_column FROM missing_table"));
589 EXPECT_FALSE(statement.is_valid());
590 EXPECT_TRUE(expecter.SawExpectedErrors());
593 EXPECT_TRUE(error_callback_called)
594 << "SQL compilation errors should call the error callback";
597 TEST_P(SQLDatabaseTest, GetUniqueStatement_ExtraContents) {
598 sql::Statement minimal(db_->GetUniqueStatement("SELECT 1"));
599 sql::Statement extra_semicolon(db_->GetUniqueStatement("SELECT 1;"));
601 // It would be nice to flag trailing comments too, as they cost binary size.
602 // However, there's no easy way of doing that.
603 sql::Statement trailing_comment(
604 db_->GetUniqueStatement("SELECT 1 -- Comment"));
606 EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("SELECT 1;SELECT 2"))
607 << "Extra statement without whitespace";
608 EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("SELECT 1; SELECT 2"))
609 << "Extra statement separated by whitespace";
610 EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("SELECT 1;-- Comment"))
611 << "Comment without whitespace";
612 EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("SELECT 1; -- Comment"))
613 << "Comment separated by whitespace";
616 TEST_P(SQLDatabaseTest, GetCachedStatement_ExtraContents) {
617 sql::Statement minimal(db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1"));
618 sql::Statement extra_semicolon(
619 db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1;"));
621 // It would be nice to flag trailing comments too, as they cost binary size.
622 // However, there's no easy way of doing that.
623 sql::Statement trailing_comment(
624 db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1 -- Comment"));
627 db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1;SELECT 2"))
628 << "Extra statement without whitespace";
630 db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1; SELECT 2"))
631 << "Extra statement separated by whitespace";
633 db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1;-- Comment"))
634 << "Comment without whitespace";
636 db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1; -- Comment"))
637 << "Comment separated by whitespace";
640 TEST_P(SQLDatabaseTest, IsSQLValid_ExtraContents) {
641 EXPECT_TRUE(db_->IsSQLValid("SELECT 1"));
642 EXPECT_TRUE(db_->IsSQLValid("SELECT 1;"))
643 << "Trailing semicolons are currently tolerated";
645 // It would be nice to flag trailing comments too, as they cost binary size.
646 // However, there's no easy way of doing that.
647 EXPECT_TRUE(db_->IsSQLValid("SELECT 1 -- Comment"))
648 << "Trailing comments are currently tolerated";
650 EXPECT_DCHECK_DEATH(db_->IsSQLValid("SELECT 1;SELECT 2"))
651 << "Extra statement without whitespace";
652 EXPECT_DCHECK_DEATH(db_->IsSQLValid("SELECT 1; SELECT 2"))
653 << "Extra statement separated by whitespace";
654 EXPECT_DCHECK_DEATH(db_->IsSQLValid("SELECT 1;-- Comment"))
655 << "Comment without whitespace";
656 EXPECT_DCHECK_DEATH(db_->IsSQLValid("SELECT 1; -- Comment"))
657 << "Comment separated by whitespace";
660 TEST_P(SQLDatabaseTest, GetUniqueStatement_NoContents) {
661 EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("")) << "Empty string";
662 EXPECT_DCHECK_DEATH(db_->GetUniqueStatement(" ")) << "Space";
663 EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("\n")) << "Newline";
664 EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("-- Comment")) << "Comment";
667 TEST_P(SQLDatabaseTest, GetCachedStatement_NoContents) {
668 EXPECT_DCHECK_DEATH(db_->GetCachedStatement(SQL_FROM_HERE, ""))
670 EXPECT_DCHECK_DEATH(db_->GetCachedStatement(SQL_FROM_HERE, " ")) << "Space";
671 EXPECT_DCHECK_DEATH(db_->GetCachedStatement(SQL_FROM_HERE, "\n"))
673 EXPECT_DCHECK_DEATH(db_->GetCachedStatement(SQL_FROM_HERE, "-- Comment"))
677 TEST_P(SQLDatabaseTest, GetReadonlyStatement) {
678 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
679 ASSERT_TRUE(db_->Execute(kCreateSql));
680 ASSERT_TRUE(db_->Execute("INSERT INTO foo (value) VALUES (12)"));
682 // PRAGMA statements do not change the database file.
684 Statement s(db_->GetReadonlyStatement("PRAGMA analysis_limit"));
685 ASSERT_TRUE(s.Step());
688 Statement s(db_->GetReadonlyStatement("PRAGMA analysis_limit=100"));
689 ASSERT_TRUE(s.is_valid());
692 // Create and insert statements should fail, while the same queries as unique
693 // statement succeeds.
695 Statement s(db_->GetReadonlyStatement(
696 "CREATE TABLE IF NOT EXISTS foo (id INTEGER PRIMARY KEY, value)"));
697 ASSERT_FALSE(s.is_valid());
698 Statement s1(db_->GetUniqueStatement(
699 "CREATE TABLE IF NOT EXISTS foo (id INTEGER PRIMARY KEY, value)"));
700 ASSERT_TRUE(s1.is_valid());
704 db_->GetReadonlyStatement("INSERT INTO foo (value) VALUES (12)"));
705 ASSERT_FALSE(s.is_valid());
707 db_->GetUniqueStatement("INSERT INTO foo (value) VALUES (12)"));
708 ASSERT_TRUE(s1.is_valid());
712 db_->GetReadonlyStatement("CREATE VIRTUAL TABLE bar USING module"));
713 ASSERT_FALSE(s.is_valid());
715 db_->GetUniqueStatement("CREATE VIRTUAL TABLE bar USING module"));
716 ASSERT_TRUE(s1.is_valid());
719 // Select statement is successful.
721 Statement s(db_->GetReadonlyStatement("SELECT * FROM foo"));
722 ASSERT_TRUE(s.Step());
723 EXPECT_EQ(s.ColumnInt(1), 12);
727 TEST_P(SQLDatabaseTest, IsSQLValid_NoContents) {
728 EXPECT_DCHECK_DEATH(db_->IsSQLValid("")) << "Empty string";
729 EXPECT_DCHECK_DEATH(db_->IsSQLValid(" ")) << "Space";
730 EXPECT_DCHECK_DEATH(db_->IsSQLValid("\n")) << "Newline";
731 EXPECT_DCHECK_DEATH(db_->IsSQLValid("-- Comment")) << "Comment";
734 // Test that Database::Raze() results in a database without the
735 // tables from the original database.
736 TEST_P(SQLDatabaseTest, Raze) {
737 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
738 ASSERT_TRUE(db_->Execute(kCreateSql));
739 ASSERT_TRUE(db_->Execute("INSERT INTO foo (value) VALUES (12)"));
741 int pragma_auto_vacuum = 0;
743 Statement s(db_->GetUniqueStatement("PRAGMA auto_vacuum"));
744 ASSERT_TRUE(s.Step());
745 pragma_auto_vacuum = s.ColumnInt(0);
746 ASSERT_TRUE(pragma_auto_vacuum == 0 || pragma_auto_vacuum == 1);
749 // If auto_vacuum is set, there's an extra page to maintain a freelist.
750 const int kExpectedPageCount = 2 + pragma_auto_vacuum;
753 Statement s(db_->GetUniqueStatement("PRAGMA page_count"));
754 ASSERT_TRUE(s.Step());
755 EXPECT_EQ(kExpectedPageCount, s.ColumnInt(0));
759 Statement s(db_->GetUniqueStatement("SELECT * FROM sqlite_schema"));
760 ASSERT_TRUE(s.Step());
761 EXPECT_EQ("table", s.ColumnString(0));
762 EXPECT_EQ("foo", s.ColumnString(1));
763 EXPECT_EQ("foo", s.ColumnString(2));
764 // Table "foo" is stored in the last page of the file.
765 EXPECT_EQ(kExpectedPageCount, s.ColumnInt(3));
766 EXPECT_EQ(kCreateSql, s.ColumnString(4));
769 ASSERT_TRUE(db_->Raze());
772 Statement s(db_->GetUniqueStatement("PRAGMA page_count"));
773 ASSERT_TRUE(s.Step());
774 EXPECT_EQ(1, s.ColumnInt(0));
777 ASSERT_EQ(0, SqliteSchemaCount(db_.get()));
780 Statement s(db_->GetUniqueStatement("PRAGMA auto_vacuum"));
781 ASSERT_TRUE(s.Step());
782 // The new database has the same auto_vacuum as a fresh database.
783 EXPECT_EQ(pragma_auto_vacuum, s.ColumnInt(0));
787 TEST_P(SQLDatabaseTest, RazeDuringSelect) {
789 db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
790 ASSERT_TRUE(db_->Execute("INSERT INTO rows(id) VALUES(1)"));
791 ASSERT_TRUE(db_->Execute("INSERT INTO rows(id) VALUES(2)"));
794 // SELECT implicitly creates a transaction while it's executing. This
795 // implicit transaction will not be caught by Raze()'s checks.
796 Statement select(db_->GetUniqueStatement("SELECT id FROM rows"));
797 ASSERT_TRUE(select.Step());
798 EXPECT_FALSE(db_->Raze()) << "Raze() should fail while SELECT is executing";
802 Statement count(db_->GetUniqueStatement("SELECT COUNT(*) FROM rows"));
803 ASSERT_TRUE(count.Step());
804 EXPECT_EQ(2, count.ColumnInt(0)) << "Raze() deleted some data";
808 // Helper for SQLDatabaseTest.RazePageSize. Creates a fresh db based on
809 // db_prefix, with the given initial page size, and verifies it against the
810 // expected size. Then changes to the final page size and razes, verifying that
811 // the fresh database ends up with the expected final page size.
812 void TestPageSize(const base::FilePath& db_prefix,
813 int initial_page_size,
814 const std::string& expected_initial_page_size,
816 const std::string& expected_final_page_size) {
817 static const char kCreateSql[] = "CREATE TABLE x (t TEXT)";
818 static const char kInsertSql1[] = "INSERT INTO x VALUES ('This is a test')";
819 static const char kInsertSql2[] = "INSERT INTO x VALUES ('That was a test')";
821 const base::FilePath db_path = db_prefix.InsertBeforeExtensionASCII(
822 base::NumberToString(initial_page_size));
823 Database::Delete(db_path);
824 Database db({.page_size = initial_page_size});
825 ASSERT_TRUE(db.Open(db_path));
826 ASSERT_TRUE(db.Execute(kCreateSql));
827 ASSERT_TRUE(db.Execute(kInsertSql1));
828 ASSERT_TRUE(db.Execute(kInsertSql2));
829 ASSERT_EQ(expected_initial_page_size,
830 ExecuteWithResult(&db, "PRAGMA page_size"));
833 // Re-open the database while setting a new |options.page_size| in the object.
834 Database razed_db({.page_size = final_page_size});
835 ASSERT_TRUE(razed_db.Open(db_path));
836 // Raze will use the page size set in the connection object, which may not
837 // match the file's page size.
838 ASSERT_TRUE(razed_db.Raze());
840 // SQLite 3.10.2 (at least) has a quirk with the sqlite3_backup() API (used by
841 // Raze()) which causes the destination database to remember the previous
842 // page_size, even if the overwriting database changed the page_size. Access
843 // the actual database to cause the cached value to be updated.
845 ExecuteWithResult(&razed_db, "SELECT COUNT(*) FROM sqlite_schema"));
847 EXPECT_EQ(expected_final_page_size,
848 ExecuteWithResult(&razed_db, "PRAGMA page_size"));
849 EXPECT_EQ("1", ExecuteWithResult(&razed_db, "PRAGMA page_count"));
852 // Verify that Recovery maintains the page size, and the virtual table
853 // works with page sizes other than SQLite's default. Also verify the case
854 // where the default page size has changed.
855 TEST_P(SQLDatabaseTest, RazePageSize) {
856 const std::string default_page_size =
857 ExecuteWithResult(db_.get(), "PRAGMA page_size");
859 // Sync uses 32k pages.
860 EXPECT_NO_FATAL_FAILURE(
861 TestPageSize(db_path_, 32768, "32768", 32768, "32768"));
863 // Many clients use 4k pages. This is the SQLite default after 3.12.0.
864 EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path_, 4096, "4096", 4096, "4096"));
866 // 1k is the default page size before 3.12.0.
867 EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path_, 1024, "1024", 1024, "1024"));
869 EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path_, 2048, "2048", 4096, "4096"));
871 // Databases with no page size specified should result in the default
872 // page size. 2k has never been the default page size.
873 ASSERT_NE("2048", default_page_size);
874 EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path_, 2048, "2048",
875 DatabaseOptions::kDefaultPageSize,
879 // Test that Raze() results are seen in other connections.
880 TEST_P(SQLDatabaseTest, RazeMultiple) {
881 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
882 ASSERT_TRUE(db_->Execute(kCreateSql));
884 Database other_db(GetDBOptions());
885 ASSERT_TRUE(other_db.Open(db_path_));
887 // Check that the second connection sees the table.
888 ASSERT_EQ(1, SqliteSchemaCount(&other_db));
890 ASSERT_TRUE(db_->Raze());
892 // The second connection sees the updated database.
893 ASSERT_EQ(0, SqliteSchemaCount(&other_db));
896 TEST_P(SQLDatabaseTest, Raze_OtherConnectionHasWriteLock) {
897 ASSERT_TRUE(db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY)"));
899 Database other_db(GetDBOptions());
900 ASSERT_TRUE(other_db.Open(db_path_));
902 Transaction other_db_transaction(&other_db);
903 ASSERT_TRUE(other_db_transaction.Begin());
904 ASSERT_TRUE(other_db.Execute("INSERT INTO rows(id) VALUES(1)"));
906 EXPECT_FALSE(db_->Raze())
907 << "Raze() should fail while another connection has a write lock";
909 ASSERT_TRUE(other_db_transaction.Commit());
910 EXPECT_TRUE(db_->Raze())
911 << "Raze() should succeed after the other connection releases the lock";
914 TEST_P(SQLDatabaseTest, Raze_OtherConnectionHasReadLock) {
915 ASSERT_TRUE(db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY)"));
916 ASSERT_TRUE(db_->Execute("INSERT INTO rows(id) VALUES(1)"));
918 if (IsWALEnabled()) {
919 // In WAL mode, read transactions in other connections do not block a write
924 Database other_db(GetDBOptions());
925 ASSERT_TRUE(other_db.Open(db_path_));
927 Statement select(other_db.GetUniqueStatement("SELECT id FROM rows"));
928 ASSERT_TRUE(select.Step());
929 EXPECT_FALSE(db_->Raze())
930 << "Raze() should fail while another connection has a read lock";
932 ASSERT_FALSE(select.Step())
933 << "The SELECT statement should not produce more than one row";
934 EXPECT_TRUE(db_->Raze())
935 << "Raze() should succeed after the other connection releases the lock";
938 TEST_P(SQLDatabaseTest, Raze_EmptyDatabaseFile) {
940 db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
943 ASSERT_TRUE(TruncateDatabase());
944 ASSERT_TRUE(db_->Open(db_path_))
945 << "Failed to reopen database after truncating";
947 EXPECT_TRUE(db_->Raze()) << "Raze() failed on an empty file";
949 db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"))
950 << "Raze() did not produce a healthy empty database";
953 // Verify that Raze() can handle a file of junk.
954 // Need exclusive mode off here as there are some subtleties (by design) around
955 // how the cache is used with it on which causes the test to fail.
956 TEST_P(SQLDatabaseTest, RazeNOTADB) {
958 Database::Delete(db_path_);
959 ASSERT_FALSE(base::PathExists(db_path_));
961 ASSERT_TRUE(OverwriteDatabaseHeader(OverwriteType::kTruncate));
962 ASSERT_TRUE(base::PathExists(db_path_));
964 // SQLite will successfully open the handle, but fail when running PRAGMA
965 // statements that access the database.
967 sql::test::ScopedErrorExpecter expecter;
968 expecter.ExpectError(SQLITE_NOTADB);
970 EXPECT_TRUE(db_->Open(db_path_));
971 ASSERT_TRUE(expecter.SawExpectedErrors());
973 EXPECT_TRUE(db_->Raze());
976 // Now empty, the open should open an empty database.
977 EXPECT_TRUE(db_->Open(db_path_));
978 EXPECT_EQ(0, SqliteSchemaCount(db_.get()));
981 // Verify that Raze() can handle a database overwritten with garbage.
982 TEST_P(SQLDatabaseTest, RazeNOTADB2) {
983 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
984 ASSERT_TRUE(db_->Execute(kCreateSql));
985 ASSERT_EQ(1, SqliteSchemaCount(db_.get()));
988 ASSERT_TRUE(OverwriteDatabaseHeader(OverwriteType::kOverwrite));
990 // SQLite will successfully open the handle, but will fail with
991 // SQLITE_NOTADB on pragma statemenets which attempt to read the
994 sql::test::ScopedErrorExpecter expecter;
995 expecter.ExpectError(SQLITE_NOTADB);
996 EXPECT_TRUE(db_->Open(db_path_));
997 ASSERT_TRUE(expecter.SawExpectedErrors());
999 EXPECT_TRUE(db_->Raze());
1002 // Now empty, the open should succeed with an empty database.
1003 EXPECT_TRUE(db_->Open(db_path_));
1004 EXPECT_EQ(0, SqliteSchemaCount(db_.get()));
1007 // Test that a callback from Open() can raze the database. This is
1008 // essential for cases where the Open() can fail entirely, so the
1009 // Raze() cannot happen later. Additionally test that when the
1010 // callback does this during Open(), the open is retried and succeeds.
1011 TEST_P(SQLDatabaseTest, RazeCallbackReopen) {
1012 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
1013 ASSERT_TRUE(db_->Execute(kCreateSql));
1014 ASSERT_EQ(1, SqliteSchemaCount(db_.get()));
1017 // Corrupt the database so that nothing works, including PRAGMAs.
1018 ASSERT_TRUE(sql::test::CorruptSizeInHeader(db_path_));
1020 // Open() will succeed, even though the PRAGMA calls within will
1021 // fail with SQLITE_CORRUPT, as will this PRAGMA.
1023 sql::test::ScopedErrorExpecter expecter;
1024 expecter.ExpectError(SQLITE_CORRUPT);
1025 ASSERT_TRUE(db_->Open(db_path_));
1026 ASSERT_FALSE(db_->Execute("PRAGMA auto_vacuum"));
1028 ASSERT_TRUE(expecter.SawExpectedErrors());
1031 db_->set_error_callback(
1032 base::BindRepeating(&RazeErrorCallback, db_.get(), SQLITE_CORRUPT));
1034 // When the PRAGMA calls in Open() raise SQLITE_CORRUPT, the error
1035 // callback will call RazeAndPoison(). Open() will then fail and be
1036 // retried. The second Open() on the empty database will succeed
1038 ASSERT_TRUE(db_->Open(db_path_));
1039 ASSERT_TRUE(db_->Execute("PRAGMA auto_vacuum"));
1040 EXPECT_EQ(0, SqliteSchemaCount(db_.get()));
1043 TEST_P(SQLDatabaseTest, RazeAndPoison_DeletesData) {
1045 db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
1046 ASSERT_TRUE(db_->Execute("INSERT INTO rows(id) VALUES(12)"));
1047 ASSERT_TRUE(db_->RazeAndPoison());
1049 // We need to call Close() in order to re-Open().
1051 ASSERT_TRUE(db_->Open(db_path_))
1052 << "RazeAndPoison() did not produce a healthy database";
1054 db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"))
1055 << "RazeAndPoison() did not produce a healthy empty database";
1058 TEST_P(SQLDatabaseTest, RazeAndPoison_IsOpen) {
1060 db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
1061 ASSERT_TRUE(db_->Execute("INSERT INTO rows(id) VALUES(12)"));
1062 ASSERT_TRUE(db_->RazeAndPoison());
1064 EXPECT_FALSE(db_->is_open())
1065 << "RazeAndPoison() did not mark the database as closed";
1068 TEST_P(SQLDatabaseTest, RazeAndPoison_Reopen_NoChanges) {
1069 ASSERT_TRUE(db_->RazeAndPoison());
1071 db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"))
1072 << "Execute() should return false after RazeAndPoison()";
1074 // We need to call Close() in order to re-Open().
1076 ASSERT_TRUE(db_->Open(db_path_))
1077 << "RazeAndPoison() did not produce a healthy database";
1079 db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"))
1080 << "Execute() returned false but went through after RazeAndPoison()";
1083 TEST_P(SQLDatabaseTest, RazeAndPoison_OpenTransaction) {
1085 db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
1086 ASSERT_TRUE(db_->Execute("INSERT INTO rows(id) VALUES(12)"));
1088 Transaction transaction(db_.get());
1089 ASSERT_TRUE(transaction.Begin());
1090 ASSERT_TRUE(db_->RazeAndPoison());
1092 EXPECT_FALSE(db_->is_open())
1093 << "RazeAndPoison() did not mark the database as closed";
1094 EXPECT_FALSE(transaction.Commit())
1095 << "RazeAndPoison() did not cancel the transaction";
1097 // We need to call Close() in order to re-Open().
1100 ASSERT_TRUE(db_->Open(db_path_));
1102 db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"))
1103 << "RazeAndPoison() did not produce a healthy empty database";
1106 TEST_P(SQLDatabaseTest, RazeAndPoison_Preload_NoCrash) {
1108 db_->RazeAndPoison();
1112 TEST_P(SQLDatabaseTest, RazeAndPoison_DoesTableExist) {
1114 db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
1115 ASSERT_TRUE(db_->DoesTableExist("rows")) << "Incorrect test setup";
1117 ASSERT_TRUE(db_->RazeAndPoison());
1118 EXPECT_FALSE(db_->DoesTableExist("rows"))
1119 << "DoesTableExist() should return false after RazeAndPoison()";
1122 TEST_P(SQLDatabaseTest, RazeAndPoison_IsSQLValid) {
1123 ASSERT_TRUE(db_->IsSQLValid("SELECT 1")) << "Incorrect test setup";
1125 ASSERT_TRUE(db_->RazeAndPoison());
1126 EXPECT_FALSE(db_->IsSQLValid("SELECT 1"))
1127 << "IsSQLValid() should return false after RazeAndPoison()";
1130 TEST_P(SQLDatabaseTest, RazeAndPoison_Execute) {
1131 ASSERT_TRUE(db_->Execute("SELECT 1")) << "Incorrect test setup";
1133 ASSERT_TRUE(db_->RazeAndPoison());
1134 EXPECT_FALSE(db_->Execute("SELECT 1"))
1135 << "Execute() should return false after RazeAndPoison()";
1138 TEST_P(SQLDatabaseTest, RazeAndPoison_GetUniqueStatement) {
1140 Statement select(db_->GetUniqueStatement("SELECT 1"));
1141 ASSERT_TRUE(select.Step()) << "Incorrect test setup";
1144 ASSERT_TRUE(db_->RazeAndPoison());
1146 Statement select(db_->GetUniqueStatement("SELECT 1"));
1147 EXPECT_FALSE(select.Step())
1148 << "GetUniqueStatement() should return an invalid Statement after "
1149 << "RazeAndPoison()";
1153 TEST_P(SQLDatabaseTest, RazeAndPoison_GetCachedStatement) {
1155 Statement select(db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1"));
1156 ASSERT_TRUE(select.Step()) << "Incorrect test setup";
1159 ASSERT_TRUE(db_->RazeAndPoison());
1161 Statement select(db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1"));
1162 EXPECT_FALSE(select.Step())
1163 << "GetCachedStatement() should return an invalid Statement after "
1164 << "RazeAndPoison()";
1168 TEST_P(SQLDatabaseTest, RazeAndPoison_InvalidatesUniqueStatement) {
1169 Statement select(db_->GetUniqueStatement("SELECT 1"));
1170 ASSERT_TRUE(select.is_valid()) << "Incorrect test setup";
1171 ASSERT_TRUE(select.Step()) << "Incorrect test setup";
1172 select.Reset(/*clear_bound_vars=*/true);
1174 ASSERT_TRUE(db_->RazeAndPoison());
1175 EXPECT_FALSE(select.is_valid())
1176 << "RazeAndPoison() should invalidate live Statements";
1177 EXPECT_FALSE(select.Step())
1178 << "RazeAndPoison() should invalidate live Statements";
1181 TEST_P(SQLDatabaseTest, RazeAndPoison_InvalidatesCachedStatement) {
1182 Statement select(db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1"));
1183 ASSERT_TRUE(select.is_valid()) << "Incorrect test setup";
1184 ASSERT_TRUE(select.Step()) << "Incorrect test setup";
1185 select.Reset(/*clear_bound_vars=*/true);
1187 ASSERT_TRUE(db_->RazeAndPoison());
1188 EXPECT_FALSE(select.is_valid())
1189 << "RazeAndPoison() should invalidate live Statements";
1190 EXPECT_FALSE(select.Step())
1191 << "RazeAndPoison() should invalidate live Statements";
1194 TEST_P(SQLDatabaseTest, RazeAndPoison_TransactionBegin) {
1196 Transaction transaction(db_.get());
1197 ASSERT_TRUE(transaction.Begin()) << "Incorrect test setup";
1198 ASSERT_TRUE(transaction.Commit()) << "Incorrect test setup";
1201 ASSERT_TRUE(db_->RazeAndPoison());
1203 Transaction transaction(db_.get());
1204 EXPECT_FALSE(transaction.Begin())
1205 << "Transaction::Begin() should return false after RazeAndPoison()";
1206 EXPECT_FALSE(transaction.IsActiveForTesting())
1207 << "RazeAndPoison() should block transactions from starting";
1211 TEST_P(SQLDatabaseTest, Close_IsSQLValid) {
1212 ASSERT_TRUE(db_->IsSQLValid("SELECT 1")) << "Incorrect test setup";
1216 EXPECT_DCHECK_DEATH_WITH({ std::ignore = db_->IsSQLValid("SELECT 1"); },
1217 "Illegal use of Database without a db");
1220 // On Windows, truncate silently fails against a memory-mapped file. One goal
1221 // of Raze() is to truncate the file to remove blocks which generate I/O errors.
1222 // Test that Raze() turns off memory mapping so that the file is truncated.
1223 // [This would not cover the case of multiple connections where one of the other
1224 // connections is memory-mapped. That is infrequent in Chromium.]
1225 TEST_P(SQLDatabaseTest, RazeTruncate) {
1226 // The empty database has 0 or 1 pages. Raze() should leave it with exactly 1
1227 // page. Not checking directly because auto_vacuum on Android adds a freelist
1229 ASSERT_TRUE(db_->Raze());
1230 int64_t expected_size;
1231 ASSERT_TRUE(base::GetFileSize(db_path_, &expected_size));
1232 ASSERT_GT(expected_size, 0);
1234 // Cause the database to take a few pages.
1235 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
1236 ASSERT_TRUE(db_->Execute(kCreateSql));
1237 for (size_t i = 0; i < 24; ++i) {
1239 db_->Execute("INSERT INTO foo (value) VALUES (randomblob(1024))"));
1242 // In WAL mode, writes don't reach the database file until a checkpoint
1244 ASSERT_TRUE(db_->CheckpointDatabase());
1247 ASSERT_TRUE(base::GetFileSize(db_path_, &db_size));
1248 ASSERT_GT(db_size, expected_size);
1250 // Make a query covering most of the database file to make sure that the
1251 // blocks are actually mapped into memory. Empirically, the truncate problem
1252 // doesn't seem to happen if no blocks are mapped.
1254 ExecuteWithResult(db_.get(), "SELECT SUM(LENGTH(value)) FROM foo"));
1256 ASSERT_TRUE(db_->Raze());
1257 ASSERT_TRUE(base::GetFileSize(db_path_, &db_size));
1258 ASSERT_EQ(expected_size, db_size);
1261 #if BUILDFLAG(IS_ANDROID)
1262 TEST_P(SQLDatabaseTest, SetTempDirForSQL) {
1263 MetaTable meta_table;
1264 // Below call needs a temporary directory in sqlite3
1265 // On Android, it can pass only when the temporary directory is set.
1266 // Otherwise, sqlite3 doesn't find the correct directory to store
1267 // temporary files and will report the error 'unable to open
1269 ASSERT_TRUE(meta_table.Init(db_.get(), 4, 4));
1271 #endif // BUILDFLAG(IS_ANDROID)
1273 TEST_P(SQLDatabaseTest, Delete) {
1274 EXPECT_TRUE(db_->Execute("CREATE TABLE x (x)"));
1277 base::FilePath journal_path = Database::JournalPath(db_path_);
1278 base::FilePath wal_path = Database::WriteAheadLogPath(db_path_);
1280 // Should have both a main database file and a journal file if
1281 // journal_mode is TRUNCATE. There is no WAL file as it is deleted on Close.
1282 ASSERT_TRUE(base::PathExists(db_path_));
1283 if (!IsWALEnabled()) { // TRUNCATE mode
1284 ASSERT_TRUE(base::PathExists(journal_path));
1287 Database::Delete(db_path_);
1288 EXPECT_FALSE(base::PathExists(db_path_));
1289 EXPECT_FALSE(base::PathExists(journal_path));
1290 EXPECT_FALSE(base::PathExists(wal_path));
1293 #if BUILDFLAG(IS_POSIX) // This test operates on POSIX file permissions.
1294 TEST_P(SQLDatabaseTest, PosixFilePermissions) {
1296 Database::Delete(db_path_);
1297 ASSERT_FALSE(base::PathExists(db_path_));
1299 // If the bots all had a restrictive umask setting such that databases are
1300 // always created with only the owner able to read them, then the code could
1301 // break without breaking the tests. Temporarily provide a more permissive
1303 ScopedUmaskSetter permissive_umask(S_IWGRP | S_IWOTH);
1305 ASSERT_TRUE(db_->Open(db_path_));
1307 // Cause the journal file to be created. If the default journal_mode is
1308 // changed back to DELETE, this test will need to be updated.
1309 EXPECT_TRUE(db_->Execute("CREATE TABLE x (x)"));
1312 ASSERT_TRUE(base::PathExists(db_path_));
1313 EXPECT_TRUE(base::GetPosixFilePermissions(db_path_, &mode));
1314 ASSERT_EQ(mode, 0600);
1316 if (IsWALEnabled()) { // WAL mode
1317 // The WAL file is created lazily on first change.
1318 ASSERT_TRUE(db_->Execute("CREATE TABLE foo (a, b)"));
1320 base::FilePath wal_path = Database::WriteAheadLogPath(db_path_);
1321 ASSERT_TRUE(base::PathExists(wal_path));
1322 EXPECT_TRUE(base::GetPosixFilePermissions(wal_path, &mode));
1323 ASSERT_EQ(mode, 0600);
1325 // The shm file doesn't exist in exclusive locking mode.
1326 if (ExecuteWithResult(db_.get(), "PRAGMA locking_mode") == "normal") {
1327 base::FilePath shm_path = Database::SharedMemoryFilePath(db_path_);
1328 ASSERT_TRUE(base::PathExists(shm_path));
1329 EXPECT_TRUE(base::GetPosixFilePermissions(shm_path, &mode));
1330 ASSERT_EQ(mode, 0600);
1332 } else { // Truncate mode
1333 base::FilePath journal_path = Database::JournalPath(db_path_);
1334 DLOG(ERROR) << "journal_path: " << journal_path;
1335 ASSERT_TRUE(base::PathExists(journal_path));
1336 EXPECT_TRUE(base::GetPosixFilePermissions(journal_path, &mode));
1337 ASSERT_EQ(mode, 0600);
1340 #endif // BUILDFLAG(IS_POSIX)
1342 TEST_P(SQLDatabaseTest, Poison_IsOpen) {
1344 EXPECT_FALSE(db_->is_open())
1345 << "Poison() did not mark the database as closed";
1348 TEST_P(SQLDatabaseTest, Poison_Close_Reopen_NoChanges) {
1351 db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"))
1352 << "Execute() should return false after Poison()";
1355 ASSERT_TRUE(db_->Open(db_path_)) << "Poison() damaged the database";
1357 db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"))
1358 << "Execute() returned false but went through after Poison()";
1361 TEST_P(SQLDatabaseTest, Poison_Preload_NoCrash) {
1367 TEST_P(SQLDatabaseTest, Poison_DoesTableExist) {
1369 db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
1370 ASSERT_TRUE(db_->DoesTableExist("rows")) << "Incorrect test setup";
1373 EXPECT_FALSE(db_->DoesTableExist("rows"))
1374 << "DoesTableExist() should return false after Poison()";
1377 TEST_P(SQLDatabaseTest, Poison_IsSQLValid) {
1378 ASSERT_TRUE(db_->IsSQLValid("SELECT 1")) << "Incorrect test setup";
1381 EXPECT_FALSE(db_->IsSQLValid("SELECT 1"))
1382 << "IsSQLValid() should return false after Poison()";
1385 TEST_P(SQLDatabaseTest, Poison_Execute) {
1386 ASSERT_TRUE(db_->Execute("SELECT 1")) << "Incorrect test setup";
1389 EXPECT_FALSE(db_->Execute("SELECT 1"))
1390 << "Execute() should return false after Poison()";
1393 TEST_P(SQLDatabaseTest, Poison_GetUniqueStatement) {
1395 Statement select(db_->GetUniqueStatement("SELECT 1"));
1396 ASSERT_TRUE(select.Step()) << "Incorrect test setup";
1401 Statement select(db_->GetUniqueStatement("SELECT 1"));
1402 EXPECT_FALSE(select.Step())
1403 << "GetUniqueStatement() should return an invalid Statement after "
1408 TEST_P(SQLDatabaseTest, Poison_GetCachedStatement) {
1410 Statement select(db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1"));
1411 ASSERT_TRUE(select.Step()) << "Incorrect test setup";
1416 Statement select(db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1"));
1417 EXPECT_FALSE(select.Step())
1418 << "GetCachedStatement() should return an invalid Statement after "
1423 TEST_P(SQLDatabaseTest, Poison_InvalidatesUniqueStatement) {
1424 Statement select(db_->GetUniqueStatement("SELECT 1"));
1425 ASSERT_TRUE(select.is_valid()) << "Incorrect test setup";
1426 ASSERT_TRUE(select.Step()) << "Incorrect test setup";
1427 select.Reset(/*clear_bound_vars=*/true);
1430 EXPECT_FALSE(select.is_valid())
1431 << "Poison() should invalidate live Statements";
1432 EXPECT_FALSE(select.Step()) << "Poison() should invalidate live Statements";
1435 TEST_P(SQLDatabaseTest, Poison_InvalidatesCachedStatement) {
1436 Statement select(db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1"));
1437 ASSERT_TRUE(select.is_valid()) << "Incorrect test setup";
1438 ASSERT_TRUE(select.Step()) << "Incorrect test setup";
1439 select.Reset(/*clear_bound_vars=*/true);
1442 EXPECT_FALSE(select.is_valid())
1443 << "Poison() should invalidate live Statements";
1444 EXPECT_FALSE(select.Step()) << "Poison() should invalidate live Statements";
1447 TEST_P(SQLDatabaseTest, Poison_TransactionBegin) {
1449 Transaction transaction(db_.get());
1450 ASSERT_TRUE(transaction.Begin()) << "Incorrect test setup";
1451 ASSERT_TRUE(transaction.Commit()) << "Incorrect test setup";
1456 Transaction transaction(db_.get());
1457 EXPECT_FALSE(transaction.Begin())
1458 << "Transaction::Begin() should return false after Poison()";
1459 EXPECT_FALSE(transaction.IsActiveForTesting())
1460 << "Poison() should block transactions from starting";
1464 TEST_P(SQLDatabaseTest, Poison_OpenTransaction) {
1465 Transaction transaction(db_.get());
1466 ASSERT_TRUE(transaction.Begin());
1469 EXPECT_FALSE(transaction.Commit())
1470 << "Poison() did not cancel the transaction";
1473 TEST_P(SQLDatabaseTest, AttachDatabase) {
1475 db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
1477 // Create a database to attach to.
1478 base::FilePath attach_path =
1479 db_path_.DirName().AppendASCII("attach_database_test.db");
1480 static constexpr char kAttachmentPoint[] = "other";
1483 ASSERT_TRUE(other_db.Open(attach_path));
1485 other_db.Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
1486 ASSERT_TRUE(other_db.Execute("INSERT INTO rows VALUES(42)"));
1489 // Cannot see the attached database, yet.
1490 EXPECT_FALSE(db_->IsSQLValid("SELECT COUNT(*) from other.rows"));
1492 EXPECT_TRUE(DatabaseTestPeer::AttachDatabase(db_.get(), attach_path,
1494 EXPECT_TRUE(db_->IsSQLValid("SELECT COUNT(*) from other.rows"));
1496 // Queries can touch both databases after the ATTACH.
1497 EXPECT_TRUE(db_->Execute("INSERT INTO rows SELECT id FROM other.rows"));
1499 Statement select(db_->GetUniqueStatement("SELECT COUNT(*) FROM rows"));
1500 ASSERT_TRUE(select.Step());
1501 EXPECT_EQ(1, select.ColumnInt(0));
1504 EXPECT_TRUE(DatabaseTestPeer::DetachDatabase(db_.get(), kAttachmentPoint));
1505 EXPECT_FALSE(db_->IsSQLValid("SELECT COUNT(*) from other.rows"));
1508 TEST_P(SQLDatabaseTest, AttachDatabaseWithOpenTransaction) {
1510 db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
1512 // Create a database to attach to.
1513 base::FilePath attach_path =
1514 db_path_.DirName().AppendASCII("attach_database_test.db");
1515 static constexpr char kAttachmentPoint[] = "other";
1518 ASSERT_TRUE(other_db.Open(attach_path));
1520 other_db.Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
1521 ASSERT_TRUE(other_db.Execute("INSERT INTO rows VALUES(42)"));
1524 // Cannot see the attached database, yet.
1525 EXPECT_FALSE(db_->IsSQLValid("SELECT COUNT(*) from other.rows"));
1527 // Attach succeeds in a transaction.
1528 Transaction transaction(db_.get());
1529 EXPECT_TRUE(transaction.Begin());
1530 EXPECT_TRUE(DatabaseTestPeer::AttachDatabase(db_.get(), attach_path,
1532 EXPECT_TRUE(db_->IsSQLValid("SELECT COUNT(*) from other.rows"));
1534 // Queries can touch both databases after the ATTACH.
1535 EXPECT_TRUE(db_->Execute("INSERT INTO rows SELECT id FROM other.rows"));
1537 Statement select(db_->GetUniqueStatement("SELECT COUNT(*) FROM rows"));
1538 ASSERT_TRUE(select.Step());
1539 EXPECT_EQ(1, select.ColumnInt(0));
1542 // Detaching the same database fails, database is locked in the transaction.
1544 sql::test::ScopedErrorExpecter expecter;
1545 expecter.ExpectError(SQLITE_ERROR);
1546 EXPECT_FALSE(DatabaseTestPeer::DetachDatabase(db_.get(), kAttachmentPoint));
1547 ASSERT_TRUE(expecter.SawExpectedErrors());
1549 EXPECT_TRUE(db_->IsSQLValid("SELECT COUNT(*) from other.rows"));
1551 // Detach succeeds when the transaction is closed.
1552 transaction.Rollback();
1553 EXPECT_TRUE(DatabaseTestPeer::DetachDatabase(db_.get(), kAttachmentPoint));
1554 EXPECT_FALSE(db_->IsSQLValid("SELECT COUNT(*) from other.rows"));
1557 TEST_P(SQLDatabaseTest, FullIntegrityCheck) {
1558 static constexpr char kTableSql[] =
1559 "CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL, value TEXT NOT NULL)";
1560 ASSERT_TRUE(db_->Execute(kTableSql));
1561 ASSERT_TRUE(db_->Execute("CREATE INDEX rows_by_value ON rows(value)"));
1564 std::vector<std::string> messages;
1565 EXPECT_TRUE(db_->FullIntegrityCheck(&messages))
1566 << "FullIntegrityCheck() failed before database was corrupted";
1567 EXPECT_THAT(messages, testing::ElementsAre("ok"))
1568 << "FullIntegrityCheck() should report ok before database is corrupted";
1572 ASSERT_TRUE(sql::test::CorruptIndexRootPage(db_path_, "rows_by_value"));
1573 ASSERT_TRUE(db_->Open(db_path_));
1576 std::vector<std::string> messages;
1577 EXPECT_TRUE(db_->FullIntegrityCheck(&messages))
1578 << "FullIntegrityCheck() failed on corrupted database";
1579 EXPECT_THAT(messages, testing::Not(testing::ElementsAre("ok")))
1580 << "FullIntegrityCheck() should not report ok for a corrupted database";
1584 TEST_P(SQLDatabaseTest, OnMemoryDump) {
1585 base::trace_event::MemoryDumpArgs args = {
1586 base::trace_event::MemoryDumpLevelOfDetail::kDetailed};
1587 base::trace_event::ProcessMemoryDump pmd(args);
1588 ASSERT_TRUE(db_->memory_dump_provider_->OnMemoryDump(args, &pmd));
1589 EXPECT_GE(pmd.allocator_dumps().size(), 1u);
1592 // Test that the functions to collect diagnostic data run to completion, without
1593 // worrying too much about what they generate (since that will change).
1594 TEST_P(SQLDatabaseTest, CollectDiagnosticInfo) {
1595 const std::string corruption_info = db_->CollectCorruptionInfo();
1596 EXPECT_TRUE(base::Contains(corruption_info, "SQLITE_CORRUPT"));
1597 EXPECT_TRUE(base::Contains(corruption_info, "integrity_check"));
1599 // A statement to see in the results.
1600 const char* kSimpleSql = "SELECT 'mountain'";
1601 Statement s(db_->GetCachedStatement(SQL_FROM_HERE, kSimpleSql));
1603 // Error includes the statement.
1605 DatabaseDiagnostics diagnostics;
1606 const std::string readonly_info =
1607 db_->CollectErrorInfo(SQLITE_READONLY, &s, &diagnostics);
1608 EXPECT_TRUE(base::Contains(readonly_info, kSimpleSql));
1609 EXPECT_EQ(diagnostics.sql_statement, kSimpleSql);
1612 // Some other error doesn't include the statement.
1614 DatabaseDiagnostics diagnostics;
1615 const std::string full_info =
1616 db_->CollectErrorInfo(SQLITE_FULL, nullptr, &diagnostics);
1617 EXPECT_FALSE(base::Contains(full_info, kSimpleSql));
1618 EXPECT_TRUE(diagnostics.sql_statement.empty());
1621 // A table to see in the SQLITE_ERROR results.
1622 EXPECT_TRUE(db_->Execute("CREATE TABLE volcano (x)"));
1624 // Version info to see in the SQLITE_ERROR results.
1625 MetaTable meta_table;
1626 ASSERT_TRUE(meta_table.Init(db_.get(), 4, 4));
1629 DatabaseDiagnostics diagnostics;
1630 const std::string error_info =
1631 db_->CollectErrorInfo(SQLITE_ERROR, &s, &diagnostics);
1632 EXPECT_TRUE(base::Contains(error_info, kSimpleSql));
1633 EXPECT_TRUE(base::Contains(error_info, "volcano"));
1634 EXPECT_TRUE(base::Contains(error_info, "version: 4"));
1635 EXPECT_EQ(diagnostics.sql_statement, kSimpleSql);
1636 EXPECT_EQ(diagnostics.version, 4);
1638 ASSERT_EQ(diagnostics.schema_sql_rows.size(), 2U);
1639 EXPECT_EQ(diagnostics.schema_sql_rows[0], "CREATE TABLE volcano (x)");
1640 EXPECT_EQ(diagnostics.schema_sql_rows[1],
1641 "CREATE TABLE meta(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY, "
1642 "value LONGVARCHAR)");
1644 ASSERT_EQ(diagnostics.schema_other_row_names.size(), 1U);
1645 EXPECT_EQ(diagnostics.schema_other_row_names[0], "sqlite_autoindex_meta_1");
1648 // Test that an error message is included in the diagnostics.
1650 sql::test::ScopedErrorExpecter error_expecter;
1651 error_expecter.ExpectError(SQLITE_ERROR);
1653 db_->Execute("INSERT INTO volcano VALUES ('bound_value1', 42, 1234)"));
1654 EXPECT_TRUE(error_expecter.SawExpectedErrors());
1656 DatabaseDiagnostics diagnostics;
1657 const std::string error_info =
1658 db_->CollectErrorInfo(SQLITE_ERROR, &s, &diagnostics);
1659 // Expect that the error message contains the table name and a column error.
1660 EXPECT_TRUE(base::Contains(diagnostics.error_message, "table"));
1661 EXPECT_TRUE(base::Contains(diagnostics.error_message, "volcano"));
1662 EXPECT_TRUE(base::Contains(diagnostics.error_message, "column"));
1664 // Expect that bound values are not present.
1665 EXPECT_FALSE(base::Contains(diagnostics.error_message, "bound_value1"));
1666 EXPECT_FALSE(base::Contains(diagnostics.error_message, "42"));
1667 EXPECT_FALSE(base::Contains(diagnostics.error_message, "1234"));
1671 // Test that a fresh database has mmap enabled by default, if mmap'ed I/O is
1672 // enabled by SQLite.
1673 TEST_P(SQLDatabaseTest, MmapInitiallyEnabled) {
1675 Statement s(db_->GetUniqueStatement("PRAGMA mmap_size"));
1676 ASSERT_TRUE(s.Step())
1677 << "All supported SQLite versions should have mmap support";
1679 // If mmap I/O is not on, attempt to turn it on. If that succeeds, then
1680 // Open() should have turned it on. If mmap support is disabled, 0 is
1681 // returned. If the VFS does not understand SQLITE_FCNTL_MMAP_SIZE (for
1682 // instance MojoVFS), -1 is returned.
1683 if (s.ColumnInt(0) <= 0) {
1684 ASSERT_TRUE(db_->Execute("PRAGMA mmap_size = 1048576"));
1686 ASSERT_TRUE(s.Step());
1687 EXPECT_LE(s.ColumnInt(0), 0);
1691 // Test that explicit disable prevents mmap'ed I/O.
1693 Database::Delete(db_path_);
1694 db_->set_mmap_disabled();
1695 ASSERT_TRUE(db_->Open(db_path_));
1696 EXPECT_EQ("0", ExecuteWithResult(db_.get(), "PRAGMA mmap_size"));
1699 // Test whether a fresh database gets mmap enabled when using alternate status
1701 TEST_P(SQLDatabaseTest, MmapInitiallyEnabledAltStatus) {
1702 // Re-open fresh database with alt-status flag set.
1704 Database::Delete(db_path_);
1706 DatabaseOptions options = GetDBOptions();
1707 options.mmap_alt_status_discouraged = true;
1708 options.enable_views_discouraged = true;
1709 db_ = std::make_unique<Database>(options);
1710 ASSERT_TRUE(db_->Open(db_path_));
1713 Statement s(db_->GetUniqueStatement("PRAGMA mmap_size"));
1714 ASSERT_TRUE(s.Step())
1715 << "All supported SQLite versions should have mmap support";
1717 // If mmap I/O is not on, attempt to turn it on. If that succeeds, then
1718 // Open() should have turned it on. If mmap support is disabled, 0 is
1719 // returned. If the VFS does not understand SQLITE_FCNTL_MMAP_SIZE (for
1720 // instance MojoVFS), -1 is returned.
1721 if (s.ColumnInt(0) <= 0) {
1722 ASSERT_TRUE(db_->Execute("PRAGMA mmap_size = 1048576"));
1724 ASSERT_TRUE(s.Step());
1725 EXPECT_LE(s.ColumnInt(0), 0);
1729 // Test that explicit disable overrides set_mmap_alt_status().
1731 Database::Delete(db_path_);
1732 db_->set_mmap_disabled();
1733 ASSERT_TRUE(db_->Open(db_path_));
1734 EXPECT_EQ("0", ExecuteWithResult(db_.get(), "PRAGMA mmap_size"));
1737 TEST_P(SQLDatabaseTest, ComputeMmapSizeForOpen) {
1738 const size_t kMmapAlot = 25 * 1024 * 1024;
1739 int64_t mmap_status = MetaTable::kMmapFailure;
1741 // If there is no meta table (as for a fresh database), assume that everything
1742 // should be mapped, and the status of the meta table is not affected.
1743 ASSERT_TRUE(!db_->DoesTableExist("meta"));
1744 ASSERT_GT(db_->ComputeMmapSizeForOpen(), kMmapAlot);
1745 ASSERT_TRUE(!db_->DoesTableExist("meta"));
1747 // When the meta table is first created, it sets up to map everything.
1748 ASSERT_TRUE(MetaTable().Init(db_.get(), 1, 1));
1749 ASSERT_TRUE(db_->DoesTableExist("meta"));
1750 ASSERT_GT(db_->ComputeMmapSizeForOpen(), kMmapAlot);
1751 ASSERT_TRUE(MetaTable::GetMmapStatus(db_.get(), &mmap_status));
1752 ASSERT_EQ(MetaTable::kMmapSuccess, mmap_status);
1754 // Preload with partial progress of one page. Should map everything.
1755 ASSERT_TRUE(db_->Execute("REPLACE INTO meta VALUES ('mmap_status', 1)"));
1756 ASSERT_GT(db_->ComputeMmapSizeForOpen(), kMmapAlot);
1757 ASSERT_TRUE(MetaTable::GetMmapStatus(db_.get(), &mmap_status));
1758 ASSERT_EQ(MetaTable::kMmapSuccess, mmap_status);
1760 // Failure status maps nothing.
1761 ASSERT_TRUE(db_->Execute("REPLACE INTO meta VALUES ('mmap_status', -2)"));
1762 ASSERT_EQ(0UL, db_->ComputeMmapSizeForOpen());
1764 // Re-initializing the meta table does not re-create the key if the table
1766 ASSERT_TRUE(db_->Execute("DELETE FROM meta WHERE key = 'mmap_status'"));
1767 ASSERT_TRUE(MetaTable().Init(db_.get(), 1, 1));
1768 ASSERT_EQ(MetaTable::kMmapSuccess, mmap_status);
1769 ASSERT_TRUE(MetaTable::GetMmapStatus(db_.get(), &mmap_status));
1770 ASSERT_EQ(0, mmap_status);
1772 // With no key, map everything and create the key.
1773 // TODO(shess): This really should be "maps everything after validating it",
1774 // but that is more complicated to structure.
1775 ASSERT_GT(db_->ComputeMmapSizeForOpen(), kMmapAlot);
1776 ASSERT_TRUE(MetaTable::GetMmapStatus(db_.get(), &mmap_status));
1777 ASSERT_EQ(MetaTable::kMmapSuccess, mmap_status);
1780 TEST_P(SQLDatabaseTest, ComputeMmapSizeForOpenAltStatus) {
1781 const size_t kMmapAlot = 25 * 1024 * 1024;
1783 // At this point, Database still expects a future [meta] table.
1784 ASSERT_FALSE(db_->DoesTableExist("meta"));
1785 ASSERT_FALSE(db_->DoesViewExist("MmapStatus"));
1786 ASSERT_GT(db_->ComputeMmapSizeForOpen(), kMmapAlot);
1787 ASSERT_FALSE(db_->DoesTableExist("meta"));
1788 ASSERT_FALSE(db_->DoesViewExist("MmapStatus"));
1790 // Using alt status, everything should be mapped, with state in the view.
1791 DatabaseOptions options = GetDBOptions();
1792 options.mmap_alt_status_discouraged = true;
1793 options.enable_views_discouraged = true;
1794 db_ = std::make_unique<Database>(options);
1795 ASSERT_TRUE(db_->Open(db_path_));
1797 ASSERT_GT(db_->ComputeMmapSizeForOpen(), kMmapAlot);
1798 ASSERT_FALSE(db_->DoesTableExist("meta"));
1799 ASSERT_TRUE(db_->DoesViewExist("MmapStatus"));
1800 EXPECT_EQ(base::NumberToString(MetaTable::kMmapSuccess),
1801 ExecuteWithResult(db_.get(), "SELECT * FROM MmapStatus"));
1803 // Also maps everything when kMmapSuccess is already in the view.
1804 ASSERT_GT(db_->ComputeMmapSizeForOpen(), kMmapAlot);
1806 // Preload with partial progress of one page. Should map everything.
1807 ASSERT_TRUE(db_->Execute("DROP VIEW MmapStatus"));
1808 ASSERT_TRUE(db_->Execute("CREATE VIEW MmapStatus (value) AS SELECT 1"));
1809 ASSERT_GT(db_->ComputeMmapSizeForOpen(), kMmapAlot);
1810 EXPECT_EQ(base::NumberToString(MetaTable::kMmapSuccess),
1811 ExecuteWithResult(db_.get(), "SELECT * FROM MmapStatus"));
1813 // Failure status leads to nothing being mapped.
1814 ASSERT_TRUE(db_->Execute("DROP VIEW MmapStatus"));
1815 ASSERT_TRUE(db_->Execute("CREATE VIEW MmapStatus (value) AS SELECT -2"));
1816 ASSERT_EQ(0UL, db_->ComputeMmapSizeForOpen());
1817 EXPECT_EQ(base::NumberToString(MetaTable::kMmapFailure),
1818 ExecuteWithResult(db_.get(), "SELECT * FROM MmapStatus"));
1821 TEST_P(SQLDatabaseTest, GetMemoryUsage) {
1822 // Databases with mmap enabled may not follow the assumptions below.
1824 db_->set_mmap_disabled();
1825 ASSERT_TRUE(db_->Open(db_path_));
1827 int initial_memory = db_->GetMemoryUsage();
1828 EXPECT_GT(initial_memory, 0)
1829 << "SQLite should always use some memory for a database";
1831 ASSERT_TRUE(db_->Execute("CREATE TABLE foo (a, b)"));
1832 ASSERT_TRUE(db_->Execute("INSERT INTO foo(a, b) VALUES (12, 13)"));
1834 int post_query_memory = db_->GetMemoryUsage();
1835 EXPECT_GT(post_query_memory, initial_memory)
1836 << "Page cache usage should go up after executing queries";
1839 int post_trim_memory = db_->GetMemoryUsage();
1840 EXPECT_GT(post_query_memory, post_trim_memory)
1841 << "Page cache usage should go down after calling TrimMemory()";
1844 TEST_P(SQLDatabaseTest, DoubleQuotedStringLiteralsDisabledByDefault) {
1845 ASSERT_TRUE(db_->Execute("CREATE TABLE data(item TEXT NOT NULL);"));
1851 std::vector<TestCase> test_cases = {
1853 {"SELECT item FROM data WHERE item >= 'string literal'", true},
1854 {"SELECT item FROM data WHERE item >= \"string literal\"", false},
1855 {"INSERT INTO data(item) VALUES('string literal')", true},
1856 {"INSERT INTO data(item) VALUES(\"string literal\")", false},
1857 {"UPDATE data SET item = 'string literal'", true},
1858 {"UPDATE data SET item = \"string literal\"", false},
1859 {"DELETE FROM data WHERE item >= 'string literal'", true},
1860 {"DELETE FROM data WHERE item >= \"string literal\"", false},
1863 {"CREATE INDEX data_item ON data(item) WHERE item >= 'string literal'",
1865 {"CREATE INDEX data_item ON data(item) WHERE item >= \"string literal\"",
1867 {"CREATE TABLE data2(item TEXT DEFAULT 'string literal')", true},
1869 // This should be an invalid DDL statement, due to the double-quoted
1870 // string literal. However, SQLite currently parses it.
1871 {"CREATE TABLE data2(item TEXT DEFAULT \"string literal\")", true},
1874 for (const TestCase& test_case : test_cases) {
1875 SCOPED_TRACE(test_case.sql);
1877 EXPECT_EQ(test_case.is_valid, db_->IsSQLValid(test_case.sql));
1881 TEST_P(SQLDatabaseTest, ForeignKeyEnforcementDisabledByDefault) {
1882 ASSERT_TRUE(db_->Execute("CREATE TABLE targets(id INTEGER PRIMARY KEY)"));
1883 // sqlite3_db_config() currently only disables foreign key enforcement. Schema
1884 // operations on foreign keys are still allowed.
1886 db_->Execute("CREATE TABLE refs("
1887 "id INTEGER PRIMARY KEY,"
1888 "target_id INTEGER REFERENCES targets(id))"));
1890 ASSERT_TRUE(db_->Execute("INSERT INTO targets(id) VALUES(42)"));
1891 ASSERT_TRUE(db_->Execute("INSERT INTO refs(id, target_id) VALUES(42, 42)"));
1893 EXPECT_TRUE(db_->Execute("DELETE FROM targets WHERE id=42"))
1894 << "Foreign key enforcement is not disabled";
1897 TEST_P(SQLDatabaseTest, TriggersDisabledByDefault) {
1898 ASSERT_TRUE(db_->Execute("CREATE TABLE data(id INTEGER)"));
1900 // sqlite3_db_config() currently only disables running triggers. Schema
1901 // operations on triggers are still allowed.
1903 db_->Execute("CREATE TRIGGER trigger AFTER INSERT ON data "
1904 "BEGIN DELETE FROM data; END"));
1906 ASSERT_TRUE(db_->Execute("INSERT INTO data(id) VALUES(42)"));
1908 Statement select(db_->GetUniqueStatement("SELECT id FROM data"));
1909 EXPECT_TRUE(select.Step())
1910 << "If the trigger did not run, the table should not be empty.";
1911 EXPECT_EQ(42, select.ColumnInt64(0));
1913 // sqlite3_db_config() currently only disables running triggers. Schema
1914 // operations on triggers are still allowed.
1915 EXPECT_TRUE(db_->Execute("DROP TRIGGER IF EXISTS trigger"));
1918 #if BUILDFLAG(IS_WIN)
1920 class SQLDatabaseTestExclusiveFileLockMode
1921 : public testing::Test,
1922 public testing::WithParamInterface<::testing::tuple<bool, bool>> {
1924 ~SQLDatabaseTestExclusiveFileLockMode() override = default;
1926 void SetUp() override {
1927 db_ = std::make_unique<Database>(GetDBOptions());
1928 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
1929 db_path_ = temp_dir_.GetPath().AppendASCII("maybelocked.sqlite");
1930 ASSERT_TRUE(db_->Open(db_path_));
1933 DatabaseOptions GetDBOptions() {
1934 DatabaseOptions options;
1935 options.wal_mode = IsWALEnabled();
1936 options.exclusive_locking = true;
1937 options.exclusive_database_file_lock = IsExclusivelockEnabled();
1941 bool IsWALEnabled() { return std::get<0>(GetParam()); }
1942 bool IsExclusivelockEnabled() { return std::get<1>(GetParam()); }
1945 base::ScopedTempDir temp_dir_;
1946 base::FilePath db_path_;
1947 std::unique_ptr<Database> db_;
1950 TEST_P(SQLDatabaseTestExclusiveFileLockMode, BasicStatement) {
1951 ASSERT_TRUE(db_->Execute("CREATE TABLE data(contents TEXT)"));
1952 EXPECT_EQ(SQLITE_OK, db_->GetErrorCode());
1954 ASSERT_TRUE(base::PathExists(db_path_));
1955 base::File open_db(db_path_, base::File::Flags::FLAG_OPEN_ALWAYS |
1956 base::File::Flags::FLAG_READ);
1958 // If exclusive lock is enabled, then the test should not be able to re-open
1959 // the database file, on Windows only.
1960 EXPECT_EQ(IsExclusivelockEnabled(), !open_db.IsValid());
1963 INSTANTIATE_TEST_SUITE_P(
1965 SQLDatabaseTestExclusiveFileLockMode,
1966 ::testing::Combine(::testing::Bool(), ::testing::Bool()),
1967 [](const auto& info) {
1968 return base::StrCat(
1969 {std::get<0>(info.param) ? "WALEnabled" : "WALDisabled",
1970 std::get<1>(info.param) ? "ExclusiveLock" : "NoExclusiveLock"});
1975 TEST(SQLInvalidDatabaseFlagsDeathTest, ExclusiveDatabaseLock) {
1976 base::ScopedTempDir temp_dir;
1977 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
1978 auto db_path = temp_dir.GetPath().AppendASCII("database_test_locked.sqlite");
1980 Database db({.exclusive_database_file_lock = true});
1982 EXPECT_CHECK_DEATH_WITH(
1983 { std::ignore = db.Open(db_path); },
1984 "exclusive_database_file_lock is only supported on Windows");
1987 #endif // BUILDFLAG(IS_WIN)
1989 class SQLDatabaseTestExclusiveMode : public testing::Test,
1990 public testing::WithParamInterface<bool> {
1992 ~SQLDatabaseTestExclusiveMode() override = default;
1994 void SetUp() override {
1995 db_ = std::make_unique<Database>(GetDBOptions());
1996 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
1997 db_path_ = temp_dir_.GetPath().AppendASCII("recovery_test.sqlite");
1998 ASSERT_TRUE(db_->Open(db_path_));
2001 DatabaseOptions GetDBOptions() {
2002 DatabaseOptions options;
2003 options.wal_mode = IsWALEnabled();
2004 options.exclusive_locking = true;
2008 bool IsWALEnabled() { return GetParam(); }
2011 base::ScopedTempDir temp_dir_;
2012 base::FilePath db_path_;
2013 std::unique_ptr<Database> db_;
2016 TEST_P(SQLDatabaseTestExclusiveMode, LockingModeExclusive) {
2017 EXPECT_EQ(ExecuteWithResult(db_.get(), "PRAGMA locking_mode"), "exclusive");
2020 TEST_P(SQLDatabaseTest, LockingModeNormal) {
2021 EXPECT_EQ(ExecuteWithResult(db_.get(), "PRAGMA locking_mode"), "normal");
2024 TEST_P(SQLDatabaseTest, OpenedInCorrectMode) {
2025 std::string expected_mode = IsWALEnabled() ? "wal" : "truncate";
2026 EXPECT_EQ(ExecuteWithResult(db_.get(), "PRAGMA journal_mode"), expected_mode);
2029 TEST_P(SQLDatabaseTest, CheckpointDatabase) {
2030 if (!IsWALEnabled())
2033 base::FilePath wal_path = Database::WriteAheadLogPath(db_path_);
2035 int64_t wal_size = 0;
2036 // WAL file initially empty.
2037 EXPECT_TRUE(base::PathExists(wal_path));
2038 base::GetFileSize(wal_path, &wal_size);
2039 EXPECT_EQ(wal_size, 0);
2042 db_->Execute("CREATE TABLE foo (id INTEGER UNIQUE, value INTEGER)"));
2043 ASSERT_TRUE(db_->Execute("INSERT INTO foo VALUES (1, 1)"));
2044 ASSERT_TRUE(db_->Execute("INSERT INTO foo VALUES (2, 2)"));
2046 // Writes reach WAL file but not db file.
2047 base::GetFileSize(wal_path, &wal_size);
2048 EXPECT_GT(wal_size, 0);
2050 int64_t db_size = 0;
2051 base::GetFileSize(db_path_, &db_size);
2052 EXPECT_EQ(db_size, db_->page_size());
2054 // Checkpoint database to immediately propagate writes to DB file.
2055 EXPECT_TRUE(db_->CheckpointDatabase());
2057 base::GetFileSize(db_path_, &db_size);
2058 EXPECT_GT(db_size, db_->page_size());
2059 EXPECT_EQ(ExecuteWithResult(db_.get(), "SELECT value FROM foo where id=1"),
2061 EXPECT_EQ(ExecuteWithResult(db_.get(), "SELECT value FROM foo where id=2"),
2065 TEST_P(SQLDatabaseTest, OpenFailsAfterCorruptSizeInHeader) {
2066 // The database file ends up empty if we don't create at least one table.
2068 db_->Execute("CREATE TABLE rows(i INTEGER PRIMARY KEY NOT NULL)"));
2071 ASSERT_TRUE(sql::test::CorruptSizeInHeader(db_path_));
2073 sql::test::ScopedErrorExpecter expecter;
2074 expecter.ExpectError(SQLITE_CORRUPT);
2075 ASSERT_TRUE(db_->Open(db_path_));
2076 EXPECT_TRUE(expecter.SawExpectedErrors());
2080 TEST_P(SQLDatabaseTest, ExecuteFailsAfterCorruptSizeInHeader) {
2082 db_->Execute("CREATE TABLE rows(i INTEGER PRIMARY KEY NOT NULL)"));
2083 constexpr static char kSelectSql[] = "SELECT * from rows";
2084 EXPECT_TRUE(db_->Execute(kSelectSql))
2085 << "The test Execute() statement fails before the header is corrupted";
2088 ASSERT_TRUE(sql::test::CorruptSizeInHeader(db_path_));
2090 sql::test::ScopedErrorExpecter expecter;
2091 expecter.ExpectError(SQLITE_CORRUPT);
2092 ASSERT_TRUE(db_->Open(db_path_));
2093 EXPECT_TRUE(expecter.SawExpectedErrors())
2094 << "Database::Open() did not encounter SQLITE_CORRUPT";
2097 sql::test::ScopedErrorExpecter expecter;
2098 expecter.ExpectError(SQLITE_CORRUPT);
2099 EXPECT_FALSE(db_->Execute(kSelectSql));
2100 EXPECT_TRUE(expecter.SawExpectedErrors())
2101 << "Database::Execute() did not encounter SQLITE_CORRUPT";
2105 TEST_P(SQLDatabaseTest, SchemaFailsAfterCorruptSizeInHeader) {
2107 db_->Execute("CREATE TABLE rows(i INTEGER PRIMARY KEY NOT NULL)"));
2108 ASSERT_TRUE(db_->DoesTableExist("rows"))
2109 << "The test schema check fails before the header is corrupted";
2112 ASSERT_TRUE(sql::test::CorruptSizeInHeader(db_path_));
2114 sql::test::ScopedErrorExpecter expecter;
2115 expecter.ExpectError(SQLITE_CORRUPT);
2116 ASSERT_TRUE(db_->Open(db_path_));
2117 EXPECT_TRUE(expecter.SawExpectedErrors())
2118 << "Database::Open() did not encounter SQLITE_CORRUPT";
2121 sql::test::ScopedErrorExpecter expecter;
2122 expecter.ExpectError(SQLITE_CORRUPT);
2123 EXPECT_FALSE(db_->DoesTableExist("rows"));
2124 EXPECT_TRUE(expecter.SawExpectedErrors())
2125 << "Database::DoesTableExist() did not encounter SQLITE_CORRUPT";
2129 TEST(SQLEmptyPathDatabaseTest, EmptyPathTest) {
2131 EXPECT_TRUE(db.OpenInMemory());
2132 EXPECT_TRUE(db.is_open());
2133 EXPECT_TRUE(db.DbPath().empty());
2136 // WAL mode is currently not supported on Fuchsia.
2137 #if !BUILDFLAG(IS_FUCHSIA)
2138 INSTANTIATE_TEST_SUITE_P(JournalMode, SQLDatabaseTest, testing::Bool());
2139 INSTANTIATE_TEST_SUITE_P(JournalMode,
2140 SQLDatabaseTestExclusiveMode,
2143 INSTANTIATE_TEST_SUITE_P(JournalMode, SQLDatabaseTest, testing::Values(false));
2144 INSTANTIATE_TEST_SUITE_P(JournalMode,
2145 SQLDatabaseTestExclusiveMode,
2146 testing::Values(false));