Repository navigation
Expand file tree
/
Copy pathDataTypesCache.h
More file actions
56 lines (45 loc) · 1.5 KB
/
Copy pathDataTypesCache.h
File metadata and controls
56 lines (45 loc) · 1.5 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#pragma once
#include <DataTypes/IDataType.h>
#include <DataTypes/DataTypeFactory.h>
namespace DB
{
const size_t MAX_DATA_TYPES_ELEMENTS = 16;
/// Simple cache of data types and their serializations to avoid creating
/// them from String using FormatFactory or creating shared_ptr explicitly.
/// It is helpful when we need to create the same data types multiple times
/// (for example in Dynamic data type).
class DataTypesCache
{
public:
struct Element
{
DataTypePtr type;
SerializationPtr serialization;
};
DataTypePtr getType(const String & type_name)
{
return getCacheElement(type_name).type;
}
SerializationPtr getSerialization(const String & type_name)
{
return getCacheElement(type_name).serialization;
}
private:
const Element & getCacheElement(const String & type_name)
{
auto it = cache.find(type_name);
if (it != cache.end())
return it->second;
/// If cache is full, just clear it.
if (cache.size() >= MAX_DATA_TYPES_ELEMENTS)
cache.clear();
auto type = DataTypeFactory::instance().get(type_name);
it = cache.emplace(type_name, Element{type, type->getDefaultSerialization()}).first;
return it->second;
}
std::unordered_map<String, Element> cache;
};
/// Return instance of a thread local cache.
/// Cache is relatively small, so it's ok to have separate instance per thread to avoid using mutex inside the cache.
DataTypesCache & getDataTypesCache();
}