summaryrefslogtreecommitdiff
path: root/project2/common/variables/lookup.cpp
blob: 42ddff2f56b53a84c7eeee873620920d877c788a (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
#include <pch.hpp>
#include "../variables.h"
#include <safeMapFind.h>
#include "../logger.h"
#include "../rowProcessor.h"
#include "../rowSet.h"
#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", NULL).as<Glib::ustring>())
		{
			e->script->loader.addLoadTarget(e, Storer::into<ElementLoader>(&rowSets));
		}
		VariableType value(ExecContext * ec) const
		{
			if (map.empty()) {
				fillCache(ec);
			}
			Key k;
			k.reserve(parameters.size());
			for (const Parameters::value_type & p : parameters) {
				k.push_back(p.second(ec));
			}
			return AdHoc::safeMapLookup<NotFound>(map, k);
		}
	private:
		void fillCache(ExecContext * ec) const
		{
			for (const RowSets::value_type & rs : rowSets) {
				rs->execute(filter, boost::bind(&VariableLookup::rowReady, this, _1, ec), ec);
			}
			Logger()->messagef(LOG_DEBUG, "%s: %s has filled cached with %zu items",
					__PRETTY_FUNCTION__, name.c_str(), map.size());
		}
		void rowReady(const RowState * rs, ExecContext * ec) const
		{
			Key k;
			for (const Parameters::value_type & p : parameters) {
				k.push_back(rs->getCurrentValue(ec, p.first));
			}
			map[k] = rs->getCurrentValue(ec, name);
		}
		mutable Map map;
		typedef ANONSTORAGEOF(RowSet) RowSets;
		RowSets rowSets;
		const Glib::ustring name;
};
DECLARE_COMPONENT_LOADER("lookup", VariableLookup, VariableLoader);