blob: 7b3e04f49106a1a80af763845d04f7e09d09a8d0 [file] [log] [blame]
[email protected]44ad7d902012-03-23 00:09:051// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]e5ffd0e42009-09-11 21:30:562// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
avi0b519202015-12-21 07:25:195#include <stddef.h>
6#include <stdint.h>
7
[email protected]7bae5742013-07-10 20:46:168#include "base/bind.h"
thestig22dfc4012014-09-05 08:29:449#include "base/files/file_util.h"
[email protected]b9b4a572014-03-17 23:11:1210#include "base/files/scoped_file.h"
[email protected]ea1a3f62012-11-16 20:34:2311#include "base/files/scoped_temp_dir.h"
[email protected]41a97c812013-02-07 02:35:3812#include "base/logging.h"
avi0b519202015-12-21 07:25:1913#include "base/macros.h"
shess7e2baba2016-10-27 23:46:0514#include "base/strings/string_number_conversions.h"
Victor Costan613b4302018-11-20 05:32:4315#include "base/test/gtest_util.h"
Devlin Cronin147687f2018-06-05 18:03:5616#include "base/test/metrics/histogram_tester.h"
Victor Costan4c2f3e922018-08-21 04:47:5917#include "base/test/scoped_feature_list.h"
ssid9f8022f2015-10-12 17:49:0318#include "base/trace_event/process_memory_dump.h"
Scott Graham57ee54822017-09-13 06:37:5619#include "build/build_config.h"
Victor Costancfbfa602018-08-01 23:24:4620#include "sql/database.h"
21#include "sql/database_memory_dump_provider.h"
[email protected]1348765a2012-07-24 08:25:5322#include "sql/meta_table.h"
[email protected]ea1a3f62012-11-16 20:34:2323#include "sql/statement.h"
Victor Costand1a217b2019-04-02 02:44:2124#include "sql/test/database_test_peer.h"
[email protected]98cf3002013-07-12 01:38:5625#include "sql/test/error_callback_support.h"
shess976814402016-06-21 06:56:2526#include "sql/test/scoped_error_expecter.h"
Scott Graham47ed2c32017-09-15 02:17:0727#include "sql/test/sql_test_base.h"
[email protected]a8848a72013-11-18 04:18:4728#include "sql/test/test_helpers.h"
[email protected]e5ffd0e42009-09-11 21:30:5629#include "testing/gtest/include/gtest/gtest.h"
[email protected]e33cba42010-08-18 23:37:0330#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5631
shess58b8df82015-06-03 00:19:3232namespace sql {
Victor Costan7f6abbbe2018-07-29 02:57:2733
[email protected]7bae5742013-07-10 20:46:1634namespace {
35
shess7e2baba2016-10-27 23:46:0536using sql::test::ExecuteWithResult;
37
[email protected]7bae5742013-07-10 20:46:1638// Helper to return the count of items in sqlite_master. Return -1 in
39// case of error.
Victor Costancfbfa602018-08-01 23:24:4640int SqliteMasterCount(sql::Database* db) {
[email protected]7bae5742013-07-10 20:46:1641 const char* kMasterCount = "SELECT COUNT(*) FROM sqlite_master";
42 sql::Statement s(db->GetUniqueStatement(kMasterCount));
43 return s.Step() ? s.ColumnInt(0) : -1;
44}
45
[email protected]98cf3002013-07-12 01:38:5646// Track the number of valid references which share the same pointer.
47// This is used to allow testing an implicitly use-after-free case by
48// explicitly having the ref count live longer than the object.
49class RefCounter {
50 public:
Victor Costancfbfa602018-08-01 23:24:4651 RefCounter(size_t* counter) : counter_(counter) { (*counter_)++; }
52 RefCounter(const RefCounter& other) : counter_(other.counter_) {
[email protected]98cf3002013-07-12 01:38:5653 (*counter_)++;
54 }
Victor Costancfbfa602018-08-01 23:24:4655 ~RefCounter() { (*counter_)--; }
[email protected]98cf3002013-07-12 01:38:5656
57 private:
58 size_t* counter_;
59
60 DISALLOW_ASSIGN(RefCounter);
61};
62
63// Empty callback for implementation of ErrorCallbackSetHelper().
Victor Costancfbfa602018-08-01 23:24:4664void IgnoreErrorCallback(int error, sql::Statement* stmt) {}
[email protected]98cf3002013-07-12 01:38:5665
Victor Costancfbfa602018-08-01 23:24:4666void ErrorCallbackSetHelper(sql::Database* db,
[email protected]98cf3002013-07-12 01:38:5667 size_t* counter,
68 const RefCounter& r,
Victor Costancfbfa602018-08-01 23:24:4669 int error,
70 sql::Statement* stmt) {
[email protected]98cf3002013-07-12 01:38:5671 // The ref count should not go to zero when changing the callback.
72 EXPECT_GT(*counter, 0u);
tzikd16d2192018-03-07 08:58:3673 db->set_error_callback(base::BindRepeating(&IgnoreErrorCallback));
[email protected]98cf3002013-07-12 01:38:5674 EXPECT_GT(*counter, 0u);
75}
76
Victor Costancfbfa602018-08-01 23:24:4677void ErrorCallbackResetHelper(sql::Database* db,
[email protected]98cf3002013-07-12 01:38:5678 size_t* counter,
79 const RefCounter& r,
Victor Costancfbfa602018-08-01 23:24:4680 int error,
81 sql::Statement* stmt) {
[email protected]98cf3002013-07-12 01:38:5682 // The ref count should not go to zero when clearing the callback.
83 EXPECT_GT(*counter, 0u);
84 db->reset_error_callback();
85 EXPECT_GT(*counter, 0u);
86}
87
shess1cf87f22016-10-25 22:18:2988// Handle errors by blowing away the database.
Victor Costancfbfa602018-08-01 23:24:4689void RazeErrorCallback(sql::Database* db,
shess1cf87f22016-10-25 22:18:2990 int expected_error,
91 int error,
92 sql::Statement* stmt) {
93 // Nothing here needs extended errors at this time.
Victor Costancfbfa602018-08-01 23:24:4694 EXPECT_EQ(expected_error, expected_error & 0xff);
95 EXPECT_EQ(expected_error, error & 0xff);
shess1cf87f22016-10-25 22:18:2996 db->RazeAndClose();
97}
98
[email protected]81a2a602013-07-17 19:10:3699#if defined(OS_POSIX)
100// Set a umask and restore the old mask on destruction. Cribbed from
101// shared_memory_unittest.cc. Used by POSIX-only UserPermission test.
102class ScopedUmaskSetter {
103 public:
104 explicit ScopedUmaskSetter(mode_t target_mask) {
105 old_umask_ = umask(target_mask);
106 }
107 ~ScopedUmaskSetter() { umask(old_umask_); }
Victor Costancfbfa602018-08-01 23:24:46108
[email protected]81a2a602013-07-17 19:10:36109 private:
110 mode_t old_umask_;
111 DISALLOW_IMPLICIT_CONSTRUCTORS(ScopedUmaskSetter);
112};
Victor Costan8a87f7e52017-11-10 01:29:30113#endif // defined(OS_POSIX)
[email protected]81a2a602013-07-17 19:10:36114
shessc8cd2a162015-10-22 20:30:46115} // namespace
116
Victor Costancfbfa602018-08-01 23:24:46117using SQLDatabaseTest = sql::SQLTestBase;
[email protected]e5ffd0e42009-09-11 21:30:56118
Victor Costancfbfa602018-08-01 23:24:46119TEST_F(SQLDatabaseTest, Execute) {
[email protected]e5ffd0e42009-09-11 21:30:56120 // Valid statement should return true.
121 ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)"));
122 EXPECT_EQ(SQLITE_OK, db().GetErrorCode());
123
124 // Invalid statement should fail.
[email protected]eff1fa522011-12-12 23:50:59125 ASSERT_EQ(SQLITE_ERROR,
126 db().ExecuteAndReturnErrorCode("CREATE TAB foo (a, b"));
[email protected]e5ffd0e42009-09-11 21:30:56127 EXPECT_EQ(SQLITE_ERROR, db().GetErrorCode());
128}
129
Victor Costancfbfa602018-08-01 23:24:46130TEST_F(SQLDatabaseTest, ExecuteWithErrorCode) {
[email protected]eff1fa522011-12-12 23:50:59131 ASSERT_EQ(SQLITE_OK,
132 db().ExecuteAndReturnErrorCode("CREATE TABLE foo (a, b)"));
Victor Costancfbfa602018-08-01 23:24:46133 ASSERT_EQ(SQLITE_ERROR, db().ExecuteAndReturnErrorCode("CREATE TABLE TABLE"));
134 ASSERT_EQ(SQLITE_ERROR, db().ExecuteAndReturnErrorCode(
135 "INSERT INTO foo(a, b) VALUES (1, 2, 3, 4)"));
[email protected]eff1fa522011-12-12 23:50:59136}
137
Victor Costancfbfa602018-08-01 23:24:46138TEST_F(SQLDatabaseTest, CachedStatement) {
Victor Costan12daa3ac92018-07-19 01:05:58139 sql::StatementID id1 = SQL_FROM_HERE;
Victor Costan87cf8c72018-07-19 19:36:04140 sql::StatementID id2 = SQL_FROM_HERE;
Victor Costan613b4302018-11-20 05:32:43141 static const char kId1Sql[] = "SELECT a FROM foo";
Victor Costan87cf8c72018-07-19 19:36:04142 static const char kId2Sql[] = "SELECT b FROM foo";
[email protected]e5ffd0e42009-09-11 21:30:56143
144 ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)"));
145 ASSERT_TRUE(db().Execute("INSERT INTO foo(a, b) VALUES (12, 13)"));
146
Victor Costan87cf8c72018-07-19 19:36:04147 sqlite3_stmt* raw_id1_statement;
148 sqlite3_stmt* raw_id2_statement;
[email protected]e5ffd0e42009-09-11 21:30:56149 {
Victor Costancfbfa602018-08-01 23:24:46150 scoped_refptr<sql::Database::StatementRef> ref_from_id1 =
Victor Costan87cf8c72018-07-19 19:36:04151 db().GetCachedStatement(id1, kId1Sql);
152 raw_id1_statement = ref_from_id1->stmt();
[email protected]e5ffd0e42009-09-11 21:30:56153
Victor Costan87cf8c72018-07-19 19:36:04154 sql::Statement from_id1(std::move(ref_from_id1));
155 ASSERT_TRUE(from_id1.is_valid());
156 ASSERT_TRUE(from_id1.Step());
157 EXPECT_EQ(12, from_id1.ColumnInt(0));
158
Victor Costancfbfa602018-08-01 23:24:46159 scoped_refptr<sql::Database::StatementRef> ref_from_id2 =
Victor Costan87cf8c72018-07-19 19:36:04160 db().GetCachedStatement(id2, kId2Sql);
161 raw_id2_statement = ref_from_id2->stmt();
162 EXPECT_NE(raw_id1_statement, raw_id2_statement);
163
164 sql::Statement from_id2(std::move(ref_from_id2));
165 ASSERT_TRUE(from_id2.is_valid());
166 ASSERT_TRUE(from_id2.Step());
167 EXPECT_EQ(13, from_id2.ColumnInt(0));
[email protected]e5ffd0e42009-09-11 21:30:56168 }
169
[email protected]e5ffd0e42009-09-11 21:30:56170 {
Victor Costancfbfa602018-08-01 23:24:46171 scoped_refptr<sql::Database::StatementRef> ref_from_id1 =
Victor Costan87cf8c72018-07-19 19:36:04172 db().GetCachedStatement(id1, kId1Sql);
173 EXPECT_EQ(raw_id1_statement, ref_from_id1->stmt())
174 << "statement was not cached";
[email protected]e5ffd0e42009-09-11 21:30:56175
Victor Costan87cf8c72018-07-19 19:36:04176 sql::Statement from_id1(std::move(ref_from_id1));
177 ASSERT_TRUE(from_id1.is_valid());
178 ASSERT_TRUE(from_id1.Step()) << "cached statement was not reset";
179 EXPECT_EQ(12, from_id1.ColumnInt(0));
180
Victor Costancfbfa602018-08-01 23:24:46181 scoped_refptr<sql::Database::StatementRef> ref_from_id2 =
Victor Costan87cf8c72018-07-19 19:36:04182 db().GetCachedStatement(id2, kId2Sql);
183 EXPECT_EQ(raw_id2_statement, ref_from_id2->stmt())
184 << "statement was not cached";
185
186 sql::Statement from_id2(std::move(ref_from_id2));
187 ASSERT_TRUE(from_id2.is_valid());
188 ASSERT_TRUE(from_id2.Step()) << "cached statement was not reset";
189 EXPECT_EQ(13, from_id2.ColumnInt(0));
[email protected]e5ffd0e42009-09-11 21:30:56190 }
Victor Costan613b4302018-11-20 05:32:43191
192 EXPECT_DCHECK_DEATH(db().GetCachedStatement(id1, kId2Sql))
193 << "Using a different SQL with the same statement ID should DCHECK";
194 EXPECT_DCHECK_DEATH(db().GetCachedStatement(id2, kId1Sql))
195 << "Using a different SQL with the same statement ID should DCHECK";
[email protected]e5ffd0e42009-09-11 21:30:56196}
197
Victor Costancfbfa602018-08-01 23:24:46198TEST_F(SQLDatabaseTest, IsSQLValidTest) {
[email protected]eff1fa522011-12-12 23:50:59199 ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)"));
200 ASSERT_TRUE(db().IsSQLValid("SELECT a FROM foo"));
201 ASSERT_FALSE(db().IsSQLValid("SELECT no_exist FROM foo"));
202}
203
Victor Costancfbfa602018-08-01 23:24:46204TEST_F(SQLDatabaseTest, DoesTableExist) {
[email protected]e5ffd0e42009-09-11 21:30:56205 EXPECT_FALSE(db().DoesTableExist("foo"));
Victor Costan70bedf22018-07-18 21:21:14206 EXPECT_FALSE(db().DoesTableExist("foo_index"));
shessa62504d2016-11-07 19:26:12207
Victor Costan70bedf22018-07-18 21:21:14208 ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)"));
209 ASSERT_TRUE(db().Execute("CREATE INDEX foo_index ON foo (a)"));
210 EXPECT_TRUE(db().DoesTableExist("foo"));
211 EXPECT_FALSE(db().DoesTableExist("foo_index"));
Victor Costanf85512e52019-04-10 20:51:36212
213 // DoesTableExist() is case-sensitive.
214 EXPECT_FALSE(db().DoesTableExist("Foo"));
215 EXPECT_FALSE(db().DoesTableExist("FOO"));
Victor Costan70bedf22018-07-18 21:21:14216}
217
Victor Costancfbfa602018-08-01 23:24:46218TEST_F(SQLDatabaseTest, DoesIndexExist) {
Victor Costan70bedf22018-07-18 21:21:14219 ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)"));
220 EXPECT_FALSE(db().DoesIndexExist("foo"));
221 EXPECT_FALSE(db().DoesIndexExist("foo_ubdex"));
222
223 ASSERT_TRUE(db().Execute("CREATE INDEX foo_index ON foo (a)"));
224 EXPECT_TRUE(db().DoesIndexExist("foo_index"));
225 EXPECT_FALSE(db().DoesIndexExist("foo"));
Victor Costanf85512e52019-04-10 20:51:36226
227 // DoesIndexExist() is case-sensitive.
228 EXPECT_FALSE(db().DoesIndexExist("Foo_index"));
229 EXPECT_FALSE(db().DoesIndexExist("Foo_Index"));
230 EXPECT_FALSE(db().DoesIndexExist("FOO_INDEX"));
Victor Costan70bedf22018-07-18 21:21:14231}
232
Victor Costancfbfa602018-08-01 23:24:46233TEST_F(SQLDatabaseTest, DoesViewExist) {
shessa62504d2016-11-07 19:26:12234 EXPECT_FALSE(db().DoesViewExist("voo"));
Victor Costan70bedf22018-07-18 21:21:14235 ASSERT_TRUE(db().Execute("CREATE VIEW voo (a) AS SELECT 1"));
shessa62504d2016-11-07 19:26:12236 EXPECT_FALSE(db().DoesIndexExist("voo"));
237 EXPECT_FALSE(db().DoesTableExist("voo"));
238 EXPECT_TRUE(db().DoesViewExist("voo"));
Victor Costanf85512e52019-04-10 20:51:36239
240 // DoesTableExist() is case-sensitive.
241 EXPECT_FALSE(db().DoesViewExist("Voo"));
242 EXPECT_FALSE(db().DoesViewExist("VOO"));
Victor Costan70bedf22018-07-18 21:21:14243}
[email protected]e5ffd0e42009-09-11 21:30:56244
Victor Costancfbfa602018-08-01 23:24:46245TEST_F(SQLDatabaseTest, DoesColumnExist) {
Victor Costan70bedf22018-07-18 21:21:14246 ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)"));
247
[email protected]e5ffd0e42009-09-11 21:30:56248 EXPECT_FALSE(db().DoesColumnExist("foo", "bar"));
249 EXPECT_TRUE(db().DoesColumnExist("foo", "a"));
250
Victor Costan70bedf22018-07-18 21:21:14251 ASSERT_FALSE(db().DoesTableExist("bar"));
[email protected]e5ffd0e42009-09-11 21:30:56252 EXPECT_FALSE(db().DoesColumnExist("bar", "b"));
shess92a2ab12015-04-09 01:59:47253
Victor Costanf85512e52019-04-10 20:51:36254 // SQLite resolves table/column names without case sensitivity.
shess92a2ab12015-04-09 01:59:47255 EXPECT_TRUE(db().DoesColumnExist("FOO", "A"));
Victor Costanf85512e52019-04-10 20:51:36256 EXPECT_TRUE(db().DoesColumnExist("FOO", "a"));
257 EXPECT_TRUE(db().DoesColumnExist("foo", "A"));
[email protected]e5ffd0e42009-09-11 21:30:56258}
259
Victor Costancfbfa602018-08-01 23:24:46260TEST_F(SQLDatabaseTest, GetLastInsertRowId) {
[email protected]e5ffd0e42009-09-11 21:30:56261 ASSERT_TRUE(db().Execute("CREATE TABLE foo (id INTEGER PRIMARY KEY, value)"));
262
263 ASSERT_TRUE(db().Execute("INSERT INTO foo (value) VALUES (12)"));
264
265 // Last insert row ID should be valid.
tfarina720d4f32015-05-11 22:31:26266 int64_t row = db().GetLastInsertRowId();
[email protected]e5ffd0e42009-09-11 21:30:56267 EXPECT_LT(0, row);
268
269 // It should be the primary key of the row we just inserted.
270 sql::Statement s(db().GetUniqueStatement("SELECT value FROM foo WHERE id=?"));
271 s.BindInt64(0, row);
272 ASSERT_TRUE(s.Step());
273 EXPECT_EQ(12, s.ColumnInt(0));
274}
[email protected]44ad7d902012-03-23 00:09:05275
Victor Costancfbfa602018-08-01 23:24:46276TEST_F(SQLDatabaseTest, Rollback) {
[email protected]44ad7d902012-03-23 00:09:05277 ASSERT_TRUE(db().BeginTransaction());
278 ASSERT_TRUE(db().BeginTransaction());
279 EXPECT_EQ(2, db().transaction_nesting());
280 db().RollbackTransaction();
281 EXPECT_FALSE(db().CommitTransaction());
282 EXPECT_TRUE(db().BeginTransaction());
283}
[email protected]8e0c01282012-04-06 19:36:49284
shess976814402016-06-21 06:56:25285// Test the scoped error expecter by attempting to insert a duplicate
[email protected]4350e322013-06-18 22:18:10286// value into an index.
Victor Costancfbfa602018-08-01 23:24:46287TEST_F(SQLDatabaseTest, ScopedErrorExpecter) {
[email protected]4350e322013-06-18 22:18:10288 const char* kCreateSql = "CREATE TABLE foo (id INTEGER UNIQUE)";
289 ASSERT_TRUE(db().Execute(kCreateSql));
290 ASSERT_TRUE(db().Execute("INSERT INTO foo (id) VALUES (12)"));
291
shess92a2ab12015-04-09 01:59:47292 {
shess976814402016-06-21 06:56:25293 sql::test::ScopedErrorExpecter expecter;
294 expecter.ExpectError(SQLITE_CONSTRAINT);
shess92a2ab12015-04-09 01:59:47295 ASSERT_FALSE(db().Execute("INSERT INTO foo (id) VALUES (12)"));
shess976814402016-06-21 06:56:25296 ASSERT_TRUE(expecter.SawExpectedErrors());
shess92a2ab12015-04-09 01:59:47297 }
298}
299
300// Test that clients of GetUntrackedStatement() can test corruption-handling
shess976814402016-06-21 06:56:25301// with ScopedErrorExpecter.
Victor Costancfbfa602018-08-01 23:24:46302TEST_F(SQLDatabaseTest, ScopedIgnoreUntracked) {
shess92a2ab12015-04-09 01:59:47303 const char* kCreateSql = "CREATE TABLE foo (id INTEGER UNIQUE)";
304 ASSERT_TRUE(db().Execute(kCreateSql));
305 ASSERT_FALSE(db().DoesTableExist("bar"));
306 ASSERT_TRUE(db().DoesTableExist("foo"));
307 ASSERT_TRUE(db().DoesColumnExist("foo", "id"));
308 db().Close();
309
310 // Corrupt the database so that nothing works, including PRAGMAs.
erg102ceb412015-06-20 01:38:13311 ASSERT_TRUE(CorruptSizeInHeaderOfDB());
shess92a2ab12015-04-09 01:59:47312
313 {
shess976814402016-06-21 06:56:25314 sql::test::ScopedErrorExpecter expecter;
315 expecter.ExpectError(SQLITE_CORRUPT);
shess92a2ab12015-04-09 01:59:47316 ASSERT_TRUE(db().Open(db_path()));
317 ASSERT_FALSE(db().DoesTableExist("bar"));
318 ASSERT_FALSE(db().DoesTableExist("foo"));
319 ASSERT_FALSE(db().DoesColumnExist("foo", "id"));
shess976814402016-06-21 06:56:25320 ASSERT_TRUE(expecter.SawExpectedErrors());
shess92a2ab12015-04-09 01:59:47321 }
[email protected]4350e322013-06-18 22:18:10322}
323
Victor Costancfbfa602018-08-01 23:24:46324TEST_F(SQLDatabaseTest, ErrorCallback) {
[email protected]98cf3002013-07-12 01:38:56325 const char* kCreateSql = "CREATE TABLE foo (id INTEGER UNIQUE)";
326 ASSERT_TRUE(db().Execute(kCreateSql));
327 ASSERT_TRUE(db().Execute("INSERT INTO foo (id) VALUES (12)"));
328
329 int error = SQLITE_OK;
330 {
331 sql::ScopedErrorCallback sec(
tzikd16d2192018-03-07 08:58:36332 &db(), base::BindRepeating(&sql::CaptureErrorCallback, &error));
[email protected]98cf3002013-07-12 01:38:56333 EXPECT_FALSE(db().Execute("INSERT INTO foo (id) VALUES (12)"));
Scott Hessdcf120482015-02-10 21:33:29334
335 // Later versions of SQLite throw SQLITE_CONSTRAINT_UNIQUE. The specific
336 // sub-error isn't really important.
Victor Costancfbfa602018-08-01 23:24:46337 EXPECT_EQ(SQLITE_CONSTRAINT, (error & 0xff));
[email protected]98cf3002013-07-12 01:38:56338 }
339
340 // Callback is no longer in force due to reset.
341 {
342 error = SQLITE_OK;
shess976814402016-06-21 06:56:25343 sql::test::ScopedErrorExpecter expecter;
344 expecter.ExpectError(SQLITE_CONSTRAINT);
[email protected]98cf3002013-07-12 01:38:56345 ASSERT_FALSE(db().Execute("INSERT INTO foo (id) VALUES (12)"));
shess976814402016-06-21 06:56:25346 ASSERT_TRUE(expecter.SawExpectedErrors());
[email protected]98cf3002013-07-12 01:38:56347 EXPECT_EQ(SQLITE_OK, error);
348 }
349
tzikd16d2192018-03-07 08:58:36350 // base::BindRepeating() can curry arguments to be passed by const reference
[email protected]81a2a602013-07-17 19:10:36351 // to the callback function. If the callback function calls
352 // re/set_error_callback(), the storage for those arguments can be
353 // deleted while the callback function is still executing.
[email protected]98cf3002013-07-12 01:38:56354 //
355 // RefCounter() counts how many objects are live using an external
356 // count. The same counter is passed to the callback, so that it
357 // can check directly even if the RefCounter object is no longer
358 // live.
359 {
360 size_t count = 0;
361 sql::ScopedErrorCallback sec(
tzikd16d2192018-03-07 08:58:36362 &db(), base::BindRepeating(&ErrorCallbackSetHelper, &db(), &count,
363 RefCounter(&count)));
[email protected]98cf3002013-07-12 01:38:56364
365 EXPECT_FALSE(db().Execute("INSERT INTO foo (id) VALUES (12)"));
366 }
367
368 // Same test, but reset_error_callback() case.
369 {
370 size_t count = 0;
371 sql::ScopedErrorCallback sec(
tzikd16d2192018-03-07 08:58:36372 &db(), base::BindRepeating(&ErrorCallbackResetHelper, &db(), &count,
373 RefCounter(&count)));
[email protected]98cf3002013-07-12 01:38:56374
375 EXPECT_FALSE(db().Execute("INSERT INTO foo (id) VALUES (12)"));
376 }
377}
378
Victor Costancfbfa602018-08-01 23:24:46379// Test that sql::Database::Raze() results in a database without the
[email protected]8e0c01282012-04-06 19:36:49380// tables from the original database.
Victor Costancfbfa602018-08-01 23:24:46381TEST_F(SQLDatabaseTest, Raze) {
[email protected]8e0c01282012-04-06 19:36:49382 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
383 ASSERT_TRUE(db().Execute(kCreateSql));
384 ASSERT_TRUE(db().Execute("INSERT INTO foo (value) VALUES (12)"));
385
[email protected]69c58452012-08-06 19:22:42386 int pragma_auto_vacuum = 0;
387 {
388 sql::Statement s(db().GetUniqueStatement("PRAGMA auto_vacuum"));
389 ASSERT_TRUE(s.Step());
390 pragma_auto_vacuum = s.ColumnInt(0);
391 ASSERT_TRUE(pragma_auto_vacuum == 0 || pragma_auto_vacuum == 1);
392 }
393
394 // If auto_vacuum is set, there's an extra page to maintain a freelist.
395 const int kExpectedPageCount = 2 + pragma_auto_vacuum;
396
[email protected]8e0c01282012-04-06 19:36:49397 {
398 sql::Statement s(db().GetUniqueStatement("PRAGMA page_count"));
399 ASSERT_TRUE(s.Step());
[email protected]69c58452012-08-06 19:22:42400 EXPECT_EQ(kExpectedPageCount, s.ColumnInt(0));
[email protected]8e0c01282012-04-06 19:36:49401 }
402
403 {
404 sql::Statement s(db().GetUniqueStatement("SELECT * FROM sqlite_master"));
405 ASSERT_TRUE(s.Step());
406 EXPECT_EQ("table", s.ColumnString(0));
407 EXPECT_EQ("foo", s.ColumnString(1));
408 EXPECT_EQ("foo", s.ColumnString(2));
[email protected]69c58452012-08-06 19:22:42409 // Table "foo" is stored in the last page of the file.
410 EXPECT_EQ(kExpectedPageCount, s.ColumnInt(3));
[email protected]8e0c01282012-04-06 19:36:49411 EXPECT_EQ(kCreateSql, s.ColumnString(4));
412 }
413
414 ASSERT_TRUE(db().Raze());
415
416 {
417 sql::Statement s(db().GetUniqueStatement("PRAGMA page_count"));
418 ASSERT_TRUE(s.Step());
419 EXPECT_EQ(1, s.ColumnInt(0));
420 }
421
[email protected]7bae5742013-07-10 20:46:16422 ASSERT_EQ(0, SqliteMasterCount(&db()));
[email protected]69c58452012-08-06 19:22:42423
424 {
425 sql::Statement s(db().GetUniqueStatement("PRAGMA auto_vacuum"));
426 ASSERT_TRUE(s.Step());
[email protected]6d42f152012-11-10 00:38:24427 // The new database has the same auto_vacuum as a fresh database.
[email protected]69c58452012-08-06 19:22:42428 EXPECT_EQ(pragma_auto_vacuum, s.ColumnInt(0));
429 }
[email protected]8e0c01282012-04-06 19:36:49430}
431
Victor Costancfbfa602018-08-01 23:24:46432// Helper for SQLDatabaseTest.RazePageSize. Creates a fresh db based on
shess7e2baba2016-10-27 23:46:05433// db_prefix, with the given initial page size, and verifies it against the
434// expected size. Then changes to the final page size and razes, verifying that
435// the fresh database ends up with the expected final page size.
436void TestPageSize(const base::FilePath& db_prefix,
437 int initial_page_size,
438 const std::string& expected_initial_page_size,
439 int final_page_size,
440 const std::string& expected_final_page_size) {
Victor Costan1d868352018-06-26 19:06:48441 static const char kCreateSql[] = "CREATE TABLE x (t TEXT)";
442 static const char kInsertSql1[] = "INSERT INTO x VALUES ('This is a test')";
443 static const char kInsertSql2[] = "INSERT INTO x VALUES ('That was a test')";
shess7e2baba2016-10-27 23:46:05444
445 const base::FilePath db_path = db_prefix.InsertBeforeExtensionASCII(
Raul Tambre6c708e32019-02-08 22:35:14446 base::NumberToString(initial_page_size));
Victor Costancfbfa602018-08-01 23:24:46447 sql::Database::Delete(db_path);
448 sql::Database db;
shess7e2baba2016-10-27 23:46:05449 db.set_page_size(initial_page_size);
450 ASSERT_TRUE(db.Open(db_path));
451 ASSERT_TRUE(db.Execute(kCreateSql));
452 ASSERT_TRUE(db.Execute(kInsertSql1));
453 ASSERT_TRUE(db.Execute(kInsertSql2));
454 ASSERT_EQ(expected_initial_page_size,
455 ExecuteWithResult(&db, "PRAGMA page_size"));
456
457 // Raze will use the page size set in the connection object, which may not
458 // match the file's page size.
459 db.set_page_size(final_page_size);
460 ASSERT_TRUE(db.Raze());
461
462 // SQLite 3.10.2 (at least) has a quirk with the sqlite3_backup() API (used by
463 // Raze()) which causes the destination database to remember the previous
464 // page_size, even if the overwriting database changed the page_size. Access
465 // the actual database to cause the cached value to be updated.
466 EXPECT_EQ("0", ExecuteWithResult(&db, "SELECT COUNT(*) FROM sqlite_master"));
467
468 EXPECT_EQ(expected_final_page_size,
469 ExecuteWithResult(&db, "PRAGMA page_size"));
470 EXPECT_EQ("1", ExecuteWithResult(&db, "PRAGMA page_count"));
471}
472
473// Verify that sql::Recovery maintains the page size, and the virtual table
474// works with page sizes other than SQLite's default. Also verify the case
475// where the default page size has changed.
Victor Costancfbfa602018-08-01 23:24:46476TEST_F(SQLDatabaseTest, RazePageSize) {
shess7e2baba2016-10-27 23:46:05477 const std::string default_page_size =
478 ExecuteWithResult(&db(), "PRAGMA page_size");
[email protected]8e0c01282012-04-06 19:36:49479
Victor Costan7f6abbbe2018-07-29 02:57:27480 // Sync uses 32k pages.
shess7e2baba2016-10-27 23:46:05481 EXPECT_NO_FATAL_FAILURE(
482 TestPageSize(db_path(), 32768, "32768", 32768, "32768"));
[email protected]8e0c01282012-04-06 19:36:49483
shess7e2baba2016-10-27 23:46:05484 // Many clients use 4k pages. This is the SQLite default after 3.12.0.
485 EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path(), 4096, "4096", 4096, "4096"));
486
487 // 1k is the default page size before 3.12.0.
488 EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path(), 1024, "1024", 1024, "1024"));
489
Victor Costancfbfa602018-08-01 23:24:46490 EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path(), 2048, "2048", 4096, "4096"));
shess7e2baba2016-10-27 23:46:05491
Victor Costan7f6abbbe2018-07-29 02:57:27492 // Databases with no page size specified should result in the default
shess7e2baba2016-10-27 23:46:05493 // page size. 2k has never been the default page size.
494 ASSERT_NE("2048", default_page_size);
Victor Costancfbfa602018-08-01 23:24:46495 EXPECT_NO_FATAL_FAILURE(TestPageSize(
496 db_path(), 2048, "2048", Database::kDefaultPageSize, default_page_size));
[email protected]8e0c01282012-04-06 19:36:49497}
498
499// Test that Raze() results are seen in other connections.
Victor Costancfbfa602018-08-01 23:24:46500TEST_F(SQLDatabaseTest, RazeMultiple) {
[email protected]8e0c01282012-04-06 19:36:49501 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
502 ASSERT_TRUE(db().Execute(kCreateSql));
503
Victor Costancfbfa602018-08-01 23:24:46504 sql::Database other_db;
[email protected]8e0c01282012-04-06 19:36:49505 ASSERT_TRUE(other_db.Open(db_path()));
506
507 // Check that the second connection sees the table.
[email protected]7bae5742013-07-10 20:46:16508 ASSERT_EQ(1, SqliteMasterCount(&other_db));
[email protected]8e0c01282012-04-06 19:36:49509
510 ASSERT_TRUE(db().Raze());
511
512 // The second connection sees the updated database.
[email protected]7bae5742013-07-10 20:46:16513 ASSERT_EQ(0, SqliteMasterCount(&other_db));
[email protected]8e0c01282012-04-06 19:36:49514}
515
Victor Costancfbfa602018-08-01 23:24:46516TEST_F(SQLDatabaseTest, RazeLocked) {
[email protected]8e0c01282012-04-06 19:36:49517 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
518 ASSERT_TRUE(db().Execute(kCreateSql));
519
520 // Open a transaction and write some data in a second connection.
521 // This will acquire a PENDING or EXCLUSIVE transaction, which will
522 // cause the raze to fail.
Victor Costancfbfa602018-08-01 23:24:46523 sql::Database other_db;
[email protected]8e0c01282012-04-06 19:36:49524 ASSERT_TRUE(other_db.Open(db_path()));
525 ASSERT_TRUE(other_db.BeginTransaction());
526 const char* kInsertSql = "INSERT INTO foo VALUES (1, 'data')";
527 ASSERT_TRUE(other_db.Execute(kInsertSql));
528
529 ASSERT_FALSE(db().Raze());
530
531 // Works after COMMIT.
532 ASSERT_TRUE(other_db.CommitTransaction());
533 ASSERT_TRUE(db().Raze());
534
535 // Re-create the database.
536 ASSERT_TRUE(db().Execute(kCreateSql));
537 ASSERT_TRUE(db().Execute(kInsertSql));
538
539 // An unfinished read transaction in the other connection also
540 // blocks raze.
Victor Costancfbfa602018-08-01 23:24:46541 const char* kQuery = "SELECT COUNT(*) FROM foo";
[email protected]8e0c01282012-04-06 19:36:49542 sql::Statement s(other_db.GetUniqueStatement(kQuery));
543 ASSERT_TRUE(s.Step());
544 ASSERT_FALSE(db().Raze());
545
546 // Complete the statement unlocks the database.
547 ASSERT_FALSE(s.Step());
548 ASSERT_TRUE(db().Raze());
549}
550
[email protected]7bae5742013-07-10 20:46:16551// Verify that Raze() can handle an empty file. SQLite should treat
552// this as an empty database.
Victor Costancfbfa602018-08-01 23:24:46553TEST_F(SQLDatabaseTest, RazeEmptyDB) {
[email protected]7bae5742013-07-10 20:46:16554 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
555 ASSERT_TRUE(db().Execute(kCreateSql));
556 db().Close();
557
erg102ceb412015-06-20 01:38:13558 TruncateDatabase();
[email protected]7bae5742013-07-10 20:46:16559
560 ASSERT_TRUE(db().Open(db_path()));
561 ASSERT_TRUE(db().Raze());
562 EXPECT_EQ(0, SqliteMasterCount(&db()));
563}
564
565// Verify that Raze() can handle a file of junk.
Victor Costancfbfa602018-08-01 23:24:46566TEST_F(SQLDatabaseTest, RazeNOTADB) {
[email protected]7bae5742013-07-10 20:46:16567 db().Close();
Victor Costancfbfa602018-08-01 23:24:46568 sql::Database::Delete(db_path());
erg102ceb412015-06-20 01:38:13569 ASSERT_FALSE(GetPathExists(db_path()));
[email protected]7bae5742013-07-10 20:46:16570
erg102ceb412015-06-20 01:38:13571 WriteJunkToDatabase(SQLTestBase::TYPE_OVERWRITE_AND_TRUNCATE);
572 ASSERT_TRUE(GetPathExists(db_path()));
[email protected]7bae5742013-07-10 20:46:16573
Scott Hessdcf120482015-02-10 21:33:29574 // SQLite will successfully open the handle, but fail when running PRAGMA
575 // statements that access the database.
[email protected]7bae5742013-07-10 20:46:16576 {
shess976814402016-06-21 06:56:25577 sql::test::ScopedErrorExpecter expecter;
Victor Costan42988a92018-02-06 02:22:14578 expecter.ExpectError(SQLITE_NOTADB);
Scott Hessdcf120482015-02-10 21:33:29579
[email protected]7bae5742013-07-10 20:46:16580 EXPECT_TRUE(db().Open(db_path()));
shess976814402016-06-21 06:56:25581 ASSERT_TRUE(expecter.SawExpectedErrors());
[email protected]7bae5742013-07-10 20:46:16582 }
583 EXPECT_TRUE(db().Raze());
584 db().Close();
585
586 // Now empty, the open should open an empty database.
587 EXPECT_TRUE(db().Open(db_path()));
588 EXPECT_EQ(0, SqliteMasterCount(&db()));
589}
590
591// Verify that Raze() can handle a database overwritten with garbage.
Victor Costancfbfa602018-08-01 23:24:46592TEST_F(SQLDatabaseTest, RazeNOTADB2) {
[email protected]7bae5742013-07-10 20:46:16593 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
594 ASSERT_TRUE(db().Execute(kCreateSql));
595 ASSERT_EQ(1, SqliteMasterCount(&db()));
596 db().Close();
597
erg102ceb412015-06-20 01:38:13598 WriteJunkToDatabase(SQLTestBase::TYPE_OVERWRITE);
[email protected]7bae5742013-07-10 20:46:16599
600 // SQLite will successfully open the handle, but will fail with
601 // SQLITE_NOTADB on pragma statemenets which attempt to read the
602 // corrupted header.
603 {
shess976814402016-06-21 06:56:25604 sql::test::ScopedErrorExpecter expecter;
605 expecter.ExpectError(SQLITE_NOTADB);
[email protected]7bae5742013-07-10 20:46:16606 EXPECT_TRUE(db().Open(db_path()));
shess976814402016-06-21 06:56:25607 ASSERT_TRUE(expecter.SawExpectedErrors());
[email protected]7bae5742013-07-10 20:46:16608 }
609 EXPECT_TRUE(db().Raze());
610 db().Close();
611
612 // Now empty, the open should succeed with an empty database.
613 EXPECT_TRUE(db().Open(db_path()));
614 EXPECT_EQ(0, SqliteMasterCount(&db()));
615}
616
617// Test that a callback from Open() can raze the database. This is
618// essential for cases where the Open() can fail entirely, so the
[email protected]fed734a2013-07-17 04:45:13619// Raze() cannot happen later. Additionally test that when the
620// callback does this during Open(), the open is retried and succeeds.
Victor Costancfbfa602018-08-01 23:24:46621TEST_F(SQLDatabaseTest, RazeCallbackReopen) {
[email protected]7bae5742013-07-10 20:46:16622 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
623 ASSERT_TRUE(db().Execute(kCreateSql));
624 ASSERT_EQ(1, SqliteMasterCount(&db()));
[email protected]7bae5742013-07-10 20:46:16625 db().Close();
626
[email protected]a8848a72013-11-18 04:18:47627 // Corrupt the database so that nothing works, including PRAGMAs.
erg102ceb412015-06-20 01:38:13628 ASSERT_TRUE(CorruptSizeInHeaderOfDB());
[email protected]7bae5742013-07-10 20:46:16629
[email protected]fed734a2013-07-17 04:45:13630 // Open() will succeed, even though the PRAGMA calls within will
631 // fail with SQLITE_CORRUPT, as will this PRAGMA.
632 {
shess976814402016-06-21 06:56:25633 sql::test::ScopedErrorExpecter expecter;
634 expecter.ExpectError(SQLITE_CORRUPT);
[email protected]fed734a2013-07-17 04:45:13635 ASSERT_TRUE(db().Open(db_path()));
636 ASSERT_FALSE(db().Execute("PRAGMA auto_vacuum"));
637 db().Close();
shess976814402016-06-21 06:56:25638 ASSERT_TRUE(expecter.SawExpectedErrors());
[email protected]fed734a2013-07-17 04:45:13639 }
640
tzikd16d2192018-03-07 08:58:36641 db().set_error_callback(
642 base::BindRepeating(&RazeErrorCallback, &db(), SQLITE_CORRUPT));
[email protected]7bae5742013-07-10 20:46:16643
[email protected]fed734a2013-07-17 04:45:13644 // When the PRAGMA calls in Open() raise SQLITE_CORRUPT, the error
645 // callback will call RazeAndClose(). Open() will then fail and be
646 // retried. The second Open() on the empty database will succeed
647 // cleanly.
648 ASSERT_TRUE(db().Open(db_path()));
649 ASSERT_TRUE(db().Execute("PRAGMA auto_vacuum"));
[email protected]7bae5742013-07-10 20:46:16650 EXPECT_EQ(0, SqliteMasterCount(&db()));
651}
652
[email protected]41a97c812013-02-07 02:35:38653// Basic test of RazeAndClose() operation.
Victor Costancfbfa602018-08-01 23:24:46654TEST_F(SQLDatabaseTest, RazeAndClose) {
[email protected]41a97c812013-02-07 02:35:38655 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
656 const char* kPopulateSql = "INSERT INTO foo (value) VALUES (12)";
657
658 // Test that RazeAndClose() closes the database, and that the
659 // database is empty when re-opened.
660 ASSERT_TRUE(db().Execute(kCreateSql));
661 ASSERT_TRUE(db().Execute(kPopulateSql));
662 ASSERT_TRUE(db().RazeAndClose());
663 ASSERT_FALSE(db().is_open());
664 db().Close();
665 ASSERT_TRUE(db().Open(db_path()));
[email protected]7bae5742013-07-10 20:46:16666 ASSERT_EQ(0, SqliteMasterCount(&db()));
[email protected]41a97c812013-02-07 02:35:38667
668 // Test that RazeAndClose() can break transactions.
669 ASSERT_TRUE(db().Execute(kCreateSql));
670 ASSERT_TRUE(db().Execute(kPopulateSql));
671 ASSERT_TRUE(db().BeginTransaction());
672 ASSERT_TRUE(db().RazeAndClose());
673 ASSERT_FALSE(db().is_open());
674 ASSERT_FALSE(db().CommitTransaction());
675 db().Close();
676 ASSERT_TRUE(db().Open(db_path()));
[email protected]7bae5742013-07-10 20:46:16677 ASSERT_EQ(0, SqliteMasterCount(&db()));
[email protected]41a97c812013-02-07 02:35:38678}
679
680// Test that various operations fail without crashing after
681// RazeAndClose().
Victor Costancfbfa602018-08-01 23:24:46682TEST_F(SQLDatabaseTest, RazeAndCloseDiagnostics) {
[email protected]41a97c812013-02-07 02:35:38683 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
684 const char* kPopulateSql = "INSERT INTO foo (value) VALUES (12)";
685 const char* kSimpleSql = "SELECT 1";
686
687 ASSERT_TRUE(db().Execute(kCreateSql));
688 ASSERT_TRUE(db().Execute(kPopulateSql));
689
690 // Test baseline expectations.
691 db().Preload();
692 ASSERT_TRUE(db().DoesTableExist("foo"));
693 ASSERT_TRUE(db().IsSQLValid(kSimpleSql));
694 ASSERT_EQ(SQLITE_OK, db().ExecuteAndReturnErrorCode(kSimpleSql));
695 ASSERT_TRUE(db().Execute(kSimpleSql));
696 ASSERT_TRUE(db().is_open());
697 {
698 sql::Statement s(db().GetUniqueStatement(kSimpleSql));
699 ASSERT_TRUE(s.Step());
700 }
701 {
702 sql::Statement s(db().GetCachedStatement(SQL_FROM_HERE, kSimpleSql));
703 ASSERT_TRUE(s.Step());
704 }
705 ASSERT_TRUE(db().BeginTransaction());
706 ASSERT_TRUE(db().CommitTransaction());
707 ASSERT_TRUE(db().BeginTransaction());
708 db().RollbackTransaction();
709
710 ASSERT_TRUE(db().RazeAndClose());
711
712 // At this point, they should all fail, but not crash.
713 db().Preload();
714 ASSERT_FALSE(db().DoesTableExist("foo"));
715 ASSERT_FALSE(db().IsSQLValid(kSimpleSql));
716 ASSERT_EQ(SQLITE_ERROR, db().ExecuteAndReturnErrorCode(kSimpleSql));
717 ASSERT_FALSE(db().Execute(kSimpleSql));
718 ASSERT_FALSE(db().is_open());
719 {
720 sql::Statement s(db().GetUniqueStatement(kSimpleSql));
721 ASSERT_FALSE(s.Step());
722 }
723 {
724 sql::Statement s(db().GetCachedStatement(SQL_FROM_HERE, kSimpleSql));
725 ASSERT_FALSE(s.Step());
726 }
727 ASSERT_FALSE(db().BeginTransaction());
728 ASSERT_FALSE(db().CommitTransaction());
729 ASSERT_FALSE(db().BeginTransaction());
730 db().RollbackTransaction();
731
732 // Close normally to reset the poisoned flag.
733 db().Close();
734
Victor Costancfbfa602018-08-01 23:24:46735// DEATH tests not supported on Android, iOS, or Fuchsia.
Scott Graham57ee54822017-09-13 06:37:56736#if !defined(OS_ANDROID) && !defined(OS_IOS) && !defined(OS_FUCHSIA)
[email protected]41a97c812013-02-07 02:35:38737 // Once the real Close() has been called, various calls enforce API
738 // usage by becoming fatal in debug mode. Since DEATH tests are
739 // expensive, just test one of them.
740 if (DLOG_IS_ON(FATAL)) {
Victor Costancfbfa602018-08-01 23:24:46741 ASSERT_DEATH({ db().IsSQLValid(kSimpleSql); },
742 "Illegal use of Database without a db");
[email protected]41a97c812013-02-07 02:35:38743 }
Victor Costan8a87f7e52017-11-10 01:29:30744#endif // !defined(OS_ANDROID) && !defined(OS_IOS) && !defined(OS_FUCHSIA)
[email protected]41a97c812013-02-07 02:35:38745}
746
747// TODO(shess): Spin up a background thread to hold other_db, to more
748// closely match real life. That would also allow testing
749// RazeWithTimeout().
750
shess92a6fb22017-04-23 04:33:30751// On Windows, truncate silently fails against a memory-mapped file. One goal
752// of Raze() is to truncate the file to remove blocks which generate I/O errors.
753// Test that Raze() turns off memory mapping so that the file is truncated.
754// [This would not cover the case of multiple connections where one of the other
755// connections is memory-mapped. That is infrequent in Chromium.]
Victor Costancfbfa602018-08-01 23:24:46756TEST_F(SQLDatabaseTest, RazeTruncate) {
shess92a6fb22017-04-23 04:33:30757 // The empty database has 0 or 1 pages. Raze() should leave it with exactly 1
758 // page. Not checking directly because auto_vacuum on Android adds a freelist
759 // page.
760 ASSERT_TRUE(db().Raze());
761 int64_t expected_size;
762 ASSERT_TRUE(base::GetFileSize(db_path(), &expected_size));
763 ASSERT_GT(expected_size, 0);
764
765 // Cause the database to take a few pages.
766 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
767 ASSERT_TRUE(db().Execute(kCreateSql));
768 for (size_t i = 0; i < 24; ++i) {
769 ASSERT_TRUE(
770 db().Execute("INSERT INTO foo (value) VALUES (randomblob(1024))"));
771 }
772 int64_t db_size;
773 ASSERT_TRUE(base::GetFileSize(db_path(), &db_size));
774 ASSERT_GT(db_size, expected_size);
775
776 // Make a query covering most of the database file to make sure that the
777 // blocks are actually mapped into memory. Empirically, the truncate problem
778 // doesn't seem to happen if no blocks are mapped.
779 EXPECT_EQ("24576",
780 ExecuteWithResult(&db(), "SELECT SUM(LENGTH(value)) FROM foo"));
781
782 ASSERT_TRUE(db().Raze());
783 ASSERT_TRUE(base::GetFileSize(db_path(), &db_size));
784 ASSERT_EQ(expected_size, db_size);
785}
786
[email protected]1348765a2012-07-24 08:25:53787#if defined(OS_ANDROID)
Victor Costancfbfa602018-08-01 23:24:46788TEST_F(SQLDatabaseTest, SetTempDirForSQL) {
[email protected]1348765a2012-07-24 08:25:53789 sql::MetaTable meta_table;
790 // Below call needs a temporary directory in sqlite3
791 // On Android, it can pass only when the temporary directory is set.
792 // Otherwise, sqlite3 doesn't find the correct directory to store
793 // temporary files and will report the error 'unable to open
794 // database file'.
795 ASSERT_TRUE(meta_table.Init(&db(), 4, 4));
796}
Victor Costan8a87f7e52017-11-10 01:29:30797#endif // defined(OS_ANDROID)
[email protected]8d2e39e2013-06-24 05:55:08798
Victor Costancfbfa602018-08-01 23:24:46799TEST_F(SQLDatabaseTest, DeleteNonWal) {
[email protected]8d2e39e2013-06-24 05:55:08800 EXPECT_TRUE(db().Execute("CREATE TABLE x (x)"));
801 db().Close();
802
803 // Should have both a main database file and a journal file because
shess2c21ecf2015-06-02 01:31:09804 // of journal_mode TRUNCATE.
Victor Costancfbfa602018-08-01 23:24:46805 base::FilePath journal_path = sql::Database::JournalPath(db_path());
erg102ceb412015-06-20 01:38:13806 ASSERT_TRUE(GetPathExists(db_path()));
Victor Costance678e72018-07-24 10:25:00807 ASSERT_TRUE(GetPathExists(journal_path));
[email protected]8d2e39e2013-06-24 05:55:08808
Victor Costancfbfa602018-08-01 23:24:46809 sql::Database::Delete(db_path());
erg102ceb412015-06-20 01:38:13810 EXPECT_FALSE(GetPathExists(db_path()));
Victor Costance678e72018-07-24 10:25:00811 EXPECT_FALSE(GetPathExists(journal_path));
[email protected]8d2e39e2013-06-24 05:55:08812}
[email protected]7bae5742013-07-10 20:46:16813
Victor Costance678e72018-07-24 10:25:00814#if defined(OS_POSIX) // This test operates on POSIX file permissions.
Victor Costancfbfa602018-08-01 23:24:46815TEST_F(SQLDatabaseTest, PosixFilePermissions) {
[email protected]81a2a602013-07-17 19:10:36816 db().Close();
Victor Costancfbfa602018-08-01 23:24:46817 sql::Database::Delete(db_path());
erg102ceb412015-06-20 01:38:13818 ASSERT_FALSE(GetPathExists(db_path()));
Victor Costance678e72018-07-24 10:25:00819
820 // If the bots all had a restrictive umask setting such that databases are
821 // always created with only the owner able to read them, then the code could
822 // break without breaking the tests. Temporarily provide a more permissive
823 // umask.
[email protected]81a2a602013-07-17 19:10:36824 ScopedUmaskSetter permissive_umask(S_IWGRP | S_IWOTH);
Victor Costance678e72018-07-24 10:25:00825
[email protected]81a2a602013-07-17 19:10:36826 ASSERT_TRUE(db().Open(db_path()));
827
Victor Costance678e72018-07-24 10:25:00828 // Cause the journal file to be created. If the default journal_mode is
829 // changed back to DELETE, this test will need to be updated.
[email protected]81a2a602013-07-17 19:10:36830 EXPECT_TRUE(db().Execute("CREATE TABLE x (x)"));
831
[email protected]81a2a602013-07-17 19:10:36832 int mode;
erg102ceb412015-06-20 01:38:13833 ASSERT_TRUE(GetPathExists(db_path()));
[email protected]b264eab2013-11-27 23:22:08834 EXPECT_TRUE(base::GetPosixFilePermissions(db_path(), &mode));
Victor Costance678e72018-07-24 10:25:00835 ASSERT_EQ(mode, 0600);
[email protected]81a2a602013-07-17 19:10:36836
Victor Costance678e72018-07-24 10:25:00837 {
Victor Costancfbfa602018-08-01 23:24:46838 base::FilePath journal_path = sql::Database::JournalPath(db_path());
Victor Costance678e72018-07-24 10:25:00839 DLOG(ERROR) << "journal_path: " << journal_path;
840 ASSERT_TRUE(GetPathExists(journal_path));
841 EXPECT_TRUE(base::GetPosixFilePermissions(journal_path, &mode));
842 ASSERT_EQ(mode, 0600);
843 }
[email protected]81a2a602013-07-17 19:10:36844
Victor Costance678e72018-07-24 10:25:00845 // Reopen the database and turn on WAL mode.
[email protected]81a2a602013-07-17 19:10:36846 db().Close();
Victor Costancfbfa602018-08-01 23:24:46847 sql::Database::Delete(db_path());
Victor Costance678e72018-07-24 10:25:00848 ASSERT_FALSE(GetPathExists(db_path()));
[email protected]81a2a602013-07-17 19:10:36849 ASSERT_TRUE(db().Open(db_path()));
Victor Costance678e72018-07-24 10:25:00850 ASSERT_TRUE(db().Execute("PRAGMA journal_mode = WAL"));
851 ASSERT_EQ("wal", ExecuteWithResult(&db(), "PRAGMA journal_mode"));
[email protected]81a2a602013-07-17 19:10:36852
Victor Costance678e72018-07-24 10:25:00853 // The WAL file is created lazily on first change.
854 ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)"));
855
856 {
Victor Costancfbfa602018-08-01 23:24:46857 base::FilePath wal_path = sql::Database::WriteAheadLogPath(db_path());
Victor Costance678e72018-07-24 10:25:00858 ASSERT_TRUE(GetPathExists(wal_path));
859 EXPECT_TRUE(base::GetPosixFilePermissions(wal_path, &mode));
860 ASSERT_EQ(mode, 0600);
861
Victor Costancfbfa602018-08-01 23:24:46862 base::FilePath shm_path = sql::Database::SharedMemoryFilePath(db_path());
Victor Costance678e72018-07-24 10:25:00863 ASSERT_TRUE(GetPathExists(shm_path));
864 EXPECT_TRUE(base::GetPosixFilePermissions(shm_path, &mode));
865 ASSERT_EQ(mode, 0600);
866 }
[email protected]81a2a602013-07-17 19:10:36867}
Wez35539132018-07-17 11:26:05868#endif // defined(OS_POSIX)
[email protected]81a2a602013-07-17 19:10:36869
[email protected]8d409412013-07-19 18:25:30870// Test that errors start happening once Poison() is called.
Victor Costancfbfa602018-08-01 23:24:46871TEST_F(SQLDatabaseTest, Poison) {
[email protected]8d409412013-07-19 18:25:30872 EXPECT_TRUE(db().Execute("CREATE TABLE x (x)"));
873
874 // Before the Poison() call, things generally work.
875 EXPECT_TRUE(db().IsSQLValid("INSERT INTO x VALUES ('x')"));
876 EXPECT_TRUE(db().Execute("INSERT INTO x VALUES ('x')"));
877 {
878 sql::Statement s(db().GetUniqueStatement("SELECT COUNT(*) FROM x"));
879 ASSERT_TRUE(s.is_valid());
880 ASSERT_TRUE(s.Step());
881 }
882
883 // Get a statement which is valid before and will exist across Poison().
884 sql::Statement valid_statement(
885 db().GetUniqueStatement("SELECT COUNT(*) FROM sqlite_master"));
886 ASSERT_TRUE(valid_statement.is_valid());
887 ASSERT_TRUE(valid_statement.Step());
888 valid_statement.Reset(true);
889
890 db().Poison();
891
892 // After the Poison() call, things fail.
893 EXPECT_FALSE(db().IsSQLValid("INSERT INTO x VALUES ('x')"));
894 EXPECT_FALSE(db().Execute("INSERT INTO x VALUES ('x')"));
895 {
896 sql::Statement s(db().GetUniqueStatement("SELECT COUNT(*) FROM x"));
897 ASSERT_FALSE(s.is_valid());
898 ASSERT_FALSE(s.Step());
899 }
900
901 // The existing statement has become invalid.
902 ASSERT_FALSE(valid_statement.is_valid());
903 ASSERT_FALSE(valid_statement.Step());
shess644fc8a2016-02-26 18:15:58904
905 // Test that poisoning the database during a transaction works (with errors).
906 // RazeErrorCallback() poisons the database, the extra COMMIT causes
907 // CommitTransaction() to throw an error while commiting.
tzikd16d2192018-03-07 08:58:36908 db().set_error_callback(
909 base::BindRepeating(&RazeErrorCallback, &db(), SQLITE_ERROR));
shess644fc8a2016-02-26 18:15:58910 db().Close();
911 ASSERT_TRUE(db().Open(db_path()));
912 EXPECT_TRUE(db().BeginTransaction());
913 EXPECT_TRUE(db().Execute("INSERT INTO x VALUES ('x')"));
914 EXPECT_TRUE(db().Execute("COMMIT"));
915 EXPECT_FALSE(db().CommitTransaction());
[email protected]8d409412013-07-19 18:25:30916}
917
Victor Costancfbfa602018-08-01 23:24:46918TEST_F(SQLDatabaseTest, AttachDatabase) {
[email protected]8d409412013-07-19 18:25:30919 EXPECT_TRUE(db().Execute("CREATE TABLE foo (a, b)"));
920
921 // Create a database to attach to.
922 base::FilePath attach_path =
Victor Costancfbfa602018-08-01 23:24:46923 db_path().DirName().AppendASCII("SQLDatabaseAttach.db");
Victor Costan1d868352018-06-26 19:06:48924 static const char kAttachmentPoint[] = "other";
[email protected]8d409412013-07-19 18:25:30925 {
Victor Costancfbfa602018-08-01 23:24:46926 sql::Database other_db;
[email protected]8d409412013-07-19 18:25:30927 ASSERT_TRUE(other_db.Open(attach_path));
928 EXPECT_TRUE(other_db.Execute("CREATE TABLE bar (a, b)"));
929 EXPECT_TRUE(other_db.Execute("INSERT INTO bar VALUES ('hello', 'world')"));
930 }
931
932 // Cannot see the attached database, yet.
933 EXPECT_FALSE(db().IsSQLValid("SELECT count(*) from other.bar"));
934
Victor Costan7f6abbbe2018-07-29 02:57:27935 EXPECT_TRUE(
Victor Costancfbfa602018-08-01 23:24:46936 DatabaseTestPeer::AttachDatabase(&db(), attach_path, kAttachmentPoint));
[email protected]8d409412013-07-19 18:25:30937 EXPECT_TRUE(db().IsSQLValid("SELECT count(*) from other.bar"));
938
Victor Costan8a87f7e52017-11-10 01:29:30939 // Queries can touch both databases after the ATTACH.
[email protected]8d409412013-07-19 18:25:30940 EXPECT_TRUE(db().Execute("INSERT INTO foo SELECT a, b FROM other.bar"));
941 {
942 sql::Statement s(db().GetUniqueStatement("SELECT COUNT(*) FROM foo"));
943 ASSERT_TRUE(s.Step());
944 EXPECT_EQ(1, s.ColumnInt(0));
945 }
946
Victor Costancfbfa602018-08-01 23:24:46947 EXPECT_TRUE(DatabaseTestPeer::DetachDatabase(&db(), kAttachmentPoint));
Victor Costan8a87f7e52017-11-10 01:29:30948 EXPECT_FALSE(db().IsSQLValid("SELECT count(*) from other.bar"));
949}
950
Victor Costancfbfa602018-08-01 23:24:46951TEST_F(SQLDatabaseTest, AttachDatabaseWithOpenTransaction) {
Victor Costan8a87f7e52017-11-10 01:29:30952 EXPECT_TRUE(db().Execute("CREATE TABLE foo (a, b)"));
953
954 // Create a database to attach to.
955 base::FilePath attach_path =
Victor Costancfbfa602018-08-01 23:24:46956 db_path().DirName().AppendASCII("SQLDatabaseAttach.db");
Victor Costan1d868352018-06-26 19:06:48957 static const char kAttachmentPoint[] = "other";
Victor Costan8a87f7e52017-11-10 01:29:30958 {
Victor Costancfbfa602018-08-01 23:24:46959 sql::Database other_db;
Victor Costan8a87f7e52017-11-10 01:29:30960 ASSERT_TRUE(other_db.Open(attach_path));
961 EXPECT_TRUE(other_db.Execute("CREATE TABLE bar (a, b)"));
962 EXPECT_TRUE(other_db.Execute("INSERT INTO bar VALUES ('hello', 'world')"));
963 }
964
965 // Cannot see the attached database, yet.
966 EXPECT_FALSE(db().IsSQLValid("SELECT count(*) from other.bar"));
967
Victor Costan8a87f7e52017-11-10 01:29:30968 // Attach succeeds in a transaction.
969 EXPECT_TRUE(db().BeginTransaction());
Victor Costan7f6abbbe2018-07-29 02:57:27970 EXPECT_TRUE(
Victor Costancfbfa602018-08-01 23:24:46971 DatabaseTestPeer::AttachDatabase(&db(), attach_path, kAttachmentPoint));
Victor Costan8a87f7e52017-11-10 01:29:30972 EXPECT_TRUE(db().IsSQLValid("SELECT count(*) from other.bar"));
973
974 // Queries can touch both databases after the ATTACH.
975 EXPECT_TRUE(db().Execute("INSERT INTO foo SELECT a, b FROM other.bar"));
976 {
977 sql::Statement s(db().GetUniqueStatement("SELECT COUNT(*) FROM foo"));
978 ASSERT_TRUE(s.Step());
979 EXPECT_EQ(1, s.ColumnInt(0));
980 }
981
982 // Detaching the same database fails, database is locked in the transaction.
983 {
984 sql::test::ScopedErrorExpecter expecter;
985 expecter.ExpectError(SQLITE_ERROR);
Victor Costancfbfa602018-08-01 23:24:46986 EXPECT_FALSE(DatabaseTestPeer::DetachDatabase(&db(), kAttachmentPoint));
[email protected]8d409412013-07-19 18:25:30987 EXPECT_TRUE(db().IsSQLValid("SELECT count(*) from other.bar"));
shess976814402016-06-21 06:56:25988 ASSERT_TRUE(expecter.SawExpectedErrors());
[email protected]8d409412013-07-19 18:25:30989 }
990
Victor Costan8a87f7e52017-11-10 01:29:30991 // Detach succeeds when the transaction is closed.
[email protected]8d409412013-07-19 18:25:30992 db().RollbackTransaction();
Victor Costancfbfa602018-08-01 23:24:46993 EXPECT_TRUE(DatabaseTestPeer::DetachDatabase(&db(), kAttachmentPoint));
[email protected]8d409412013-07-19 18:25:30994 EXPECT_FALSE(db().IsSQLValid("SELECT count(*) from other.bar"));
995}
996
Victor Costancfbfa602018-08-01 23:24:46997TEST_F(SQLDatabaseTest, Basic_QuickIntegrityCheck) {
[email protected]579446c2013-12-16 18:36:52998 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
999 ASSERT_TRUE(db().Execute(kCreateSql));
1000 EXPECT_TRUE(db().QuickIntegrityCheck());
1001 db().Close();
1002
erg102ceb412015-06-20 01:38:131003 ASSERT_TRUE(CorruptSizeInHeaderOfDB());
[email protected]579446c2013-12-16 18:36:521004
1005 {
shess976814402016-06-21 06:56:251006 sql::test::ScopedErrorExpecter expecter;
1007 expecter.ExpectError(SQLITE_CORRUPT);
[email protected]579446c2013-12-16 18:36:521008 ASSERT_TRUE(db().Open(db_path()));
1009 EXPECT_FALSE(db().QuickIntegrityCheck());
shess976814402016-06-21 06:56:251010 ASSERT_TRUE(expecter.SawExpectedErrors());
[email protected]579446c2013-12-16 18:36:521011 }
1012}
1013
Victor Costancfbfa602018-08-01 23:24:461014TEST_F(SQLDatabaseTest, Basic_FullIntegrityCheck) {
[email protected]579446c2013-12-16 18:36:521015 const std::string kOk("ok");
1016 std::vector<std::string> messages;
1017
1018 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
1019 ASSERT_TRUE(db().Execute(kCreateSql));
1020 EXPECT_TRUE(db().FullIntegrityCheck(&messages));
1021 EXPECT_EQ(1u, messages.size());
1022 EXPECT_EQ(kOk, messages[0]);
1023 db().Close();
1024
erg102ceb412015-06-20 01:38:131025 ASSERT_TRUE(CorruptSizeInHeaderOfDB());
[email protected]579446c2013-12-16 18:36:521026
1027 {
shess976814402016-06-21 06:56:251028 sql::test::ScopedErrorExpecter expecter;
1029 expecter.ExpectError(SQLITE_CORRUPT);
[email protected]579446c2013-12-16 18:36:521030 ASSERT_TRUE(db().Open(db_path()));
1031 EXPECT_TRUE(db().FullIntegrityCheck(&messages));
1032 EXPECT_LT(1u, messages.size());
1033 EXPECT_NE(kOk, messages[0]);
shess976814402016-06-21 06:56:251034 ASSERT_TRUE(expecter.SawExpectedErrors());
[email protected]579446c2013-12-16 18:36:521035 }
1036
1037 // TODO(shess): CorruptTableOrIndex could be used to produce a
1038 // file that would pass the quick check and fail the full check.
1039}
1040
Victor Costancfbfa602018-08-01 23:24:461041TEST_F(SQLDatabaseTest, OnMemoryDump) {
ssid9f8022f2015-10-12 17:49:031042 base::trace_event::MemoryDumpArgs args = {
1043 base::trace_event::MemoryDumpLevelOfDetail::DETAILED};
erikchenf62ea042018-05-25 21:30:571044 base::trace_event::ProcessMemoryDump pmd(args);
ssid3be5b1ec2016-01-13 14:21:571045 ASSERT_TRUE(db().memory_dump_provider_->OnMemoryDump(args, &pmd));
ssid9f8022f2015-10-12 17:49:031046 EXPECT_GE(pmd.allocator_dumps().size(), 1u);
1047}
1048
shessc8cd2a162015-10-22 20:30:461049// Test that the functions to collect diagnostic data run to completion, without
1050// worrying too much about what they generate (since that will change).
Victor Costancfbfa602018-08-01 23:24:461051TEST_F(SQLDatabaseTest, CollectDiagnosticInfo) {
shessc8cd2a162015-10-22 20:30:461052 const std::string corruption_info = db().CollectCorruptionInfo();
1053 EXPECT_NE(std::string::npos, corruption_info.find("SQLITE_CORRUPT"));
1054 EXPECT_NE(std::string::npos, corruption_info.find("integrity_check"));
shessc8cd2a162015-10-22 20:30:461055
1056 // A statement to see in the results.
1057 const char* kSimpleSql = "SELECT 'mountain'";
1058 Statement s(db().GetCachedStatement(SQL_FROM_HERE, kSimpleSql));
1059
1060 // Error includes the statement.
1061 const std::string readonly_info = db().CollectErrorInfo(SQLITE_READONLY, &s);
1062 EXPECT_NE(std::string::npos, readonly_info.find(kSimpleSql));
1063
1064 // Some other error doesn't include the statment.
1065 // TODO(shess): This is weak.
Victor Costanbd623112018-07-18 04:17:271066 const std::string full_info = db().CollectErrorInfo(SQLITE_FULL, nullptr);
shessc8cd2a162015-10-22 20:30:461067 EXPECT_EQ(std::string::npos, full_info.find(kSimpleSql));
1068
1069 // A table to see in the SQLITE_ERROR results.
1070 EXPECT_TRUE(db().Execute("CREATE TABLE volcano (x)"));
1071
1072 // Version info to see in the SQLITE_ERROR results.
1073 sql::MetaTable meta_table;
1074 ASSERT_TRUE(meta_table.Init(&db(), 4, 4));
1075
1076 const std::string error_info = db().CollectErrorInfo(SQLITE_ERROR, &s);
1077 EXPECT_NE(std::string::npos, error_info.find(kSimpleSql));
1078 EXPECT_NE(std::string::npos, error_info.find("volcano"));
1079 EXPECT_NE(std::string::npos, error_info.find("version: 4"));
1080}
1081
shess9bf2c672015-12-18 01:18:081082// Test that a fresh database has mmap enabled by default, if mmap'ed I/O is
1083// enabled by SQLite.
Victor Costancfbfa602018-08-01 23:24:461084TEST_F(SQLDatabaseTest, MmapInitiallyEnabled) {
shess9bf2c672015-12-18 01:18:081085 {
1086 sql::Statement s(db().GetUniqueStatement("PRAGMA mmap_size"));
Victor Costan42988a92018-02-06 02:22:141087 ASSERT_TRUE(s.Step())
1088 << "All supported SQLite versions should have mmap support";
shess9bf2c672015-12-18 01:18:081089
1090 // If mmap I/O is not on, attempt to turn it on. If that succeeds, then
1091 // Open() should have turned it on. If mmap support is disabled, 0 is
1092 // returned. If the VFS does not understand SQLITE_FCNTL_MMAP_SIZE (for
1093 // instance MojoVFS), -1 is returned.
1094 if (s.ColumnInt(0) <= 0) {
1095 ASSERT_TRUE(db().Execute("PRAGMA mmap_size = 1048576"));
1096 s.Reset(true);
1097 ASSERT_TRUE(s.Step());
1098 EXPECT_LE(s.ColumnInt(0), 0);
1099 }
1100 }
1101
1102 // Test that explicit disable prevents mmap'ed I/O.
1103 db().Close();
Victor Costancfbfa602018-08-01 23:24:461104 sql::Database::Delete(db_path());
shess9bf2c672015-12-18 01:18:081105 db().set_mmap_disabled();
1106 ASSERT_TRUE(db().Open(db_path()));
shessa62504d2016-11-07 19:26:121107 EXPECT_EQ("0", ExecuteWithResult(&db(), "PRAGMA mmap_size"));
1108}
1109
1110// Test whether a fresh database gets mmap enabled when using alternate status
1111// storage.
Victor Costancfbfa602018-08-01 23:24:461112TEST_F(SQLDatabaseTest, MmapInitiallyEnabledAltStatus) {
shessa62504d2016-11-07 19:26:121113 // Re-open fresh database with alt-status flag set.
1114 db().Close();
Victor Costancfbfa602018-08-01 23:24:461115 sql::Database::Delete(db_path());
shessa62504d2016-11-07 19:26:121116 db().set_mmap_alt_status();
1117 ASSERT_TRUE(db().Open(db_path()));
1118
shess9bf2c672015-12-18 01:18:081119 {
1120 sql::Statement s(db().GetUniqueStatement("PRAGMA mmap_size"));
Victor Costan42988a92018-02-06 02:22:141121 ASSERT_TRUE(s.Step())
1122 << "All supported SQLite versions should have mmap support";
shessa62504d2016-11-07 19:26:121123
1124 // If mmap I/O is not on, attempt to turn it on. If that succeeds, then
1125 // Open() should have turned it on. If mmap support is disabled, 0 is
1126 // returned. If the VFS does not understand SQLITE_FCNTL_MMAP_SIZE (for
1127 // instance MojoVFS), -1 is returned.
1128 if (s.ColumnInt(0) <= 0) {
1129 ASSERT_TRUE(db().Execute("PRAGMA mmap_size = 1048576"));
1130 s.Reset(true);
1131 ASSERT_TRUE(s.Step());
1132 EXPECT_LE(s.ColumnInt(0), 0);
1133 }
shess9bf2c672015-12-18 01:18:081134 }
shessa62504d2016-11-07 19:26:121135
1136 // Test that explicit disable overrides set_mmap_alt_status().
1137 db().Close();
Victor Costancfbfa602018-08-01 23:24:461138 sql::Database::Delete(db_path());
shessa62504d2016-11-07 19:26:121139 db().set_mmap_disabled();
1140 ASSERT_TRUE(db().Open(db_path()));
1141 EXPECT_EQ("0", ExecuteWithResult(&db(), "PRAGMA mmap_size"));
shess9bf2c672015-12-18 01:18:081142}
1143
Victor Costancfbfa602018-08-01 23:24:461144TEST_F(SQLDatabaseTest, GetAppropriateMmapSize) {
shess9bf2c672015-12-18 01:18:081145 const size_t kMmapAlot = 25 * 1024 * 1024;
shess9e77283d2016-06-13 23:53:201146 int64_t mmap_status = MetaTable::kMmapFailure;
shess9bf2c672015-12-18 01:18:081147
1148 // If there is no meta table (as for a fresh database), assume that everything
shess9e77283d2016-06-13 23:53:201149 // should be mapped, and the status of the meta table is not affected.
shess9bf2c672015-12-18 01:18:081150 ASSERT_TRUE(!db().DoesTableExist("meta"));
1151 ASSERT_GT(db().GetAppropriateMmapSize(), kMmapAlot);
shess9e77283d2016-06-13 23:53:201152 ASSERT_TRUE(!db().DoesTableExist("meta"));
shess9bf2c672015-12-18 01:18:081153
1154 // When the meta table is first created, it sets up to map everything.
1155 MetaTable().Init(&db(), 1, 1);
1156 ASSERT_TRUE(db().DoesTableExist("meta"));
1157 ASSERT_GT(db().GetAppropriateMmapSize(), kMmapAlot);
1158 ASSERT_TRUE(MetaTable::GetMmapStatus(&db(), &mmap_status));
1159 ASSERT_EQ(MetaTable::kMmapSuccess, mmap_status);
1160
shessa7b07acd2017-03-19 23:59:381161 // Preload with partial progress of one page. Should map everything.
1162 ASSERT_TRUE(db().Execute("REPLACE INTO meta VALUES ('mmap_status', 1)"));
1163 ASSERT_GT(db().GetAppropriateMmapSize(), kMmapAlot);
1164 ASSERT_TRUE(MetaTable::GetMmapStatus(&db(), &mmap_status));
1165 ASSERT_EQ(MetaTable::kMmapSuccess, mmap_status);
1166
shess9bf2c672015-12-18 01:18:081167 // Failure status maps nothing.
1168 ASSERT_TRUE(db().Execute("REPLACE INTO meta VALUES ('mmap_status', -2)"));
1169 ASSERT_EQ(0UL, db().GetAppropriateMmapSize());
1170
1171 // Re-initializing the meta table does not re-create the key if the table
1172 // already exists.
1173 ASSERT_TRUE(db().Execute("DELETE FROM meta WHERE key = 'mmap_status'"));
1174 MetaTable().Init(&db(), 1, 1);
1175 ASSERT_EQ(MetaTable::kMmapSuccess, mmap_status);
1176 ASSERT_TRUE(MetaTable::GetMmapStatus(&db(), &mmap_status));
1177 ASSERT_EQ(0, mmap_status);
1178
1179 // With no key, map everything and create the key.
1180 // TODO(shess): This really should be "maps everything after validating it",
1181 // but that is more complicated to structure.
1182 ASSERT_GT(db().GetAppropriateMmapSize(), kMmapAlot);
1183 ASSERT_TRUE(MetaTable::GetMmapStatus(&db(), &mmap_status));
1184 ASSERT_EQ(MetaTable::kMmapSuccess, mmap_status);
1185}
shess9bf2c672015-12-18 01:18:081186
Victor Costancfbfa602018-08-01 23:24:461187TEST_F(SQLDatabaseTest, GetAppropriateMmapSizeAltStatus) {
shessa62504d2016-11-07 19:26:121188 const size_t kMmapAlot = 25 * 1024 * 1024;
1189
Victor Costancfbfa602018-08-01 23:24:461190 // At this point, Database still expects a future [meta] table.
shessa62504d2016-11-07 19:26:121191 ASSERT_FALSE(db().DoesTableExist("meta"));
1192 ASSERT_FALSE(db().DoesViewExist("MmapStatus"));
1193 ASSERT_GT(db().GetAppropriateMmapSize(), kMmapAlot);
1194 ASSERT_FALSE(db().DoesTableExist("meta"));
1195 ASSERT_FALSE(db().DoesViewExist("MmapStatus"));
1196
1197 // Using alt status, everything should be mapped, with state in the view.
1198 db().set_mmap_alt_status();
1199 ASSERT_GT(db().GetAppropriateMmapSize(), kMmapAlot);
1200 ASSERT_FALSE(db().DoesTableExist("meta"));
1201 ASSERT_TRUE(db().DoesViewExist("MmapStatus"));
Raul Tambre6c708e32019-02-08 22:35:141202 EXPECT_EQ(base::NumberToString(MetaTable::kMmapSuccess),
shessa62504d2016-11-07 19:26:121203 ExecuteWithResult(&db(), "SELECT * FROM MmapStatus"));
1204
shessa7b07acd2017-03-19 23:59:381205 // Also maps everything when kMmapSuccess is already in the view.
shessa62504d2016-11-07 19:26:121206 ASSERT_GT(db().GetAppropriateMmapSize(), kMmapAlot);
1207
shessa7b07acd2017-03-19 23:59:381208 // Preload with partial progress of one page. Should map everything.
1209 ASSERT_TRUE(db().Execute("DROP VIEW MmapStatus"));
1210 ASSERT_TRUE(db().Execute("CREATE VIEW MmapStatus (value) AS SELECT 1"));
1211 ASSERT_GT(db().GetAppropriateMmapSize(), kMmapAlot);
Raul Tambre6c708e32019-02-08 22:35:141212 EXPECT_EQ(base::NumberToString(MetaTable::kMmapSuccess),
shessa7b07acd2017-03-19 23:59:381213 ExecuteWithResult(&db(), "SELECT * FROM MmapStatus"));
1214
shessa62504d2016-11-07 19:26:121215 // Failure status leads to nothing being mapped.
1216 ASSERT_TRUE(db().Execute("DROP VIEW MmapStatus"));
shessa7b07acd2017-03-19 23:59:381217 ASSERT_TRUE(db().Execute("CREATE VIEW MmapStatus (value) AS SELECT -2"));
shessa62504d2016-11-07 19:26:121218 ASSERT_EQ(0UL, db().GetAppropriateMmapSize());
Raul Tambre6c708e32019-02-08 22:35:141219 EXPECT_EQ(base::NumberToString(MetaTable::kMmapFailure),
shessa62504d2016-11-07 19:26:121220 ExecuteWithResult(&db(), "SELECT * FROM MmapStatus"));
1221}
1222
shess9e77283d2016-06-13 23:53:201223// To prevent invalid SQL from accidentally shipping to production, prepared
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521224// statements which fail to compile with SQLITE_ERROR call DLOG(DCHECK). This
shess9e77283d2016-06-13 23:53:201225// case cannot be suppressed with an error callback.
Victor Costancfbfa602018-08-01 23:24:461226TEST_F(SQLDatabaseTest, CompileError) {
1227// DEATH tests not supported on Android, iOS, or Fuchsia.
Scott Graham57ee54822017-09-13 06:37:561228#if !defined(OS_ANDROID) && !defined(OS_IOS) && !defined(OS_FUCHSIA)
shess9e77283d2016-06-13 23:53:201229 if (DLOG_IS_ON(FATAL)) {
tzikd16d2192018-03-07 08:58:361230 db().set_error_callback(base::BindRepeating(&IgnoreErrorCallback));
Victor Costancfbfa602018-08-01 23:24:461231 ASSERT_DEATH({ db().GetUniqueStatement("SELECT x"); },
1232 "SQL compile error no such column: x");
shess9e77283d2016-06-13 23:53:201233 }
Victor Costan8a87f7e52017-11-10 01:29:301234#endif // !defined(OS_ANDROID) && !defined(OS_IOS) && !defined(OS_FUCHSIA)
shess9e77283d2016-06-13 23:53:201235}
1236
shessc8cd2a162015-10-22 20:30:461237} // namespace sql