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 #ifndef CHROME_BROWSER_EXTENSIONS_ACTIVITY_LOG_DATABASE_STRING_TABLE_H_ 6 #define CHROME_BROWSER_EXTENSIONS_ACTIVITY_LOG_DATABASE_STRING_TABLE_H_ 7 8 #include <map> 9 #include <string> 10 11 #include "base/basictypes.h" 12 13 namespace sql { 14 class Connection; 15 } // namespace sql 16 17 namespace extensions { 18 19 // A class for maintaining a persistent mapping between strings and integers. 20 // This is used to help compress the contents of the activity log database on 21 // disk by replacing repeated strings by smaller integers. 22 // 23 // The mapping from integers to strings is maintained in a database table, but 24 // the mapping is also cached in memory. 25 // 26 // The database table used to store the strings is configurable, but its layout 27 // is fixed: it always consists of just two columns, "id" and "value". 28 // 29 // All calls to DatabaseStringTable must occur on the database thread. 30 class DatabaseStringTable { 31 public: 32 explicit DatabaseStringTable(const std::string& table); 33 34 ~DatabaseStringTable(); 35 36 // Initialize the database table. This will create the table if it does not 37 // exist. Returns true on success; false on error. 38 bool Initialize(sql::Connection* connection); 39 40 // Interns a string in the database table and sets *id to the corresponding 41 // integer. If the string already exists, the existing number is returned; 42 // otherwise, new database row is inserted with the new string. Returns true 43 // on success and false on database error. 44 bool StringToInt(sql::Connection* connection, 45 const std::string& value, 46 int64* id); 47 48 // Looks up an integer value and converts it to a string (which is stored in 49 // *value). Returns true on success. A false return does not necessarily 50 // indicate a database error; it might simply be that the value cannot be 51 // found. 52 bool IntToString(sql::Connection* connection, int64 id, std::string* value); 53 54 // Clear the in-memory cache; this should be called if the underlying 55 // database table has been manipulated and the cache may be stale. 56 void ClearCache(); 57 58 private: 59 // In-memory caches of recently accessed values. 60 std::map<int64, std::string> id_to_value_; 61 std::map<std::string, int64> value_to_id_; 62 63 // The name of the database table where the mapping is stored. 64 std::string table_; 65 66 DISALLOW_COPY_AND_ASSIGN(DatabaseStringTable); 67 }; 68 69 } // namespace extensions 70 71 #endif // CHROME_BROWSER_EXTENSIONS_ACTIVITY_LOG_DATABASE_STRING_TABLE_H_ 72