Home | History | Annotate | Download | only in test
      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 
      5 #include "sql/test/test_helpers.h"
      6 
      7 #include <string>
      8 
      9 #include "base/file_util.h"
     10 #include "sql/connection.h"
     11 #include "sql/statement.h"
     12 #include "testing/gtest/include/gtest/gtest.h"
     13 
     14 namespace {
     15 
     16 size_t CountSQLItemsOfType(sql::Connection* db, const char* type) {
     17   const char kTypeSQL[] = "SELECT COUNT(*) FROM sqlite_master WHERE type = ?";
     18   sql::Statement s(db->GetUniqueStatement(kTypeSQL));
     19   s.BindCString(0, type);
     20   EXPECT_TRUE(s.Step());
     21   return s.ColumnInt(0);
     22 }
     23 
     24 // Get page size for the database.
     25 bool GetPageSize(sql::Connection* db, int* page_size) {
     26   sql::Statement s(db->GetUniqueStatement("PRAGMA page_size"));
     27   if (!s.Step())
     28     return false;
     29   *page_size = s.ColumnInt(0);
     30   return true;
     31 }
     32 
     33 // Get |name|'s root page number in the database.
     34 bool GetRootPage(sql::Connection* db, const char* name, int* page_number) {
     35   const char kPageSql[] = "SELECT rootpage FROM sqlite_master WHERE name = ?";
     36   sql::Statement s(db->GetUniqueStatement(kPageSql));
     37   s.BindString(0, name);
     38   if (!s.Step())
     39     return false;
     40   *page_number = s.ColumnInt(0);
     41   return true;
     42 }
     43 
     44 // Helper for reading a number from the SQLite header.
     45 // See net/base/big_endian.h.
     46 unsigned ReadBigEndian(unsigned char* buf, size_t bytes) {
     47   unsigned r = buf[0];
     48   for (size_t i = 1; i < bytes; i++) {
     49     r <<= 8;
     50     r |= buf[i];
     51   }
     52   return r;
     53 }
     54 
     55 // Helper for writing a number to the SQLite header.
     56 void WriteBigEndian(unsigned val, unsigned char* buf, size_t bytes) {
     57   for (size_t i = 0; i < bytes; i++) {
     58     buf[bytes - i - 1] = (val & 0xFF);
     59     val >>= 8;
     60   }
     61 }
     62 
     63 }  // namespace
     64 
     65 namespace sql {
     66 namespace test {
     67 
     68 bool CorruptSizeInHeader(const base::FilePath& db_path) {
     69   // See http://www.sqlite.org/fileformat.html#database_header
     70   const size_t kHeaderSize = 100;
     71   const size_t kPageSizeOffset = 16;
     72   const size_t kFileChangeCountOffset = 24;
     73   const size_t kPageCountOffset = 28;
     74   const size_t kVersionValidForOffset = 92;  // duplicate kFileChangeCountOffset
     75 
     76   unsigned char header[kHeaderSize];
     77 
     78   file_util::ScopedFILE file(base::OpenFile(db_path, "rb+"));
     79   if (!file.get())
     80     return false;
     81 
     82   if (0 != fseek(file.get(), 0, SEEK_SET))
     83     return false;
     84   if (1u != fread(header, sizeof(header), 1, file.get()))
     85     return false;
     86 
     87   int64 db_size = 0;
     88   if (!base::GetFileSize(db_path, &db_size))
     89     return false;
     90 
     91   const unsigned page_size = ReadBigEndian(header + kPageSizeOffset, 2);
     92 
     93   // One larger than the expected size.
     94   const unsigned page_count = (db_size + page_size) / page_size;
     95   WriteBigEndian(page_count, header + kPageCountOffset, 4);
     96 
     97   // Update change count so outstanding readers know the info changed.
     98   // Both spots must match for the page count to be considered valid.
     99   unsigned change_count = ReadBigEndian(header + kFileChangeCountOffset, 4);
    100   WriteBigEndian(change_count + 1, header + kFileChangeCountOffset, 4);
    101   WriteBigEndian(change_count + 1, header + kVersionValidForOffset, 4);
    102 
    103   if (0 != fseek(file.get(), 0, SEEK_SET))
    104     return false;
    105   if (1u != fwrite(header, sizeof(header), 1, file.get()))
    106     return false;
    107 
    108   return true;
    109 }
    110 
    111 bool CorruptTableOrIndex(const base::FilePath& db_path,
    112                          const char* tree_name,
    113                          const char* update_sql) {
    114   sql::Connection db;
    115   if (!db.Open(db_path))
    116     return false;
    117 
    118   int page_size = 0;
    119   if (!GetPageSize(&db, &page_size))
    120     return false;
    121 
    122   int page_number = 0;
    123   if (!GetRootPage(&db, tree_name, &page_number))
    124     return false;
    125 
    126   // SQLite uses 1-based page numbering.
    127   const long int page_ofs = (page_number - 1) * page_size;
    128   scoped_ptr<char[]> page_buf(new char[page_size]);
    129 
    130   // Get the page into page_buf.
    131   file_util::ScopedFILE file(base::OpenFile(db_path, "rb+"));
    132   if (!file.get())
    133     return false;
    134   if (0 != fseek(file.get(), page_ofs, SEEK_SET))
    135     return false;
    136   if (1u != fread(page_buf.get(), page_size, 1, file.get()))
    137     return false;
    138 
    139   // Require the page to be a leaf node.  A multilevel tree would be
    140   // very hard to restore correctly.
    141   if (page_buf[0] != 0xD && page_buf[0] != 0xA)
    142     return false;
    143 
    144   // The update has to work, and make changes.
    145   if (!db.Execute(update_sql))
    146     return false;
    147   if (db.GetLastChangeCount() == 0)
    148     return false;
    149 
    150   // Ensure that the database is fully flushed.
    151   db.Close();
    152 
    153   // Check that the stored page actually changed.  This catches usage
    154   // errors where |update_sql| is not related to |tree_name|.
    155   scoped_ptr<char[]> check_page_buf(new char[page_size]);
    156   // The on-disk data should have changed.
    157   if (0 != fflush(file.get()))
    158     return false;
    159   if (0 != fseek(file.get(), page_ofs, SEEK_SET))
    160     return false;
    161   if (1u != fread(check_page_buf.get(), page_size, 1, file.get()))
    162     return false;
    163   if (!memcmp(check_page_buf.get(), page_buf.get(), page_size))
    164     return false;
    165 
    166   // Put the original page back.
    167   if (0 != fseek(file.get(), page_ofs, SEEK_SET))
    168     return false;
    169   if (1u != fwrite(page_buf.get(), page_size, 1, file.get()))
    170     return false;
    171 
    172   return true;
    173 }
    174 
    175 size_t CountSQLTables(sql::Connection* db) {
    176   return CountSQLItemsOfType(db, "table");
    177 }
    178 
    179 size_t CountSQLIndices(sql::Connection* db) {
    180   return CountSQLItemsOfType(db, "index");
    181 }
    182 
    183 size_t CountTableColumns(sql::Connection* db, const char* table) {
    184   // TODO(shess): sql::Connection::QuoteForSQL() would make sense.
    185   std::string quoted_table;
    186   {
    187     const char kQuoteSQL[] = "SELECT quote(?)";
    188     sql::Statement s(db->GetUniqueStatement(kQuoteSQL));
    189     s.BindCString(0, table);
    190     EXPECT_TRUE(s.Step());
    191     quoted_table = s.ColumnString(0);
    192   }
    193 
    194   std::string sql = "PRAGMA table_info(" + quoted_table + ")";
    195   sql::Statement s(db->GetUniqueStatement(sql.c_str()));
    196   size_t rows = 0;
    197   while (s.Step()) {
    198     ++rows;
    199   }
    200   EXPECT_TRUE(s.Succeeded());
    201   return rows;
    202 }
    203 
    204 bool CountTableRows(sql::Connection* db, const char* table, size_t* count) {
    205   // TODO(shess): Table should probably be quoted with [] or "".  See
    206   // http://www.sqlite.org/lang_keywords.html .  Meanwhile, odd names
    207   // will throw an error.
    208   std::string sql = "SELECT COUNT(*) FROM ";
    209   sql += table;
    210   sql::Statement s(db->GetUniqueStatement(sql.c_str()));
    211   if (!s.Step())
    212     return false;
    213 
    214   *count = s.ColumnInt64(0);
    215   return true;
    216 }
    217 
    218 bool CreateDatabaseFromSQL(const base::FilePath& db_path,
    219                            const base::FilePath& sql_path) {
    220   if (base::PathExists(db_path) || !base::PathExists(sql_path))
    221     return false;
    222 
    223   std::string sql;
    224   if (!base::ReadFileToString(sql_path, &sql))
    225     return false;
    226 
    227   sql::Connection db;
    228   if (!db.Open(db_path))
    229     return false;
    230 
    231   // TODO(shess): Android defaults to auto_vacuum mode.
    232   // Unfortunately, this makes certain kinds of tests which manipulate
    233   // the raw database hard/impossible to write.
    234   // http://crbug.com/307303 is for exploring this test issue.
    235   ignore_result(db.Execute("PRAGMA auto_vacuum = 0"));
    236 
    237   return db.Execute(sql.c_str());
    238 }
    239 
    240 std::string IntegrityCheck(sql::Connection* db) {
    241   sql::Statement statement(db->GetUniqueStatement("PRAGMA integrity_check"));
    242 
    243   // SQLite should always return a row of data.
    244   EXPECT_TRUE(statement.Step());
    245 
    246   return statement.ColumnString(0);
    247 }
    248 
    249 }  // namespace test
    250 }  // namespace sql
    251