summaryrefslogtreecommitdiff
path: root/project2/sql/sqlTest.cpp
blob: a4375f113e50b4b334a059c0f848fa2ed628dd4d (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
#include "pch.hpp"
#include "sqlTest.h"
#include "scriptLoader.h"
#include "selectcommand.h"
#include "column.h"
#include "rdbmsDataSource.h"
#include "commonObjects.h"
#include "sqlVariableBinder.h"
#include <boost/foreach.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

DECLARE_LOADER("sqltest", SqlTest);

class CantCompareNulls : public std::exception { };

SqlTest::SqlTest(ScriptNodePtr p) :
	SourceObject(p),
	Test(p),
	dataSource(p, "datasource"),
	filter(p, "filter", ""),
	testOp(p, "testOp", "=="),
	testValue(p, "testValue"),
	sqlCommand(p->child("sql")),
	db(NULL)
{
}

SqlTest::~SqlTest()
{
}

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

class HandleDoCompare : public DB::HandleField {
	public:
		HandleDoCompare(const VariableType & tV, const std::string & tO) :
			retVal(false),
			testValue(tV),
			testOp(tO) {
		}
		void null() {
			throw CantCompareNulls();
		}
		void string(const char *c , size_t l) {
			doTest(Glib::ustring(c, c + l));
		}
		void integer(int64_t val) {
			doTest(val);
		}
		void floatingpoint(double val) {
			doTest(val);
		}
		void timestamp(const struct tm & val) {
			doTest(boost::posix_time::ptime_from_tm(val));
		}
		bool operator()() const {
			return retVal;
		}
	private:
		template <typename TV>
		void doTest(const TV & val) {
			TV tv = testValue;
			if ((testOp == "==" || testOp == "=") && val == tv) {
				retVal = true;
			}
			else if (testOp == "<" && val < tv) {
				retVal = true;
			}
			else if (testOp == ">" && val > tv) {
				retVal = true;
			}
			else if (testOp == "!=" && val != tv) {
				retVal = true;
			}
			else if ((testOp == "<=" || testOp == "=<") && val <= tv) {
				retVal = true;
			}
			else if ((testOp == ">=" || testOp == "=>") && val >= tv) {
				retVal = true;
			}
		}
		bool retVal;
		const VariableType & testValue;
		std::string testOp;
};
bool
SqlTest::passes() const
{
	boost::shared_ptr<DB::SelectCommand> query = boost::shared_ptr<DB::SelectCommand>(
			db->getWritable().newSelectCommand(sqlCommand.getSqlFor(filter())));
	unsigned int offset = 0;
	sqlCommand.bindParams(query.get(), offset);
	HandleDoCompare h(testValue, testOp());
	while (query->fetch()) {
		(*query)[0].apply(h);
	}
	return h();
}