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
|
#include <pch.hpp>
#include "cache.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 <boost/foreach.hpp>
#include "options.h"
#include <boost/algorithm/string/predicate.hpp>
typedef boost::shared_ptr<DB::SelectCommand> SelectPtr;
typedef boost::shared_ptr<DB::ModifyCommand> ModifyPtr;
class SqlCache : public Cache {
public:
SqlCache(ScriptNodePtr p) :
Cache(p),
db(NULL)
{
}
void loadComplete(const CommonObjects * co)
{
db = co->dataSource<RdbmsDataSource>(DataSource);
}
static void appendKeyCols(Buffer * sql, unsigned int * off, const Glib::ustring & col)
{
if ((*off)++) {
sql->append(", ");
}
sql->append(col.c_str());
}
static void appendKeyBinds(Buffer * sql, unsigned int * off)
{
if ((*off)++) {
sql->append(", ");
}
sql->append("?");
}
static void appendKeyAnds(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) :
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 RowProcessor * rp) 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;
}
}
BOOST_FOREACH(const unsigned int & c, colCols) {
const DB::Column & col = (*s)[c];
col.apply(h);
ss.fields[&c - &colCols.front()] = h.variable;
}
ss.process(rp);
}
} while (s->fetch());
}
private:
SelectPtr s;
mutable std::vector<unsigned int> colCols;
mutable int64_t cacheId;
};
RowSetCPtr getCachedRowSet(const Glib::ustring & n, const Glib::ustring & f, const IHaveParameters * ps) const
{
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(boost::bind(appendKeyAnds, &sql, _1), ps);
sql.appendf(" ORDER BY r.p2_cacheid DESC, r.p2_row");
SelectPtr gh(db->getReadonly().newSelectCommand(sql));
unsigned int offset = 0;
gh->bindParamT(offset++, time(NULL) - CacheLife);
applyKeys(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 {
Buffer sql;
sql.appendf("INSERT INTO %s_%s_%s_rows(p2_row", HeaderTable.c_str(), n.c_str(), f.c_str());
BOOST_FOREACH(const Values::value_type & a, attrs) {
sql.appendf(", p2attr_%s", a.first.c_str());
}
BOOST_FOREACH(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(")");
ModifyPtr m(db->getWritable().newModifyCommand(sql));
unsigned int offset = 0;
m->bindParamI(offset++, row++);
BOOST_FOREACH(const Values::value_type & a, attrs) {
boost::apply_visitor<const SqlVariableBinder, const VariableType>(SqlVariableBinder(m.get(), offset++), a.second);
}
BOOST_FOREACH(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(const Glib::ustring & n, const Glib::ustring & f, const IHaveParameters * ps)
{
Buffer sp;
sp.appendf("SAVEPOINT sp%p", this);
ModifyPtr s = ModifyPtr(db->getWritable().newModifyCommand(sp));
s->execute();
// Header
Buffer del;
del.appendf("INSERT INTO %s(p2_time) VALUES(?)", HeaderTable.c_str());
ModifyPtr h = ModifyPtr(db->getWritable().newModifyCommand(del));
h->bindParamT(0, time(NULL));
h->execute();
// Record set header
Buffer sql;
sql.appendf("INSERT INTO %s_%s_%s(", HeaderTable.c_str(), n.c_str(), f.c_str());
unsigned int offset = 0;
applyKeys(boost::bind(appendKeyCols, &sql, &offset, _1), ps);
sql.appendf(") VALUES(");
offset = 0;
applyKeys(boost::bind(appendKeyBinds, &sql, &offset), ps);
sql.appendf(")");
ModifyPtr m(db->getWritable().newModifyCommand(sql));
offset = 0;
applyKeys(boost::bind(bindKeyValues, m.get(), &offset, _2), ps);
m->execute();
return new SqlCachePresenter(n, f, db);
}
void save(const Glib::ustring & , const Glib::ustring & , const IHaveParameters * )
{
Buffer sp;
sp.appendf("RELEASE SAVEPOINT sp%p", this);
ModifyPtr s = ModifyPtr(db->getWritable().newModifyCommand(sp));
s->execute();
}
void discard(const Glib::ustring & , const Glib::ustring & , const IHaveParameters * )
{
Buffer sp;
sp.appendf("ROLLBACK TO SAVEPOINT sp%p", this);
ModifyPtr s = ModifyPtr(db->getWritable().newModifyCommand(sp));
s->execute();
}
INITOPTIONS;
private:
friend class CustomSqlCacheLoader;
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 CustomSqlCacheLoader : public ElementLoader::For<SqlCache> {
public:
void onIdle()
{
if (!SqlCache::DataSource.empty()) {
boost::intrusive_ptr<CommonObjects> co = new CommonObjects();
RdbmsDataSource * db = co->dataSource<RdbmsDataSource>(SqlCache::DataSource);
Buffer del;
del.appendf("DELETE FROM %s WHERE p2_time < ?", SqlCache::HeaderTable.c_str());
ModifyPtr m(db->getWritable().newModifyCommand(del));
m->bindParamT(0, time(NULL) - SqlCache::CacheLife);
m->execute();
db->commit();
}
}
};
DECLARE_CUSTOM_LOADER("sqlcache", CustomSqlCacheLoader);
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)
|