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