summaryrefslogtreecommitdiff
path: root/project2/sql/sqlCache.cpp
blob: cc2b451769fae2bf2c3f29406b9e834dce4bcdbf (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
#include <pch.hpp>
#include "rowSetCache.h"
#include "sqlVariableBinder.h"
#include "sqlHandleAsVariableType.h"
#include "buffer.h"
#include "selectcommand.h"
#include "modifycommand.h"
#include "column.h"
#include "commonObjects.h"
#include "rdbmsDataSource.h"
#include "logger.h"
#include "scriptLoader.h"
#include "iHaveParameters.h"
#include "rowSet.h"
#include "options.h"
#include <boost/algorithm/string/predicate.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

typedef boost::shared_ptr<DB::SelectCommand> SelectPtr;
typedef boost::shared_ptr<DB::ModifyCommand> ModifyPtr;

class SqlCache : public RowSetCache {
	public:
		SqlCache(ScriptNodePtr p) :
			RowSetCache(p),
			db(NULL)
		{
		}

		void loadComplete(const CommonObjects * co)
		{
			db = co->dataSource<RdbmsDataSource>(DataSource);
		}

		static void appendKeyCols(AdHoc::Buffer * sql, unsigned int * off, const Glib::ustring & col)
		{
			if ((*off)++) {
				sql->append(", ");
			}
			sql->append(col.c_str());
		}

		static void appendKeyBinds(AdHoc::Buffer * sql, unsigned int * off)
		{
			if ((*off)++) {
				sql->append(", ");
			}
			sql->append("?");
		}

		static void appendKeyAnds(AdHoc::Buffer * sql, const Glib::ustring & col)
		{
			sql->appendf(" AND h.%s = ?", col.c_str());
		}

		static void bindKeyValues(DB::Command * cmd, unsigned int * offset, const VariableType & v)
		{
			boost::apply_visitor<const SqlVariableBinder, const VariableType>(SqlVariableBinder(cmd, (*offset)++), v);
		}

		class SqlCacheRowSet : public RowSet {
			public:
				SqlCacheRowSet(SelectPtr r) :
					SourceObject(ScriptNodePtr()),
					RowSet(NULL),
					s(r) {
				}
				class SqlCacheRowState : public RowState {
					public:
						SqlCacheRowState(const SqlCacheRowSet * s) :
							sc(s) {
							}
						const Columns & getColumns() const {
							return columns;
						}
						RowAttribute resolveAttr(const Glib::ustring & attrName) const {
							return boost::bind(&SqlCacheRowState::getAttrCol, this, "p2attr_" + attrName);
						}
					private:
						VariableType getAttrCol(const Glib::ustring & col) const {
							HandleAsVariableType h;
							(*sc->s)[col].apply(h);
							return h.variable;
						}
						mutable Columns columns;
						friend class SqlCacheRowSet;
						const SqlCacheRowSet * sc;
				};
				void execute(const Glib::ustring&, const RowProcessorCallback & rp, ExecContext * ec) const {
					SqlCacheRowState ss(this);
					HandleAsVariableType h;
					do {
						if (!(*s)["p2_cacheid"].isNull()) {
							if (colCols.empty()) {
								(*s)["p2_cacheid"].apply(h);
								cacheId = h.variable;
								unsigned int colNo = 0;
								for (unsigned int c = 0; c < s->columnCount(); c++) {
									const DB::Column & col = (*s)[c];
									if (!boost::algorithm::starts_with(col.name, "p2attr_") &&
											!boost::algorithm::starts_with(col.name, "p2_")) {
										ss.columns.insert(new Column(colNo++, col.name));
										colCols.push_back(c);
									}
								}
								ss.fields.resize(colCols.size());
							}
							else {
								(*s)["p2_cacheid"].apply(h);
								if (cacheId != (int64_t)h.variable) {
									break;
								}
							}
							for (const unsigned int & c : colCols) {
								const DB::Column & col = (*s)[c];
								col.apply(h);
								ss.fields[&c - &colCols.front()] = h.variable;
							}
							ss.process(ec, rp);
						}
					} while (s->fetch());
				}
			private:
				SelectPtr s;
				mutable std::vector<unsigned int> colCols;
				mutable int64_t cacheId;
		};

		RowSetCPtr getCachedRowSet(ExecContext * ec, const Glib::ustring & n, const Glib::ustring & f, const IHaveParameters * ps) const
		{
			AdHoc::Buffer sql;
			sql.appendf("SELECT r.* \
					FROM %s p, %s_%s_%s h LEFT OUTER JOIN %s_%s_%s_rows r \
						ON h.p2_cacheid = r.p2_cacheid \
					WHERE p.p2_time > ? \
					AND p.p2_cacheid = h.p2_cacheid",
					HeaderTable.c_str(),
					HeaderTable.c_str(), n.c_str(), f.c_str(),
					HeaderTable.c_str(),n.c_str(), f.c_str());
			applyKeys(ec, boost::bind(appendKeyAnds, &sql, _1), ps);
			sql.appendf(" ORDER BY r.p2_cacheid DESC, r.p2_row");
			auto con = db->getReadonly();
			SelectPtr gh(con->newSelectCommand(sql));
			unsigned int offset = 0;
			gh->bindParamT(offset++, boost::posix_time::microsec_clock::universal_time() - boost::posix_time::seconds(CacheLife));
			applyKeys(ec, boost::bind(bindKeyValues, gh.get(), &offset, _2), ps);
			if (gh->fetch()) {
				return new SqlCacheRowSet(gh);
			}
			return NULL;
		}

		class SqlCachePresenter : public RowSetPresenter {
			public:
				SqlCachePresenter(const Glib::ustring & name, const Glib::ustring & filter, const RdbmsDataSource * d) :
					row(1),
					db(d),
					n(name),
					f(filter) {
				}
				void addNewRow(const Glib::ustring &) const {
				}
				void addAttribute(const Glib::ustring & name, const VariableType & value) const {
					attrs[name] = value;
				}
				void addNamedValue(const Glib::ustring & name, const VariableType & value) const {
					cols[name] = value;
				}
				void finishRow() const {
					AdHoc::Buffer sql;
					sql.appendf("INSERT INTO %s_%s_%s_rows(p2_row", HeaderTable.c_str(), n.c_str(), f.c_str());
					for (const Values::value_type & a : attrs) {
						sql.appendf(", p2attr_%s", a.first.c_str());
					}
					for (const Values::value_type & v : cols) {
						sql.appendf(", %s", v.first.c_str());
					}
					sql.appendf(") VALUES(?");
					for (size_t x = attrs.size(); x > 0; x -= 1) {
						sql.append(", ?");
					}
					for (size_t x = cols.size(); x > 0; x -= 1) {
						sql.append(", ?");
					}
					sql.appendf(")");
					auto con = db->getWritable();
					ModifyPtr m(con->newModifyCommand(sql));
					unsigned int offset = 0;
					m->bindParamI(offset++, row++);
					for (const Values::value_type & a : attrs) {
						boost::apply_visitor<const SqlVariableBinder, const VariableType>(SqlVariableBinder(m.get(), offset++), a.second);
					}
					for (const Values::value_type & v : cols) {
						boost::apply_visitor<const SqlVariableBinder, const VariableType>(SqlVariableBinder(m.get(), offset++), v.second);
					}
					m->execute();
					cols.clear();
					attrs.clear();
				}
			private:
				mutable unsigned int row;
				const RdbmsDataSource * db;
				const Glib::ustring n, f;
				typedef std::map<Glib::ustring, VariableType> Values;
				mutable Values cols, attrs;
		};

		RowSetPresenterPtr openFor(ExecContext * ec, const Glib::ustring & n, const Glib::ustring & f, const IHaveParameters * ps)
		{
			AdHoc::Buffer sp;
			sp.appendf("SAVEPOINT sp%p", this);
			auto con = db->getWritable();
			ModifyPtr s = ModifyPtr(con->newModifyCommand(sp));
			s->execute();
			// Header
			AdHoc::Buffer del;
			del.appendf("INSERT INTO %s(p2_time) VALUES(?)", HeaderTable.c_str());
			ModifyPtr h = ModifyPtr(con->newModifyCommand(del));
			h->bindParamT(0, boost::posix_time::microsec_clock::universal_time());
			h->execute();
			// Record set header
			AdHoc::Buffer sql;
			sql.appendf("INSERT INTO %s_%s_%s(", HeaderTable.c_str(), n.c_str(), f.c_str());
			unsigned int offset = 0;
			applyKeys(ec, boost::bind(appendKeyCols, &sql, &offset, _1), ps);
			sql.appendf(") VALUES(");
			offset = 0;
			applyKeys(ec, boost::bind(appendKeyBinds, &sql, &offset), ps);
			sql.appendf(")");
			ModifyPtr m(con->newModifyCommand(sql));
			offset = 0;
			applyKeys(ec, boost::bind(bindKeyValues, m.get(), &offset, _2), ps);
			m->execute();
			return new SqlCachePresenter(n, f, db);
		}

		void save(ExecContext *, const Glib::ustring & , const Glib::ustring & , const IHaveParameters * )
		{
			AdHoc::Buffer sp;
			sp.appendf("RELEASE SAVEPOINT sp%p", this);
			auto con = db->getWritable();
			ModifyPtr s = ModifyPtr(con->newModifyCommand(sp));
			s->execute();
		}

		void discard(ExecContext *, const Glib::ustring & , const Glib::ustring & , const IHaveParameters * )
		{
			AdHoc::Buffer sp;
			sp.appendf("ROLLBACK TO SAVEPOINT sp%p", this);
			auto con = db->getWritable();
			ModifyPtr s = ModifyPtr(con->newModifyCommand(sp));
			s->execute();
		}

		INITOPTIONS;
	private:
		friend class CustomSqlCacheFactory;
		const RdbmsDataSource * db;
		static std::string DataSource;
		static std::string HeaderTable;
		static time_t CacheLife;
};

std::string SqlCache::DataSource;
std::string SqlCache::HeaderTable;
time_t SqlCache::CacheLife;

class CustomSqlCacheFactory : public RowSetCacheFactory::For<SqlCache>, public LifeCycle {
	public:
		void onIdle() override
		{
			try {
				if (!SqlCache::DataSource.empty()) {
					boost::intrusive_ptr<CommonObjects> co = new CommonObjects();
					RdbmsDataSource * db = co->dataSource<RdbmsDataSource>(SqlCache::DataSource);
					auto con = db->getWritable();
					ModifyPtr m(con->newModifyCommand(stringbf("DELETE FROM %s WHERE p2_time < ?", SqlCache::HeaderTable)));
					m->bindParamT(0, boost::posix_time::microsec_clock::universal_time() - boost::posix_time::seconds(SqlCache::CacheLife));
					m->execute();
					db->commit();
				}
			}
			catch (...) {
				Logger()->messagebf(LOG_WARNING, "Failed to purge expired caches from table %s", SqlCache::HeaderTable);
			}
		}
};
NAMEDPLUGIN("sqlcache", CustomSqlCacheFactory, RowSetCacheFactory);

DECLARE_OPTIONS(SqlCache, "SQL Cache options")
("cache.sql.dataSource", Options::value(&DataSource),
 "The default datasource to connect to")
("cache.sql.headerTable", Options::value(&HeaderTable, "p2cache"),
 "The filename to store the data in")
("cache.sql.life", Options::value(&CacheLife, 3600),
 "The age of cache entries after which they are removed (seconds)")
END_OPTIONS(SqlCache)