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