blob: 05d357ad6f2a26c2a5b3a4f52ccc3c9d9220bdb1 [file] [log] [blame]
[email protected]60e60dd2012-04-28 08:16:041// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]67361b32011-04-12 20:13:062// 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]67361b32011-04-12 20:13:068#include <string>
9
[email protected]526b4662013-06-14 04:09:1210#include "base/bind.h"
thestig22dfc4012014-09-05 08:29:4411#include "base/files/file_util.h"
shess53adf162015-12-17 22:07:2612#include "base/files/memory_mapped_file.h"
[email protected]ea1a3f62012-11-16 20:34:2313#include "base/files/scoped_temp_dir.h"
Scott Graham502836c2017-09-14 23:26:2314#include "build/build_config.h"
[email protected]f0a54b22011-07-19 18:40:2115#include "sql/connection.h"
16#include "sql/statement.h"
erg102ceb412015-06-20 01:38:1317#include "sql/test/sql_test_base.h"
engedybe80d53e2015-01-22 09:54:5018#include "sql/test/test_helpers.h"
[email protected]67361b32011-04-12 20:13:0619#include "testing/gtest/include/gtest/gtest.h"
20#include "third_party/sqlite/sqlite3.h"
21
shess5f2c3442017-01-24 02:15:1022#if defined(OS_MACOSX) && !defined(OS_IOS)
23#include <CoreFoundation/CoreFoundation.h>
24#include <CoreServices/CoreServices.h>
25
26#include "base/mac/mac_util.h"
27#include "base/mac/scoped_cftyperef.h"
28#endif
29
[email protected]67361b32011-04-12 20:13:0630// Test that certain features are/are-not enabled in our SQLite.
31
shessf7fcc452017-04-19 22:10:4132namespace sql {
[email protected]67361b32011-04-12 20:13:0633namespace {
34
shessf7fcc452017-04-19 22:10:4135using sql::test::ExecuteWithResult;
36using sql::test::ExecuteWithResults;
37
[email protected]526b4662013-06-14 04:09:1238void CaptureErrorCallback(int* error_pointer, std::string* sql_text,
39 int error, sql::Statement* stmt) {
40 *error_pointer = error;
Victor Costanbd623112018-07-18 04:17:2741 const char* text = stmt ? stmt->GetSQLStatement() : nullptr;
[email protected]526b4662013-06-14 04:09:1242 *sql_text = text ? text : "no statement available";
43}
[email protected]67361b32011-04-12 20:13:0644
shessf7fcc452017-04-19 22:10:4145} // namespace
46
erg102ceb412015-06-20 01:38:1347class SQLiteFeaturesTest : public sql::SQLTestBase {
[email protected]67361b32011-04-12 20:13:0648 public:
[email protected]49dc4f22012-10-17 17:41:1649 SQLiteFeaturesTest() : error_(SQLITE_OK) {}
[email protected]67361b32011-04-12 20:13:0650
dcheng1b3b125e2014-12-22 23:00:2451 void SetUp() override {
erg102ceb412015-06-20 01:38:1352 SQLTestBase::SetUp();
[email protected]99034682012-06-13 03:31:1653
[email protected]49dc4f22012-10-17 17:41:1654 // The error delegate will set |error_| and |sql_text_| when any sqlite
55 // statement operation returns an error code.
erg102ceb412015-06-20 01:38:1356 db().set_error_callback(
tzikd16d2192018-03-07 08:58:3657 base::BindRepeating(&CaptureErrorCallback, &error_, &sql_text_));
[email protected]67361b32011-04-12 20:13:0658 }
59
dcheng1b3b125e2014-12-22 23:00:2460 void TearDown() override {
[email protected]67361b32011-04-12 20:13:0661 // If any error happened the original sql statement can be found in
[email protected]49dc4f22012-10-17 17:41:1662 // |sql_text_|.
engedybe80d53e2015-01-22 09:54:5063 EXPECT_EQ(SQLITE_OK, error_) << sql_text_;
erg102ceb412015-06-20 01:38:1364
65 SQLTestBase::TearDown();
[email protected]67361b32011-04-12 20:13:0666 }
67
Scott Hessdcf120482015-02-10 21:33:2968 int error() { return error_; }
[email protected]67361b32011-04-12 20:13:0669
[email protected]67361b32011-04-12 20:13:0670 private:
[email protected]49dc4f22012-10-17 17:41:1671 // The error code of the most recent error.
72 int error_;
73 // Original statement which has caused the error.
74 std::string sql_text_;
[email protected]67361b32011-04-12 20:13:0675};
76
77// Do not include fts1 support, it is not useful, and nobody is
78// looking at it.
79TEST_F(SQLiteFeaturesTest, NoFTS1) {
[email protected]eff1fa522011-12-12 23:50:5980 ASSERT_EQ(SQLITE_ERROR, db().ExecuteAndReturnErrorCode(
81 "CREATE VIRTUAL TABLE foo USING fts1(x)"));
[email protected]67361b32011-04-12 20:13:0682}
83
shess37437cb2015-03-11 20:24:4684// Do not include fts2 support, it is not useful, and nobody is
85// looking at it.
86TEST_F(SQLiteFeaturesTest, NoFTS2) {
87 ASSERT_EQ(SQLITE_ERROR, db().ExecuteAndReturnErrorCode(
88 "CREATE VIRTUAL TABLE foo USING fts2(x)"));
[email protected]67361b32011-04-12 20:13:0689}
shess355d9a1e2015-01-10 00:42:2990
shess37437cb2015-03-11 20:24:4691// fts3 used to be used for history files, and may also be used by WebDatabase
92// clients.
[email protected]67361b32011-04-12 20:13:0693TEST_F(SQLiteFeaturesTest, FTS3) {
94 ASSERT_TRUE(db().Execute("CREATE VIRTUAL TABLE foo USING fts3(x)"));
95}
96
shess37437cb2015-03-11 20:24:4697// Originally history used fts2, which Chromium patched to treat "foo*" as a
98// prefix search, though the icu tokenizer would return it as two tokens {"foo",
99// "*"}. Test that fts3 works correctly.
shess355d9a1e2015-01-10 00:42:29100TEST_F(SQLiteFeaturesTest, FTS3_Prefix) {
Victor Costan1d868352018-06-26 19:06:48101 static const char kCreateSql[] =
shess355d9a1e2015-01-10 00:42:29102 "CREATE VIRTUAL TABLE foo USING fts3(x, tokenize icu)";
103 ASSERT_TRUE(db().Execute(kCreateSql));
104
105 ASSERT_TRUE(db().Execute("INSERT INTO foo (x) VALUES ('test')"));
106
shessf7fcc452017-04-19 22:10:41107 EXPECT_EQ("test",
108 ExecuteWithResult(&db(), "SELECT x FROM foo WHERE x MATCH 'te*'"));
shess355d9a1e2015-01-10 00:42:29109}
shess355d9a1e2015-01-10 00:42:29110
shess156733db2015-01-21 21:52:24111// Verify that Chromium's SQLite is compiled with HAVE_USLEEP defined. With
112// HAVE_USLEEP, SQLite uses usleep() with millisecond granularity. Otherwise it
113// uses sleep() with second granularity.
114TEST_F(SQLiteFeaturesTest, UsesUsleep) {
115 base::TimeTicks before = base::TimeTicks::Now();
116 sqlite3_sleep(1);
117 base::TimeDelta delta = base::TimeTicks::Now() - before;
118
shessf7fcc452017-04-19 22:10:41119 // It is not impossible for this to be over 1000 if things are compiled
120 // correctly, but that is very unlikely. Most platforms seem to be exactly
121 // 1ms, with the rest at 2ms, and the worst observed cases was ASAN at 7ms.
shess156733db2015-01-21 21:52:24122 EXPECT_LT(delta.InMilliseconds(), 1000);
123}
shess156733db2015-01-21 21:52:24124
engedybe80d53e2015-01-22 09:54:50125// Ensure that our SQLite version has working foreign key support with cascade
126// delete support.
127TEST_F(SQLiteFeaturesTest, ForeignKeySupport) {
128 ASSERT_TRUE(db().Execute("PRAGMA foreign_keys=1"));
129 ASSERT_TRUE(db().Execute("CREATE TABLE parents (id INTEGER PRIMARY KEY)"));
130 ASSERT_TRUE(db().Execute(
131 "CREATE TABLE children ("
132 " id INTEGER PRIMARY KEY,"
133 " pid INTEGER NOT NULL REFERENCES parents(id) ON DELETE CASCADE)"));
Victor Costan1d868352018-06-26 19:06:48134 static const char kSelectParentsSql[] = "SELECT * FROM parents ORDER BY id";
135 static const char kSelectChildrenSql[] = "SELECT * FROM children ORDER BY id";
engedybe80d53e2015-01-22 09:54:50136
137 // Inserting without a matching parent should fail with constraint violation.
Victor Costan1d868352018-06-26 19:06:48138 EXPECT_EQ("", ExecuteWithResult(&db(), kSelectParentsSql));
shessf7fcc452017-04-19 22:10:41139 const int insert_error =
140 db().ExecuteAndReturnErrorCode("INSERT INTO children VALUES (10, 1)");
Victor Costan86ca4312018-02-07 21:34:10141 EXPECT_EQ(SQLITE_CONSTRAINT | SQLITE_CONSTRAINT_FOREIGNKEY, insert_error);
Victor Costan1d868352018-06-26 19:06:48142 EXPECT_EQ("", ExecuteWithResult(&db(), kSelectChildrenSql));
engedybe80d53e2015-01-22 09:54:50143
144 // Inserting with a matching parent should work.
145 ASSERT_TRUE(db().Execute("INSERT INTO parents VALUES (1)"));
Victor Costan1d868352018-06-26 19:06:48146 EXPECT_EQ("1", ExecuteWithResults(&db(), kSelectParentsSql, "|", "\n"));
engedybe80d53e2015-01-22 09:54:50147 EXPECT_TRUE(db().Execute("INSERT INTO children VALUES (11, 1)"));
148 EXPECT_TRUE(db().Execute("INSERT INTO children VALUES (12, 1)"));
shessf7fcc452017-04-19 22:10:41149 EXPECT_EQ("11|1\n12|1",
Victor Costan1d868352018-06-26 19:06:48150 ExecuteWithResults(&db(), kSelectChildrenSql, "|", "\n"));
engedybe80d53e2015-01-22 09:54:50151
shessf7fcc452017-04-19 22:10:41152 // Deleting the parent should cascade, deleting the children as well.
engedybe80d53e2015-01-22 09:54:50153 ASSERT_TRUE(db().Execute("DELETE FROM parents"));
Victor Costan1d868352018-06-26 19:06:48154 EXPECT_EQ("", ExecuteWithResult(&db(), kSelectParentsSql));
155 EXPECT_EQ("", ExecuteWithResult(&db(), kSelectChildrenSql));
engedybe80d53e2015-01-22 09:54:50156}
157
Victor Costanbc7ab062018-04-20 19:03:56158// Ensure that our SQLite version supports booleans.
159TEST_F(SQLiteFeaturesTest, BooleanSupport) {
160 ASSERT_TRUE(
161 db().Execute("CREATE TABLE flags ("
162 " id INTEGER PRIMARY KEY,"
163 " true_flag BOOL NOT NULL DEFAULT TRUE,"
164 " false_flag BOOL NOT NULL DEFAULT FALSE)"));
165 ASSERT_TRUE(db().Execute(
166 "ALTER TABLE flags ADD COLUMN true_flag2 BOOL NOT NULL DEFAULT TRUE"));
167 ASSERT_TRUE(db().Execute(
168 "ALTER TABLE flags ADD COLUMN false_flag2 BOOL NOT NULL DEFAULT FALSE"));
169 ASSERT_TRUE(db().Execute("INSERT INTO flags (id) VALUES (1)"));
170
171 sql::Statement s(db().GetUniqueStatement(
172 "SELECT true_flag, false_flag, true_flag2, false_flag2"
173 " FROM flags WHERE id=1;"));
174 ASSERT_TRUE(s.Step());
175
Victor Costanf087c842018-04-27 00:47:50176 EXPECT_TRUE(s.ColumnBool(0)) << " default TRUE at table creation time";
Victor Costanbc7ab062018-04-20 19:03:56177 EXPECT_TRUE(!s.ColumnBool(1)) << " default FALSE at table creation time";
178
Victor Costanf087c842018-04-27 00:47:50179 EXPECT_TRUE(s.ColumnBool(2)) << " default TRUE added by altering the table";
Victor Costanbc7ab062018-04-20 19:03:56180 EXPECT_TRUE(!s.ColumnBool(3)) << " default FALSE added by altering the table";
181}
182
Victor Costan42988a92018-02-06 02:22:14183#if defined(OS_FUCHSIA)
shess53adf162015-12-17 22:07:26184// If the platform cannot support SQLite mmap'ed I/O, make sure SQLite isn't
185// offering to support it.
186TEST_F(SQLiteFeaturesTest, NoMmap) {
187 // For recent versions of SQLite, SQLITE_MAX_MMAP_SIZE=0 can be used to
188 // disable mmap support. Alternately, sqlite3_config() could be used. In
189 // that case, the pragma will run successfully, but the size will always be 0.
190 //
Victor Costan42988a92018-02-06 02:22:14191 // Historical note: The SQLite version bundled with iOS 9 and below does not
192 // have mmap support. Chrome now requires iOS 10 and above. This is only
193 // relevant when USE_SYSTEM_SQLITE is defined.
shess53adf162015-12-17 22:07:26194 //
195 // MojoVFS implements a no-op for xFileControl(). PRAGMA mmap_size is
196 // implemented in terms of SQLITE_FCNTL_MMAP_SIZE. In that case, the pragma
197 // will succeed but with no effect.
198 ignore_result(db().Execute("PRAGMA mmap_size = 1048576"));
199 sql::Statement s(db().GetUniqueStatement("PRAGMA mmap_size"));
200 ASSERT_TRUE(!s.Step() || !s.ColumnInt64(0));
201}
Victor Costan42988a92018-02-06 02:22:14202#endif // defined(OS_FUCHSIA)
rohitrao83d6b83a2016-06-21 07:25:57203
Scott Graham47ed2c32017-09-15 02:17:07204#if !defined(OS_FUCHSIA)
shess53adf162015-12-17 22:07:26205// Verify that OS file writes are reflected in the memory mapping of a
206// memory-mapped file. Normally SQLite writes to memory-mapped files using
207// memcpy(), which should stay consistent. Our SQLite is slightly patched to
208// mmap read only, then write using OS file writes. If the memory-mapped
209// version doesn't reflect the OS file writes, SQLite's memory-mapped I/O should
210// be disabled on this platform using SQLITE_MAX_MMAP_SIZE=0.
211TEST_F(SQLiteFeaturesTest, Mmap) {
212 // Try to turn on mmap'ed I/O.
213 ignore_result(db().Execute("PRAGMA mmap_size = 1048576"));
214 {
215 sql::Statement s(db().GetUniqueStatement("PRAGMA mmap_size"));
216
Victor Costan42988a92018-02-06 02:22:14217 // Historical note: The SQLite version bundled with iOS 9 and below does
218 // not have mmap support. Chrome now requires iOS 10 and above. This is
219 // only relevant when USE_SYSTEM_SQLITE is defined.
220
shess53adf162015-12-17 22:07:26221 ASSERT_TRUE(s.Step());
222 ASSERT_GT(s.ColumnInt64(0), 0);
shess53adf162015-12-17 22:07:26223 }
224 db().Close();
225
avi0b519202015-12-21 07:25:19226 const uint32_t kFlags =
227 base::File::FLAG_OPEN | base::File::FLAG_READ | base::File::FLAG_WRITE;
shess53adf162015-12-17 22:07:26228 char buf[4096];
229
230 // Create a file with a block of '0', a block of '1', and a block of '2'.
231 {
232 base::File f(db_path(), kFlags);
233 ASSERT_TRUE(f.IsValid());
234 memset(buf, '0', sizeof(buf));
235 ASSERT_EQ(f.Write(0*sizeof(buf), buf, sizeof(buf)), (int)sizeof(buf));
236
237 memset(buf, '1', sizeof(buf));
238 ASSERT_EQ(f.Write(1*sizeof(buf), buf, sizeof(buf)), (int)sizeof(buf));
239
240 memset(buf, '2', sizeof(buf));
241 ASSERT_EQ(f.Write(2*sizeof(buf), buf, sizeof(buf)), (int)sizeof(buf));
242 }
243
244 // mmap the file and verify that everything looks right.
245 {
246 base::MemoryMappedFile m;
247 ASSERT_TRUE(m.Initialize(db_path()));
248
249 memset(buf, '0', sizeof(buf));
250 ASSERT_EQ(0, memcmp(buf, m.data() + 0*sizeof(buf), sizeof(buf)));
251
252 memset(buf, '1', sizeof(buf));
253 ASSERT_EQ(0, memcmp(buf, m.data() + 1*sizeof(buf), sizeof(buf)));
254
255 memset(buf, '2', sizeof(buf));
256 ASSERT_EQ(0, memcmp(buf, m.data() + 2*sizeof(buf), sizeof(buf)));
257
258 // Scribble some '3' into the first page of the file, and verify that it
259 // looks the same in the memory mapping.
260 {
261 base::File f(db_path(), kFlags);
262 ASSERT_TRUE(f.IsValid());
263 memset(buf, '3', sizeof(buf));
264 ASSERT_EQ(f.Write(0*sizeof(buf), buf, sizeof(buf)), (int)sizeof(buf));
265 }
266 ASSERT_EQ(0, memcmp(buf, m.data() + 0*sizeof(buf), sizeof(buf)));
267
268 // Repeat with a single '4' in case page-sized blocks are different.
269 const size_t kOffset = 1*sizeof(buf) + 123;
270 ASSERT_NE('4', m.data()[kOffset]);
271 {
272 base::File f(db_path(), kFlags);
273 ASSERT_TRUE(f.IsValid());
274 buf[0] = '4';
275 ASSERT_EQ(f.Write(kOffset, buf, 1), 1);
276 }
277 ASSERT_EQ('4', m.data()[kOffset]);
278 }
279}
Scott Graham47ed2c32017-09-15 02:17:07280#endif // !defined(OS_FUCHSIA)
shess53adf162015-12-17 22:07:26281
shess001ae162016-10-20 04:04:32282// Verify that http://crbug.com/248608 is fixed. In this bug, the
283// compiled regular expression is effectively cached with the prepared
284// statement, causing errors if the regular expression is rebound.
285TEST_F(SQLiteFeaturesTest, CachedRegexp) {
286 ASSERT_TRUE(db().Execute("CREATE TABLE r (id INTEGER UNIQUE, x TEXT)"));
287 ASSERT_TRUE(db().Execute("INSERT INTO r VALUES (1, 'this is a test')"));
288 ASSERT_TRUE(db().Execute("INSERT INTO r VALUES (2, 'that was a test')"));
289 ASSERT_TRUE(db().Execute("INSERT INTO r VALUES (3, 'this is a stickup')"));
290 ASSERT_TRUE(db().Execute("INSERT INTO r VALUES (4, 'that sucks')"));
291
Victor Costan1d868352018-06-26 19:06:48292 static const char kSimpleSql[] = "SELECT SUM(id) FROM r WHERE x REGEXP ?";
shess001ae162016-10-20 04:04:32293 sql::Statement s(db().GetCachedStatement(SQL_FROM_HERE, kSimpleSql));
294
295 s.BindString(0, "this.*");
296 ASSERT_TRUE(s.Step());
297 EXPECT_EQ(4, s.ColumnInt(0));
298
299 s.Reset(true);
300 s.BindString(0, "that.*");
301 ASSERT_TRUE(s.Step());
302 EXPECT_EQ(6, s.ColumnInt(0));
303
304 s.Reset(true);
305 s.BindString(0, ".*test");
306 ASSERT_TRUE(s.Step());
307 EXPECT_EQ(3, s.ColumnInt(0));
308
309 s.Reset(true);
310 s.BindString(0, ".* s[a-z]+");
311 ASSERT_TRUE(s.Step());
312 EXPECT_EQ(7, s.ColumnInt(0));
313}
314
shess5f2c3442017-01-24 02:15:10315#if defined(OS_MACOSX) && !defined(OS_IOS)
316base::ScopedCFTypeRef<CFURLRef> CFURLRefForPath(const base::FilePath& path){
317 base::ScopedCFTypeRef<CFStringRef> urlString(
318 CFStringCreateWithFileSystemRepresentation(
319 kCFAllocatorDefault, path.value().c_str()));
320 base::ScopedCFTypeRef<CFURLRef> url(
321 CFURLCreateWithFileSystemPath(kCFAllocatorDefault, urlString,
322 kCFURLPOSIXPathStyle, FALSE));
323 return url;
324}
325
326// If a database file is marked to be excluded from Time Machine, verify that
327// journal files are also excluded.
328// TODO(shess): Disabled because CSBackupSetItemExcluded() does not work on the
329// bots, though it's fine on dev machines. See <http://crbug.com/410350>.
330TEST_F(SQLiteFeaturesTest, DISABLED_TimeMachine) {
331 ASSERT_TRUE(db().Execute("CREATE TABLE t (id INTEGER PRIMARY KEY)"));
332 db().Close();
333
334 base::FilePath journal(db_path().value() + FILE_PATH_LITERAL("-journal"));
335 ASSERT_TRUE(GetPathExists(db_path()));
336 ASSERT_TRUE(GetPathExists(journal));
337
338 base::ScopedCFTypeRef<CFURLRef> dbURL(CFURLRefForPath(db_path()));
339 base::ScopedCFTypeRef<CFURLRef> journalURL(CFURLRefForPath(journal));
340
341 // Not excluded to start.
Victor Costanbd623112018-07-18 04:17:27342 EXPECT_FALSE(CSBackupIsItemExcluded(dbURL, nullptr));
343 EXPECT_FALSE(CSBackupIsItemExcluded(journalURL, nullptr));
shess5f2c3442017-01-24 02:15:10344
345 // Exclude the main database file.
346 EXPECT_TRUE(base::mac::SetFileBackupExclusion(db_path()));
347
348 Boolean excluded_by_path = FALSE;
349 EXPECT_TRUE(CSBackupIsItemExcluded(dbURL, &excluded_by_path));
350 EXPECT_FALSE(excluded_by_path);
Victor Costanbd623112018-07-18 04:17:27351 EXPECT_FALSE(CSBackupIsItemExcluded(journalURL, nullptr));
shess5f2c3442017-01-24 02:15:10352
353 EXPECT_TRUE(db().Open(db_path()));
354 ASSERT_TRUE(db().Execute("INSERT INTO t VALUES (1)"));
355 EXPECT_TRUE(CSBackupIsItemExcluded(dbURL, &excluded_by_path));
356 EXPECT_FALSE(excluded_by_path);
357 EXPECT_TRUE(CSBackupIsItemExcluded(journalURL, &excluded_by_path));
358 EXPECT_FALSE(excluded_by_path);
359
360 // TODO(shess): In WAL mode this will touch -wal and -shm files. -shm files
361 // could be always excluded.
362}
363#endif
364
shesse8127932017-03-27 19:16:10365// Test that Chromium's patch to make auto_vacuum integrate with
366// SQLITE_FCNTL_CHUNK_SIZE is working.
367TEST_F(SQLiteFeaturesTest, SmartAutoVacuum) {
368 // Turn on auto_vacuum, and set the page size low to make results obvious.
369 // These settings require re-writing the database, which VACUUM does.
370 ASSERT_TRUE(db().Execute("PRAGMA auto_vacuum = FULL"));
371 ASSERT_TRUE(db().Execute("PRAGMA page_size = 1024"));
372 ASSERT_TRUE(db().Execute("VACUUM"));
373
374 // Code-coverage of the PRAGMA set/get implementation.
Victor Costan1d868352018-06-26 19:06:48375 static const char kPragmaSql[] = "PRAGMA auto_vacuum_slack_pages";
shesse8127932017-03-27 19:16:10376 ASSERT_EQ("0", sql::test::ExecuteWithResult(&db(), kPragmaSql));
377 ASSERT_TRUE(db().Execute("PRAGMA auto_vacuum_slack_pages = 4"));
378 ASSERT_EQ("4", sql::test::ExecuteWithResult(&db(), kPragmaSql));
379 // Max out at 255.
380 ASSERT_TRUE(db().Execute("PRAGMA auto_vacuum_slack_pages = 1000"));
381 ASSERT_EQ("255", sql::test::ExecuteWithResult(&db(), kPragmaSql));
382 ASSERT_TRUE(db().Execute("PRAGMA auto_vacuum_slack_pages = 0"));
383
384 // With page_size=1024, the following will insert rows which take up an
385 // overflow page, plus a small header in a b-tree node. An empty table takes
386 // a single page, so for small row counts each insert will add one page, and
387 // each delete will remove one page.
Victor Costan1d868352018-06-26 19:06:48388 static const char kCreateSql[] =
389 "CREATE TABLE t (id INTEGER PRIMARY KEY, value)";
390 static const char kInsertSql[] =
391 "INSERT INTO t (value) VALUES (randomblob(980))";
shesse8127932017-03-27 19:16:10392#if !defined(OS_WIN)
Victor Costan1d868352018-06-26 19:06:48393 static const char kDeleteSql[] =
394 "DELETE FROM t WHERE id = (SELECT MIN(id) FROM t)";
shesse8127932017-03-27 19:16:10395#endif
396
397 // This database will be 34 overflow pages plus the table's root page plus the
398 // SQLite header page plus the freelist page.
399 ASSERT_TRUE(db().Execute(kCreateSql));
400 {
401 sql::Statement s(db().GetUniqueStatement(kInsertSql));
402 for (int i = 0; i < 34; ++i) {
403 s.Reset(true);
404 ASSERT_TRUE(s.Run());
405 }
406 }
407 ASSERT_EQ("37", sql::test::ExecuteWithResult(&db(), "PRAGMA page_count"));
408
409 // http://sqlite.org/mmap.html indicates that Windows will silently fail when
410 // truncating a memory-mapped file. That pretty much invalidates these tests
411 // against the actual file size.
412#if !defined(OS_WIN)
413 // Each delete will delete a single page, including crossing a
414 // multiple-of-four boundary.
415 {
416 sql::Statement s(db().GetUniqueStatement(kDeleteSql));
417 for (int i = 0; i < 5; ++i) {
418 int64_t file_size_before, file_size_after;
419 ASSERT_TRUE(base::GetFileSize(db_path(), &file_size_before));
420
421 s.Reset(true);
422 ASSERT_TRUE(s.Run());
423
424 ASSERT_TRUE(base::GetFileSize(db_path(), &file_size_after));
425 ASSERT_EQ(file_size_after, file_size_before - 1024);
426 }
427 }
428
429 // Turn on "smart" auto-vacuum to remove 4 pages at a time.
430 ASSERT_TRUE(db().Execute("PRAGMA auto_vacuum_slack_pages = 4"));
431
432 // No pages removed, then four deleted at once.
433 {
434 sql::Statement s(db().GetUniqueStatement(kDeleteSql));
435 for (int i = 0; i < 3; ++i) {
436 int64_t file_size_before, file_size_after;
437 ASSERT_TRUE(base::GetFileSize(db_path(), &file_size_before));
438
439 s.Reset(true);
440 ASSERT_TRUE(s.Run());
441
442 ASSERT_TRUE(base::GetFileSize(db_path(), &file_size_after));
443 ASSERT_EQ(file_size_after, file_size_before);
444 }
445
446 int64_t file_size_before, file_size_after;
447 ASSERT_TRUE(base::GetFileSize(db_path(), &file_size_before));
448
449 s.Reset(true);
450 ASSERT_TRUE(s.Run());
451
452 ASSERT_TRUE(base::GetFileSize(db_path(), &file_size_after));
453 ASSERT_EQ(file_size_after, file_size_before - 4096);
454 }
455#endif
456}
shesse8127932017-03-27 19:16:10457
Victor Costan86ca4312018-02-07 21:34:10458#if !defined(OS_FUCHSIA)
shessf7fcc452017-04-19 22:10:41459// SQLite WAL mode defaults to checkpointing the WAL on close. This would push
460// additional work into Chromium shutdown. Verify that SQLite supports a config
461// option to not checkpoint on close.
462TEST_F(SQLiteFeaturesTest, WALNoClose) {
463 base::FilePath wal_path(db_path().value() + FILE_PATH_LITERAL("-wal"));
464
465 // Turn on WAL mode, then verify that the mode changed (WAL is supported).
466 ASSERT_TRUE(db().Execute("PRAGMA journal_mode = WAL"));
467 ASSERT_EQ("wal", ExecuteWithResult(&db(), "PRAGMA journal_mode"));
468
469 // The WAL file is created lazily on first change.
470 ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)"));
471
472 // By default, the WAL is checkpointed then deleted on close.
473 ASSERT_TRUE(GetPathExists(wal_path));
474 db().Close();
475 ASSERT_FALSE(GetPathExists(wal_path));
476
477 // Reopen and configure the database to not checkpoint WAL on close.
478 ASSERT_TRUE(Reopen());
479 ASSERT_TRUE(db().Execute("PRAGMA journal_mode = WAL"));
480 ASSERT_TRUE(db().Execute("ALTER TABLE foo ADD COLUMN c"));
Victor Costanbd623112018-07-18 04:17:27481 ASSERT_EQ(SQLITE_OK,
482 sqlite3_db_config(db().db_, SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, 1,
483 nullptr));
shessf7fcc452017-04-19 22:10:41484 ASSERT_TRUE(GetPathExists(wal_path));
485 db().Close();
486 ASSERT_TRUE(GetPathExists(wal_path));
487}
488#endif
489
490} // namespace sql