blob: 24435fe182e2ffef132be45d25d3836619cc5f81 [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"
Victor Costancfbfa602018-08-01 23:24:4615#include "sql/database.h"
[email protected]f0a54b22011-07-19 18:40:2116#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)
shess5f2c3442017-01-24 02:15:1023#include "base/mac/mac_util.h"
shess5f2c3442017-01-24 02:15:1024#endif
25
[email protected]67361b32011-04-12 20:13:0626// Test that certain features are/are-not enabled in our SQLite.
27
shessf7fcc452017-04-19 22:10:4128namespace sql {
[email protected]67361b32011-04-12 20:13:0629namespace {
30
shessf7fcc452017-04-19 22:10:4131using sql::test::ExecuteWithResult;
32using sql::test::ExecuteWithResults;
33
[email protected]526b4662013-06-14 04:09:1234void CaptureErrorCallback(int* error_pointer, std::string* sql_text,
35 int error, sql::Statement* stmt) {
36 *error_pointer = error;
Victor Costanbd623112018-07-18 04:17:2737 const char* text = stmt ? stmt->GetSQLStatement() : nullptr;
[email protected]526b4662013-06-14 04:09:1238 *sql_text = text ? text : "no statement available";
39}
[email protected]67361b32011-04-12 20:13:0640
shessf7fcc452017-04-19 22:10:4141} // namespace
42
erg102ceb412015-06-20 01:38:1343class SQLiteFeaturesTest : public sql::SQLTestBase {
[email protected]67361b32011-04-12 20:13:0644 public:
[email protected]49dc4f22012-10-17 17:41:1645 SQLiteFeaturesTest() : error_(SQLITE_OK) {}
[email protected]67361b32011-04-12 20:13:0646
dcheng1b3b125e2014-12-22 23:00:2447 void SetUp() override {
erg102ceb412015-06-20 01:38:1348 SQLTestBase::SetUp();
[email protected]99034682012-06-13 03:31:1649
[email protected]49dc4f22012-10-17 17:41:1650 // The error delegate will set |error_| and |sql_text_| when any sqlite
51 // statement operation returns an error code.
erg102ceb412015-06-20 01:38:1352 db().set_error_callback(
tzikd16d2192018-03-07 08:58:3653 base::BindRepeating(&CaptureErrorCallback, &error_, &sql_text_));
[email protected]67361b32011-04-12 20:13:0654 }
55
dcheng1b3b125e2014-12-22 23:00:2456 void TearDown() override {
[email protected]67361b32011-04-12 20:13:0657 // If any error happened the original sql statement can be found in
[email protected]49dc4f22012-10-17 17:41:1658 // |sql_text_|.
engedybe80d53e2015-01-22 09:54:5059 EXPECT_EQ(SQLITE_OK, error_) << sql_text_;
erg102ceb412015-06-20 01:38:1360
61 SQLTestBase::TearDown();
[email protected]67361b32011-04-12 20:13:0662 }
63
Scott Hessdcf120482015-02-10 21:33:2964 int error() { return error_; }
[email protected]67361b32011-04-12 20:13:0665
[email protected]67361b32011-04-12 20:13:0666 private:
[email protected]49dc4f22012-10-17 17:41:1667 // The error code of the most recent error.
68 int error_;
69 // Original statement which has caused the error.
70 std::string sql_text_;
[email protected]67361b32011-04-12 20:13:0671};
72
73// Do not include fts1 support, it is not useful, and nobody is
74// looking at it.
75TEST_F(SQLiteFeaturesTest, NoFTS1) {
[email protected]eff1fa522011-12-12 23:50:5976 ASSERT_EQ(SQLITE_ERROR, db().ExecuteAndReturnErrorCode(
77 "CREATE VIRTUAL TABLE foo USING fts1(x)"));
[email protected]67361b32011-04-12 20:13:0678}
79
shess37437cb2015-03-11 20:24:4680// Do not include fts2 support, it is not useful, and nobody is
81// looking at it.
82TEST_F(SQLiteFeaturesTest, NoFTS2) {
83 ASSERT_EQ(SQLITE_ERROR, db().ExecuteAndReturnErrorCode(
84 "CREATE VIRTUAL TABLE foo USING fts2(x)"));
[email protected]67361b32011-04-12 20:13:0685}
shess355d9a1e2015-01-10 00:42:2986
shess37437cb2015-03-11 20:24:4687// fts3 used to be used for history files, and may also be used by WebDatabase
88// clients.
[email protected]67361b32011-04-12 20:13:0689TEST_F(SQLiteFeaturesTest, FTS3) {
90 ASSERT_TRUE(db().Execute("CREATE VIRTUAL TABLE foo USING fts3(x)"));
91}
92
shess37437cb2015-03-11 20:24:4693// Originally history used fts2, which Chromium patched to treat "foo*" as a
94// prefix search, though the icu tokenizer would return it as two tokens {"foo",
95// "*"}. Test that fts3 works correctly.
shess355d9a1e2015-01-10 00:42:2996TEST_F(SQLiteFeaturesTest, FTS3_Prefix) {
Victor Costan1d868352018-06-26 19:06:4897 static const char kCreateSql[] =
shess355d9a1e2015-01-10 00:42:2998 "CREATE VIRTUAL TABLE foo USING fts3(x, tokenize icu)";
99 ASSERT_TRUE(db().Execute(kCreateSql));
100
101 ASSERT_TRUE(db().Execute("INSERT INTO foo (x) VALUES ('test')"));
102
shessf7fcc452017-04-19 22:10:41103 EXPECT_EQ("test",
104 ExecuteWithResult(&db(), "SELECT x FROM foo WHERE x MATCH 'te*'"));
shess355d9a1e2015-01-10 00:42:29105}
shess355d9a1e2015-01-10 00:42:29106
shess156733db2015-01-21 21:52:24107// Verify that Chromium's SQLite is compiled with HAVE_USLEEP defined. With
108// HAVE_USLEEP, SQLite uses usleep() with millisecond granularity. Otherwise it
109// uses sleep() with second granularity.
110TEST_F(SQLiteFeaturesTest, UsesUsleep) {
111 base::TimeTicks before = base::TimeTicks::Now();
112 sqlite3_sleep(1);
113 base::TimeDelta delta = base::TimeTicks::Now() - before;
114
shessf7fcc452017-04-19 22:10:41115 // It is not impossible for this to be over 1000 if things are compiled
116 // correctly, but that is very unlikely. Most platforms seem to be exactly
117 // 1ms, with the rest at 2ms, and the worst observed cases was ASAN at 7ms.
shess156733db2015-01-21 21:52:24118 EXPECT_LT(delta.InMilliseconds(), 1000);
119}
shess156733db2015-01-21 21:52:24120
engedybe80d53e2015-01-22 09:54:50121// Ensure that our SQLite version has working foreign key support with cascade
122// delete support.
123TEST_F(SQLiteFeaturesTest, ForeignKeySupport) {
124 ASSERT_TRUE(db().Execute("PRAGMA foreign_keys=1"));
125 ASSERT_TRUE(db().Execute("CREATE TABLE parents (id INTEGER PRIMARY KEY)"));
126 ASSERT_TRUE(db().Execute(
127 "CREATE TABLE children ("
128 " id INTEGER PRIMARY KEY,"
129 " pid INTEGER NOT NULL REFERENCES parents(id) ON DELETE CASCADE)"));
Victor Costan1d868352018-06-26 19:06:48130 static const char kSelectParentsSql[] = "SELECT * FROM parents ORDER BY id";
131 static const char kSelectChildrenSql[] = "SELECT * FROM children ORDER BY id";
engedybe80d53e2015-01-22 09:54:50132
133 // Inserting without a matching parent should fail with constraint violation.
Victor Costan1d868352018-06-26 19:06:48134 EXPECT_EQ("", ExecuteWithResult(&db(), kSelectParentsSql));
shessf7fcc452017-04-19 22:10:41135 const int insert_error =
136 db().ExecuteAndReturnErrorCode("INSERT INTO children VALUES (10, 1)");
Victor Costan86ca4312018-02-07 21:34:10137 EXPECT_EQ(SQLITE_CONSTRAINT | SQLITE_CONSTRAINT_FOREIGNKEY, insert_error);
Victor Costan1d868352018-06-26 19:06:48138 EXPECT_EQ("", ExecuteWithResult(&db(), kSelectChildrenSql));
engedybe80d53e2015-01-22 09:54:50139
140 // Inserting with a matching parent should work.
141 ASSERT_TRUE(db().Execute("INSERT INTO parents VALUES (1)"));
Victor Costan1d868352018-06-26 19:06:48142 EXPECT_EQ("1", ExecuteWithResults(&db(), kSelectParentsSql, "|", "\n"));
engedybe80d53e2015-01-22 09:54:50143 EXPECT_TRUE(db().Execute("INSERT INTO children VALUES (11, 1)"));
144 EXPECT_TRUE(db().Execute("INSERT INTO children VALUES (12, 1)"));
shessf7fcc452017-04-19 22:10:41145 EXPECT_EQ("11|1\n12|1",
Victor Costan1d868352018-06-26 19:06:48146 ExecuteWithResults(&db(), kSelectChildrenSql, "|", "\n"));
engedybe80d53e2015-01-22 09:54:50147
shessf7fcc452017-04-19 22:10:41148 // Deleting the parent should cascade, deleting the children as well.
engedybe80d53e2015-01-22 09:54:50149 ASSERT_TRUE(db().Execute("DELETE FROM parents"));
Victor Costan1d868352018-06-26 19:06:48150 EXPECT_EQ("", ExecuteWithResult(&db(), kSelectParentsSql));
151 EXPECT_EQ("", ExecuteWithResult(&db(), kSelectChildrenSql));
engedybe80d53e2015-01-22 09:54:50152}
153
Victor Costanbc7ab062018-04-20 19:03:56154// Ensure that our SQLite version supports booleans.
155TEST_F(SQLiteFeaturesTest, BooleanSupport) {
156 ASSERT_TRUE(
157 db().Execute("CREATE TABLE flags ("
158 " id INTEGER PRIMARY KEY,"
159 " true_flag BOOL NOT NULL DEFAULT TRUE,"
160 " false_flag BOOL NOT NULL DEFAULT FALSE)"));
161 ASSERT_TRUE(db().Execute(
162 "ALTER TABLE flags ADD COLUMN true_flag2 BOOL NOT NULL DEFAULT TRUE"));
163 ASSERT_TRUE(db().Execute(
164 "ALTER TABLE flags ADD COLUMN false_flag2 BOOL NOT NULL DEFAULT FALSE"));
165 ASSERT_TRUE(db().Execute("INSERT INTO flags (id) VALUES (1)"));
166
167 sql::Statement s(db().GetUniqueStatement(
168 "SELECT true_flag, false_flag, true_flag2, false_flag2"
169 " FROM flags WHERE id=1;"));
170 ASSERT_TRUE(s.Step());
171
Victor Costanf087c842018-04-27 00:47:50172 EXPECT_TRUE(s.ColumnBool(0)) << " default TRUE at table creation time";
Victor Costanbc7ab062018-04-20 19:03:56173 EXPECT_TRUE(!s.ColumnBool(1)) << " default FALSE at table creation time";
174
Victor Costanf087c842018-04-27 00:47:50175 EXPECT_TRUE(s.ColumnBool(2)) << " default TRUE added by altering the table";
Victor Costanbc7ab062018-04-20 19:03:56176 EXPECT_TRUE(!s.ColumnBool(3)) << " default FALSE added by altering the table";
177}
178
Victor Costan02bf6b6d2019-05-21 23:27:27179TEST_F(SQLiteFeaturesTest, IcuEnabled) {
180 sql::Statement lower_en(
181 db().GetUniqueStatement("SELECT lower('I', 'en_us')"));
182 ASSERT_TRUE(lower_en.Step());
183 EXPECT_EQ("i", lower_en.ColumnString(0));
184
185 sql::Statement lower_tr(
186 db().GetUniqueStatement("SELECT lower('I', 'tr_tr')"));
187 ASSERT_TRUE(lower_tr.Step());
188 EXPECT_EQ("\u0131", lower_tr.ColumnString(0));
189}
190
shess53adf162015-12-17 22:07:26191// Verify that OS file writes are reflected in the memory mapping of a
192// memory-mapped file. Normally SQLite writes to memory-mapped files using
193// memcpy(), which should stay consistent. Our SQLite is slightly patched to
194// mmap read only, then write using OS file writes. If the memory-mapped
195// version doesn't reflect the OS file writes, SQLite's memory-mapped I/O should
196// be disabled on this platform using SQLITE_MAX_MMAP_SIZE=0.
197TEST_F(SQLiteFeaturesTest, Mmap) {
198 // Try to turn on mmap'ed I/O.
199 ignore_result(db().Execute("PRAGMA mmap_size = 1048576"));
200 {
201 sql::Statement s(db().GetUniqueStatement("PRAGMA mmap_size"));
202
shess53adf162015-12-17 22:07:26203 ASSERT_TRUE(s.Step());
204 ASSERT_GT(s.ColumnInt64(0), 0);
shess53adf162015-12-17 22:07:26205 }
206 db().Close();
207
avi0b519202015-12-21 07:25:19208 const uint32_t kFlags =
209 base::File::FLAG_OPEN | base::File::FLAG_READ | base::File::FLAG_WRITE;
shess53adf162015-12-17 22:07:26210 char buf[4096];
211
212 // Create a file with a block of '0', a block of '1', and a block of '2'.
213 {
214 base::File f(db_path(), kFlags);
215 ASSERT_TRUE(f.IsValid());
216 memset(buf, '0', sizeof(buf));
217 ASSERT_EQ(f.Write(0*sizeof(buf), buf, sizeof(buf)), (int)sizeof(buf));
218
219 memset(buf, '1', sizeof(buf));
220 ASSERT_EQ(f.Write(1*sizeof(buf), buf, sizeof(buf)), (int)sizeof(buf));
221
222 memset(buf, '2', sizeof(buf));
223 ASSERT_EQ(f.Write(2*sizeof(buf), buf, sizeof(buf)), (int)sizeof(buf));
224 }
225
226 // mmap the file and verify that everything looks right.
227 {
228 base::MemoryMappedFile m;
229 ASSERT_TRUE(m.Initialize(db_path()));
230
231 memset(buf, '0', sizeof(buf));
232 ASSERT_EQ(0, memcmp(buf, m.data() + 0*sizeof(buf), sizeof(buf)));
233
234 memset(buf, '1', sizeof(buf));
235 ASSERT_EQ(0, memcmp(buf, m.data() + 1*sizeof(buf), sizeof(buf)));
236
237 memset(buf, '2', sizeof(buf));
238 ASSERT_EQ(0, memcmp(buf, m.data() + 2*sizeof(buf), sizeof(buf)));
239
240 // Scribble some '3' into the first page of the file, and verify that it
241 // looks the same in the memory mapping.
242 {
243 base::File f(db_path(), kFlags);
244 ASSERT_TRUE(f.IsValid());
245 memset(buf, '3', sizeof(buf));
246 ASSERT_EQ(f.Write(0*sizeof(buf), buf, sizeof(buf)), (int)sizeof(buf));
247 }
248 ASSERT_EQ(0, memcmp(buf, m.data() + 0*sizeof(buf), sizeof(buf)));
249
250 // Repeat with a single '4' in case page-sized blocks are different.
251 const size_t kOffset = 1*sizeof(buf) + 123;
252 ASSERT_NE('4', m.data()[kOffset]);
253 {
254 base::File f(db_path(), kFlags);
255 ASSERT_TRUE(f.IsValid());
256 buf[0] = '4';
257 ASSERT_EQ(f.Write(kOffset, buf, 1), 1);
258 }
259 ASSERT_EQ('4', m.data()[kOffset]);
260 }
261}
shess53adf162015-12-17 22:07:26262
shess001ae162016-10-20 04:04:32263// Verify that http://crbug.com/248608 is fixed. In this bug, the
264// compiled regular expression is effectively cached with the prepared
265// statement, causing errors if the regular expression is rebound.
266TEST_F(SQLiteFeaturesTest, CachedRegexp) {
267 ASSERT_TRUE(db().Execute("CREATE TABLE r (id INTEGER UNIQUE, x TEXT)"));
268 ASSERT_TRUE(db().Execute("INSERT INTO r VALUES (1, 'this is a test')"));
269 ASSERT_TRUE(db().Execute("INSERT INTO r VALUES (2, 'that was a test')"));
270 ASSERT_TRUE(db().Execute("INSERT INTO r VALUES (3, 'this is a stickup')"));
271 ASSERT_TRUE(db().Execute("INSERT INTO r VALUES (4, 'that sucks')"));
272
Victor Costan1d868352018-06-26 19:06:48273 static const char kSimpleSql[] = "SELECT SUM(id) FROM r WHERE x REGEXP ?";
shess001ae162016-10-20 04:04:32274 sql::Statement s(db().GetCachedStatement(SQL_FROM_HERE, kSimpleSql));
275
276 s.BindString(0, "this.*");
277 ASSERT_TRUE(s.Step());
278 EXPECT_EQ(4, s.ColumnInt(0));
279
280 s.Reset(true);
281 s.BindString(0, "that.*");
282 ASSERT_TRUE(s.Step());
283 EXPECT_EQ(6, s.ColumnInt(0));
284
285 s.Reset(true);
286 s.BindString(0, ".*test");
287 ASSERT_TRUE(s.Step());
288 EXPECT_EQ(3, s.ColumnInt(0));
289
290 s.Reset(true);
291 s.BindString(0, ".* s[a-z]+");
292 ASSERT_TRUE(s.Step());
293 EXPECT_EQ(7, s.ColumnInt(0));
294}
295
shess5f2c3442017-01-24 02:15:10296#if defined(OS_MACOSX) && !defined(OS_IOS)
shess5f2c3442017-01-24 02:15:10297// If a database file is marked to be excluded from Time Machine, verify that
298// journal files are also excluded.
Victor Costan653b14f2018-07-23 19:32:33299TEST_F(SQLiteFeaturesTest, TimeMachine) {
shess5f2c3442017-01-24 02:15:10300 ASSERT_TRUE(db().Execute("CREATE TABLE t (id INTEGER PRIMARY KEY)"));
301 db().Close();
302
Victor Costan7e74dce2019-01-28 20:15:25303 base::FilePath journal_path = sql::Database::JournalPath(db_path());
shess5f2c3442017-01-24 02:15:10304 ASSERT_TRUE(GetPathExists(db_path()));
Victor Costan7e74dce2019-01-28 20:15:25305 ASSERT_TRUE(GetPathExists(journal_path));
shess5f2c3442017-01-24 02:15:10306
307 // Not excluded to start.
Victor Costan7e74dce2019-01-28 20:15:25308 EXPECT_FALSE(base::mac::GetFileBackupExclusion(db_path()));
309 EXPECT_FALSE(base::mac::GetFileBackupExclusion(journal_path));
shess5f2c3442017-01-24 02:15:10310
311 // Exclude the main database file.
312 EXPECT_TRUE(base::mac::SetFileBackupExclusion(db_path()));
313
Victor Costan7e74dce2019-01-28 20:15:25314 EXPECT_TRUE(base::mac::GetFileBackupExclusion(db_path()));
315 EXPECT_FALSE(base::mac::GetFileBackupExclusion(journal_path));
shess5f2c3442017-01-24 02:15:10316
317 EXPECT_TRUE(db().Open(db_path()));
318 ASSERT_TRUE(db().Execute("INSERT INTO t VALUES (1)"));
Victor Costan7e74dce2019-01-28 20:15:25319 EXPECT_TRUE(base::mac::GetFileBackupExclusion(db_path()));
320 EXPECT_TRUE(base::mac::GetFileBackupExclusion(journal_path));
shess5f2c3442017-01-24 02:15:10321
322 // TODO(shess): In WAL mode this will touch -wal and -shm files. -shm files
323 // could be always excluded.
324}
325#endif
326
Victor Costan86ca4312018-02-07 21:34:10327#if !defined(OS_FUCHSIA)
shessf7fcc452017-04-19 22:10:41328// SQLite WAL mode defaults to checkpointing the WAL on close. This would push
329// additional work into Chromium shutdown. Verify that SQLite supports a config
330// option to not checkpoint on close.
331TEST_F(SQLiteFeaturesTest, WALNoClose) {
Victor Costancfbfa602018-08-01 23:24:46332 base::FilePath wal_path = sql::Database::WriteAheadLogPath(db_path());
shessf7fcc452017-04-19 22:10:41333
334 // Turn on WAL mode, then verify that the mode changed (WAL is supported).
335 ASSERT_TRUE(db().Execute("PRAGMA journal_mode = WAL"));
336 ASSERT_EQ("wal", ExecuteWithResult(&db(), "PRAGMA journal_mode"));
337
338 // The WAL file is created lazily on first change.
339 ASSERT_TRUE(db().Execute("CREATE TABLE foo (a, b)"));
340
341 // By default, the WAL is checkpointed then deleted on close.
342 ASSERT_TRUE(GetPathExists(wal_path));
343 db().Close();
344 ASSERT_FALSE(GetPathExists(wal_path));
345
346 // Reopen and configure the database to not checkpoint WAL on close.
347 ASSERT_TRUE(Reopen());
348 ASSERT_TRUE(db().Execute("PRAGMA journal_mode = WAL"));
349 ASSERT_TRUE(db().Execute("ALTER TABLE foo ADD COLUMN c"));
Victor Costanbd623112018-07-18 04:17:27350 ASSERT_EQ(SQLITE_OK,
351 sqlite3_db_config(db().db_, SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, 1,
352 nullptr));
shessf7fcc452017-04-19 22:10:41353 ASSERT_TRUE(GetPathExists(wal_path));
354 db().Close();
355 ASSERT_TRUE(GetPathExists(wal_path));
356}
357#endif
358
359} // namespace sql