Cache.h 4.2 KB
Newer Older
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#ifndef CACHE_H
#define CACHE_H

#include <memory>
#include <mutex>
#include <unordered_map>

#include "SqliteTools.h"

template <typename TYPE>
class PrimaryKeyCacheKeyPolicy
{
    public:
        typedef unsigned int KeyType;
        static unsigned int key( const std::shared_ptr<TYPE>& self )
        {
            return self->id();
        }
        static unsigned int key( sqlite3_stmt* stmt )
        {
            return Traits<unsigned int>::Load( stmt, 0 );
        }
};

/**
 * This utility class eases up the implementation of caching.
 *
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
28
29
30
31
32
33
34
35
36
37
38
 * It is driven by 2 policy classes:
 * - TABLEPOLICY describes the basics required to fetch a record. It has 2 static fields:
 *      - Name: the table name
 *      - CacheColumn: The column used to cache records.
 * - CACHEPOLICY describes which column to use for caching by providing two "key" methods.
 *   One that takes a sqlite3_stmt and one that takes an instance of the type being cached
 *
 * The default CACHEPOLICY implementation bases itself on an unsigned int column, assumed
 * to be the primary key, at index 0 of a fetch statement.
 *
 * Other template parameter:
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
39
40
41
42
43
 * - IMPL: The actual implementation. Typically the type that inherits this class
 * - INTF: An interface that express the type. This is used when fetching containers, as they
 *         are not polymorphic.
 *
 * How to use it:
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
44
 * - Inherit this class and specify the template parameter & policies accordingly
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
45
46
47
48
49
50
51
52
53
54
55
56
 * - Make this class a friend class of the class you inherit from
 */
template <typename IMPL, typename INTF, typename TABLEPOLICY, typename CACHEPOLICY = PrimaryKeyCacheKeyPolicy<IMPL>>
class Cache
{
    public:
        static std::shared_ptr<IMPL> fetch( sqlite3* dbConnection, const typename CACHEPOLICY::KeyType& key )
        {
            std::lock_guard<std::mutex> lock( Mutex );
            auto it = Store.find( key );
            if ( it != Store.end() )
                return it->second;
57
            static const std::string req = "SELECT * FROM" + TABLEPOLICY::Name +
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
58
59
60
61
62
63
64
65
66
67
68
69
70
71
                            " WHERE " + TABLEPOLICY::CacheColumn + " = ?";
            auto res = SqliteTools::fetchOne<IMPL>( dbConnection, req.c_str(), key );
            Store[key] = res;
            return res;
        }

        /*
         * Will fetch all elements from the database & cache them.
         *
         * @param res   A reference to the result vector. All existing elements will
         *              be discarded.
         */
        static bool fetchAll( sqlite3* dbConnection, std::vector<std::shared_ptr<INTF>>& res )
        {
72
            static const std::string req = "SELECT * FROM " + TABLEPOLICY::Name;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
            return SqliteTools::fetchAll<IMPL, INTF>( dbConnection, req.c_str(), res );
        }

        static std::shared_ptr<IMPL> load( sqlite3* dbConnection, sqlite3_stmt* stmt )
        {
            auto cacheKey = CACHEPOLICY::key( stmt );

            std::lock_guard<std::mutex> lock( Mutex );
            auto it = Store.find( cacheKey );
            if ( it != Store.end() )
                return it->second;
            auto inst = std::make_shared<IMPL>( dbConnection, stmt );
            Store[cacheKey] = inst;
            return inst;
        }

        /*
         * Create a new instance of the cache class.
         * This doesn't check for the existence of a similar entity already cached.
         */
        template <typename... Args>
        static std::shared_ptr<IMPL> create( Args&&... args )
        {
            auto res = std::make_shared<IMPL>( std::forward<Args>( args )... );

            typename CACHEPOLICY::KeyType cacheKey = CACHEPOLICY::key( res );

            std::lock_guard<std::mutex> lock( Mutex );
            Store[cacheKey] = res;
            return res;
        }

    private:
        static std::unordered_map<typename CACHEPOLICY::KeyType, std::shared_ptr<IMPL>> Store;
        static std::mutex Mutex;
};

template <typename IMPL, typename INTF, typename TABLEPOLICY, typename CACHEPOLICY>
std::unordered_map<typename CACHEPOLICY::KeyType, std::shared_ptr<IMPL>>
Cache<IMPL, INTF, TABLEPOLICY, CACHEPOLICY>::Store;

template <typename IMPL, typename INTF, typename TABLEPOLICY, typename CACHEPOLICY>
std::mutex Cache<IMPL, INTF, TABLEPOLICY, CACHEPOLICY>::Mutex;

#endif // CACHE_H