Ben Murdoch | ca12bfa | 2013-07-23 11:17:05 +0100 | [diff] [blame] | 1 | // Copyright 2013 The Chromium Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
Ben Murdoch | 2385ea3 | 2013-08-06 11:01:04 +0100 | [diff] [blame] | 5 | #include "base/bind.h" |
Ben Murdoch | ca12bfa | 2013-07-23 11:17:05 +0100 | [diff] [blame] | 6 | #include "base/file_util.h" |
| 7 | #include "base/files/scoped_temp_dir.h" |
| 8 | #include "base/logging.h" |
Torne (Richard Coles) | f2477e0 | 2013-11-28 11:55:43 +0000 | [diff] [blame] | 9 | #include "base/strings/string_number_conversions.h" |
Ben Murdoch | ca12bfa | 2013-07-23 11:17:05 +0100 | [diff] [blame] | 10 | #include "base/strings/stringprintf.h" |
| 11 | #include "sql/connection.h" |
| 12 | #include "sql/meta_table.h" |
| 13 | #include "sql/recovery.h" |
| 14 | #include "sql/statement.h" |
| 15 | #include "sql/test/scoped_error_ignorer.h" |
| 16 | #include "testing/gtest/include/gtest/gtest.h" |
| 17 | #include "third_party/sqlite/sqlite3.h" |
| 18 | |
| 19 | namespace { |
| 20 | |
| 21 | // Execute |sql|, and stringify the results with |column_sep| between |
| 22 | // columns and |row_sep| between rows. |
| 23 | // TODO(shess): Promote this to a central testing helper. |
| 24 | std::string ExecuteWithResults(sql::Connection* db, |
| 25 | const char* sql, |
| 26 | const char* column_sep, |
| 27 | const char* row_sep) { |
| 28 | sql::Statement s(db->GetUniqueStatement(sql)); |
| 29 | std::string ret; |
| 30 | while (s.Step()) { |
| 31 | if (!ret.empty()) |
| 32 | ret += row_sep; |
| 33 | for (int i = 0; i < s.ColumnCount(); ++i) { |
| 34 | if (i > 0) |
| 35 | ret += column_sep; |
Torne (Richard Coles) | f2477e0 | 2013-11-28 11:55:43 +0000 | [diff] [blame] | 36 | if (s.ColumnType(i) == sql::COLUMN_TYPE_NULL) { |
| 37 | ret += "<null>"; |
| 38 | } else if (s.ColumnType(i) == sql::COLUMN_TYPE_BLOB) { |
| 39 | ret += "<x'"; |
| 40 | ret += base::HexEncode(s.ColumnBlob(i), s.ColumnByteLength(i)); |
| 41 | ret += "'>"; |
| 42 | } else { |
| 43 | ret += s.ColumnString(i); |
| 44 | } |
Ben Murdoch | ca12bfa | 2013-07-23 11:17:05 +0100 | [diff] [blame] | 45 | } |
| 46 | } |
| 47 | return ret; |
| 48 | } |
| 49 | |
| 50 | // Dump consistent human-readable representation of the database |
| 51 | // schema. For tables or indices, this will contain the sql command |
| 52 | // to create the table or index. For certain automatic SQLite |
| 53 | // structures with no sql, the name is used. |
| 54 | std::string GetSchema(sql::Connection* db) { |
| 55 | const char kSql[] = |
| 56 | "SELECT COALESCE(sql, name) FROM sqlite_master ORDER BY 1"; |
| 57 | return ExecuteWithResults(db, kSql, "|", "\n"); |
| 58 | } |
| 59 | |
Torne (Richard Coles) | f2477e0 | 2013-11-28 11:55:43 +0000 | [diff] [blame] | 60 | #if !defined(USE_SYSTEM_SQLITE) |
Ben Murdoch | 2385ea3 | 2013-08-06 11:01:04 +0100 | [diff] [blame] | 61 | int GetPageSize(sql::Connection* db) { |
| 62 | sql::Statement s(db->GetUniqueStatement("PRAGMA page_size")); |
| 63 | EXPECT_TRUE(s.Step()); |
| 64 | return s.ColumnInt(0); |
| 65 | } |
| 66 | |
| 67 | // Get |name|'s root page number in the database. |
| 68 | int GetRootPage(sql::Connection* db, const char* name) { |
| 69 | const char kPageSql[] = "SELECT rootpage FROM sqlite_master WHERE name = ?"; |
| 70 | sql::Statement s(db->GetUniqueStatement(kPageSql)); |
| 71 | s.BindString(0, name); |
| 72 | EXPECT_TRUE(s.Step()); |
| 73 | return s.ColumnInt(0); |
| 74 | } |
| 75 | |
| 76 | // Helper to read a SQLite page into a buffer. |page_no| is 1-based |
| 77 | // per SQLite usage. |
| 78 | bool ReadPage(const base::FilePath& path, size_t page_no, |
| 79 | char* buf, size_t page_size) { |
| 80 | file_util::ScopedFILE file(file_util::OpenFile(path, "rb")); |
| 81 | if (!file.get()) |
| 82 | return false; |
| 83 | if (0 != fseek(file.get(), (page_no - 1) * page_size, SEEK_SET)) |
| 84 | return false; |
| 85 | if (1u != fread(buf, page_size, 1, file.get())) |
| 86 | return false; |
| 87 | return true; |
| 88 | } |
| 89 | |
| 90 | // Helper to write a SQLite page into a buffer. |page_no| is 1-based |
| 91 | // per SQLite usage. |
| 92 | bool WritePage(const base::FilePath& path, size_t page_no, |
| 93 | const char* buf, size_t page_size) { |
| 94 | file_util::ScopedFILE file(file_util::OpenFile(path, "rb+")); |
| 95 | if (!file.get()) |
| 96 | return false; |
| 97 | if (0 != fseek(file.get(), (page_no - 1) * page_size, SEEK_SET)) |
| 98 | return false; |
| 99 | if (1u != fwrite(buf, page_size, 1, file.get())) |
| 100 | return false; |
| 101 | return true; |
| 102 | } |
Torne (Richard Coles) | f2477e0 | 2013-11-28 11:55:43 +0000 | [diff] [blame] | 103 | #endif // !defined(USE_SYSTEM_SQLITE) |
Ben Murdoch | 2385ea3 | 2013-08-06 11:01:04 +0100 | [diff] [blame] | 104 | |
Ben Murdoch | ca12bfa | 2013-07-23 11:17:05 +0100 | [diff] [blame] | 105 | class SQLRecoveryTest : public testing::Test { |
| 106 | public: |
| 107 | SQLRecoveryTest() {} |
| 108 | |
| 109 | virtual void SetUp() { |
| 110 | ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); |
| 111 | ASSERT_TRUE(db_.Open(db_path())); |
| 112 | } |
| 113 | |
| 114 | virtual void TearDown() { |
| 115 | db_.Close(); |
| 116 | } |
| 117 | |
| 118 | sql::Connection& db() { return db_; } |
| 119 | |
| 120 | base::FilePath db_path() { |
| 121 | return temp_dir_.path().AppendASCII("SQLRecoveryTest.db"); |
| 122 | } |
| 123 | |
| 124 | bool Reopen() { |
| 125 | db_.Close(); |
| 126 | return db_.Open(db_path()); |
| 127 | } |
| 128 | |
| 129 | private: |
| 130 | base::ScopedTempDir temp_dir_; |
| 131 | sql::Connection db_; |
| 132 | }; |
| 133 | |
| 134 | TEST_F(SQLRecoveryTest, RecoverBasic) { |
| 135 | const char kCreateSql[] = "CREATE TABLE x (t TEXT)"; |
| 136 | const char kInsertSql[] = "INSERT INTO x VALUES ('This is a test')"; |
| 137 | ASSERT_TRUE(db().Execute(kCreateSql)); |
| 138 | ASSERT_TRUE(db().Execute(kInsertSql)); |
| 139 | ASSERT_EQ("CREATE TABLE x (t TEXT)", GetSchema(&db())); |
| 140 | |
| 141 | // If the Recovery handle goes out of scope without being |
| 142 | // Recovered(), the database is razed. |
| 143 | { |
| 144 | scoped_ptr<sql::Recovery> recovery = sql::Recovery::Begin(&db(), db_path()); |
| 145 | ASSERT_TRUE(recovery.get()); |
| 146 | } |
| 147 | EXPECT_FALSE(db().is_open()); |
| 148 | ASSERT_TRUE(Reopen()); |
| 149 | EXPECT_TRUE(db().is_open()); |
| 150 | ASSERT_EQ("", GetSchema(&db())); |
| 151 | |
| 152 | // Recreate the database. |
| 153 | ASSERT_TRUE(db().Execute(kCreateSql)); |
| 154 | ASSERT_TRUE(db().Execute(kInsertSql)); |
| 155 | ASSERT_EQ("CREATE TABLE x (t TEXT)", GetSchema(&db())); |
| 156 | |
| 157 | // Unrecoverable() also razes. |
| 158 | { |
| 159 | scoped_ptr<sql::Recovery> recovery = sql::Recovery::Begin(&db(), db_path()); |
| 160 | ASSERT_TRUE(recovery.get()); |
| 161 | sql::Recovery::Unrecoverable(recovery.Pass()); |
| 162 | |
| 163 | // TODO(shess): Test that calls to recover.db() start failing. |
| 164 | } |
| 165 | EXPECT_FALSE(db().is_open()); |
| 166 | ASSERT_TRUE(Reopen()); |
| 167 | EXPECT_TRUE(db().is_open()); |
| 168 | ASSERT_EQ("", GetSchema(&db())); |
| 169 | |
| 170 | // Recreate the database. |
| 171 | ASSERT_TRUE(db().Execute(kCreateSql)); |
| 172 | ASSERT_TRUE(db().Execute(kInsertSql)); |
| 173 | ASSERT_EQ("CREATE TABLE x (t TEXT)", GetSchema(&db())); |
| 174 | |
| 175 | // Recovered() replaces the original with the "recovered" version. |
| 176 | { |
| 177 | scoped_ptr<sql::Recovery> recovery = sql::Recovery::Begin(&db(), db_path()); |
| 178 | ASSERT_TRUE(recovery.get()); |
| 179 | |
| 180 | // Create the new version of the table. |
| 181 | ASSERT_TRUE(recovery->db()->Execute(kCreateSql)); |
| 182 | |
| 183 | // Insert different data to distinguish from original database. |
| 184 | const char kAltInsertSql[] = "INSERT INTO x VALUES ('That was a test')"; |
| 185 | ASSERT_TRUE(recovery->db()->Execute(kAltInsertSql)); |
| 186 | |
| 187 | // Successfully recovered. |
| 188 | ASSERT_TRUE(sql::Recovery::Recovered(recovery.Pass())); |
| 189 | } |
| 190 | EXPECT_FALSE(db().is_open()); |
| 191 | ASSERT_TRUE(Reopen()); |
| 192 | EXPECT_TRUE(db().is_open()); |
| 193 | ASSERT_EQ("CREATE TABLE x (t TEXT)", GetSchema(&db())); |
| 194 | |
| 195 | const char* kXSql = "SELECT * FROM x ORDER BY 1"; |
Ben Murdoch | 2385ea3 | 2013-08-06 11:01:04 +0100 | [diff] [blame] | 196 | ASSERT_EQ("That was a test", |
| 197 | ExecuteWithResults(&db(), kXSql, "|", "\n")); |
Ben Murdoch | ca12bfa | 2013-07-23 11:17:05 +0100 | [diff] [blame] | 198 | } |
| 199 | |
Ben Murdoch | 2385ea3 | 2013-08-06 11:01:04 +0100 | [diff] [blame] | 200 | // The recovery virtual table is only supported for Chromium's SQLite. |
| 201 | #if !defined(USE_SYSTEM_SQLITE) |
| 202 | |
| 203 | // Run recovery through its paces on a valid database. |
| 204 | TEST_F(SQLRecoveryTest, VirtualTable) { |
| 205 | const char kCreateSql[] = "CREATE TABLE x (t TEXT)"; |
| 206 | ASSERT_TRUE(db().Execute(kCreateSql)); |
| 207 | ASSERT_TRUE(db().Execute("INSERT INTO x VALUES ('This is a test')")); |
| 208 | ASSERT_TRUE(db().Execute("INSERT INTO x VALUES ('That was a test')")); |
| 209 | |
| 210 | // Successfully recover the database. |
| 211 | { |
| 212 | scoped_ptr<sql::Recovery> recovery = sql::Recovery::Begin(&db(), db_path()); |
| 213 | |
| 214 | // Tables to recover original DB, now at [corrupt]. |
| 215 | const char kRecoveryCreateSql[] = |
| 216 | "CREATE VIRTUAL TABLE temp.recover_x using recover(" |
| 217 | " corrupt.x," |
| 218 | " t TEXT STRICT" |
| 219 | ")"; |
| 220 | ASSERT_TRUE(recovery->db()->Execute(kRecoveryCreateSql)); |
| 221 | |
| 222 | // Re-create the original schema. |
| 223 | ASSERT_TRUE(recovery->db()->Execute(kCreateSql)); |
| 224 | |
| 225 | // Copy the data from the recovery tables to the new database. |
| 226 | const char kRecoveryCopySql[] = |
| 227 | "INSERT INTO x SELECT t FROM recover_x"; |
| 228 | ASSERT_TRUE(recovery->db()->Execute(kRecoveryCopySql)); |
| 229 | |
| 230 | // Successfully recovered. |
| 231 | ASSERT_TRUE(sql::Recovery::Recovered(recovery.Pass())); |
| 232 | } |
| 233 | |
| 234 | // Since the database was not corrupt, the entire schema and all |
| 235 | // data should be recovered. |
| 236 | ASSERT_TRUE(Reopen()); |
| 237 | ASSERT_EQ("CREATE TABLE x (t TEXT)", GetSchema(&db())); |
| 238 | |
| 239 | const char* kXSql = "SELECT * FROM x ORDER BY 1"; |
| 240 | ASSERT_EQ("That was a test\nThis is a test", |
| 241 | ExecuteWithResults(&db(), kXSql, "|", "\n")); |
| 242 | } |
| 243 | |
| 244 | void RecoveryCallback(sql::Connection* db, const base::FilePath& db_path, |
| 245 | int* record_error, int error, sql::Statement* stmt) { |
| 246 | *record_error = error; |
| 247 | |
| 248 | // Clear the error callback to prevent reentrancy. |
| 249 | db->reset_error_callback(); |
| 250 | |
| 251 | scoped_ptr<sql::Recovery> recovery = sql::Recovery::Begin(db, db_path); |
| 252 | ASSERT_TRUE(recovery.get()); |
| 253 | |
| 254 | const char kRecoveryCreateSql[] = |
| 255 | "CREATE VIRTUAL TABLE temp.recover_x using recover(" |
| 256 | " corrupt.x," |
| 257 | " id INTEGER STRICT," |
| 258 | " v INTEGER STRICT" |
| 259 | ")"; |
| 260 | const char kCreateTable[] = "CREATE TABLE x (id INTEGER, v INTEGER)"; |
| 261 | const char kCreateIndex[] = "CREATE UNIQUE INDEX x_id ON x (id)"; |
| 262 | |
| 263 | // Replicate data over. |
| 264 | const char kRecoveryCopySql[] = |
| 265 | "INSERT OR REPLACE INTO x SELECT id, v FROM recover_x"; |
| 266 | |
| 267 | ASSERT_TRUE(recovery->db()->Execute(kRecoveryCreateSql)); |
| 268 | ASSERT_TRUE(recovery->db()->Execute(kCreateTable)); |
| 269 | ASSERT_TRUE(recovery->db()->Execute(kCreateIndex)); |
| 270 | ASSERT_TRUE(recovery->db()->Execute(kRecoveryCopySql)); |
| 271 | |
| 272 | ASSERT_TRUE(sql::Recovery::Recovered(recovery.Pass())); |
| 273 | } |
| 274 | |
| 275 | // Build a database, corrupt it by making an index reference to |
| 276 | // deleted row, then recover when a query selects that row. |
| 277 | TEST_F(SQLRecoveryTest, RecoverCorruptIndex) { |
| 278 | const char kCreateTable[] = "CREATE TABLE x (id INTEGER, v INTEGER)"; |
| 279 | const char kCreateIndex[] = "CREATE UNIQUE INDEX x_id ON x (id)"; |
| 280 | ASSERT_TRUE(db().Execute(kCreateTable)); |
| 281 | ASSERT_TRUE(db().Execute(kCreateIndex)); |
| 282 | |
| 283 | // Insert a bit of data. |
| 284 | { |
| 285 | ASSERT_TRUE(db().BeginTransaction()); |
| 286 | |
| 287 | const char kInsertSql[] = "INSERT INTO x (id, v) VALUES (?, ?)"; |
| 288 | sql::Statement s(db().GetUniqueStatement(kInsertSql)); |
| 289 | for (int i = 0; i < 10; ++i) { |
| 290 | s.Reset(true); |
| 291 | s.BindInt(0, i); |
| 292 | s.BindInt(1, i); |
| 293 | EXPECT_FALSE(s.Step()); |
| 294 | EXPECT_TRUE(s.Succeeded()); |
| 295 | } |
| 296 | |
| 297 | ASSERT_TRUE(db().CommitTransaction()); |
| 298 | } |
| 299 | |
| 300 | |
| 301 | // Capture the index's root page into |buf|. |
| 302 | int index_page = GetRootPage(&db(), "x_id"); |
| 303 | int page_size = GetPageSize(&db()); |
| 304 | scoped_ptr<char[]> buf(new char[page_size]); |
| 305 | ASSERT_TRUE(ReadPage(db_path(), index_page, buf.get(), page_size)); |
| 306 | |
| 307 | // Delete the row from the table and index. |
| 308 | ASSERT_TRUE(db().Execute("DELETE FROM x WHERE id = 0")); |
| 309 | |
| 310 | // Close to clear any cached data. |
| 311 | db().Close(); |
| 312 | |
| 313 | // Put the stale index page back. |
| 314 | ASSERT_TRUE(WritePage(db_path(), index_page, buf.get(), page_size)); |
| 315 | |
| 316 | // At this point, the index references a value not in the table. |
| 317 | |
| 318 | ASSERT_TRUE(Reopen()); |
| 319 | |
| 320 | int error = SQLITE_OK; |
| 321 | db().set_error_callback(base::Bind(&RecoveryCallback, |
| 322 | &db(), db_path(), &error)); |
| 323 | |
| 324 | // This works before the callback is called. |
| 325 | const char kTrivialSql[] = "SELECT COUNT(*) FROM sqlite_master"; |
| 326 | EXPECT_TRUE(db().IsSQLValid(kTrivialSql)); |
| 327 | |
| 328 | // TODO(shess): Could this be delete? Anything which fails should work. |
| 329 | const char kSelectSql[] = "SELECT v FROM x WHERE id = 0"; |
| 330 | ASSERT_FALSE(db().Execute(kSelectSql)); |
| 331 | EXPECT_EQ(SQLITE_CORRUPT, error); |
| 332 | |
| 333 | // Database handle has been poisoned. |
| 334 | EXPECT_FALSE(db().IsSQLValid(kTrivialSql)); |
| 335 | |
| 336 | ASSERT_TRUE(Reopen()); |
| 337 | |
| 338 | // The recovered table should reflect the deletion. |
| 339 | const char kSelectAllSql[] = "SELECT v FROM x ORDER BY id"; |
| 340 | EXPECT_EQ("1,2,3,4,5,6,7,8,9", |
| 341 | ExecuteWithResults(&db(), kSelectAllSql, "|", ",")); |
| 342 | |
| 343 | // The failing statement should now succeed, with no results. |
| 344 | EXPECT_EQ("", ExecuteWithResults(&db(), kSelectSql, "|", ",")); |
| 345 | } |
| 346 | |
| 347 | // Build a database, corrupt it by making a table contain a row not |
| 348 | // referenced by the index, then recover the database. |
| 349 | TEST_F(SQLRecoveryTest, RecoverCorruptTable) { |
| 350 | const char kCreateTable[] = "CREATE TABLE x (id INTEGER, v INTEGER)"; |
| 351 | const char kCreateIndex[] = "CREATE UNIQUE INDEX x_id ON x (id)"; |
| 352 | ASSERT_TRUE(db().Execute(kCreateTable)); |
| 353 | ASSERT_TRUE(db().Execute(kCreateIndex)); |
| 354 | |
| 355 | // Insert a bit of data. |
| 356 | { |
| 357 | ASSERT_TRUE(db().BeginTransaction()); |
| 358 | |
| 359 | const char kInsertSql[] = "INSERT INTO x (id, v) VALUES (?, ?)"; |
| 360 | sql::Statement s(db().GetUniqueStatement(kInsertSql)); |
| 361 | for (int i = 0; i < 10; ++i) { |
| 362 | s.Reset(true); |
| 363 | s.BindInt(0, i); |
| 364 | s.BindInt(1, i); |
| 365 | EXPECT_FALSE(s.Step()); |
| 366 | EXPECT_TRUE(s.Succeeded()); |
| 367 | } |
| 368 | |
| 369 | ASSERT_TRUE(db().CommitTransaction()); |
| 370 | } |
| 371 | |
| 372 | // Capture the table's root page into |buf|. |
| 373 | // Find the page the table is stored on. |
| 374 | const int table_page = GetRootPage(&db(), "x"); |
| 375 | const int page_size = GetPageSize(&db()); |
| 376 | scoped_ptr<char[]> buf(new char[page_size]); |
| 377 | ASSERT_TRUE(ReadPage(db_path(), table_page, buf.get(), page_size)); |
| 378 | |
| 379 | // Delete the row from the table and index. |
| 380 | ASSERT_TRUE(db().Execute("DELETE FROM x WHERE id = 0")); |
| 381 | |
| 382 | // Close to clear any cached data. |
| 383 | db().Close(); |
| 384 | |
| 385 | // Put the stale table page back. |
| 386 | ASSERT_TRUE(WritePage(db_path(), table_page, buf.get(), page_size)); |
| 387 | |
| 388 | // At this point, the table contains a value not referenced by the |
| 389 | // index. |
| 390 | // TODO(shess): Figure out a query which causes SQLite to notice |
| 391 | // this organically. Meanwhile, just handle it manually. |
| 392 | |
| 393 | ASSERT_TRUE(Reopen()); |
| 394 | |
| 395 | // Index shows one less than originally inserted. |
| 396 | const char kCountSql[] = "SELECT COUNT (*) FROM x"; |
| 397 | EXPECT_EQ("9", ExecuteWithResults(&db(), kCountSql, "|", ",")); |
| 398 | |
| 399 | // A full table scan shows all of the original data. |
| 400 | const char kDistinctSql[] = "SELECT DISTINCT COUNT (id) FROM x"; |
| 401 | EXPECT_EQ("10", ExecuteWithResults(&db(), kDistinctSql, "|", ",")); |
| 402 | |
| 403 | // Insert id 0 again. Since it is not in the index, the insert |
| 404 | // succeeds, but results in a duplicate value in the table. |
| 405 | const char kInsertSql[] = "INSERT INTO x (id, v) VALUES (0, 100)"; |
| 406 | ASSERT_TRUE(db().Execute(kInsertSql)); |
| 407 | |
| 408 | // Duplication is visible. |
| 409 | EXPECT_EQ("10", ExecuteWithResults(&db(), kCountSql, "|", ",")); |
| 410 | EXPECT_EQ("11", ExecuteWithResults(&db(), kDistinctSql, "|", ",")); |
| 411 | |
| 412 | // This works before the callback is called. |
| 413 | const char kTrivialSql[] = "SELECT COUNT(*) FROM sqlite_master"; |
| 414 | EXPECT_TRUE(db().IsSQLValid(kTrivialSql)); |
| 415 | |
| 416 | // Call the recovery callback manually. |
| 417 | int error = SQLITE_OK; |
| 418 | RecoveryCallback(&db(), db_path(), &error, SQLITE_CORRUPT, NULL); |
| 419 | EXPECT_EQ(SQLITE_CORRUPT, error); |
| 420 | |
| 421 | // Database handle has been poisoned. |
| 422 | EXPECT_FALSE(db().IsSQLValid(kTrivialSql)); |
| 423 | |
| 424 | ASSERT_TRUE(Reopen()); |
| 425 | |
| 426 | // The recovered table has consistency between the index and the table. |
| 427 | EXPECT_EQ("10", ExecuteWithResults(&db(), kCountSql, "|", ",")); |
| 428 | EXPECT_EQ("10", ExecuteWithResults(&db(), kDistinctSql, "|", ",")); |
| 429 | |
| 430 | // The expected value was retained. |
| 431 | const char kSelectSql[] = "SELECT v FROM x WHERE id = 0"; |
| 432 | EXPECT_EQ("100", ExecuteWithResults(&db(), kSelectSql, "|", ",")); |
| 433 | } |
Torne (Richard Coles) | f2477e0 | 2013-11-28 11:55:43 +0000 | [diff] [blame] | 434 | |
| 435 | TEST_F(SQLRecoveryTest, Meta) { |
| 436 | const int kVersion = 3; |
| 437 | const int kCompatibleVersion = 2; |
| 438 | |
| 439 | { |
| 440 | sql::MetaTable meta; |
| 441 | EXPECT_TRUE(meta.Init(&db(), kVersion, kCompatibleVersion)); |
| 442 | EXPECT_EQ(kVersion, meta.GetVersionNumber()); |
| 443 | } |
| 444 | |
| 445 | // Test expected case where everything works. |
| 446 | { |
| 447 | scoped_ptr<sql::Recovery> recovery = sql::Recovery::Begin(&db(), db_path()); |
| 448 | EXPECT_TRUE(recovery->SetupMeta()); |
| 449 | int version = 0; |
| 450 | EXPECT_TRUE(recovery->GetMetaVersionNumber(&version)); |
| 451 | EXPECT_EQ(kVersion, version); |
| 452 | |
| 453 | sql::Recovery::Rollback(recovery.Pass()); |
| 454 | } |
| 455 | ASSERT_TRUE(Reopen()); // Handle was poisoned. |
| 456 | |
| 457 | // Test version row missing. |
| 458 | EXPECT_TRUE(db().Execute("DELETE FROM meta WHERE key = 'version'")); |
| 459 | { |
| 460 | scoped_ptr<sql::Recovery> recovery = sql::Recovery::Begin(&db(), db_path()); |
| 461 | EXPECT_TRUE(recovery->SetupMeta()); |
| 462 | int version = 0; |
| 463 | EXPECT_FALSE(recovery->GetMetaVersionNumber(&version)); |
| 464 | EXPECT_EQ(0, version); |
| 465 | |
| 466 | sql::Recovery::Rollback(recovery.Pass()); |
| 467 | } |
| 468 | ASSERT_TRUE(Reopen()); // Handle was poisoned. |
| 469 | |
| 470 | // Test meta table missing. |
| 471 | EXPECT_TRUE(db().Execute("DROP TABLE meta")); |
| 472 | { |
| 473 | sql::ScopedErrorIgnorer ignore_errors; |
| 474 | ignore_errors.IgnoreError(SQLITE_CORRUPT); // From virtual table. |
| 475 | scoped_ptr<sql::Recovery> recovery = sql::Recovery::Begin(&db(), db_path()); |
| 476 | EXPECT_FALSE(recovery->SetupMeta()); |
| 477 | ASSERT_TRUE(ignore_errors.CheckIgnoredErrors()); |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | // Baseline AutoRecoverTable() test. |
| 482 | TEST_F(SQLRecoveryTest, AutoRecoverTable) { |
| 483 | // BIGINT and VARCHAR to test type affinity. |
| 484 | const char kCreateSql[] = "CREATE TABLE x (id BIGINT, t TEXT, v VARCHAR)"; |
| 485 | ASSERT_TRUE(db().Execute(kCreateSql)); |
| 486 | ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (11, 'This is', 'a test')")); |
| 487 | ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (5, 'That was', 'a test')")); |
| 488 | |
| 489 | // Save aside a copy of the original schema and data. |
| 490 | const std::string orig_schema(GetSchema(&db())); |
| 491 | const char kXSql[] = "SELECT * FROM x ORDER BY 1"; |
| 492 | const std::string orig_data(ExecuteWithResults(&db(), kXSql, "|", "\n")); |
| 493 | |
| 494 | // Create a lame-duck table which will not be propagated by recovery to |
| 495 | // detect that the recovery code actually ran. |
| 496 | ASSERT_TRUE(db().Execute("CREATE TABLE y (c TEXT)")); |
| 497 | ASSERT_NE(orig_schema, GetSchema(&db())); |
| 498 | |
| 499 | { |
| 500 | scoped_ptr<sql::Recovery> recovery = sql::Recovery::Begin(&db(), db_path()); |
| 501 | ASSERT_TRUE(recovery->db()->Execute(kCreateSql)); |
| 502 | |
| 503 | // Save a copy of the temp db's schema before recovering the table. |
| 504 | const char kTempSchemaSql[] = "SELECT name, sql FROM sqlite_temp_master"; |
| 505 | const std::string temp_schema( |
| 506 | ExecuteWithResults(recovery->db(), kTempSchemaSql, "|", "\n")); |
| 507 | |
| 508 | size_t rows = 0; |
| 509 | EXPECT_TRUE(recovery->AutoRecoverTable("x", 0, &rows)); |
| 510 | EXPECT_EQ(2u, rows); |
| 511 | |
| 512 | // Test that any additional temp tables were cleaned up. |
| 513 | EXPECT_EQ(temp_schema, |
| 514 | ExecuteWithResults(recovery->db(), kTempSchemaSql, "|", "\n")); |
| 515 | |
| 516 | ASSERT_TRUE(sql::Recovery::Recovered(recovery.Pass())); |
| 517 | } |
| 518 | |
| 519 | // Since the database was not corrupt, the entire schema and all |
| 520 | // data should be recovered. |
| 521 | ASSERT_TRUE(Reopen()); |
| 522 | ASSERT_EQ(orig_schema, GetSchema(&db())); |
| 523 | ASSERT_EQ(orig_data, ExecuteWithResults(&db(), kXSql, "|", "\n")); |
| 524 | |
| 525 | // Recovery fails if the target table doesn't exist. |
| 526 | { |
| 527 | scoped_ptr<sql::Recovery> recovery = sql::Recovery::Begin(&db(), db_path()); |
| 528 | ASSERT_TRUE(recovery->db()->Execute(kCreateSql)); |
| 529 | |
| 530 | // TODO(shess): Should this failure implicitly lead to Raze()? |
| 531 | size_t rows = 0; |
| 532 | EXPECT_FALSE(recovery->AutoRecoverTable("y", 0, &rows)); |
| 533 | |
| 534 | sql::Recovery::Unrecoverable(recovery.Pass()); |
| 535 | } |
| 536 | } |
| 537 | |
| 538 | // Test that default values correctly replace nulls. The recovery |
| 539 | // virtual table reads directly from the database, so DEFAULT is not |
| 540 | // interpretted at that level. |
| 541 | TEST_F(SQLRecoveryTest, AutoRecoverTableWithDefault) { |
| 542 | ASSERT_TRUE(db().Execute("CREATE TABLE x (id INTEGER)")); |
| 543 | ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (5)")); |
| 544 | ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (15)")); |
| 545 | |
| 546 | // ALTER effectively leaves the new columns NULL in the first two |
| 547 | // rows. The row with 17 will get the default injected at insert |
| 548 | // time, while the row with 42 will get the actual value provided. |
| 549 | // Embedded "'" to make sure default-handling continues to be quoted |
| 550 | // correctly. |
| 551 | ASSERT_TRUE(db().Execute("ALTER TABLE x ADD COLUMN t TEXT DEFAULT 'a''a'")); |
| 552 | ASSERT_TRUE(db().Execute("ALTER TABLE x ADD COLUMN b BLOB DEFAULT x'AA55'")); |
| 553 | ASSERT_TRUE(db().Execute("ALTER TABLE x ADD COLUMN i INT DEFAULT 93")); |
| 554 | ASSERT_TRUE(db().Execute("INSERT INTO x (id) VALUES (17)")); |
| 555 | ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (42, 'b', x'1234', 12)")); |
| 556 | |
| 557 | // Save aside a copy of the original schema and data. |
| 558 | const std::string orig_schema(GetSchema(&db())); |
| 559 | const char kXSql[] = "SELECT * FROM x ORDER BY 1"; |
| 560 | const std::string orig_data(ExecuteWithResults(&db(), kXSql, "|", "\n")); |
| 561 | |
| 562 | // Create a lame-duck table which will not be propagated by recovery to |
| 563 | // detect that the recovery code actually ran. |
| 564 | ASSERT_TRUE(db().Execute("CREATE TABLE y (c TEXT)")); |
| 565 | ASSERT_NE(orig_schema, GetSchema(&db())); |
| 566 | |
| 567 | // Mechanically adjust the stored schema and data to allow detecting |
| 568 | // where the default value is coming from. The target table is just |
| 569 | // like the original with the default for [t] changed, to signal |
| 570 | // defaults coming from the recovery system. The two %5 rows should |
| 571 | // get the target-table default for [t], while the others should get |
| 572 | // the source-table default. |
| 573 | std::string final_schema(orig_schema); |
| 574 | std::string final_data(orig_data); |
| 575 | size_t pos; |
| 576 | while ((pos = final_schema.find("'a''a'")) != std::string::npos) { |
| 577 | final_schema.replace(pos, 6, "'c''c'"); |
| 578 | } |
| 579 | while ((pos = final_data.find("5|a'a")) != std::string::npos) { |
| 580 | final_data.replace(pos, 5, "5|c'c"); |
| 581 | } |
| 582 | |
| 583 | { |
| 584 | scoped_ptr<sql::Recovery> recovery = sql::Recovery::Begin(&db(), db_path()); |
| 585 | // Different default to detect which table provides the default. |
| 586 | ASSERT_TRUE(recovery->db()->Execute(final_schema.c_str())); |
| 587 | |
| 588 | size_t rows = 0; |
| 589 | EXPECT_TRUE(recovery->AutoRecoverTable("x", 0, &rows)); |
| 590 | EXPECT_EQ(4u, rows); |
| 591 | |
| 592 | ASSERT_TRUE(sql::Recovery::Recovered(recovery.Pass())); |
| 593 | } |
| 594 | |
| 595 | // Since the database was not corrupt, the entire schema and all |
| 596 | // data should be recovered. |
| 597 | ASSERT_TRUE(Reopen()); |
| 598 | ASSERT_EQ(final_schema, GetSchema(&db())); |
| 599 | ASSERT_EQ(final_data, ExecuteWithResults(&db(), kXSql, "|", "\n")); |
| 600 | } |
| 601 | |
| 602 | // Test that rows with NULL in a NOT NULL column are filtered |
| 603 | // correctly. In the wild, this would probably happen due to |
| 604 | // corruption, but here it is simulated by recovering a table which |
| 605 | // allowed nulls into a table which does not. |
| 606 | TEST_F(SQLRecoveryTest, AutoRecoverTableNullFilter) { |
| 607 | const char kOrigSchema[] = "CREATE TABLE x (id INTEGER, t TEXT)"; |
| 608 | const char kFinalSchema[] = "CREATE TABLE x (id INTEGER, t TEXT NOT NULL)"; |
| 609 | |
| 610 | ASSERT_TRUE(db().Execute(kOrigSchema)); |
| 611 | ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (5, null)")); |
| 612 | ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (15, 'this is a test')")); |
| 613 | |
| 614 | // Create a lame-duck table which will not be propagated by recovery to |
| 615 | // detect that the recovery code actually ran. |
| 616 | ASSERT_EQ(kOrigSchema, GetSchema(&db())); |
| 617 | ASSERT_TRUE(db().Execute("CREATE TABLE y (c TEXT)")); |
| 618 | ASSERT_NE(kOrigSchema, GetSchema(&db())); |
| 619 | |
| 620 | { |
| 621 | scoped_ptr<sql::Recovery> recovery = sql::Recovery::Begin(&db(), db_path()); |
| 622 | ASSERT_TRUE(recovery->db()->Execute(kFinalSchema)); |
| 623 | |
| 624 | size_t rows = 0; |
| 625 | EXPECT_TRUE(recovery->AutoRecoverTable("x", 0, &rows)); |
| 626 | EXPECT_EQ(1u, rows); |
| 627 | |
| 628 | ASSERT_TRUE(sql::Recovery::Recovered(recovery.Pass())); |
| 629 | } |
| 630 | |
| 631 | // The schema should be the same, but only one row of data should |
| 632 | // have been recovered. |
| 633 | ASSERT_TRUE(Reopen()); |
| 634 | ASSERT_EQ(kFinalSchema, GetSchema(&db())); |
| 635 | const char kXSql[] = "SELECT * FROM x ORDER BY 1"; |
| 636 | ASSERT_EQ("15|this is a test", ExecuteWithResults(&db(), kXSql, "|", "\n")); |
| 637 | } |
| 638 | |
| 639 | // Test AutoRecoverTable with a ROWID alias. |
| 640 | TEST_F(SQLRecoveryTest, AutoRecoverTableWithRowid) { |
| 641 | // The rowid alias is almost always the first column, intentionally |
| 642 | // put it later. |
| 643 | const char kCreateSql[] = |
| 644 | "CREATE TABLE x (t TEXT, id INTEGER PRIMARY KEY NOT NULL)"; |
| 645 | ASSERT_TRUE(db().Execute(kCreateSql)); |
| 646 | ASSERT_TRUE(db().Execute("INSERT INTO x VALUES ('This is a test', null)")); |
| 647 | ASSERT_TRUE(db().Execute("INSERT INTO x VALUES ('That was a test', null)")); |
| 648 | |
| 649 | // Save aside a copy of the original schema and data. |
| 650 | const std::string orig_schema(GetSchema(&db())); |
| 651 | const char kXSql[] = "SELECT * FROM x ORDER BY 1"; |
| 652 | const std::string orig_data(ExecuteWithResults(&db(), kXSql, "|", "\n")); |
| 653 | |
| 654 | // Create a lame-duck table which will not be propagated by recovery to |
| 655 | // detect that the recovery code actually ran. |
| 656 | ASSERT_TRUE(db().Execute("CREATE TABLE y (c TEXT)")); |
| 657 | ASSERT_NE(orig_schema, GetSchema(&db())); |
| 658 | |
| 659 | { |
| 660 | scoped_ptr<sql::Recovery> recovery = sql::Recovery::Begin(&db(), db_path()); |
| 661 | ASSERT_TRUE(recovery->db()->Execute(kCreateSql)); |
| 662 | |
| 663 | size_t rows = 0; |
| 664 | EXPECT_TRUE(recovery->AutoRecoverTable("x", 0, &rows)); |
| 665 | EXPECT_EQ(2u, rows); |
| 666 | |
| 667 | ASSERT_TRUE(sql::Recovery::Recovered(recovery.Pass())); |
| 668 | } |
| 669 | |
| 670 | // Since the database was not corrupt, the entire schema and all |
| 671 | // data should be recovered. |
| 672 | ASSERT_TRUE(Reopen()); |
| 673 | ASSERT_EQ(orig_schema, GetSchema(&db())); |
| 674 | ASSERT_EQ(orig_data, ExecuteWithResults(&db(), kXSql, "|", "\n")); |
| 675 | } |
| 676 | |
| 677 | // Test that a compound primary key doesn't fire the ROWID code. |
| 678 | TEST_F(SQLRecoveryTest, AutoRecoverTableWithCompoundKey) { |
| 679 | const char kCreateSql[] = |
| 680 | "CREATE TABLE x (" |
| 681 | "id INTEGER NOT NULL," |
| 682 | "id2 TEXT NOT NULL," |
| 683 | "t TEXT," |
| 684 | "PRIMARY KEY (id, id2)" |
| 685 | ")"; |
| 686 | ASSERT_TRUE(db().Execute(kCreateSql)); |
| 687 | |
| 688 | // NOTE(shess): Do not accidentally use [id] 1, 2, 3, as those will |
| 689 | // be the ROWID values. |
| 690 | ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (1, 'a', 'This is a test')")); |
| 691 | ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (1, 'b', 'That was a test')")); |
| 692 | ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (2, 'a', 'Another test')")); |
| 693 | |
| 694 | // Save aside a copy of the original schema and data. |
| 695 | const std::string orig_schema(GetSchema(&db())); |
| 696 | const char kXSql[] = "SELECT * FROM x ORDER BY 1"; |
| 697 | const std::string orig_data(ExecuteWithResults(&db(), kXSql, "|", "\n")); |
| 698 | |
| 699 | // Create a lame-duck table which will not be propagated by recovery to |
| 700 | // detect that the recovery code actually ran. |
| 701 | ASSERT_TRUE(db().Execute("CREATE TABLE y (c TEXT)")); |
| 702 | ASSERT_NE(orig_schema, GetSchema(&db())); |
| 703 | |
| 704 | { |
| 705 | scoped_ptr<sql::Recovery> recovery = sql::Recovery::Begin(&db(), db_path()); |
| 706 | ASSERT_TRUE(recovery->db()->Execute(kCreateSql)); |
| 707 | |
| 708 | size_t rows = 0; |
| 709 | EXPECT_TRUE(recovery->AutoRecoverTable("x", 0, &rows)); |
| 710 | EXPECT_EQ(3u, rows); |
| 711 | |
| 712 | ASSERT_TRUE(sql::Recovery::Recovered(recovery.Pass())); |
| 713 | } |
| 714 | |
| 715 | // Since the database was not corrupt, the entire schema and all |
| 716 | // data should be recovered. |
| 717 | ASSERT_TRUE(Reopen()); |
| 718 | ASSERT_EQ(orig_schema, GetSchema(&db())); |
| 719 | ASSERT_EQ(orig_data, ExecuteWithResults(&db(), kXSql, "|", "\n")); |
| 720 | } |
| 721 | |
| 722 | // Test |extend_columns| support. |
| 723 | TEST_F(SQLRecoveryTest, AutoRecoverTableExtendColumns) { |
| 724 | const char kCreateSql[] = "CREATE TABLE x (id INTEGER PRIMARY KEY, t0 TEXT)"; |
| 725 | ASSERT_TRUE(db().Execute(kCreateSql)); |
| 726 | ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (1, 'This is')")); |
| 727 | ASSERT_TRUE(db().Execute("INSERT INTO x VALUES (2, 'That was')")); |
| 728 | |
| 729 | // Save aside a copy of the original schema and data. |
| 730 | const std::string orig_schema(GetSchema(&db())); |
| 731 | const char kXSql[] = "SELECT * FROM x ORDER BY 1"; |
| 732 | const std::string orig_data(ExecuteWithResults(&db(), kXSql, "|", "\n")); |
| 733 | |
| 734 | // Modify the table to add a column, and add data to that column. |
| 735 | ASSERT_TRUE(db().Execute("ALTER TABLE x ADD COLUMN t1 TEXT")); |
| 736 | ASSERT_TRUE(db().Execute("UPDATE x SET t1 = 'a test'")); |
| 737 | ASSERT_NE(orig_schema, GetSchema(&db())); |
| 738 | ASSERT_NE(orig_data, ExecuteWithResults(&db(), kXSql, "|", "\n")); |
| 739 | |
| 740 | { |
| 741 | scoped_ptr<sql::Recovery> recovery = sql::Recovery::Begin(&db(), db_path()); |
| 742 | ASSERT_TRUE(recovery->db()->Execute(kCreateSql)); |
| 743 | size_t rows = 0; |
| 744 | EXPECT_TRUE(recovery->AutoRecoverTable("x", 1, &rows)); |
| 745 | EXPECT_EQ(2u, rows); |
| 746 | ASSERT_TRUE(sql::Recovery::Recovered(recovery.Pass())); |
| 747 | } |
| 748 | |
| 749 | // Since the database was not corrupt, the entire schema and all |
| 750 | // data should be recovered. |
| 751 | ASSERT_TRUE(Reopen()); |
| 752 | ASSERT_EQ(orig_schema, GetSchema(&db())); |
| 753 | ASSERT_EQ(orig_data, ExecuteWithResults(&db(), kXSql, "|", "\n")); |
| 754 | } |
Ben Murdoch | 2385ea3 | 2013-08-06 11:01:04 +0100 | [diff] [blame] | 755 | #endif // !defined(USE_SYSTEM_SQLITE) |
| 756 | |
Ben Murdoch | ca12bfa | 2013-07-23 11:17:05 +0100 | [diff] [blame] | 757 | } // namespace |