1//===----------------------------------------------------------------------===//
2// DuckDB
3//
4// duckdb/storage/object_cache.hpp
5//
6//
7//===----------------------------------------------------------------------===//
8
9#pragma once
10
11#include "duckdb/common/common.hpp"
12#include "duckdb/common/string.hpp"
13#include "duckdb/common/unordered_map.hpp"
14#include "duckdb/common/mutex.hpp"
15#include "duckdb/main/client_context.hpp"
16#include "duckdb/main/database.hpp"
17
18namespace duckdb {
19class ClientContext;
20
21//! ObjectCache is the base class for objects caches in DuckDB
22class ObjectCacheEntry {
23public:
24 virtual ~ObjectCacheEntry() {
25 }
26
27 virtual string GetObjectType() = 0;
28};
29
30class ObjectCache {
31public:
32 shared_ptr<ObjectCacheEntry> GetObject(const string &key) {
33 lock_guard<mutex> glock(lock);
34 auto entry = cache.find(x: key);
35 if (entry == cache.end()) {
36 return nullptr;
37 }
38 return entry->second;
39 }
40
41 template <class T>
42 shared_ptr<T> Get(const string &key) {
43 shared_ptr<ObjectCacheEntry> object = GetObject(key);
44 if (!object || object->GetObjectType() != T::ObjectType()) {
45 return nullptr;
46 }
47 return std::static_pointer_cast<T, ObjectCacheEntry>(object);
48 }
49
50 void Put(string key, shared_ptr<ObjectCacheEntry> value) {
51 lock_guard<mutex> glock(lock);
52 cache[key] = std::move(value);
53 }
54
55 DUCKDB_API static ObjectCache &GetObjectCache(ClientContext &context);
56 DUCKDB_API static bool ObjectCacheEnabled(ClientContext &context);
57
58private:
59 //! Object Cache
60 unordered_map<string, shared_ptr<ObjectCacheEntry>> cache;
61 mutex lock;
62};
63
64} // namespace duckdb
65