blob: d9dd9d9f46005bd727b5ca6c9215a7f696f77436 [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"
shess58b8df82015-06-03 00:19:3214#include "base/metrics/statistics_recorder.h"
15#include "base/test/histogram_tester.h"
ssid9f8022f2015-10-12 17:49:0316#include "base/trace_event/process_memory_dump.h"
[email protected]f0a54b22011-07-19 18:40:2117#include "sql/connection.h"
ssid3be5b1ec2016-01-13 14:21:5718#include "sql/connection_memory_dump_provider.h"
erg102ceb412015-06-20 01:38:1319#include "sql/correct_sql_test_base.h"
[email protected]1348765a2012-07-24 08:25:5320#include "sql/meta_table.h"
[email protected]ea1a3f62012-11-16 20:34:2321#include "sql/statement.h"
[email protected]98cf3002013-07-12 01:38:5622#include "sql/test/error_callback_support.h"
[email protected]4350e322013-06-18 22:18:1023#include "sql/test/scoped_error_ignorer.h"
[email protected]a8848a72013-11-18 04:18:4724#include "sql/test/test_helpers.h"
[email protected]e5ffd0e42009-09-11 21:30:5625#include "testing/gtest/include/gtest/gtest.h"
[email protected]e33cba42010-08-18 23:37:0326#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5627
shess58b8df82015-06-03 00:19:3228namespace sql {
29namespace test {
30
31// Replaces the database time source with an object that steps forward 1ms on
32// each check, and which can be jumped forward an arbitrary amount of time
33// programmatically.
34class ScopedMockTimeSource {
35 public:
36 ScopedMockTimeSource(Connection& db)
37 : db_(db),
38 delta_(base::TimeDelta::FromMilliseconds(1)) {
39 // Save the current source and replace it.
40 save_.swap(db_.clock_);
41 db_.clock_.reset(new MockTimeSource(*this));
42 }
43 ~ScopedMockTimeSource() {
44 // Put original source back.
45 db_.clock_.swap(save_);
46 }
47
48 void adjust(const base::TimeDelta& delta) {
49 current_time_ += delta;
50 }
51
52 private:
53 class MockTimeSource : public TimeSource {
54 public:
55 MockTimeSource(ScopedMockTimeSource& owner)
56 : owner_(owner) {
57 }
58 ~MockTimeSource() override {}
59
60 base::TimeTicks Now() override {
61 base::TimeTicks ret(owner_.current_time_);
62 owner_.current_time_ += owner_.delta_;
63 return ret;
64 }
65
66 private:
67 ScopedMockTimeSource& owner_;
68 DISALLOW_COPY_AND_ASSIGN(MockTimeSource);
69 };
70
71 Connection& db_;
72
73 // Saves original source from |db_|.
74 scoped_ptr<TimeSource> save_;
75
76 // Current time returned by mock.
77 base::TimeTicks current_time_;
78
79 // How far to jump on each Now() call.
80 base::TimeDelta delta_;
81
82 DISALLOW_COPY_AND_ASSIGN(ScopedMockTimeSource);
83};
84
85// Allow a test to add a SQLite function in a scoped context.
86class ScopedScalarFunction {
87 public:
88 ScopedScalarFunction(
89 sql::Connection& db,
90 const char* function_name,
91 int args,
92 base::Callback<void(sqlite3_context*,int,sqlite3_value**)> cb)
93 : db_(db.db_), function_name_(function_name), cb_(cb) {
shess6ce9d1f02015-09-02 19:37:4394 sqlite3_create_function_v2(db_, function_name, args, SQLITE_UTF8,
95 this, &Run, NULL, NULL, NULL);
shess58b8df82015-06-03 00:19:3296 }
97 ~ScopedScalarFunction() {
shess6ce9d1f02015-09-02 19:37:4398 sqlite3_create_function_v2(db_, function_name_, 0, SQLITE_UTF8,
99 NULL, NULL, NULL, NULL, NULL);
shess58b8df82015-06-03 00:19:32100 }
101
102 private:
103 static void Run(sqlite3_context* context, int argc, sqlite3_value** argv) {
104 ScopedScalarFunction* t = static_cast<ScopedScalarFunction*>(
105 sqlite3_user_data(context));
106 t->cb_.Run(context, argc, argv);
107 }
108
109 sqlite3* db_;
110 const char* function_name_;
111 base::Callback<void(sqlite3_context*,int,sqlite3_value**)> cb_;
112
113 DISALLOW_COPY_AND_ASSIGN(ScopedScalarFunction);
114};
115
116// Allow a test to add a SQLite commit hook in a scoped context.
117class ScopedCommitHook {
118 public:
119 ScopedCommitHook(sql::Connection& db,
120 base::Callback<int(void)> cb)
121 : db_(db.db_),
122 cb_(cb) {
shess6ce9d1f02015-09-02 19:37:43123 sqlite3_commit_hook(db_, &Run, this);
shess58b8df82015-06-03 00:19:32124 }
125 ~ScopedCommitHook() {
shess6ce9d1f02015-09-02 19:37:43126 sqlite3_commit_hook(db_, NULL, NULL);
shess58b8df82015-06-03 00:19:32127 }
128
129 private:
130 static int Run(void* p) {
131 ScopedCommitHook* t = static_cast<ScopedCommitHook*>(p);
132 return t->cb_.Run();
133 }
134
135 sqlite3* db_;
136 base::Callback<int(void)> cb_;
137
138 DISALLOW_COPY_AND_ASSIGN(ScopedCommitHook);
139};
140
141} // namespace test
shess58b8df82015-06-03 00:19:32142
[email protected]7bae5742013-07-10 20:46:16143namespace {
144
145// Helper to return the count of items in sqlite_master. Return -1 in
146// case of error.
147int SqliteMasterCount(sql::Connection* db) {
148 const char* kMasterCount = "SELECT COUNT(*) FROM sqlite_master";
149 sql::Statement s(db->GetUniqueStatement(kMasterCount));
150 return s.Step() ? s.ColumnInt(0) : -1;
151}
152
[email protected]98cf3002013-07-12 01:38:56153// Track the number of valid references which share the same pointer.
154// This is used to allow testing an implicitly use-after-free case by
155// explicitly having the ref count live longer than the object.
156class RefCounter {
157 public:
158 RefCounter(size_t* counter)
159 : counter_(counter) {
160 (*counter_)++;
161 }
162 RefCounter(const RefCounter& other)
163 : counter_(other.counter_) {
164 (*counter_)++;
165 }
166 ~RefCounter() {
167 (*counter_)--;
168 }
169
170 private:
171 size_t* counter_;
172
173 DISALLOW_ASSIGN(RefCounter);
174};
175
176// Empty callback for implementation of ErrorCallbackSetHelper().
177void IgnoreErrorCallback(int error, sql::Statement* stmt) {
178}
179
180void ErrorCallbackSetHelper(sql::Connection* db,
181 size_t* counter,
182 const RefCounter& r,
183 int error, sql::Statement* stmt) {
184 // The ref count should not go to zero when changing the callback.
185 EXPECT_GT(*counter, 0u);
186 db->set_error_callback(base::Bind(&IgnoreErrorCallback));
187 EXPECT_GT(*counter, 0u);
188}
189
190void ErrorCallbackResetHelper(sql::Connection* db,
191 size_t* counter,
192 const RefCounter& r,
193 int error, sql::Statement* stmt) {
194 // The ref count should not go to zero when clearing the callback.
195 EXPECT_GT(*counter, 0u);
196 db->reset_error_callback();
197 EXPECT_GT(*counter, 0u);
198}
199
[email protected]81a2a602013-07-17 19:10:36200#if defined(OS_POSIX)
201// Set a umask and restore the old mask on destruction. Cribbed from
202// shared_memory_unittest.cc. Used by POSIX-only UserPermission test.
203class ScopedUmaskSetter {
204 public:
205 explicit ScopedUmaskSetter(mode_t target_mask) {
206 old_umask_ = umask(target_mask);
207 }
208 ~ScopedUmaskSetter() { umask(old_umask_); }
209 private:
210 mode_t old_umask_;
211 DISALLOW_IMPLICIT_CONSTRUCTORS(ScopedUmaskSetter);
212};
213#endif
214
shessc8cd2a162015-10-22 20:30:46215// SQLite function to adjust mock time by |argv[0]| milliseconds.
216void sqlite_adjust_millis(sql::test::ScopedMockTimeSource* time_mock,
217 sqlite3_context* context,
218 int argc, sqlite3_value** argv) {
avi0b519202015-12-21 07:25:19219 int64_t milliseconds = argc > 0 ? sqlite3_value_int64(argv[0]) : 1000;
shessc8cd2a162015-10-22 20:30:46220 time_mock->adjust(base::TimeDelta::FromMilliseconds(milliseconds));
221 sqlite3_result_int64(context, milliseconds);
222}
223
224// Adjust mock time by |milliseconds| on commit.
225int adjust_commit_hook(sql::test::ScopedMockTimeSource* time_mock,
avi0b519202015-12-21 07:25:19226 int64_t milliseconds) {
shessc8cd2a162015-10-22 20:30:46227 time_mock->adjust(base::TimeDelta::FromMilliseconds(milliseconds));
228 return SQLITE_OK;
229}
230
231const char kCommitTime[] = "Sqlite.CommitTime.Test";
232const char kAutoCommitTime[] = "Sqlite.AutoCommitTime.Test";
233const char kUpdateTime[] = "Sqlite.UpdateTime.Test";
234const char kQueryTime[] = "Sqlite.QueryTime.Test";
235
236} // namespace
237
erg102ceb412015-06-20 01:38:13238class SQLConnectionTest : public sql::SQLTestBase {
[email protected]e5ffd0e42009-09-11 21:30:56239 public:
dcheng1b3b125e2014-12-22 23:00:24240 void SetUp() override {
shess58b8df82015-06-03 00:19:32241 // Any macro histograms which fire before the recorder is initialized cannot
242 // be tested. So this needs to be ahead of Open().
243 base::StatisticsRecorder::Initialize();
244
erg102ceb412015-06-20 01:38:13245 SQLTestBase::SetUp();
[email protected]e5ffd0e42009-09-11 21:30:56246 }
247
[email protected]7bae5742013-07-10 20:46:16248 // Handle errors by blowing away the database.
249 void RazeErrorCallback(int expected_error, int error, sql::Statement* stmt) {
shess644fc8a2016-02-26 18:15:58250 // Nothing here needs extended errors at this time.
251 EXPECT_EQ(expected_error, expected_error&0xff);
252 EXPECT_EQ(expected_error, error&0xff);
erg102ceb412015-06-20 01:38:13253 db().RazeAndClose();
[email protected]7bae5742013-07-10 20:46:16254 }
[email protected]e5ffd0e42009-09-11 21:30:56255};
256
257TEST_F(SQLConnectionTest, Execute) {
258 // Valid statement should return true.
259 ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)"));
260 EXPECT_EQ(SQLITE_OK, db().GetErrorCode());
261
262 // Invalid statement should fail.
[email protected]eff1fa522011-12-12 23:50:59263 ASSERT_EQ(SQLITE_ERROR,
264 db().ExecuteAndReturnErrorCode("CREATE TAB foo (a, b"));
[email protected]e5ffd0e42009-09-11 21:30:56265 EXPECT_EQ(SQLITE_ERROR, db().GetErrorCode());
266}
267
[email protected]eff1fa522011-12-12 23:50:59268TEST_F(SQLConnectionTest, ExecuteWithErrorCode) {
269 ASSERT_EQ(SQLITE_OK,
270 db().ExecuteAndReturnErrorCode("CREATE TABLE foo (a, b)"));
271 ASSERT_EQ(SQLITE_ERROR,
272 db().ExecuteAndReturnErrorCode("CREATE TABLE TABLE"));
273 ASSERT_EQ(SQLITE_ERROR,
274 db().ExecuteAndReturnErrorCode(
275 "INSERT INTO foo(a, b) VALUES (1, 2, 3, 4)"));
276}
277
[email protected]e5ffd0e42009-09-11 21:30:56278TEST_F(SQLConnectionTest, CachedStatement) {
279 sql::StatementID id1("foo", 12);
280
281 ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)"));
282 ASSERT_TRUE(db().Execute("INSERT INTO foo(a, b) VALUES (12, 13)"));
283
284 // Create a new cached statement.
285 {
286 sql::Statement s(db().GetCachedStatement(id1, "SELECT a FROM foo"));
[email protected]eff1fa522011-12-12 23:50:59287 ASSERT_TRUE(s.is_valid());
[email protected]e5ffd0e42009-09-11 21:30:56288
289 ASSERT_TRUE(s.Step());
290 EXPECT_EQ(12, s.ColumnInt(0));
291 }
292
293 // The statement should be cached still.
294 EXPECT_TRUE(db().HasCachedStatement(id1));
295
296 {
297 // Get the same statement using different SQL. This should ignore our
298 // SQL and use the cached one (so it will be valid).
299 sql::Statement s(db().GetCachedStatement(id1, "something invalid("));
[email protected]eff1fa522011-12-12 23:50:59300 ASSERT_TRUE(s.is_valid());
[email protected]e5ffd0e42009-09-11 21:30:56301
302 ASSERT_TRUE(s.Step());
303 EXPECT_EQ(12, s.ColumnInt(0));
304 }
305
306 // Make sure other statements aren't marked as cached.
307 EXPECT_FALSE(db().HasCachedStatement(SQL_FROM_HERE));
308}
309
[email protected]eff1fa522011-12-12 23:50:59310TEST_F(SQLConnectionTest, IsSQLValidTest) {
311 ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)"));
312 ASSERT_TRUE(db().IsSQLValid("SELECT a FROM foo"));
313 ASSERT_FALSE(db().IsSQLValid("SELECT no_exist FROM foo"));
314}
315
[email protected]e5ffd0e42009-09-11 21:30:56316TEST_F(SQLConnectionTest, DoesStuffExist) {
317 // Test DoesTableExist.
318 EXPECT_FALSE(db().DoesTableExist("foo"));
319 ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)"));
shess92a2ab12015-04-09 01:59:47320 ASSERT_TRUE(db().Execute("CREATE INDEX foo_a ON foo (a)"));
[email protected]e5ffd0e42009-09-11 21:30:56321 EXPECT_TRUE(db().DoesTableExist("foo"));
shess92a2ab12015-04-09 01:59:47322 EXPECT_TRUE(db().DoesIndexExist("foo_a"));
[email protected]e5ffd0e42009-09-11 21:30:56323
324 // Test DoesColumnExist.
325 EXPECT_FALSE(db().DoesColumnExist("foo", "bar"));
326 EXPECT_TRUE(db().DoesColumnExist("foo", "a"));
327
[email protected]e7afe2452010-08-22 16:19:13328 // Testing for a column on a nonexistent table.
[email protected]e5ffd0e42009-09-11 21:30:56329 EXPECT_FALSE(db().DoesColumnExist("bar", "b"));
shess92a2ab12015-04-09 01:59:47330
331 // Names are not case sensitive.
332 EXPECT_TRUE(db().DoesTableExist("FOO"));
333 EXPECT_TRUE(db().DoesColumnExist("FOO", "A"));
[email protected]e5ffd0e42009-09-11 21:30:56334}
335
336TEST_F(SQLConnectionTest, GetLastInsertRowId) {
337 ASSERT_TRUE(db().Execute("CREATE TABLE foo (id INTEGER PRIMARY KEY, value)"));
338
339 ASSERT_TRUE(db().Execute("INSERT INTO foo (value) VALUES (12)"));
340
341 // Last insert row ID should be valid.
tfarina720d4f32015-05-11 22:31:26342 int64_t row = db().GetLastInsertRowId();
[email protected]e5ffd0e42009-09-11 21:30:56343 EXPECT_LT(0, row);
344
345 // It should be the primary key of the row we just inserted.
346 sql::Statement s(db().GetUniqueStatement("SELECT value FROM foo WHERE id=?"));
347 s.BindInt64(0, row);
348 ASSERT_TRUE(s.Step());
349 EXPECT_EQ(12, s.ColumnInt(0));
350}
[email protected]44ad7d902012-03-23 00:09:05351
352TEST_F(SQLConnectionTest, Rollback) {
353 ASSERT_TRUE(db().BeginTransaction());
354 ASSERT_TRUE(db().BeginTransaction());
355 EXPECT_EQ(2, db().transaction_nesting());
356 db().RollbackTransaction();
357 EXPECT_FALSE(db().CommitTransaction());
358 EXPECT_TRUE(db().BeginTransaction());
359}
[email protected]8e0c01282012-04-06 19:36:49360
[email protected]4350e322013-06-18 22:18:10361// Test the scoped error ignorer by attempting to insert a duplicate
362// value into an index.
363TEST_F(SQLConnectionTest, ScopedIgnoreError) {
364 const char* kCreateSql = "CREATE TABLE foo (id INTEGER UNIQUE)";
365 ASSERT_TRUE(db().Execute(kCreateSql));
366 ASSERT_TRUE(db().Execute("INSERT INTO foo (id) VALUES (12)"));
367
shess92a2ab12015-04-09 01:59:47368 {
369 sql::ScopedErrorIgnorer ignore_errors;
370 ignore_errors.IgnoreError(SQLITE_CONSTRAINT);
371 ASSERT_FALSE(db().Execute("INSERT INTO foo (id) VALUES (12)"));
372 ASSERT_TRUE(ignore_errors.CheckIgnoredErrors());
373 }
374}
375
376// Test that clients of GetUntrackedStatement() can test corruption-handling
377// with ScopedErrorIgnorer.
378TEST_F(SQLConnectionTest, ScopedIgnoreUntracked) {
379 const char* kCreateSql = "CREATE TABLE foo (id INTEGER UNIQUE)";
380 ASSERT_TRUE(db().Execute(kCreateSql));
381 ASSERT_FALSE(db().DoesTableExist("bar"));
382 ASSERT_TRUE(db().DoesTableExist("foo"));
383 ASSERT_TRUE(db().DoesColumnExist("foo", "id"));
384 db().Close();
385
386 // Corrupt the database so that nothing works, including PRAGMAs.
erg102ceb412015-06-20 01:38:13387 ASSERT_TRUE(CorruptSizeInHeaderOfDB());
shess92a2ab12015-04-09 01:59:47388
389 {
390 sql::ScopedErrorIgnorer ignore_errors;
391 ignore_errors.IgnoreError(SQLITE_CORRUPT);
392 ASSERT_TRUE(db().Open(db_path()));
393 ASSERT_FALSE(db().DoesTableExist("bar"));
394 ASSERT_FALSE(db().DoesTableExist("foo"));
395 ASSERT_FALSE(db().DoesColumnExist("foo", "id"));
396 ASSERT_TRUE(ignore_errors.CheckIgnoredErrors());
397 }
[email protected]4350e322013-06-18 22:18:10398}
399
[email protected]98cf3002013-07-12 01:38:56400TEST_F(SQLConnectionTest, ErrorCallback) {
401 const char* kCreateSql = "CREATE TABLE foo (id INTEGER UNIQUE)";
402 ASSERT_TRUE(db().Execute(kCreateSql));
403 ASSERT_TRUE(db().Execute("INSERT INTO foo (id) VALUES (12)"));
404
405 int error = SQLITE_OK;
406 {
407 sql::ScopedErrorCallback sec(
408 &db(), base::Bind(&sql::CaptureErrorCallback, &error));
[email protected]98cf3002013-07-12 01:38:56409 EXPECT_FALSE(db().Execute("INSERT INTO foo (id) VALUES (12)"));
Scott Hessdcf120482015-02-10 21:33:29410
411 // Later versions of SQLite throw SQLITE_CONSTRAINT_UNIQUE. The specific
412 // sub-error isn't really important.
413 EXPECT_EQ(SQLITE_CONSTRAINT, (error&0xff));
[email protected]98cf3002013-07-12 01:38:56414 }
415
416 // Callback is no longer in force due to reset.
417 {
418 error = SQLITE_OK;
419 sql::ScopedErrorIgnorer ignore_errors;
420 ignore_errors.IgnoreError(SQLITE_CONSTRAINT);
421 ASSERT_FALSE(db().Execute("INSERT INTO foo (id) VALUES (12)"));
422 ASSERT_TRUE(ignore_errors.CheckIgnoredErrors());
423 EXPECT_EQ(SQLITE_OK, error);
424 }
425
426 // base::Bind() can curry arguments to be passed by const reference
[email protected]81a2a602013-07-17 19:10:36427 // to the callback function. If the callback function calls
428 // re/set_error_callback(), the storage for those arguments can be
429 // deleted while the callback function is still executing.
[email protected]98cf3002013-07-12 01:38:56430 //
431 // RefCounter() counts how many objects are live using an external
432 // count. The same counter is passed to the callback, so that it
433 // can check directly even if the RefCounter object is no longer
434 // live.
435 {
436 size_t count = 0;
437 sql::ScopedErrorCallback sec(
438 &db(), base::Bind(&ErrorCallbackSetHelper,
439 &db(), &count, RefCounter(&count)));
440
441 EXPECT_FALSE(db().Execute("INSERT INTO foo (id) VALUES (12)"));
442 }
443
444 // Same test, but reset_error_callback() case.
445 {
446 size_t count = 0;
447 sql::ScopedErrorCallback sec(
448 &db(), base::Bind(&ErrorCallbackResetHelper,
449 &db(), &count, RefCounter(&count)));
450
451 EXPECT_FALSE(db().Execute("INSERT INTO foo (id) VALUES (12)"));
452 }
453}
454
[email protected]8e0c01282012-04-06 19:36:49455// Test that sql::Connection::Raze() results in a database without the
456// tables from the original database.
457TEST_F(SQLConnectionTest, Raze) {
458 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
459 ASSERT_TRUE(db().Execute(kCreateSql));
460 ASSERT_TRUE(db().Execute("INSERT INTO foo (value) VALUES (12)"));
461
[email protected]69c58452012-08-06 19:22:42462 int pragma_auto_vacuum = 0;
463 {
464 sql::Statement s(db().GetUniqueStatement("PRAGMA auto_vacuum"));
465 ASSERT_TRUE(s.Step());
466 pragma_auto_vacuum = s.ColumnInt(0);
467 ASSERT_TRUE(pragma_auto_vacuum == 0 || pragma_auto_vacuum == 1);
468 }
469
470 // If auto_vacuum is set, there's an extra page to maintain a freelist.
471 const int kExpectedPageCount = 2 + pragma_auto_vacuum;
472
[email protected]8e0c01282012-04-06 19:36:49473 {
474 sql::Statement s(db().GetUniqueStatement("PRAGMA page_count"));
475 ASSERT_TRUE(s.Step());
[email protected]69c58452012-08-06 19:22:42476 EXPECT_EQ(kExpectedPageCount, s.ColumnInt(0));
[email protected]8e0c01282012-04-06 19:36:49477 }
478
479 {
480 sql::Statement s(db().GetUniqueStatement("SELECT * FROM sqlite_master"));
481 ASSERT_TRUE(s.Step());
482 EXPECT_EQ("table", s.ColumnString(0));
483 EXPECT_EQ("foo", s.ColumnString(1));
484 EXPECT_EQ("foo", s.ColumnString(2));
[email protected]69c58452012-08-06 19:22:42485 // Table "foo" is stored in the last page of the file.
486 EXPECT_EQ(kExpectedPageCount, s.ColumnInt(3));
[email protected]8e0c01282012-04-06 19:36:49487 EXPECT_EQ(kCreateSql, s.ColumnString(4));
488 }
489
490 ASSERT_TRUE(db().Raze());
491
492 {
493 sql::Statement s(db().GetUniqueStatement("PRAGMA page_count"));
494 ASSERT_TRUE(s.Step());
495 EXPECT_EQ(1, s.ColumnInt(0));
496 }
497
[email protected]7bae5742013-07-10 20:46:16498 ASSERT_EQ(0, SqliteMasterCount(&db()));
[email protected]69c58452012-08-06 19:22:42499
500 {
501 sql::Statement s(db().GetUniqueStatement("PRAGMA auto_vacuum"));
502 ASSERT_TRUE(s.Step());
[email protected]6d42f152012-11-10 00:38:24503 // The new database has the same auto_vacuum as a fresh database.
[email protected]69c58452012-08-06 19:22:42504 EXPECT_EQ(pragma_auto_vacuum, s.ColumnInt(0));
505 }
[email protected]8e0c01282012-04-06 19:36:49506}
507
508// Test that Raze() maintains page_size.
509TEST_F(SQLConnectionTest, RazePageSize) {
[email protected]e73e89222012-07-13 18:55:22510 // Fetch the default page size and double it for use in this test.
[email protected]8e0c01282012-04-06 19:36:49511 // Scoped to release statement before Close().
[email protected]e73e89222012-07-13 18:55:22512 int default_page_size = 0;
[email protected]8e0c01282012-04-06 19:36:49513 {
514 sql::Statement s(db().GetUniqueStatement("PRAGMA page_size"));
515 ASSERT_TRUE(s.Step());
[email protected]e73e89222012-07-13 18:55:22516 default_page_size = s.ColumnInt(0);
[email protected]8e0c01282012-04-06 19:36:49517 }
[email protected]e73e89222012-07-13 18:55:22518 ASSERT_GT(default_page_size, 0);
519 const int kPageSize = 2 * default_page_size;
[email protected]8e0c01282012-04-06 19:36:49520
521 // Re-open the database to allow setting the page size.
522 db().Close();
523 db().set_page_size(kPageSize);
524 ASSERT_TRUE(db().Open(db_path()));
525
526 // page_size should match the indicated value.
527 sql::Statement s(db().GetUniqueStatement("PRAGMA page_size"));
528 ASSERT_TRUE(s.Step());
529 ASSERT_EQ(kPageSize, s.ColumnInt(0));
530
531 // After raze, page_size should still match the indicated value.
532 ASSERT_TRUE(db().Raze());
[email protected]389e0a42012-04-25 21:36:41533 s.Reset(true);
[email protected]8e0c01282012-04-06 19:36:49534 ASSERT_TRUE(s.Step());
535 ASSERT_EQ(kPageSize, s.ColumnInt(0));
536}
537
538// Test that Raze() results are seen in other connections.
539TEST_F(SQLConnectionTest, RazeMultiple) {
540 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
541 ASSERT_TRUE(db().Execute(kCreateSql));
542
543 sql::Connection other_db;
544 ASSERT_TRUE(other_db.Open(db_path()));
545
546 // Check that the second connection sees the table.
[email protected]7bae5742013-07-10 20:46:16547 ASSERT_EQ(1, SqliteMasterCount(&other_db));
[email protected]8e0c01282012-04-06 19:36:49548
549 ASSERT_TRUE(db().Raze());
550
551 // The second connection sees the updated database.
[email protected]7bae5742013-07-10 20:46:16552 ASSERT_EQ(0, SqliteMasterCount(&other_db));
[email protected]8e0c01282012-04-06 19:36:49553}
554
erg102ceb412015-06-20 01:38:13555// TODO(erg): Enable this in the next patch once I add locking.
556#if !defined(MOJO_APPTEST_IMPL)
[email protected]8e0c01282012-04-06 19:36:49557TEST_F(SQLConnectionTest, RazeLocked) {
558 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
559 ASSERT_TRUE(db().Execute(kCreateSql));
560
561 // Open a transaction and write some data in a second connection.
562 // This will acquire a PENDING or EXCLUSIVE transaction, which will
563 // cause the raze to fail.
564 sql::Connection other_db;
565 ASSERT_TRUE(other_db.Open(db_path()));
566 ASSERT_TRUE(other_db.BeginTransaction());
567 const char* kInsertSql = "INSERT INTO foo VALUES (1, 'data')";
568 ASSERT_TRUE(other_db.Execute(kInsertSql));
569
570 ASSERT_FALSE(db().Raze());
571
572 // Works after COMMIT.
573 ASSERT_TRUE(other_db.CommitTransaction());
574 ASSERT_TRUE(db().Raze());
575
576 // Re-create the database.
577 ASSERT_TRUE(db().Execute(kCreateSql));
578 ASSERT_TRUE(db().Execute(kInsertSql));
579
580 // An unfinished read transaction in the other connection also
581 // blocks raze.
582 const char *kQuery = "SELECT COUNT(*) FROM foo";
583 sql::Statement s(other_db.GetUniqueStatement(kQuery));
584 ASSERT_TRUE(s.Step());
585 ASSERT_FALSE(db().Raze());
586
587 // Complete the statement unlocks the database.
588 ASSERT_FALSE(s.Step());
589 ASSERT_TRUE(db().Raze());
590}
erg102ceb412015-06-20 01:38:13591#endif
[email protected]8e0c01282012-04-06 19:36:49592
[email protected]7bae5742013-07-10 20:46:16593// Verify that Raze() can handle an empty file. SQLite should treat
594// this as an empty database.
595TEST_F(SQLConnectionTest, RazeEmptyDB) {
596 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
597 ASSERT_TRUE(db().Execute(kCreateSql));
598 db().Close();
599
erg102ceb412015-06-20 01:38:13600 TruncateDatabase();
[email protected]7bae5742013-07-10 20:46:16601
602 ASSERT_TRUE(db().Open(db_path()));
603 ASSERT_TRUE(db().Raze());
604 EXPECT_EQ(0, SqliteMasterCount(&db()));
605}
606
607// Verify that Raze() can handle a file of junk.
608TEST_F(SQLConnectionTest, RazeNOTADB) {
609 db().Close();
610 sql::Connection::Delete(db_path());
erg102ceb412015-06-20 01:38:13611 ASSERT_FALSE(GetPathExists(db_path()));
[email protected]7bae5742013-07-10 20:46:16612
erg102ceb412015-06-20 01:38:13613 WriteJunkToDatabase(SQLTestBase::TYPE_OVERWRITE_AND_TRUNCATE);
614 ASSERT_TRUE(GetPathExists(db_path()));
[email protected]7bae5742013-07-10 20:46:16615
Scott Hessdcf120482015-02-10 21:33:29616 // SQLite will successfully open the handle, but fail when running PRAGMA
617 // statements that access the database.
[email protected]7bae5742013-07-10 20:46:16618 {
619 sql::ScopedErrorIgnorer ignore_errors;
Scott Hessdcf120482015-02-10 21:33:29620
621 // Earlier versions of Chromium compiled against SQLite 3.6.7.3, which
622 // returned SQLITE_IOERR_SHORT_READ in this case. Some platforms may still
623 // compile against an earlier SQLite via USE_SYSTEM_SQLITE.
sdefresne4472cfb2015-04-10 16:54:22624 if (ignore_errors.SQLiteLibVersionNumber() < 3008005) {
Scott Hessdcf120482015-02-10 21:33:29625 ignore_errors.IgnoreError(SQLITE_IOERR_SHORT_READ);
626 } else {
627 ignore_errors.IgnoreError(SQLITE_NOTADB);
628 }
629
[email protected]7bae5742013-07-10 20:46:16630 EXPECT_TRUE(db().Open(db_path()));
631 ASSERT_TRUE(ignore_errors.CheckIgnoredErrors());
632 }
633 EXPECT_TRUE(db().Raze());
634 db().Close();
635
636 // Now empty, the open should open an empty database.
637 EXPECT_TRUE(db().Open(db_path()));
638 EXPECT_EQ(0, SqliteMasterCount(&db()));
639}
640
641// Verify that Raze() can handle a database overwritten with garbage.
642TEST_F(SQLConnectionTest, RazeNOTADB2) {
643 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
644 ASSERT_TRUE(db().Execute(kCreateSql));
645 ASSERT_EQ(1, SqliteMasterCount(&db()));
646 db().Close();
647
erg102ceb412015-06-20 01:38:13648 WriteJunkToDatabase(SQLTestBase::TYPE_OVERWRITE);
[email protected]7bae5742013-07-10 20:46:16649
650 // SQLite will successfully open the handle, but will fail with
651 // SQLITE_NOTADB on pragma statemenets which attempt to read the
652 // corrupted header.
653 {
654 sql::ScopedErrorIgnorer ignore_errors;
655 ignore_errors.IgnoreError(SQLITE_NOTADB);
656 EXPECT_TRUE(db().Open(db_path()));
657 ASSERT_TRUE(ignore_errors.CheckIgnoredErrors());
658 }
659 EXPECT_TRUE(db().Raze());
660 db().Close();
661
662 // Now empty, the open should succeed with an empty database.
663 EXPECT_TRUE(db().Open(db_path()));
664 EXPECT_EQ(0, SqliteMasterCount(&db()));
665}
666
667// Test that a callback from Open() can raze the database. This is
668// essential for cases where the Open() can fail entirely, so the
[email protected]fed734a2013-07-17 04:45:13669// Raze() cannot happen later. Additionally test that when the
670// callback does this during Open(), the open is retried and succeeds.
[email protected]fed734a2013-07-17 04:45:13671TEST_F(SQLConnectionTest, RazeCallbackReopen) {
[email protected]7bae5742013-07-10 20:46:16672 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
673 ASSERT_TRUE(db().Execute(kCreateSql));
674 ASSERT_EQ(1, SqliteMasterCount(&db()));
[email protected]7bae5742013-07-10 20:46:16675 db().Close();
676
[email protected]a8848a72013-11-18 04:18:47677 // Corrupt the database so that nothing works, including PRAGMAs.
erg102ceb412015-06-20 01:38:13678 ASSERT_TRUE(CorruptSizeInHeaderOfDB());
[email protected]7bae5742013-07-10 20:46:16679
[email protected]fed734a2013-07-17 04:45:13680 // Open() will succeed, even though the PRAGMA calls within will
681 // fail with SQLITE_CORRUPT, as will this PRAGMA.
682 {
683 sql::ScopedErrorIgnorer ignore_errors;
684 ignore_errors.IgnoreError(SQLITE_CORRUPT);
685 ASSERT_TRUE(db().Open(db_path()));
686 ASSERT_FALSE(db().Execute("PRAGMA auto_vacuum"));
687 db().Close();
688 ASSERT_TRUE(ignore_errors.CheckIgnoredErrors());
689 }
690
[email protected]7bae5742013-07-10 20:46:16691 db().set_error_callback(base::Bind(&SQLConnectionTest::RazeErrorCallback,
692 base::Unretained(this),
693 SQLITE_CORRUPT));
694
[email protected]fed734a2013-07-17 04:45:13695 // When the PRAGMA calls in Open() raise SQLITE_CORRUPT, the error
696 // callback will call RazeAndClose(). Open() will then fail and be
697 // retried. The second Open() on the empty database will succeed
698 // cleanly.
699 ASSERT_TRUE(db().Open(db_path()));
700 ASSERT_TRUE(db().Execute("PRAGMA auto_vacuum"));
[email protected]7bae5742013-07-10 20:46:16701 EXPECT_EQ(0, SqliteMasterCount(&db()));
702}
703
[email protected]41a97c812013-02-07 02:35:38704// Basic test of RazeAndClose() operation.
705TEST_F(SQLConnectionTest, RazeAndClose) {
706 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
707 const char* kPopulateSql = "INSERT INTO foo (value) VALUES (12)";
708
709 // Test that RazeAndClose() closes the database, and that the
710 // database is empty when re-opened.
711 ASSERT_TRUE(db().Execute(kCreateSql));
712 ASSERT_TRUE(db().Execute(kPopulateSql));
713 ASSERT_TRUE(db().RazeAndClose());
714 ASSERT_FALSE(db().is_open());
715 db().Close();
716 ASSERT_TRUE(db().Open(db_path()));
[email protected]7bae5742013-07-10 20:46:16717 ASSERT_EQ(0, SqliteMasterCount(&db()));
[email protected]41a97c812013-02-07 02:35:38718
719 // Test that RazeAndClose() can break transactions.
720 ASSERT_TRUE(db().Execute(kCreateSql));
721 ASSERT_TRUE(db().Execute(kPopulateSql));
722 ASSERT_TRUE(db().BeginTransaction());
723 ASSERT_TRUE(db().RazeAndClose());
724 ASSERT_FALSE(db().is_open());
725 ASSERT_FALSE(db().CommitTransaction());
726 db().Close();
727 ASSERT_TRUE(db().Open(db_path()));
[email protected]7bae5742013-07-10 20:46:16728 ASSERT_EQ(0, SqliteMasterCount(&db()));
[email protected]41a97c812013-02-07 02:35:38729}
730
731// Test that various operations fail without crashing after
732// RazeAndClose().
733TEST_F(SQLConnectionTest, RazeAndCloseDiagnostics) {
734 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
735 const char* kPopulateSql = "INSERT INTO foo (value) VALUES (12)";
736 const char* kSimpleSql = "SELECT 1";
737
738 ASSERT_TRUE(db().Execute(kCreateSql));
739 ASSERT_TRUE(db().Execute(kPopulateSql));
740
741 // Test baseline expectations.
742 db().Preload();
743 ASSERT_TRUE(db().DoesTableExist("foo"));
744 ASSERT_TRUE(db().IsSQLValid(kSimpleSql));
745 ASSERT_EQ(SQLITE_OK, db().ExecuteAndReturnErrorCode(kSimpleSql));
746 ASSERT_TRUE(db().Execute(kSimpleSql));
747 ASSERT_TRUE(db().is_open());
748 {
749 sql::Statement s(db().GetUniqueStatement(kSimpleSql));
750 ASSERT_TRUE(s.Step());
751 }
752 {
753 sql::Statement s(db().GetCachedStatement(SQL_FROM_HERE, kSimpleSql));
754 ASSERT_TRUE(s.Step());
755 }
756 ASSERT_TRUE(db().BeginTransaction());
757 ASSERT_TRUE(db().CommitTransaction());
758 ASSERT_TRUE(db().BeginTransaction());
759 db().RollbackTransaction();
760
761 ASSERT_TRUE(db().RazeAndClose());
762
763 // At this point, they should all fail, but not crash.
764 db().Preload();
765 ASSERT_FALSE(db().DoesTableExist("foo"));
766 ASSERT_FALSE(db().IsSQLValid(kSimpleSql));
767 ASSERT_EQ(SQLITE_ERROR, db().ExecuteAndReturnErrorCode(kSimpleSql));
768 ASSERT_FALSE(db().Execute(kSimpleSql));
769 ASSERT_FALSE(db().is_open());
770 {
771 sql::Statement s(db().GetUniqueStatement(kSimpleSql));
772 ASSERT_FALSE(s.Step());
773 }
774 {
775 sql::Statement s(db().GetCachedStatement(SQL_FROM_HERE, kSimpleSql));
776 ASSERT_FALSE(s.Step());
777 }
778 ASSERT_FALSE(db().BeginTransaction());
779 ASSERT_FALSE(db().CommitTransaction());
780 ASSERT_FALSE(db().BeginTransaction());
781 db().RollbackTransaction();
782
783 // Close normally to reset the poisoned flag.
784 db().Close();
785
786 // DEATH tests not supported on Android or iOS.
787#if !defined(OS_ANDROID) && !defined(OS_IOS)
788 // Once the real Close() has been called, various calls enforce API
789 // usage by becoming fatal in debug mode. Since DEATH tests are
790 // expensive, just test one of them.
791 if (DLOG_IS_ON(FATAL)) {
792 ASSERT_DEATH({
793 db().IsSQLValid(kSimpleSql);
794 }, "Illegal use of connection without a db");
795 }
796#endif
797}
798
799// TODO(shess): Spin up a background thread to hold other_db, to more
800// closely match real life. That would also allow testing
801// RazeWithTimeout().
802
[email protected]1348765a2012-07-24 08:25:53803#if defined(OS_ANDROID)
804TEST_F(SQLConnectionTest, SetTempDirForSQL) {
805
806 sql::MetaTable meta_table;
807 // Below call needs a temporary directory in sqlite3
808 // On Android, it can pass only when the temporary directory is set.
809 // Otherwise, sqlite3 doesn't find the correct directory to store
810 // temporary files and will report the error 'unable to open
811 // database file'.
812 ASSERT_TRUE(meta_table.Init(&db(), 4, 4));
813}
814#endif
[email protected]8d2e39e2013-06-24 05:55:08815
816TEST_F(SQLConnectionTest, Delete) {
817 EXPECT_TRUE(db().Execute("CREATE TABLE x (x)"));
818 db().Close();
819
820 // Should have both a main database file and a journal file because
shess2c21ecf2015-06-02 01:31:09821 // of journal_mode TRUNCATE.
[email protected]8d2e39e2013-06-24 05:55:08822 base::FilePath journal(db_path().value() + FILE_PATH_LITERAL("-journal"));
erg102ceb412015-06-20 01:38:13823 ASSERT_TRUE(GetPathExists(db_path()));
824 ASSERT_TRUE(GetPathExists(journal));
[email protected]8d2e39e2013-06-24 05:55:08825
826 sql::Connection::Delete(db_path());
erg102ceb412015-06-20 01:38:13827 EXPECT_FALSE(GetPathExists(db_path()));
828 EXPECT_FALSE(GetPathExists(journal));
[email protected]8d2e39e2013-06-24 05:55:08829}
[email protected]7bae5742013-07-10 20:46:16830
erg102ceb412015-06-20 01:38:13831// This test manually sets on disk permissions; this doesn't apply to the mojo
832// fork.
833#if defined(OS_POSIX) && !defined(MOJO_APPTEST_IMPL)
[email protected]81a2a602013-07-17 19:10:36834// Test that set_restrict_to_user() trims database permissions so that
835// only the owner (and root) can read.
836TEST_F(SQLConnectionTest, UserPermission) {
837 // If the bots all had a restrictive umask setting such that
838 // databases are always created with only the owner able to read
839 // them, then the code could break without breaking the tests.
840 // Temporarily provide a more permissive umask.
841 db().Close();
842 sql::Connection::Delete(db_path());
erg102ceb412015-06-20 01:38:13843 ASSERT_FALSE(GetPathExists(db_path()));
[email protected]81a2a602013-07-17 19:10:36844 ScopedUmaskSetter permissive_umask(S_IWGRP | S_IWOTH);
845 ASSERT_TRUE(db().Open(db_path()));
846
847 // Cause the journal file to be created. If the default
848 // journal_mode is changed back to DELETE, then parts of this test
849 // will need to be updated.
850 EXPECT_TRUE(db().Execute("CREATE TABLE x (x)"));
851
852 base::FilePath journal(db_path().value() + FILE_PATH_LITERAL("-journal"));
853 int mode;
854
855 // Given a permissive umask, the database is created with permissive
856 // read access for the database and journal.
erg102ceb412015-06-20 01:38:13857 ASSERT_TRUE(GetPathExists(db_path()));
858 ASSERT_TRUE(GetPathExists(journal));
[email protected]b264eab2013-11-27 23:22:08859 mode = base::FILE_PERMISSION_MASK;
860 EXPECT_TRUE(base::GetPosixFilePermissions(db_path(), &mode));
861 ASSERT_NE((mode & base::FILE_PERMISSION_USER_MASK), mode);
862 mode = base::FILE_PERMISSION_MASK;
863 EXPECT_TRUE(base::GetPosixFilePermissions(journal, &mode));
864 ASSERT_NE((mode & base::FILE_PERMISSION_USER_MASK), mode);
[email protected]81a2a602013-07-17 19:10:36865
866 // Re-open with restricted permissions and verify that the modes
867 // changed for both the main database and the journal.
868 db().Close();
869 db().set_restrict_to_user();
870 ASSERT_TRUE(db().Open(db_path()));
erg102ceb412015-06-20 01:38:13871 ASSERT_TRUE(GetPathExists(db_path()));
872 ASSERT_TRUE(GetPathExists(journal));
[email protected]b264eab2013-11-27 23:22:08873 mode = base::FILE_PERMISSION_MASK;
874 EXPECT_TRUE(base::GetPosixFilePermissions(db_path(), &mode));
875 ASSERT_EQ((mode & base::FILE_PERMISSION_USER_MASK), mode);
876 mode = base::FILE_PERMISSION_MASK;
877 EXPECT_TRUE(base::GetPosixFilePermissions(journal, &mode));
878 ASSERT_EQ((mode & base::FILE_PERMISSION_USER_MASK), mode);
[email protected]81a2a602013-07-17 19:10:36879
880 // Delete and re-create the database, the restriction should still apply.
881 db().Close();
882 sql::Connection::Delete(db_path());
883 ASSERT_TRUE(db().Open(db_path()));
erg102ceb412015-06-20 01:38:13884 ASSERT_TRUE(GetPathExists(db_path()));
885 ASSERT_FALSE(GetPathExists(journal));
[email protected]b264eab2013-11-27 23:22:08886 mode = base::FILE_PERMISSION_MASK;
887 EXPECT_TRUE(base::GetPosixFilePermissions(db_path(), &mode));
888 ASSERT_EQ((mode & base::FILE_PERMISSION_USER_MASK), mode);
[email protected]81a2a602013-07-17 19:10:36889
890 // Verify that journal creation inherits the restriction.
891 EXPECT_TRUE(db().Execute("CREATE TABLE x (x)"));
erg102ceb412015-06-20 01:38:13892 ASSERT_TRUE(GetPathExists(journal));
[email protected]b264eab2013-11-27 23:22:08893 mode = base::FILE_PERMISSION_MASK;
894 EXPECT_TRUE(base::GetPosixFilePermissions(journal, &mode));
895 ASSERT_EQ((mode & base::FILE_PERMISSION_USER_MASK), mode);
[email protected]81a2a602013-07-17 19:10:36896}
897#endif // defined(OS_POSIX)
898
[email protected]8d409412013-07-19 18:25:30899// Test that errors start happening once Poison() is called.
900TEST_F(SQLConnectionTest, Poison) {
901 EXPECT_TRUE(db().Execute("CREATE TABLE x (x)"));
902
903 // Before the Poison() call, things generally work.
904 EXPECT_TRUE(db().IsSQLValid("INSERT INTO x VALUES ('x')"));
905 EXPECT_TRUE(db().Execute("INSERT INTO x VALUES ('x')"));
906 {
907 sql::Statement s(db().GetUniqueStatement("SELECT COUNT(*) FROM x"));
908 ASSERT_TRUE(s.is_valid());
909 ASSERT_TRUE(s.Step());
910 }
911
912 // Get a statement which is valid before and will exist across Poison().
913 sql::Statement valid_statement(
914 db().GetUniqueStatement("SELECT COUNT(*) FROM sqlite_master"));
915 ASSERT_TRUE(valid_statement.is_valid());
916 ASSERT_TRUE(valid_statement.Step());
917 valid_statement.Reset(true);
918
919 db().Poison();
920
921 // After the Poison() call, things fail.
922 EXPECT_FALSE(db().IsSQLValid("INSERT INTO x VALUES ('x')"));
923 EXPECT_FALSE(db().Execute("INSERT INTO x VALUES ('x')"));
924 {
925 sql::Statement s(db().GetUniqueStatement("SELECT COUNT(*) FROM x"));
926 ASSERT_FALSE(s.is_valid());
927 ASSERT_FALSE(s.Step());
928 }
929
930 // The existing statement has become invalid.
931 ASSERT_FALSE(valid_statement.is_valid());
932 ASSERT_FALSE(valid_statement.Step());
shess644fc8a2016-02-26 18:15:58933
934 // Test that poisoning the database during a transaction works (with errors).
935 // RazeErrorCallback() poisons the database, the extra COMMIT causes
936 // CommitTransaction() to throw an error while commiting.
937 db().set_error_callback(base::Bind(&SQLConnectionTest::RazeErrorCallback,
938 base::Unretained(this),
939 SQLITE_ERROR));
940 db().Close();
941 ASSERT_TRUE(db().Open(db_path()));
942 EXPECT_TRUE(db().BeginTransaction());
943 EXPECT_TRUE(db().Execute("INSERT INTO x VALUES ('x')"));
944 EXPECT_TRUE(db().Execute("COMMIT"));
945 EXPECT_FALSE(db().CommitTransaction());
[email protected]8d409412013-07-19 18:25:30946}
947
948// Test attaching and detaching databases from the connection.
949TEST_F(SQLConnectionTest, Attach) {
950 EXPECT_TRUE(db().Execute("CREATE TABLE foo (a, b)"));
951
952 // Create a database to attach to.
953 base::FilePath attach_path =
954 db_path().DirName().AppendASCII("SQLConnectionAttach.db");
955 const char kAttachmentPoint[] = "other";
956 {
957 sql::Connection other_db;
958 ASSERT_TRUE(other_db.Open(attach_path));
959 EXPECT_TRUE(other_db.Execute("CREATE TABLE bar (a, b)"));
960 EXPECT_TRUE(other_db.Execute("INSERT INTO bar VALUES ('hello', 'world')"));
961 }
962
963 // Cannot see the attached database, yet.
964 EXPECT_FALSE(db().IsSQLValid("SELECT count(*) from other.bar"));
965
966 // Attach fails in a transaction.
967 EXPECT_TRUE(db().BeginTransaction());
968 {
969 sql::ScopedErrorIgnorer ignore_errors;
970 ignore_errors.IgnoreError(SQLITE_ERROR);
971 EXPECT_FALSE(db().AttachDatabase(attach_path, kAttachmentPoint));
972 ASSERT_TRUE(ignore_errors.CheckIgnoredErrors());
973 }
974
975 // Attach succeeds when the transaction is closed.
976 db().RollbackTransaction();
977 EXPECT_TRUE(db().AttachDatabase(attach_path, kAttachmentPoint));
978 EXPECT_TRUE(db().IsSQLValid("SELECT count(*) from other.bar"));
979
980 // Queries can touch both databases.
981 EXPECT_TRUE(db().Execute("INSERT INTO foo SELECT a, b FROM other.bar"));
982 {
983 sql::Statement s(db().GetUniqueStatement("SELECT COUNT(*) FROM foo"));
984 ASSERT_TRUE(s.Step());
985 EXPECT_EQ(1, s.ColumnInt(0));
986 }
987
988 // Detach also fails in a transaction.
989 EXPECT_TRUE(db().BeginTransaction());
990 {
991 sql::ScopedErrorIgnorer ignore_errors;
992 ignore_errors.IgnoreError(SQLITE_ERROR);
993 EXPECT_FALSE(db().DetachDatabase(kAttachmentPoint));
994 EXPECT_TRUE(db().IsSQLValid("SELECT count(*) from other.bar"));
995 ASSERT_TRUE(ignore_errors.CheckIgnoredErrors());
996 }
997
998 // Detach succeeds outside of a transaction.
999 db().RollbackTransaction();
1000 EXPECT_TRUE(db().DetachDatabase(kAttachmentPoint));
1001
1002 EXPECT_FALSE(db().IsSQLValid("SELECT count(*) from other.bar"));
1003}
1004
[email protected]579446c2013-12-16 18:36:521005TEST_F(SQLConnectionTest, Basic_QuickIntegrityCheck) {
1006 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
1007 ASSERT_TRUE(db().Execute(kCreateSql));
1008 EXPECT_TRUE(db().QuickIntegrityCheck());
1009 db().Close();
1010
erg102ceb412015-06-20 01:38:131011 ASSERT_TRUE(CorruptSizeInHeaderOfDB());
[email protected]579446c2013-12-16 18:36:521012
1013 {
1014 sql::ScopedErrorIgnorer ignore_errors;
1015 ignore_errors.IgnoreError(SQLITE_CORRUPT);
1016 ASSERT_TRUE(db().Open(db_path()));
1017 EXPECT_FALSE(db().QuickIntegrityCheck());
1018 ASSERT_TRUE(ignore_errors.CheckIgnoredErrors());
1019 }
1020}
1021
1022TEST_F(SQLConnectionTest, Basic_FullIntegrityCheck) {
1023 const std::string kOk("ok");
1024 std::vector<std::string> messages;
1025
1026 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
1027 ASSERT_TRUE(db().Execute(kCreateSql));
1028 EXPECT_TRUE(db().FullIntegrityCheck(&messages));
1029 EXPECT_EQ(1u, messages.size());
1030 EXPECT_EQ(kOk, messages[0]);
1031 db().Close();
1032
erg102ceb412015-06-20 01:38:131033 ASSERT_TRUE(CorruptSizeInHeaderOfDB());
[email protected]579446c2013-12-16 18:36:521034
1035 {
1036 sql::ScopedErrorIgnorer ignore_errors;
1037 ignore_errors.IgnoreError(SQLITE_CORRUPT);
1038 ASSERT_TRUE(db().Open(db_path()));
1039 EXPECT_TRUE(db().FullIntegrityCheck(&messages));
1040 EXPECT_LT(1u, messages.size());
1041 EXPECT_NE(kOk, messages[0]);
1042 ASSERT_TRUE(ignore_errors.CheckIgnoredErrors());
1043 }
1044
1045 // TODO(shess): CorruptTableOrIndex could be used to produce a
1046 // file that would pass the quick check and fail the full check.
1047}
1048
shess58b8df82015-06-03 00:19:321049// Test Sqlite.Stats histogram for execute-oriented calls.
1050TEST_F(SQLConnectionTest, EventsExecute) {
1051 // Re-open with histogram tag.
1052 db().Close();
1053 db().set_histogram_tag("Test");
1054 ASSERT_TRUE(db().Open(db_path()));
1055
1056 // Open() uses Execute() extensively, don't track those calls.
1057 base::HistogramTester tester;
1058
1059 const char kHistogramName[] = "Sqlite.Stats.Test";
1060 const char kGlobalHistogramName[] = "Sqlite.Stats";
1061
1062 ASSERT_TRUE(db().BeginTransaction());
1063 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
1064 EXPECT_TRUE(db().Execute(kCreateSql));
1065 EXPECT_TRUE(db().Execute("INSERT INTO foo VALUES (10, 'text')"));
1066 EXPECT_TRUE(db().Execute("INSERT INTO foo VALUES (11, 'text')"));
1067 EXPECT_TRUE(db().Execute("INSERT INTO foo VALUES (12, 'text')"));
1068 EXPECT_TRUE(db().Execute("INSERT INTO foo VALUES (13, 'text')"));
1069 EXPECT_TRUE(db().Execute("INSERT INTO foo VALUES (14, 'text')"));
1070 EXPECT_TRUE(db().Execute("INSERT INTO foo VALUES (15, 'text');"
1071 "INSERT INTO foo VALUES (16, 'text');"
1072 "INSERT INTO foo VALUES (17, 'text');"
1073 "INSERT INTO foo VALUES (18, 'text');"
1074 "INSERT INTO foo VALUES (19, 'text')"));
1075 ASSERT_TRUE(db().CommitTransaction());
1076 ASSERT_TRUE(db().BeginTransaction());
1077 EXPECT_TRUE(db().Execute("INSERT INTO foo VALUES (20, 'text')"));
1078 db().RollbackTransaction();
1079 EXPECT_TRUE(db().Execute("INSERT INTO foo VALUES (20, 'text')"));
1080 EXPECT_TRUE(db().Execute("INSERT INTO foo VALUES (21, 'text')"));
1081
1082 // The create, 5 inserts, multi-statement insert, rolled-back insert, 2
1083 // inserts outside transaction.
1084 tester.ExpectBucketCount(kHistogramName, sql::Connection::EVENT_EXECUTE, 10);
1085 tester.ExpectBucketCount(kGlobalHistogramName,
1086 sql::Connection::EVENT_EXECUTE, 10);
1087
1088 // All of the executes, with the multi-statement inserts broken out, plus one
1089 // for each begin, commit, and rollback.
1090 tester.ExpectBucketCount(kHistogramName,
1091 sql::Connection::EVENT_STATEMENT_RUN, 18);
1092 tester.ExpectBucketCount(kGlobalHistogramName,
1093 sql::Connection::EVENT_STATEMENT_RUN, 18);
1094
1095 tester.ExpectBucketCount(kHistogramName,
1096 sql::Connection::EVENT_STATEMENT_ROWS, 0);
1097 tester.ExpectBucketCount(kGlobalHistogramName,
1098 sql::Connection::EVENT_STATEMENT_ROWS, 0);
1099 tester.ExpectBucketCount(kHistogramName,
1100 sql::Connection::EVENT_STATEMENT_SUCCESS, 18);
1101 tester.ExpectBucketCount(kGlobalHistogramName,
1102 sql::Connection::EVENT_STATEMENT_SUCCESS, 18);
1103
1104 // The 2 inserts outside the transaction.
1105 tester.ExpectBucketCount(kHistogramName,
1106 sql::Connection::EVENT_CHANGES_AUTOCOMMIT, 2);
1107 tester.ExpectBucketCount(kGlobalHistogramName,
1108 sql::Connection::EVENT_CHANGES_AUTOCOMMIT, 2);
1109
1110 // 11 inserts inside transactions.
1111 tester.ExpectBucketCount(kHistogramName, sql::Connection::EVENT_CHANGES, 11);
1112 tester.ExpectBucketCount(kGlobalHistogramName,
1113 sql::Connection::EVENT_CHANGES, 11);
1114
1115 tester.ExpectBucketCount(kHistogramName, sql::Connection::EVENT_BEGIN, 2);
1116 tester.ExpectBucketCount(kGlobalHistogramName,
1117 sql::Connection::EVENT_BEGIN, 2);
1118 tester.ExpectBucketCount(kHistogramName, sql::Connection::EVENT_COMMIT, 1);
1119 tester.ExpectBucketCount(kGlobalHistogramName,
1120 sql::Connection::EVENT_COMMIT, 1);
1121 tester.ExpectBucketCount(kHistogramName, sql::Connection::EVENT_ROLLBACK, 1);
1122 tester.ExpectBucketCount(kGlobalHistogramName,
1123 sql::Connection::EVENT_ROLLBACK, 1);
1124}
1125
1126// Test Sqlite.Stats histogram for prepared statements.
1127TEST_F(SQLConnectionTest, EventsStatement) {
1128 // Re-open with histogram tag.
1129 db().Close();
1130 db().set_histogram_tag("Test");
1131 ASSERT_TRUE(db().Open(db_path()));
1132
1133 const char kHistogramName[] = "Sqlite.Stats.Test";
1134 const char kGlobalHistogramName[] = "Sqlite.Stats";
1135
1136 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
1137 EXPECT_TRUE(db().Execute(kCreateSql));
1138 EXPECT_TRUE(db().Execute("INSERT INTO foo VALUES (10, 'text')"));
1139 EXPECT_TRUE(db().Execute("INSERT INTO foo VALUES (11, 'text')"));
1140 EXPECT_TRUE(db().Execute("INSERT INTO foo VALUES (12, 'text')"));
1141
1142 {
1143 base::HistogramTester tester;
1144
1145 {
1146 sql::Statement s(db().GetUniqueStatement("SELECT value FROM foo"));
1147 while (s.Step()) {
1148 }
1149 }
1150
1151 tester.ExpectBucketCount(kHistogramName,
1152 sql::Connection::EVENT_STATEMENT_RUN, 1);
1153 tester.ExpectBucketCount(kGlobalHistogramName,
1154 sql::Connection::EVENT_STATEMENT_RUN, 1);
1155 tester.ExpectBucketCount(kHistogramName,
1156 sql::Connection::EVENT_STATEMENT_ROWS, 3);
1157 tester.ExpectBucketCount(kGlobalHistogramName,
1158 sql::Connection::EVENT_STATEMENT_ROWS, 3);
1159 tester.ExpectBucketCount(kHistogramName,
1160 sql::Connection::EVENT_STATEMENT_SUCCESS, 1);
1161 tester.ExpectBucketCount(kGlobalHistogramName,
1162 sql::Connection::EVENT_STATEMENT_SUCCESS, 1);
1163 }
1164
1165 {
1166 base::HistogramTester tester;
1167
1168 {
1169 sql::Statement s(db().GetUniqueStatement(
1170 "SELECT value FROM foo WHERE id > 10"));
1171 while (s.Step()) {
1172 }
1173 }
1174
1175 tester.ExpectBucketCount(kHistogramName,
1176 sql::Connection::EVENT_STATEMENT_RUN, 1);
1177 tester.ExpectBucketCount(kGlobalHistogramName,
1178 sql::Connection::EVENT_STATEMENT_RUN, 1);
1179 tester.ExpectBucketCount(kHistogramName,
1180 sql::Connection::EVENT_STATEMENT_ROWS, 2);
1181 tester.ExpectBucketCount(kGlobalHistogramName,
1182 sql::Connection::EVENT_STATEMENT_ROWS, 2);
1183 tester.ExpectBucketCount(kHistogramName,
1184 sql::Connection::EVENT_STATEMENT_SUCCESS, 1);
1185 tester.ExpectBucketCount(kGlobalHistogramName,
1186 sql::Connection::EVENT_STATEMENT_SUCCESS, 1);
1187 }
1188}
1189
shess58b8df82015-06-03 00:19:321190// Read-only query allocates time to QueryTime, but not others.
1191TEST_F(SQLConnectionTest, TimeQuery) {
1192 // Re-open with histogram tag. Use an in-memory database to minimize variance
1193 // due to filesystem.
1194 db().Close();
1195 db().set_histogram_tag("Test");
1196 ASSERT_TRUE(db().OpenInMemory());
1197
1198 sql::test::ScopedMockTimeSource time_mock(db());
1199
1200 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
1201 EXPECT_TRUE(db().Execute(kCreateSql));
1202
1203 // Function to inject pauses into statements.
1204 sql::test::ScopedScalarFunction scoper(
1205 db(), "milliadjust", 1, base::Bind(&sqlite_adjust_millis, &time_mock));
1206
1207 base::HistogramTester tester;
1208
1209 EXPECT_TRUE(db().Execute("SELECT milliadjust(10)"));
1210
1211 scoped_ptr<base::HistogramSamples> samples(
1212 tester.GetHistogramSamplesSinceCreation(kQueryTime));
1213 ASSERT_TRUE(samples);
1214 // 10 for the adjust, 1 for the measurement.
1215 EXPECT_EQ(11, samples->sum());
1216
1217 samples = tester.GetHistogramSamplesSinceCreation(kUpdateTime);
vabrae960432015-08-03 08:12:541218 EXPECT_EQ(0, samples->sum());
shess58b8df82015-06-03 00:19:321219
1220 samples = tester.GetHistogramSamplesSinceCreation(kCommitTime);
vabrae960432015-08-03 08:12:541221 EXPECT_EQ(0, samples->sum());
shess58b8df82015-06-03 00:19:321222
1223 samples = tester.GetHistogramSamplesSinceCreation(kAutoCommitTime);
vabrae960432015-08-03 08:12:541224 EXPECT_EQ(0, samples->sum());
shess58b8df82015-06-03 00:19:321225}
1226
1227// Autocommit update allocates time to QueryTime, UpdateTime, and
1228// AutoCommitTime.
1229TEST_F(SQLConnectionTest, TimeUpdateAutocommit) {
1230 // Re-open with histogram tag. Use an in-memory database to minimize variance
1231 // due to filesystem.
1232 db().Close();
1233 db().set_histogram_tag("Test");
1234 ASSERT_TRUE(db().OpenInMemory());
1235
1236 sql::test::ScopedMockTimeSource time_mock(db());
1237
1238 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
1239 EXPECT_TRUE(db().Execute(kCreateSql));
1240
1241 // Function to inject pauses into statements.
1242 sql::test::ScopedScalarFunction scoper(
1243 db(), "milliadjust", 1, base::Bind(&sqlite_adjust_millis, &time_mock));
1244
1245 base::HistogramTester tester;
1246
1247 EXPECT_TRUE(db().Execute("INSERT INTO foo VALUES (10, milliadjust(10))"));
1248
1249 scoped_ptr<base::HistogramSamples> samples(
1250 tester.GetHistogramSamplesSinceCreation(kQueryTime));
1251 ASSERT_TRUE(samples);
1252 // 10 for the adjust, 1 for the measurement.
1253 EXPECT_EQ(11, samples->sum());
1254
1255 samples = tester.GetHistogramSamplesSinceCreation(kUpdateTime);
1256 ASSERT_TRUE(samples);
1257 // 10 for the adjust, 1 for the measurement.
1258 EXPECT_EQ(11, samples->sum());
1259
1260 samples = tester.GetHistogramSamplesSinceCreation(kCommitTime);
vabrae960432015-08-03 08:12:541261 EXPECT_EQ(0, samples->sum());
shess58b8df82015-06-03 00:19:321262
1263 samples = tester.GetHistogramSamplesSinceCreation(kAutoCommitTime);
1264 ASSERT_TRUE(samples);
1265 // 10 for the adjust, 1 for the measurement.
1266 EXPECT_EQ(11, samples->sum());
1267}
1268
1269// Update with explicit transaction allocates time to QueryTime, UpdateTime, and
1270// CommitTime.
1271TEST_F(SQLConnectionTest, TimeUpdateTransaction) {
1272 // Re-open with histogram tag. Use an in-memory database to minimize variance
1273 // due to filesystem.
1274 db().Close();
1275 db().set_histogram_tag("Test");
1276 ASSERT_TRUE(db().OpenInMemory());
1277
1278 sql::test::ScopedMockTimeSource time_mock(db());
1279
1280 const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
1281 EXPECT_TRUE(db().Execute(kCreateSql));
1282
1283 // Function to inject pauses into statements.
1284 sql::test::ScopedScalarFunction scoper(
1285 db(), "milliadjust", 1, base::Bind(&sqlite_adjust_millis, &time_mock));
1286
1287 base::HistogramTester tester;
1288
1289 {
1290 // Make the commit slow.
1291 sql::test::ScopedCommitHook scoped_hook(
1292 db(), base::Bind(adjust_commit_hook, &time_mock, 100));
1293 ASSERT_TRUE(db().BeginTransaction());
1294 EXPECT_TRUE(db().Execute(
1295 "INSERT INTO foo VALUES (11, milliadjust(10))"));
1296 EXPECT_TRUE(db().Execute(
1297 "UPDATE foo SET value = milliadjust(10) WHERE id = 11"));
1298 EXPECT_TRUE(db().CommitTransaction());
1299 }
1300
1301 scoped_ptr<base::HistogramSamples> samples(
1302 tester.GetHistogramSamplesSinceCreation(kQueryTime));
1303 ASSERT_TRUE(samples);
1304 // 10 for insert adjust, 10 for update adjust, 100 for commit adjust, 1 for
1305 // measuring each of BEGIN, INSERT, UPDATE, and COMMIT.
1306 EXPECT_EQ(124, samples->sum());
1307
1308 samples = tester.GetHistogramSamplesSinceCreation(kUpdateTime);
1309 ASSERT_TRUE(samples);
1310 // 10 for insert adjust, 10 for update adjust, 100 for commit adjust, 1 for
1311 // measuring each of INSERT, UPDATE, and COMMIT.
1312 EXPECT_EQ(123, samples->sum());
1313
1314 samples = tester.GetHistogramSamplesSinceCreation(kCommitTime);
1315 ASSERT_TRUE(samples);
1316 // 100 for commit adjust, 1 for measuring COMMIT.
1317 EXPECT_EQ(101, samples->sum());
1318
1319 samples = tester.GetHistogramSamplesSinceCreation(kAutoCommitTime);
vabrae960432015-08-03 08:12:541320 EXPECT_EQ(0, samples->sum());
shess58b8df82015-06-03 00:19:321321}
1322
ssid9f8022f2015-10-12 17:49:031323TEST_F(SQLConnectionTest, OnMemoryDump) {
1324 base::trace_event::ProcessMemoryDump pmd(nullptr);
1325 base::trace_event::MemoryDumpArgs args = {
1326 base::trace_event::MemoryDumpLevelOfDetail::DETAILED};
ssid3be5b1ec2016-01-13 14:21:571327 ASSERT_TRUE(db().memory_dump_provider_->OnMemoryDump(args, &pmd));
ssid9f8022f2015-10-12 17:49:031328 EXPECT_GE(pmd.allocator_dumps().size(), 1u);
1329}
1330
shessc8cd2a162015-10-22 20:30:461331// Test that the functions to collect diagnostic data run to completion, without
1332// worrying too much about what they generate (since that will change).
1333TEST_F(SQLConnectionTest, CollectDiagnosticInfo) {
1334 // NOTE(shess): Mojo doesn't support everything CollectCorruptionInfo() uses,
1335 // but it's not really clear if adding support would be useful.
1336#if !defined(MOJO_APPTEST_IMPL)
1337 const std::string corruption_info = db().CollectCorruptionInfo();
1338 EXPECT_NE(std::string::npos, corruption_info.find("SQLITE_CORRUPT"));
1339 EXPECT_NE(std::string::npos, corruption_info.find("integrity_check"));
1340#endif
1341
1342 // A statement to see in the results.
1343 const char* kSimpleSql = "SELECT 'mountain'";
1344 Statement s(db().GetCachedStatement(SQL_FROM_HERE, kSimpleSql));
1345
1346 // Error includes the statement.
1347 const std::string readonly_info = db().CollectErrorInfo(SQLITE_READONLY, &s);
1348 EXPECT_NE(std::string::npos, readonly_info.find(kSimpleSql));
1349
1350 // Some other error doesn't include the statment.
1351 // TODO(shess): This is weak.
1352 const std::string full_info = db().CollectErrorInfo(SQLITE_FULL, NULL);
1353 EXPECT_EQ(std::string::npos, full_info.find(kSimpleSql));
1354
1355 // A table to see in the SQLITE_ERROR results.
1356 EXPECT_TRUE(db().Execute("CREATE TABLE volcano (x)"));
1357
1358 // Version info to see in the SQLITE_ERROR results.
1359 sql::MetaTable meta_table;
1360 ASSERT_TRUE(meta_table.Init(&db(), 4, 4));
1361
1362 const std::string error_info = db().CollectErrorInfo(SQLITE_ERROR, &s);
1363 EXPECT_NE(std::string::npos, error_info.find(kSimpleSql));
1364 EXPECT_NE(std::string::npos, error_info.find("volcano"));
1365 EXPECT_NE(std::string::npos, error_info.find("version: 4"));
1366}
1367
1368#if !defined(MOJO_APPTEST_IMPL)
1369TEST_F(SQLConnectionTest, RegisterIntentToUpload) {
1370 base::FilePath breadcrumb_path(
1371 db_path().DirName().Append(FILE_PATH_LITERAL("sqlite-diag")));
1372
1373 // No stale diagnostic store.
1374 ASSERT_TRUE(!base::PathExists(breadcrumb_path));
1375
1376 // The histogram tag is required to enable diagnostic features.
1377 EXPECT_FALSE(db().RegisterIntentToUpload());
1378 EXPECT_TRUE(!base::PathExists(breadcrumb_path));
1379
1380 db().Close();
1381 db().set_histogram_tag("Test");
1382 ASSERT_TRUE(db().Open(db_path()));
1383
1384 // Should signal upload only once.
1385 EXPECT_TRUE(db().RegisterIntentToUpload());
1386 EXPECT_TRUE(base::PathExists(breadcrumb_path));
1387 EXPECT_FALSE(db().RegisterIntentToUpload());
1388
1389 // Changing the histogram tag should allow new upload to succeed.
1390 db().Close();
1391 db().set_histogram_tag("NewTest");
1392 ASSERT_TRUE(db().Open(db_path()));
1393 EXPECT_TRUE(db().RegisterIntentToUpload());
1394 EXPECT_FALSE(db().RegisterIntentToUpload());
1395
1396 // Old tag is still prevented.
1397 db().Close();
1398 db().set_histogram_tag("Test");
1399 ASSERT_TRUE(db().Open(db_path()));
1400 EXPECT_FALSE(db().RegisterIntentToUpload());
1401}
1402#endif // !defined(MOJO_APPTEST_IMPL)
1403
shess9bf2c672015-12-18 01:18:081404// Test that a fresh database has mmap enabled by default, if mmap'ed I/O is
1405// enabled by SQLite.
1406TEST_F(SQLConnectionTest, MmapInitiallyEnabled) {
1407 {
1408 sql::Statement s(db().GetUniqueStatement("PRAGMA mmap_size"));
1409
1410 // SQLite doesn't have mmap support (perhaps an early iOS release).
1411 if (!s.Step())
1412 return;
1413
1414 // If mmap I/O is not on, attempt to turn it on. If that succeeds, then
1415 // Open() should have turned it on. If mmap support is disabled, 0 is
1416 // returned. If the VFS does not understand SQLITE_FCNTL_MMAP_SIZE (for
1417 // instance MojoVFS), -1 is returned.
1418 if (s.ColumnInt(0) <= 0) {
1419 ASSERT_TRUE(db().Execute("PRAGMA mmap_size = 1048576"));
1420 s.Reset(true);
1421 ASSERT_TRUE(s.Step());
1422 EXPECT_LE(s.ColumnInt(0), 0);
1423 }
1424 }
1425
1426 // Test that explicit disable prevents mmap'ed I/O.
1427 db().Close();
1428 sql::Connection::Delete(db_path());
1429 db().set_mmap_disabled();
1430 ASSERT_TRUE(db().Open(db_path()));
1431 {
1432 sql::Statement s(db().GetUniqueStatement("PRAGMA mmap_size"));
1433 ASSERT_TRUE(s.Step());
1434 EXPECT_LE(s.ColumnInt(0), 0);
1435 }
1436}
1437
1438// Test specific operation of the GetAppropriateMmapSize() helper.
1439#if defined(OS_IOS)
1440TEST_F(SQLConnectionTest, GetAppropriateMmapSize) {
1441 ASSERT_EQ(0UL, db().GetAppropriateMmapSize());
1442}
1443#else
1444TEST_F(SQLConnectionTest, GetAppropriateMmapSize) {
1445 const size_t kMmapAlot = 25 * 1024 * 1024;
1446
1447 // If there is no meta table (as for a fresh database), assume that everything
1448 // should be mapped.
1449 ASSERT_TRUE(!db().DoesTableExist("meta"));
1450 ASSERT_GT(db().GetAppropriateMmapSize(), kMmapAlot);
1451
1452 // Getting the status fails if there is an error. GetAppropriateMmapSize()
1453 // should not call GetMmapStatus() if the table does not exist, but this is an
1454 // easy error to setup for testing.
1455 int64_t mmap_status;
1456 {
1457 sql::ScopedErrorIgnorer ignore_errors;
1458 ignore_errors.IgnoreError(SQLITE_ERROR);
1459 ASSERT_FALSE(MetaTable::GetMmapStatus(&db(), &mmap_status));
1460 ASSERT_TRUE(ignore_errors.CheckIgnoredErrors());
1461 }
1462
1463 // When the meta table is first created, it sets up to map everything.
1464 MetaTable().Init(&db(), 1, 1);
1465 ASSERT_TRUE(db().DoesTableExist("meta"));
1466 ASSERT_GT(db().GetAppropriateMmapSize(), kMmapAlot);
1467 ASSERT_TRUE(MetaTable::GetMmapStatus(&db(), &mmap_status));
1468 ASSERT_EQ(MetaTable::kMmapSuccess, mmap_status);
1469
1470 // Failure status maps nothing.
1471 ASSERT_TRUE(db().Execute("REPLACE INTO meta VALUES ('mmap_status', -2)"));
1472 ASSERT_EQ(0UL, db().GetAppropriateMmapSize());
1473
1474 // Re-initializing the meta table does not re-create the key if the table
1475 // already exists.
1476 ASSERT_TRUE(db().Execute("DELETE FROM meta WHERE key = 'mmap_status'"));
1477 MetaTable().Init(&db(), 1, 1);
1478 ASSERT_EQ(MetaTable::kMmapSuccess, mmap_status);
1479 ASSERT_TRUE(MetaTable::GetMmapStatus(&db(), &mmap_status));
1480 ASSERT_EQ(0, mmap_status);
1481
1482 // With no key, map everything and create the key.
1483 // TODO(shess): This really should be "maps everything after validating it",
1484 // but that is more complicated to structure.
1485 ASSERT_GT(db().GetAppropriateMmapSize(), kMmapAlot);
1486 ASSERT_TRUE(MetaTable::GetMmapStatus(&db(), &mmap_status));
1487 ASSERT_EQ(MetaTable::kMmapSuccess, mmap_status);
1488}
1489#endif
1490
shessc8cd2a162015-10-22 20:30:461491} // namespace sql