]> granicus.if.org Git - icinga2/blob - lib/db_ido/dbtype.hpp
Merge pull request #7185 from Icinga/bugfix/gelfwriter-wrong-log-facility
[icinga2] / lib / db_ido / dbtype.hpp
1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
2
3 #ifndef DBTYPE_H
4 #define DBTYPE_H
5
6 #include "db_ido/i2-db_ido.hpp"
7 #include "base/object.hpp"
8 #include "base/registry.hpp"
9 #include "base/singleton.hpp"
10 #include <set>
11
12 namespace icinga
13 {
14
15 class DbObject;
16
17 /**
18  * A database object type.
19  *
20  * @ingroup ido
21  */
22 class DbType final : public Object
23 {
24 public:
25         DECLARE_PTR_TYPEDEFS(DbType);
26
27         typedef std::function<intrusive_ptr<DbObject> (const intrusive_ptr<DbType>&, const String&, const String&)> ObjectFactory;
28         typedef std::map<String, DbType::Ptr> TypeMap;
29         typedef std::map<std::pair<String, String>, intrusive_ptr<DbObject> > ObjectMap;
30
31         DbType(String name, String table, long tid, String idcolumn, ObjectFactory factory);
32
33         String GetName() const;
34         String GetTable() const;
35         long GetTypeID() const;
36         String GetIDColumn() const;
37
38         static void RegisterType(const DbType::Ptr& type);
39
40         static DbType::Ptr GetByName(const String& name);
41         static DbType::Ptr GetByID(long tid);
42
43         intrusive_ptr<DbObject> GetOrCreateObjectByName(const String& name1, const String& name2);
44
45         static std::set<DbType::Ptr> GetAllTypes();
46
47 private:
48         String m_Name;
49         String m_Table;
50         long m_TypeID;
51         String m_IDColumn;
52         ObjectFactory m_ObjectFactory;
53
54         static boost::mutex& GetStaticMutex();
55         static TypeMap& GetTypes();
56
57         ObjectMap m_Objects;
58 };
59
60 /**
61  * A registry for DbType objects.
62  *
63  * @ingroup ido
64  */
65 class DbTypeRegistry : public Registry<DbTypeRegistry, DbType::Ptr>
66 {
67 public:
68         static DbTypeRegistry *GetInstance();
69 };
70
71 /**
72  * Factory function for DbObject-based classes.
73  *
74  * @ingroup ido
75  */
76 template<typename T>
77 intrusive_ptr<T> DbObjectFactory(const DbType::Ptr& type, const String& name1, const String& name2)
78 {
79         return new T(type, name1, name2);
80 }
81
82 #define REGISTER_DBTYPE(name, table, tid, idcolumn, type) \
83         INITIALIZE_ONCE([]() { \
84                 DbType::Ptr dbtype = new DbType(#name, table, tid, idcolumn, DbObjectFactory<type>); \
85                 DbType::RegisterType(dbtype); \
86         })
87
88 }
89
90 #endif /* DBTYPE_H */