test_helpers.cc revision 4e180b6a0b4720a9b8e9e959a882386f690f08ff
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 14namespace { 15 16size_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} // namespace 25 26namespace sql { 27namespace test { 28 29size_t CountSQLTables(sql::Connection* db) { 30 return CountSQLItemsOfType(db, "table"); 31} 32 33size_t CountSQLIndices(sql::Connection* db) { 34 return CountSQLItemsOfType(db, "index"); 35} 36 37size_t CountTableColumns(sql::Connection* db, const char* table) { 38 // TODO(shess): sql::Connection::QuoteForSQL() would make sense. 39 std::string quoted_table; 40 { 41 const char kQuoteSQL[] = "SELECT quote(?)"; 42 sql::Statement s(db->GetUniqueStatement(kQuoteSQL)); 43 s.BindCString(0, table); 44 EXPECT_TRUE(s.Step()); 45 quoted_table = s.ColumnString(0); 46 } 47 48 std::string sql = "PRAGMA table_info(" + quoted_table + ")"; 49 sql::Statement s(db->GetUniqueStatement(sql.c_str())); 50 size_t rows = 0; 51 while (s.Step()) { 52 ++rows; 53 } 54 EXPECT_TRUE(s.Succeeded()); 55 return rows; 56} 57 58bool CountTableRows(sql::Connection* db, const char* table, size_t* count) { 59 // TODO(shess): Table should probably be quoted with [] or "". See 60 // http://www.sqlite.org/lang_keywords.html . Meanwhile, odd names 61 // will throw an error. 62 std::string sql = "SELECT COUNT(*) FROM "; 63 sql += table; 64 sql::Statement s(db->GetUniqueStatement(sql.c_str())); 65 if (!s.Step()) 66 return false; 67 68 *count = s.ColumnInt64(0); 69 return true; 70} 71 72bool CreateDatabaseFromSQL(const base::FilePath& db_path, 73 const base::FilePath& sql_path) { 74 if (base::PathExists(db_path) || !base::PathExists(sql_path)) 75 return false; 76 77 std::string sql; 78 if (!base::ReadFileToString(sql_path, &sql)) 79 return false; 80 81 sql::Connection db; 82 if (!db.Open(db_path)) 83 return false; 84 85 // TODO(shess): Android defaults to auto_vacuum mode. 86 // Unfortunately, this makes certain kinds of tests which manipulate 87 // the raw database hard/impossible to write. 88 // http://crbug.com/307303 is for exploring this test issue. 89 ignore_result(db.Execute("PRAGMA auto_vacuum = 0")); 90 91 return db.Execute(sql.c_str()); 92} 93 94} // namespace test 95} // namespace sql 96