[M120 Migration][VD] Fix url crash in RequestCertificateConfirm
[platform/framework/web/chromium-efl.git] / sql / database_unittest.cc
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.
4
5 #include "sql/database.h"
6
7 #include <stddef.h>
8 #include <stdint.h>
9 #include <cstdint>
10
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"
39
40 namespace sql {
41
42 namespace {
43
44 using sql::test::ExecuteWithResult;
45
46 // Helper to return the count of items in sqlite_schema.  Return -1 in
47 // case of error.
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;
52 }
53
54 // Handle errors by blowing away the database.
55 void RazeErrorCallback(Database* db,
56                        int expected_error,
57                        int error,
58                        Statement* stmt) {
59   // Nothing here needs extended errors at this time.
60   EXPECT_EQ(expected_error, expected_error & 0xff);
61   EXPECT_EQ(expected_error, error & 0xff);
62   db->RazeAndPoison();
63 }
64
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 {
69  public:
70   explicit ScopedUmaskSetter(mode_t target_mask) {
71     old_umask_ = umask(target_mask);
72   }
73   ~ScopedUmaskSetter() { umask(old_umask_); }
74
75   ScopedUmaskSetter(const ScopedUmaskSetter&) = delete;
76   ScopedUmaskSetter& operator=(const ScopedUmaskSetter&) = delete;
77
78  private:
79   mode_t old_umask_;
80 };
81 #endif  // BUILDFLAG(IS_POSIX)
82
83 }  // namespace
84
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> {
88  public:
89   enum class OverwriteType {
90     kTruncate,
91     kOverwrite,
92   };
93
94   ~SQLDatabaseTest() override = default;
95
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_));
101   }
102
103   DatabaseOptions GetDBOptions() {
104     DatabaseOptions options;
105     options.wal_mode = IsWALEnabled();
106     // TODO(crbug.com/1120969): Remove after switching to exclusive mode on by
107     // default.
108     options.exclusive_locking = false;
109 #if BUILDFLAG(IS_FUCHSIA)  // Exclusive mode needs to be enabled to enter WAL
110                            // mode on Fuchsia
111     if (IsWALEnabled()) {
112       options.exclusive_locking = true;
113     }
114 #endif  // BUILDFLAG(IS_FUCHSIA)
115     return options;
116   }
117
118   bool IsWALEnabled() { return GetParam(); }
119
120   bool TruncateDatabase() {
121     base::File file(db_path_,
122                     base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
123     return file.SetLength(0);
124   }
125
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))
131         return false;
132     }
133
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;
137   }
138
139  protected:
140   base::ScopedTempDir temp_dir_;
141   base::FilePath db_path_;
142   std::unique_ptr<Database> db_;
143 };
144
145 TEST_P(SQLDatabaseTest, Execute_ValidStatement) {
146   ASSERT_TRUE(db_->Execute("CREATE TABLE data(contents TEXT)"));
147   EXPECT_EQ(SQLITE_OK, db_->GetErrorCode());
148 }
149
150 TEST_P(SQLDatabaseTest, Execute_InvalidStatement) {
151   {
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());
156   }
157   EXPECT_EQ(SQLITE_ERROR, db_->GetErrorCode());
158 }
159
160 TEST_P(SQLDatabaseTest, ExecuteScriptForTesting_OneLineValid) {
161   ASSERT_TRUE(db_->ExecuteScriptForTesting("CREATE TABLE data(contents TEXT)"));
162   EXPECT_EQ(SQLITE_OK, db_->GetErrorCode());
163 }
164
165 TEST_P(SQLDatabaseTest, ExecuteScriptForTesting_OneLineInvalid) {
166   ASSERT_FALSE(db_->ExecuteScriptForTesting("CREATE TABLE data("));
167   EXPECT_EQ(SQLITE_ERROR, db_->GetErrorCode());
168 }
169
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";
177
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";
184
185   EXPECT_TRUE(db_->ExecuteScriptForTesting("CREATE TABLE data8(id);-- Comment"))
186       << "Comment without whitespace";
187   EXPECT_TRUE(
188       db_->ExecuteScriptForTesting("CREATE TABLE data9(id); -- Comment"))
189       << "Comment sepatated by whitespace";
190 }
191
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);
197   )"));
198   EXPECT_EQ(SQLITE_OK, db_->GetErrorCode());
199
200   // DoesColumnExist() is implemented directly on top of a SQLite call. The
201   // other schema functions use sql::Statement infrastructure to query the
202   // schema table.
203   EXPECT_TRUE(db_->DoesColumnExist("data1", "contents"));
204   EXPECT_TRUE(db_->DoesColumnExist("data2", "contents"));
205   EXPECT_TRUE(db_->DoesColumnExist("data3", "contents"));
206 }
207
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);
213   )"));
214   EXPECT_EQ(SQLITE_ERROR, db_->GetErrorCode());
215
216   EXPECT_TRUE(db_->DoesColumnExist("data1", "contents"));
217   EXPECT_FALSE(db_->DoesColumnExist("data3", "contents"));
218 }
219
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);
226   )"));
227   EXPECT_EQ(SQLITE_CONSTRAINT_UNIQUE, db_->GetErrorCode());
228
229   EXPECT_TRUE(db_->DoesColumnExist("data1", "contents"));
230   EXPECT_FALSE(db_->DoesColumnExist("data3", "contents"));
231 }
232
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";
238
239   ASSERT_TRUE(db_->Execute("CREATE TABLE foo (a, b)"));
240   ASSERT_TRUE(db_->Execute("INSERT INTO foo(a, b) VALUES (12, 13)"));
241
242   sqlite3_stmt* raw_id1_statement;
243   sqlite3_stmt* raw_id2_statement;
244   {
245     scoped_refptr<Database::StatementRef> ref_from_id1 =
246         db_->GetCachedStatement(id1, kId1Sql);
247     raw_id1_statement = ref_from_id1->stmt();
248
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));
253
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);
258
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));
263   }
264
265   {
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";
270
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));
275
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";
280
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));
285   }
286
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";
291 }
292
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"));
297 }
298
299 TEST_P(SQLDatabaseTest, DoesTableExist) {
300   EXPECT_FALSE(db_->DoesTableExist("foo"));
301   EXPECT_FALSE(db_->DoesTableExist("foo_index"));
302
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"));
307
308   // DoesTableExist() is case-sensitive.
309   EXPECT_FALSE(db_->DoesTableExist("Foo"));
310   EXPECT_FALSE(db_->DoesTableExist("FOO"));
311 }
312
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"));
317
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"));
321
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"));
326 }
327
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"));
334
335   // DoesTableExist() is case-sensitive.
336   EXPECT_FALSE(db_->DoesViewExist("Voo"));
337   EXPECT_FALSE(db_->DoesViewExist("VOO"));
338 }
339
340 TEST_P(SQLDatabaseTest, DoesColumnExist) {
341   ASSERT_TRUE(db_->Execute("CREATE TABLE foo (a, b)"));
342
343   EXPECT_FALSE(db_->DoesColumnExist("foo", "bar"));
344   EXPECT_TRUE(db_->DoesColumnExist("foo", "a"));
345
346   ASSERT_FALSE(db_->DoesTableExist("bar"));
347   EXPECT_FALSE(db_->DoesColumnExist("bar", "b"));
348
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"));
353 }
354
355 TEST_P(SQLDatabaseTest, GetLastInsertRowId) {
356   ASSERT_TRUE(db_->Execute("CREATE TABLE foo (id INTEGER PRIMARY KEY, value)"));
357
358   ASSERT_TRUE(db_->Execute("INSERT INTO foo (value) VALUES (12)"));
359
360   // Last insert row ID should be valid.
361   int64_t row = db_->GetLastInsertRowId();
362   EXPECT_LT(0, row);
363
364   // It should be the primary key of the row we just inserted.
365   Statement s(db_->GetUniqueStatement("SELECT value FROM foo WHERE id=?"));
366   s.BindInt64(0, row);
367   ASSERT_TRUE(s.Step());
368   EXPECT_EQ(12, s.ColumnInt(0));
369 }
370
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)"));
377
378   {
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());
383   }
384 }
385
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"));
392   db_->Close();
393
394   // Corrupt the database so that nothing works, including PRAGMAs.
395   ASSERT_TRUE(sql::test::CorruptSizeInHeader(db_path_));
396
397   {
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());
405   }
406 }
407
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)"));
413
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;
420       }));
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";
427 }
428
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";
433 }
434
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)"));
440
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;
447       }));
448   db_->reset_error_callback();
449
450   {
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";
457   }
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()";
462 }
463
464 // Sets a flag to true/false to track being alive.
465 class LifeTracker {
466  public:
467   explicit LifeTracker(bool* flag_ptr) : flag_ptr_(flag_ptr) {
468     DCHECK(flag_ptr != nullptr);
469     DCHECK(!*flag_ptr)
470         << "LifeTracker's flag should be set to false prior to construction";
471     *flag_ptr_ = true;
472   }
473
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;
479   }
480
481   // base::RepeatingCallback only requires move-construction support.
482   LifeTracker& operator=(const LifeTracker& rhs) = delete;
483
484   ~LifeTracker() {
485     DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
486     if (flag_ptr_)
487       *flag_ptr_ = false;
488   }
489
490  private:
491   SEQUENCE_CHECKER(sequence_checker_);
492   raw_ptr<bool> flag_ptr_ GUARDED_BY_CONTEXT(sequence_checker_);
493 };
494
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()";
513       },
514       base::Unretained(db_.get()), base::Unretained(&is_alive),
515       LifeTracker(&is_alive)));
516
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";
522 }
523
524 TEST_P(SQLDatabaseTest, Execute_CompilationError) {
525   bool error_callback_called = false;
526   db_->set_error_callback(base::BindLambdaForTesting([&](int error,
527                                                          sql::Statement*
528                                                              statement) {
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;
534   }));
535
536   {
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());
541   }
542
543   EXPECT_TRUE(error_callback_called)
544       << "SQL compilation errors should call the error callback";
545 }
546
547 TEST_P(SQLDatabaseTest, GetUniqueStatement_CompilationError) {
548   bool error_callback_called = false;
549   db_->set_error_callback(base::BindLambdaForTesting([&](int error,
550                                                          sql::Statement*
551                                                              statement) {
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;
557   }));
558
559   {
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());
566   }
567
568   EXPECT_TRUE(error_callback_called)
569       << "SQL compilation errors should call the error callback";
570 }
571
572 TEST_P(SQLDatabaseTest, GetCachedStatement_CompilationError) {
573   bool error_callback_called = false;
574   db_->set_error_callback(base::BindLambdaForTesting([&](int error,
575                                                          sql::Statement*
576                                                              statement) {
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;
582   }));
583
584   {
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());
591   }
592
593   EXPECT_TRUE(error_callback_called)
594       << "SQL compilation errors should call the error callback";
595 }
596
597 TEST_P(SQLDatabaseTest, GetUniqueStatement_ExtraContents) {
598   sql::Statement minimal(db_->GetUniqueStatement("SELECT 1"));
599   sql::Statement extra_semicolon(db_->GetUniqueStatement("SELECT 1;"));
600
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"));
605
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";
614 }
615
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;"));
620
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"));
625
626   EXPECT_DCHECK_DEATH(
627       db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1;SELECT 2"))
628       << "Extra statement without whitespace";
629   EXPECT_DCHECK_DEATH(
630       db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1; SELECT 2"))
631       << "Extra statement separated by whitespace";
632   EXPECT_DCHECK_DEATH(
633       db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1;-- Comment"))
634       << "Comment without whitespace";
635   EXPECT_DCHECK_DEATH(
636       db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1; -- Comment"))
637       << "Comment separated by whitespace";
638 }
639
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";
644
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";
649
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";
658 }
659
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";
665 }
666
667 TEST_P(SQLDatabaseTest, GetCachedStatement_NoContents) {
668   EXPECT_DCHECK_DEATH(db_->GetCachedStatement(SQL_FROM_HERE, ""))
669       << "Empty string";
670   EXPECT_DCHECK_DEATH(db_->GetCachedStatement(SQL_FROM_HERE, " ")) << "Space";
671   EXPECT_DCHECK_DEATH(db_->GetCachedStatement(SQL_FROM_HERE, "\n"))
672       << "Newline";
673   EXPECT_DCHECK_DEATH(db_->GetCachedStatement(SQL_FROM_HERE, "-- Comment"))
674       << "Comment";
675 }
676
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)"));
681
682   // PRAGMA statements do not change the database file.
683   {
684     Statement s(db_->GetReadonlyStatement("PRAGMA analysis_limit"));
685     ASSERT_TRUE(s.Step());
686   }
687   {
688     Statement s(db_->GetReadonlyStatement("PRAGMA analysis_limit=100"));
689     ASSERT_TRUE(s.is_valid());
690   }
691
692   // Create and insert statements should fail, while the same queries as unique
693   // statement succeeds.
694   {
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());
701   }
702   {
703     Statement s(
704         db_->GetReadonlyStatement("INSERT INTO foo (value) VALUES (12)"));
705     ASSERT_FALSE(s.is_valid());
706     Statement s1(
707         db_->GetUniqueStatement("INSERT INTO foo (value) VALUES (12)"));
708     ASSERT_TRUE(s1.is_valid());
709   }
710   {
711     Statement s(
712         db_->GetReadonlyStatement("CREATE VIRTUAL TABLE bar USING module"));
713     ASSERT_FALSE(s.is_valid());
714     Statement s1(
715         db_->GetUniqueStatement("CREATE VIRTUAL TABLE bar USING module"));
716     ASSERT_TRUE(s1.is_valid());
717   }
718
719   // Select statement is successful.
720   {
721     Statement s(db_->GetReadonlyStatement("SELECT * FROM foo"));
722     ASSERT_TRUE(s.Step());
723     EXPECT_EQ(s.ColumnInt(1), 12);
724   }
725 }
726
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";
732 }
733
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)"));
740
741   int pragma_auto_vacuum = 0;
742   {
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);
747   }
748
749   // If auto_vacuum is set, there's an extra page to maintain a freelist.
750   const int kExpectedPageCount = 2 + pragma_auto_vacuum;
751
752   {
753     Statement s(db_->GetUniqueStatement("PRAGMA page_count"));
754     ASSERT_TRUE(s.Step());
755     EXPECT_EQ(kExpectedPageCount, s.ColumnInt(0));
756   }
757
758   {
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));
767   }
768
769   ASSERT_TRUE(db_->Raze());
770
771   {
772     Statement s(db_->GetUniqueStatement("PRAGMA page_count"));
773     ASSERT_TRUE(s.Step());
774     EXPECT_EQ(1, s.ColumnInt(0));
775   }
776
777   ASSERT_EQ(0, SqliteSchemaCount(db_.get()));
778
779   {
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));
784   }
785 }
786
787 TEST_P(SQLDatabaseTest, RazeDuringSelect) {
788   ASSERT_TRUE(
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)"));
792
793   {
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";
799   }
800
801   {
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";
805   }
806 }
807
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,
815                   int final_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')";
820
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"));
831   db.Close();
832
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());
839
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.
844   EXPECT_EQ("0",
845             ExecuteWithResult(&razed_db, "SELECT COUNT(*) FROM sqlite_schema"));
846
847   EXPECT_EQ(expected_final_page_size,
848             ExecuteWithResult(&razed_db, "PRAGMA page_size"));
849   EXPECT_EQ("1", ExecuteWithResult(&razed_db, "PRAGMA page_count"));
850 }
851
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");
858
859   // Sync uses 32k pages.
860   EXPECT_NO_FATAL_FAILURE(
861       TestPageSize(db_path_, 32768, "32768", 32768, "32768"));
862
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"));
865
866   // 1k is the default page size before 3.12.0.
867   EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path_, 1024, "1024", 1024, "1024"));
868
869   EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path_, 2048, "2048", 4096, "4096"));
870
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,
876                                        default_page_size));
877 }
878
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));
883
884   Database other_db(GetDBOptions());
885   ASSERT_TRUE(other_db.Open(db_path_));
886
887   // Check that the second connection sees the table.
888   ASSERT_EQ(1, SqliteSchemaCount(&other_db));
889
890   ASSERT_TRUE(db_->Raze());
891
892   // The second connection sees the updated database.
893   ASSERT_EQ(0, SqliteSchemaCount(&other_db));
894 }
895
896 TEST_P(SQLDatabaseTest, Raze_OtherConnectionHasWriteLock) {
897   ASSERT_TRUE(db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY)"));
898
899   Database other_db(GetDBOptions());
900   ASSERT_TRUE(other_db.Open(db_path_));
901
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)"));
905
906   EXPECT_FALSE(db_->Raze())
907       << "Raze() should fail while another connection has a write lock";
908
909   ASSERT_TRUE(other_db_transaction.Commit());
910   EXPECT_TRUE(db_->Raze())
911       << "Raze() should succeed after the other connection releases the lock";
912 }
913
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)"));
917
918   if (IsWALEnabled()) {
919     // In WAL mode, read transactions in other connections do not block a write
920     // transaction.
921     return;
922   }
923
924   Database other_db(GetDBOptions());
925   ASSERT_TRUE(other_db.Open(db_path_));
926
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";
931
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";
936 }
937
938 TEST_P(SQLDatabaseTest, Raze_EmptyDatabaseFile) {
939   ASSERT_TRUE(
940       db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
941   db_->Close();
942
943   ASSERT_TRUE(TruncateDatabase());
944   ASSERT_TRUE(db_->Open(db_path_))
945       << "Failed to reopen database after truncating";
946
947   EXPECT_TRUE(db_->Raze()) << "Raze() failed on an empty file";
948   EXPECT_TRUE(
949       db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"))
950       << "Raze() did not produce a healthy empty database";
951 }
952
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) {
957   db_->Close();
958   Database::Delete(db_path_);
959   ASSERT_FALSE(base::PathExists(db_path_));
960
961   ASSERT_TRUE(OverwriteDatabaseHeader(OverwriteType::kTruncate));
962   ASSERT_TRUE(base::PathExists(db_path_));
963
964   // SQLite will successfully open the handle, but fail when running PRAGMA
965   // statements that access the database.
966   {
967     sql::test::ScopedErrorExpecter expecter;
968     expecter.ExpectError(SQLITE_NOTADB);
969
970     EXPECT_TRUE(db_->Open(db_path_));
971     ASSERT_TRUE(expecter.SawExpectedErrors());
972   }
973   EXPECT_TRUE(db_->Raze());
974   db_->Close();
975
976   // Now empty, the open should open an empty database.
977   EXPECT_TRUE(db_->Open(db_path_));
978   EXPECT_EQ(0, SqliteSchemaCount(db_.get()));
979 }
980
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()));
986   db_->Close();
987
988   ASSERT_TRUE(OverwriteDatabaseHeader(OverwriteType::kOverwrite));
989
990   // SQLite will successfully open the handle, but will fail with
991   // SQLITE_NOTADB on pragma statemenets which attempt to read the
992   // corrupted header.
993   {
994     sql::test::ScopedErrorExpecter expecter;
995     expecter.ExpectError(SQLITE_NOTADB);
996     EXPECT_TRUE(db_->Open(db_path_));
997     ASSERT_TRUE(expecter.SawExpectedErrors());
998   }
999   EXPECT_TRUE(db_->Raze());
1000   db_->Close();
1001
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()));
1005 }
1006
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()));
1015   db_->Close();
1016
1017   // Corrupt the database so that nothing works, including PRAGMAs.
1018   ASSERT_TRUE(sql::test::CorruptSizeInHeader(db_path_));
1019
1020   // Open() will succeed, even though the PRAGMA calls within will
1021   // fail with SQLITE_CORRUPT, as will this PRAGMA.
1022   {
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"));
1027     db_->Close();
1028     ASSERT_TRUE(expecter.SawExpectedErrors());
1029   }
1030
1031   db_->set_error_callback(
1032       base::BindRepeating(&RazeErrorCallback, db_.get(), SQLITE_CORRUPT));
1033
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
1037   // cleanly.
1038   ASSERT_TRUE(db_->Open(db_path_));
1039   ASSERT_TRUE(db_->Execute("PRAGMA auto_vacuum"));
1040   EXPECT_EQ(0, SqliteSchemaCount(db_.get()));
1041 }
1042
1043 TEST_P(SQLDatabaseTest, RazeAndPoison_DeletesData) {
1044   ASSERT_TRUE(
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());
1048
1049   // We need to call Close() in order to re-Open().
1050   db_->Close();
1051   ASSERT_TRUE(db_->Open(db_path_))
1052       << "RazeAndPoison() did not produce a healthy database";
1053   EXPECT_TRUE(
1054       db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"))
1055       << "RazeAndPoison() did not produce a healthy empty database";
1056 }
1057
1058 TEST_P(SQLDatabaseTest, RazeAndPoison_IsOpen) {
1059   ASSERT_TRUE(
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());
1063
1064   EXPECT_FALSE(db_->is_open())
1065       << "RazeAndPoison() did not mark the database as closed";
1066 }
1067
1068 TEST_P(SQLDatabaseTest, RazeAndPoison_Reopen_NoChanges) {
1069   ASSERT_TRUE(db_->RazeAndPoison());
1070   EXPECT_FALSE(
1071       db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"))
1072       << "Execute() should return false after RazeAndPoison()";
1073
1074   // We need to call Close() in order to re-Open().
1075   db_->Close();
1076   ASSERT_TRUE(db_->Open(db_path_))
1077       << "RazeAndPoison() did not produce a healthy database";
1078   EXPECT_TRUE(
1079       db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"))
1080       << "Execute() returned false but went through after RazeAndPoison()";
1081 }
1082
1083 TEST_P(SQLDatabaseTest, RazeAndPoison_OpenTransaction) {
1084   ASSERT_TRUE(
1085       db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
1086   ASSERT_TRUE(db_->Execute("INSERT INTO rows(id) VALUES(12)"));
1087
1088   Transaction transaction(db_.get());
1089   ASSERT_TRUE(transaction.Begin());
1090   ASSERT_TRUE(db_->RazeAndPoison());
1091
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";
1096
1097   // We need to call Close() in order to re-Open().
1098   db_->Close();
1099
1100   ASSERT_TRUE(db_->Open(db_path_));
1101   EXPECT_TRUE(
1102       db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"))
1103       << "RazeAndPoison() did not produce a healthy empty database";
1104 }
1105
1106 TEST_P(SQLDatabaseTest, RazeAndPoison_Preload_NoCrash) {
1107   db_->Preload();
1108   db_->RazeAndPoison();
1109   db_->Preload();
1110 }
1111
1112 TEST_P(SQLDatabaseTest, RazeAndPoison_DoesTableExist) {
1113   ASSERT_TRUE(
1114       db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
1115   ASSERT_TRUE(db_->DoesTableExist("rows")) << "Incorrect test setup";
1116
1117   ASSERT_TRUE(db_->RazeAndPoison());
1118   EXPECT_FALSE(db_->DoesTableExist("rows"))
1119       << "DoesTableExist() should return false after RazeAndPoison()";
1120 }
1121
1122 TEST_P(SQLDatabaseTest, RazeAndPoison_IsSQLValid) {
1123   ASSERT_TRUE(db_->IsSQLValid("SELECT 1")) << "Incorrect test setup";
1124
1125   ASSERT_TRUE(db_->RazeAndPoison());
1126   EXPECT_FALSE(db_->IsSQLValid("SELECT 1"))
1127       << "IsSQLValid() should return false after RazeAndPoison()";
1128 }
1129
1130 TEST_P(SQLDatabaseTest, RazeAndPoison_Execute) {
1131   ASSERT_TRUE(db_->Execute("SELECT 1")) << "Incorrect test setup";
1132
1133   ASSERT_TRUE(db_->RazeAndPoison());
1134   EXPECT_FALSE(db_->Execute("SELECT 1"))
1135       << "Execute() should return false after RazeAndPoison()";
1136 }
1137
1138 TEST_P(SQLDatabaseTest, RazeAndPoison_GetUniqueStatement) {
1139   {
1140     Statement select(db_->GetUniqueStatement("SELECT 1"));
1141     ASSERT_TRUE(select.Step()) << "Incorrect test setup";
1142   }
1143
1144   ASSERT_TRUE(db_->RazeAndPoison());
1145   {
1146     Statement select(db_->GetUniqueStatement("SELECT 1"));
1147     EXPECT_FALSE(select.Step())
1148         << "GetUniqueStatement() should return an invalid Statement after "
1149         << "RazeAndPoison()";
1150   }
1151 }
1152
1153 TEST_P(SQLDatabaseTest, RazeAndPoison_GetCachedStatement) {
1154   {
1155     Statement select(db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1"));
1156     ASSERT_TRUE(select.Step()) << "Incorrect test setup";
1157   }
1158
1159   ASSERT_TRUE(db_->RazeAndPoison());
1160   {
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()";
1165   }
1166 }
1167
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);
1173
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";
1179 }
1180
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);
1186
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";
1192 }
1193
1194 TEST_P(SQLDatabaseTest, RazeAndPoison_TransactionBegin) {
1195   {
1196     Transaction transaction(db_.get());
1197     ASSERT_TRUE(transaction.Begin()) << "Incorrect test setup";
1198     ASSERT_TRUE(transaction.Commit()) << "Incorrect test setup";
1199   }
1200
1201   ASSERT_TRUE(db_->RazeAndPoison());
1202   {
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";
1208   }
1209 }
1210
1211 TEST_P(SQLDatabaseTest, Close_IsSQLValid) {
1212   ASSERT_TRUE(db_->IsSQLValid("SELECT 1")) << "Incorrect test setup";
1213
1214   db_->Close();
1215
1216   EXPECT_DCHECK_DEATH_WITH({ std::ignore = db_->IsSQLValid("SELECT 1"); },
1217                            "Illegal use of Database without a db");
1218 }
1219
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
1228   // page.
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);
1233
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) {
1238     ASSERT_TRUE(
1239         db_->Execute("INSERT INTO foo (value) VALUES (randomblob(1024))"));
1240   }
1241
1242   // In WAL mode, writes don't reach the database file until a checkpoint
1243   // happens.
1244   ASSERT_TRUE(db_->CheckpointDatabase());
1245
1246   int64_t db_size;
1247   ASSERT_TRUE(base::GetFileSize(db_path_, &db_size));
1248   ASSERT_GT(db_size, expected_size);
1249
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.
1253   EXPECT_EQ("24576",
1254             ExecuteWithResult(db_.get(), "SELECT SUM(LENGTH(value)) FROM foo"));
1255
1256   ASSERT_TRUE(db_->Raze());
1257   ASSERT_TRUE(base::GetFileSize(db_path_, &db_size));
1258   ASSERT_EQ(expected_size, db_size);
1259 }
1260
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
1268   // database file'.
1269   ASSERT_TRUE(meta_table.Init(db_.get(), 4, 4));
1270 }
1271 #endif  // BUILDFLAG(IS_ANDROID)
1272
1273 TEST_P(SQLDatabaseTest, Delete) {
1274   EXPECT_TRUE(db_->Execute("CREATE TABLE x (x)"));
1275   db_->Close();
1276
1277   base::FilePath journal_path = Database::JournalPath(db_path_);
1278   base::FilePath wal_path = Database::WriteAheadLogPath(db_path_);
1279
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));
1285   }
1286
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));
1291 }
1292
1293 #if BUILDFLAG(IS_POSIX)  // This test operates on POSIX file permissions.
1294 TEST_P(SQLDatabaseTest, PosixFilePermissions) {
1295   db_->Close();
1296   Database::Delete(db_path_);
1297   ASSERT_FALSE(base::PathExists(db_path_));
1298
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
1302   // umask.
1303   ScopedUmaskSetter permissive_umask(S_IWGRP | S_IWOTH);
1304
1305   ASSERT_TRUE(db_->Open(db_path_));
1306
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)"));
1310
1311   int mode;
1312   ASSERT_TRUE(base::PathExists(db_path_));
1313   EXPECT_TRUE(base::GetPosixFilePermissions(db_path_, &mode));
1314   ASSERT_EQ(mode, 0600);
1315
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)"));
1319
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);
1324
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);
1331     }
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);
1338   }
1339 }
1340 #endif  // BUILDFLAG(IS_POSIX)
1341
1342 TEST_P(SQLDatabaseTest, Poison_IsOpen) {
1343   db_->Poison();
1344   EXPECT_FALSE(db_->is_open())
1345       << "Poison() did not mark the database as closed";
1346 }
1347
1348 TEST_P(SQLDatabaseTest, Poison_Close_Reopen_NoChanges) {
1349   db_->Poison();
1350   EXPECT_FALSE(
1351       db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"))
1352       << "Execute() should return false after Poison()";
1353
1354   db_->Close();
1355   ASSERT_TRUE(db_->Open(db_path_)) << "Poison() damaged the database";
1356   EXPECT_TRUE(
1357       db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"))
1358       << "Execute() returned false but went through after Poison()";
1359 }
1360
1361 TEST_P(SQLDatabaseTest, Poison_Preload_NoCrash) {
1362   db_->Preload();
1363   db_->Poison();
1364   db_->Preload();
1365 }
1366
1367 TEST_P(SQLDatabaseTest, Poison_DoesTableExist) {
1368   ASSERT_TRUE(
1369       db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
1370   ASSERT_TRUE(db_->DoesTableExist("rows")) << "Incorrect test setup";
1371
1372   db_->Poison();
1373   EXPECT_FALSE(db_->DoesTableExist("rows"))
1374       << "DoesTableExist() should return false after Poison()";
1375 }
1376
1377 TEST_P(SQLDatabaseTest, Poison_IsSQLValid) {
1378   ASSERT_TRUE(db_->IsSQLValid("SELECT 1")) << "Incorrect test setup";
1379
1380   db_->Poison();
1381   EXPECT_FALSE(db_->IsSQLValid("SELECT 1"))
1382       << "IsSQLValid() should return false after Poison()";
1383 }
1384
1385 TEST_P(SQLDatabaseTest, Poison_Execute) {
1386   ASSERT_TRUE(db_->Execute("SELECT 1")) << "Incorrect test setup";
1387
1388   db_->Poison();
1389   EXPECT_FALSE(db_->Execute("SELECT 1"))
1390       << "Execute() should return false after Poison()";
1391 }
1392
1393 TEST_P(SQLDatabaseTest, Poison_GetUniqueStatement) {
1394   {
1395     Statement select(db_->GetUniqueStatement("SELECT 1"));
1396     ASSERT_TRUE(select.Step()) << "Incorrect test setup";
1397   }
1398
1399   db_->Poison();
1400   {
1401     Statement select(db_->GetUniqueStatement("SELECT 1"));
1402     EXPECT_FALSE(select.Step())
1403         << "GetUniqueStatement() should return an invalid Statement after "
1404         << "Poison()";
1405   }
1406 }
1407
1408 TEST_P(SQLDatabaseTest, Poison_GetCachedStatement) {
1409   {
1410     Statement select(db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1"));
1411     ASSERT_TRUE(select.Step()) << "Incorrect test setup";
1412   }
1413
1414   db_->Poison();
1415   {
1416     Statement select(db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1"));
1417     EXPECT_FALSE(select.Step())
1418         << "GetCachedStatement() should return an invalid Statement after "
1419         << "Poison()";
1420   }
1421 }
1422
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);
1428
1429   db_->Poison();
1430   EXPECT_FALSE(select.is_valid())
1431       << "Poison() should invalidate live Statements";
1432   EXPECT_FALSE(select.Step()) << "Poison() should invalidate live Statements";
1433 }
1434
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);
1440
1441   db_->Poison();
1442   EXPECT_FALSE(select.is_valid())
1443       << "Poison() should invalidate live Statements";
1444   EXPECT_FALSE(select.Step()) << "Poison() should invalidate live Statements";
1445 }
1446
1447 TEST_P(SQLDatabaseTest, Poison_TransactionBegin) {
1448   {
1449     Transaction transaction(db_.get());
1450     ASSERT_TRUE(transaction.Begin()) << "Incorrect test setup";
1451     ASSERT_TRUE(transaction.Commit()) << "Incorrect test setup";
1452   }
1453
1454   db_->Poison();
1455   {
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";
1461   }
1462 }
1463
1464 TEST_P(SQLDatabaseTest, Poison_OpenTransaction) {
1465   Transaction transaction(db_.get());
1466   ASSERT_TRUE(transaction.Begin());
1467
1468   db_->Poison();
1469   EXPECT_FALSE(transaction.Commit())
1470       << "Poison() did not cancel the transaction";
1471 }
1472
1473 TEST_P(SQLDatabaseTest, AttachDatabase) {
1474   ASSERT_TRUE(
1475       db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
1476
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";
1481   {
1482     Database other_db;
1483     ASSERT_TRUE(other_db.Open(attach_path));
1484     ASSERT_TRUE(
1485         other_db.Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
1486     ASSERT_TRUE(other_db.Execute("INSERT INTO rows VALUES(42)"));
1487   }
1488
1489   // Cannot see the attached database, yet.
1490   EXPECT_FALSE(db_->IsSQLValid("SELECT COUNT(*) from other.rows"));
1491
1492   EXPECT_TRUE(DatabaseTestPeer::AttachDatabase(db_.get(), attach_path,
1493                                                kAttachmentPoint));
1494   EXPECT_TRUE(db_->IsSQLValid("SELECT COUNT(*) from other.rows"));
1495
1496   // Queries can touch both databases after the ATTACH.
1497   EXPECT_TRUE(db_->Execute("INSERT INTO rows SELECT id FROM other.rows"));
1498   {
1499     Statement select(db_->GetUniqueStatement("SELECT COUNT(*) FROM rows"));
1500     ASSERT_TRUE(select.Step());
1501     EXPECT_EQ(1, select.ColumnInt(0));
1502   }
1503
1504   EXPECT_TRUE(DatabaseTestPeer::DetachDatabase(db_.get(), kAttachmentPoint));
1505   EXPECT_FALSE(db_->IsSQLValid("SELECT COUNT(*) from other.rows"));
1506 }
1507
1508 TEST_P(SQLDatabaseTest, AttachDatabaseWithOpenTransaction) {
1509   ASSERT_TRUE(
1510       db_->Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
1511
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";
1516   {
1517     Database other_db;
1518     ASSERT_TRUE(other_db.Open(attach_path));
1519     ASSERT_TRUE(
1520         other_db.Execute("CREATE TABLE rows(id INTEGER PRIMARY KEY NOT NULL)"));
1521     ASSERT_TRUE(other_db.Execute("INSERT INTO rows VALUES(42)"));
1522   }
1523
1524   // Cannot see the attached database, yet.
1525   EXPECT_FALSE(db_->IsSQLValid("SELECT COUNT(*) from other.rows"));
1526
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,
1531                                                kAttachmentPoint));
1532   EXPECT_TRUE(db_->IsSQLValid("SELECT COUNT(*) from other.rows"));
1533
1534   // Queries can touch both databases after the ATTACH.
1535   EXPECT_TRUE(db_->Execute("INSERT INTO rows SELECT id FROM other.rows"));
1536   {
1537     Statement select(db_->GetUniqueStatement("SELECT COUNT(*) FROM rows"));
1538     ASSERT_TRUE(select.Step());
1539     EXPECT_EQ(1, select.ColumnInt(0));
1540   }
1541
1542   // Detaching the same database fails, database is locked in the transaction.
1543   {
1544     sql::test::ScopedErrorExpecter expecter;
1545     expecter.ExpectError(SQLITE_ERROR);
1546     EXPECT_FALSE(DatabaseTestPeer::DetachDatabase(db_.get(), kAttachmentPoint));
1547     ASSERT_TRUE(expecter.SawExpectedErrors());
1548   }
1549   EXPECT_TRUE(db_->IsSQLValid("SELECT COUNT(*) from other.rows"));
1550
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"));
1555 }
1556
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)"));
1562
1563   {
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";
1569   }
1570
1571   db_->Close();
1572   ASSERT_TRUE(sql::test::CorruptIndexRootPage(db_path_, "rows_by_value"));
1573   ASSERT_TRUE(db_->Open(db_path_));
1574
1575   {
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";
1581   }
1582 }
1583
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);
1590 }
1591
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"));
1598
1599   // A statement to see in the results.
1600   const char* kSimpleSql = "SELECT 'mountain'";
1601   Statement s(db_->GetCachedStatement(SQL_FROM_HERE, kSimpleSql));
1602
1603   // Error includes the statement.
1604   {
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);
1610   }
1611
1612   // Some other error doesn't include the statement.
1613   {
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());
1619   }
1620
1621   // A table to see in the SQLITE_ERROR results.
1622   EXPECT_TRUE(db_->Execute("CREATE TABLE volcano (x)"));
1623
1624   // Version info to see in the SQLITE_ERROR results.
1625   MetaTable meta_table;
1626   ASSERT_TRUE(meta_table.Init(db_.get(), 4, 4));
1627
1628   {
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);
1637
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)");
1643
1644     ASSERT_EQ(diagnostics.schema_other_row_names.size(), 1U);
1645     EXPECT_EQ(diagnostics.schema_other_row_names[0], "sqlite_autoindex_meta_1");
1646   }
1647
1648   // Test that an error message is included in the diagnostics.
1649   {
1650     sql::test::ScopedErrorExpecter error_expecter;
1651     error_expecter.ExpectError(SQLITE_ERROR);
1652     EXPECT_FALSE(
1653         db_->Execute("INSERT INTO volcano VALUES ('bound_value1', 42, 1234)"));
1654     EXPECT_TRUE(error_expecter.SawExpectedErrors());
1655
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"));
1663
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"));
1668   }
1669 }
1670
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) {
1674   {
1675     Statement s(db_->GetUniqueStatement("PRAGMA mmap_size"));
1676     ASSERT_TRUE(s.Step())
1677         << "All supported SQLite versions should have mmap support";
1678
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"));
1685       s.Reset(true);
1686       ASSERT_TRUE(s.Step());
1687       EXPECT_LE(s.ColumnInt(0), 0);
1688     }
1689   }
1690
1691   // Test that explicit disable prevents mmap'ed I/O.
1692   db_->Close();
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"));
1697 }
1698
1699 // Test whether a fresh database gets mmap enabled when using alternate status
1700 // storage.
1701 TEST_P(SQLDatabaseTest, MmapInitiallyEnabledAltStatus) {
1702   // Re-open fresh database with alt-status flag set.
1703   db_->Close();
1704   Database::Delete(db_path_);
1705
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_));
1711
1712   {
1713     Statement s(db_->GetUniqueStatement("PRAGMA mmap_size"));
1714     ASSERT_TRUE(s.Step())
1715         << "All supported SQLite versions should have mmap support";
1716
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"));
1723       s.Reset(true);
1724       ASSERT_TRUE(s.Step());
1725       EXPECT_LE(s.ColumnInt(0), 0);
1726     }
1727   }
1728
1729   // Test that explicit disable overrides set_mmap_alt_status().
1730   db_->Close();
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"));
1735 }
1736
1737 TEST_P(SQLDatabaseTest, ComputeMmapSizeForOpen) {
1738   const size_t kMmapAlot = 25 * 1024 * 1024;
1739   int64_t mmap_status = MetaTable::kMmapFailure;
1740
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"));
1746
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);
1753
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);
1759
1760   // Failure status maps nothing.
1761   ASSERT_TRUE(db_->Execute("REPLACE INTO meta VALUES ('mmap_status', -2)"));
1762   ASSERT_EQ(0UL, db_->ComputeMmapSizeForOpen());
1763
1764   // Re-initializing the meta table does not re-create the key if the table
1765   // already exists.
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);
1771
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);
1778 }
1779
1780 TEST_P(SQLDatabaseTest, ComputeMmapSizeForOpenAltStatus) {
1781   const size_t kMmapAlot = 25 * 1024 * 1024;
1782
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"));
1789
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_));
1796
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"));
1802
1803   // Also maps everything when kMmapSuccess is already in the view.
1804   ASSERT_GT(db_->ComputeMmapSizeForOpen(), kMmapAlot);
1805
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"));
1812
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"));
1819 }
1820
1821 TEST_P(SQLDatabaseTest, GetMemoryUsage) {
1822   // Databases with mmap enabled may not follow the assumptions below.
1823   db_->Close();
1824   db_->set_mmap_disabled();
1825   ASSERT_TRUE(db_->Open(db_path_));
1826
1827   int initial_memory = db_->GetMemoryUsage();
1828   EXPECT_GT(initial_memory, 0)
1829       << "SQLite should always use some memory for a database";
1830
1831   ASSERT_TRUE(db_->Execute("CREATE TABLE foo (a, b)"));
1832   ASSERT_TRUE(db_->Execute("INSERT INTO foo(a, b) VALUES (12, 13)"));
1833
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";
1837
1838   db_->TrimMemory();
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()";
1842 }
1843
1844 TEST_P(SQLDatabaseTest, DoubleQuotedStringLiteralsDisabledByDefault) {
1845   ASSERT_TRUE(db_->Execute("CREATE TABLE data(item TEXT NOT NULL);"));
1846
1847   struct TestCase {
1848     const char* sql;
1849     bool is_valid;
1850   };
1851   std::vector<TestCase> test_cases = {
1852       // DML tests.
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},
1861
1862       // DDL tests.
1863       {"CREATE INDEX data_item ON data(item) WHERE item >= 'string literal'",
1864        true},
1865       {"CREATE INDEX data_item ON data(item) WHERE item >= \"string literal\"",
1866        false},
1867       {"CREATE TABLE data2(item TEXT DEFAULT 'string literal')", true},
1868
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},
1872   };
1873
1874   for (const TestCase& test_case : test_cases) {
1875     SCOPED_TRACE(test_case.sql);
1876
1877     EXPECT_EQ(test_case.is_valid, db_->IsSQLValid(test_case.sql));
1878   }
1879 }
1880
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.
1885   ASSERT_TRUE(
1886       db_->Execute("CREATE TABLE refs("
1887                    "id INTEGER PRIMARY KEY,"
1888                    "target_id INTEGER REFERENCES targets(id))"));
1889
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)"));
1892
1893   EXPECT_TRUE(db_->Execute("DELETE FROM targets WHERE id=42"))
1894       << "Foreign key enforcement is not disabled";
1895 }
1896
1897 TEST_P(SQLDatabaseTest, TriggersDisabledByDefault) {
1898   ASSERT_TRUE(db_->Execute("CREATE TABLE data(id INTEGER)"));
1899
1900   // sqlite3_db_config() currently only disables running triggers. Schema
1901   // operations on triggers are still allowed.
1902   EXPECT_TRUE(
1903       db_->Execute("CREATE TRIGGER trigger AFTER INSERT ON data "
1904                    "BEGIN DELETE FROM data; END"));
1905
1906   ASSERT_TRUE(db_->Execute("INSERT INTO data(id) VALUES(42)"));
1907
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));
1912
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"));
1916 }
1917
1918 #if BUILDFLAG(IS_WIN)
1919
1920 class SQLDatabaseTestExclusiveFileLockMode
1921     : public testing::Test,
1922       public testing::WithParamInterface<::testing::tuple<bool, bool>> {
1923  public:
1924   ~SQLDatabaseTestExclusiveFileLockMode() override = default;
1925
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_));
1931   }
1932
1933   DatabaseOptions GetDBOptions() {
1934     DatabaseOptions options;
1935     options.wal_mode = IsWALEnabled();
1936     options.exclusive_locking = true;
1937     options.exclusive_database_file_lock = IsExclusivelockEnabled();
1938     return options;
1939   }
1940
1941   bool IsWALEnabled() { return std::get<0>(GetParam()); }
1942   bool IsExclusivelockEnabled() { return std::get<1>(GetParam()); }
1943
1944  protected:
1945   base::ScopedTempDir temp_dir_;
1946   base::FilePath db_path_;
1947   std::unique_ptr<Database> db_;
1948 };
1949
1950 TEST_P(SQLDatabaseTestExclusiveFileLockMode, BasicStatement) {
1951   ASSERT_TRUE(db_->Execute("CREATE TABLE data(contents TEXT)"));
1952   EXPECT_EQ(SQLITE_OK, db_->GetErrorCode());
1953
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);
1957
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());
1961 }
1962
1963 INSTANTIATE_TEST_SUITE_P(
1964     All,
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"});
1971     });
1972
1973 #else
1974
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");
1979
1980   Database db({.exclusive_database_file_lock = true});
1981
1982   EXPECT_CHECK_DEATH_WITH(
1983       { std::ignore = db.Open(db_path); },
1984       "exclusive_database_file_lock is only supported on Windows");
1985 }
1986
1987 #endif  // BUILDFLAG(IS_WIN)
1988
1989 class SQLDatabaseTestExclusiveMode : public testing::Test,
1990                                      public testing::WithParamInterface<bool> {
1991  public:
1992   ~SQLDatabaseTestExclusiveMode() override = default;
1993
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_));
1999   }
2000
2001   DatabaseOptions GetDBOptions() {
2002     DatabaseOptions options;
2003     options.wal_mode = IsWALEnabled();
2004     options.exclusive_locking = true;
2005     return options;
2006   }
2007
2008   bool IsWALEnabled() { return GetParam(); }
2009
2010  protected:
2011   base::ScopedTempDir temp_dir_;
2012   base::FilePath db_path_;
2013   std::unique_ptr<Database> db_;
2014 };
2015
2016 TEST_P(SQLDatabaseTestExclusiveMode, LockingModeExclusive) {
2017   EXPECT_EQ(ExecuteWithResult(db_.get(), "PRAGMA locking_mode"), "exclusive");
2018 }
2019
2020 TEST_P(SQLDatabaseTest, LockingModeNormal) {
2021   EXPECT_EQ(ExecuteWithResult(db_.get(), "PRAGMA locking_mode"), "normal");
2022 }
2023
2024 TEST_P(SQLDatabaseTest, OpenedInCorrectMode) {
2025   std::string expected_mode = IsWALEnabled() ? "wal" : "truncate";
2026   EXPECT_EQ(ExecuteWithResult(db_.get(), "PRAGMA journal_mode"), expected_mode);
2027 }
2028
2029 TEST_P(SQLDatabaseTest, CheckpointDatabase) {
2030   if (!IsWALEnabled())
2031     return;
2032
2033   base::FilePath wal_path = Database::WriteAheadLogPath(db_path_);
2034
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);
2040
2041   ASSERT_TRUE(
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)"));
2045
2046   // Writes reach WAL file but not db file.
2047   base::GetFileSize(wal_path, &wal_size);
2048   EXPECT_GT(wal_size, 0);
2049
2050   int64_t db_size = 0;
2051   base::GetFileSize(db_path_, &db_size);
2052   EXPECT_EQ(db_size, db_->page_size());
2053
2054   // Checkpoint database to immediately propagate writes to DB file.
2055   EXPECT_TRUE(db_->CheckpointDatabase());
2056
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"),
2060             "1");
2061   EXPECT_EQ(ExecuteWithResult(db_.get(), "SELECT value FROM foo where id=2"),
2062             "2");
2063 }
2064
2065 TEST_P(SQLDatabaseTest, OpenFailsAfterCorruptSizeInHeader) {
2066   // The database file ends up empty if we don't create at least one table.
2067   ASSERT_TRUE(
2068       db_->Execute("CREATE TABLE rows(i INTEGER PRIMARY KEY NOT NULL)"));
2069   db_->Close();
2070
2071   ASSERT_TRUE(sql::test::CorruptSizeInHeader(db_path_));
2072   {
2073     sql::test::ScopedErrorExpecter expecter;
2074     expecter.ExpectError(SQLITE_CORRUPT);
2075     ASSERT_TRUE(db_->Open(db_path_));
2076     EXPECT_TRUE(expecter.SawExpectedErrors());
2077   }
2078 }
2079
2080 TEST_P(SQLDatabaseTest, ExecuteFailsAfterCorruptSizeInHeader) {
2081   ASSERT_TRUE(
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";
2086   db_->Close();
2087
2088   ASSERT_TRUE(sql::test::CorruptSizeInHeader(db_path_));
2089   {
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";
2095   }
2096   {
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";
2102   }
2103 }
2104
2105 TEST_P(SQLDatabaseTest, SchemaFailsAfterCorruptSizeInHeader) {
2106   ASSERT_TRUE(
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";
2110   db_->Close();
2111
2112   ASSERT_TRUE(sql::test::CorruptSizeInHeader(db_path_));
2113   {
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";
2119   }
2120   {
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";
2126   }
2127 }
2128
2129 TEST(SQLEmptyPathDatabaseTest, EmptyPathTest) {
2130   Database db;
2131   EXPECT_TRUE(db.OpenInMemory());
2132   EXPECT_TRUE(db.is_open());
2133   EXPECT_TRUE(db.DbPath().empty());
2134 }
2135
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,
2141                          testing::Bool());
2142 #else
2143 INSTANTIATE_TEST_SUITE_P(JournalMode, SQLDatabaseTest, testing::Values(false));
2144 INSTANTIATE_TEST_SUITE_P(JournalMode,
2145                          SQLDatabaseTestExclusiveMode,
2146                          testing::Values(false));
2147 #endif
2148 }  // namespace sql