summaryrefslogtreecommitdiff
path: root/project2/common/variables/lookup.cpp
blob: 2a963381bb9a4c2e986c869c25128ae40fb84b0c (plain)
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <pch.hpp>
#include "../variables.h"
#include <safeMapFind.h>
#include "../logger.h"
#include "../rowProcessor.h"
#include "../rowSet.h"
#include <boost/foreach.hpp>
#include "../scriptLoader.h"
#include "../scriptStorage.h"


/// Variable implementation that looks up it's value in a map of key(s)/value pairs
class VariableLookup : public VariableImplDyn, public RowProcessor {
	private:
		typedef std::vector<VariableType> Key;
		typedef std::map<Key, VariableType> Map;
	public:
		class NotFound : public std::runtime_error {
			public:
				NotFound(const Key & k) :
					std::runtime_error(mklist(k)) {
				}
				static std::string mklist(const Key & k) {
					std::string l("(");
					for (Key::const_iterator kp = k.begin(); kp != k.end(); ++kp) {
						if (kp != k.begin()) l += ", ";
						l += kp->operator const std::string &();
					}
					l += ")";
					return l;
				}
		};
		VariableLookup(ScriptNodePtr e) :
			VariableImplDyn(e),
			RowProcessor(e),
			name(e->value("name").as<Glib::ustring>())
		{
			e->script->loader.addLoadTarget(e, Storer::into<ElementLoader>(&rowSets));
		}
		VariableType value() const
		{
			if (map.empty()) {
				fillCache();
			}
			Key k;
			k.reserve(parameters.size());
			BOOST_FOREACH(const Parameters::value_type & p, parameters) {
				k.push_back(p.second);
			}
			return safeMapLookup<NotFound>(map, k);
		}
	private:
		void fillCache() const
		{
			BOOST_FOREACH(const RowSets::value_type & rs, rowSets) {
				rs->execute(filter, this);
			}
			Logger()->messagef(LOG_DEBUG, "%s: %s has filled cached with %zu items",
					__PRETTY_FUNCTION__, name.c_str(), map.size());
		}
		void rowReady(const RowState * rs) const
		{
			Key k;
			BOOST_FOREACH(const Parameters::value_type & p, parameters) {
				k.push_back(rs->getCurrentValue(p.first));
			}
			map[k] = rs->getCurrentValue(name);
		}
		mutable Map map;
		typedef ANONSTORAGEOF(RowSet) RowSets;
		RowSets rowSets;
		const Glib::ustring name;
};
DECLARE_COMPONENT_LOADER("lookup", VariableLookup, VariableLoader);