summaryrefslogtreecommitdiff
path: root/libmysqlpp/my-connection.cpp
blob: 97924e34b275eff7a4309c593c2342a9d95b5697 (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
#include "my-connection.h"
#include "my-error.h"
#include "my-selectcommand.h"
#include "my-modifycommand.h"
#include <nvpParse.h>
#include <runtimeContext.h>
#include <ucontext.h>
#include <optional>
#include <compileTimeFormatter.h>

NAMEDFACTORY("mysql", MySQL::Connection, DB::ConnectionFactory);

MySQL::ConnectionError::ConnectionError(MYSQL * m) :
	MySQL::Error(m)
{
}

class Opts {
	public:
		Opts() { port = 3306; }
		using OptString = std::optional<std::string>;
		OptString server;
		OptString user;
		OptString password;
		OptString database;
		unsigned int port;
		OptString unix_socket;
		OptString options;
};

const char *
operator~(const Opts::OptString & os)
{
	if (os) {
		return os->c_str();
	}
	return nullptr;
}

namespace std {
	template <typename T>
	std::istream &
	operator>>(std::istream & s, std::optional<T> & o)
	{
		o = T();
		return (s >> *o);
	}
}

using namespace AdHoc;
NvpTarget(Opts) OptsTargetMap {
	NvpValue(Opts, server),
	NvpValue(Opts, user),
	NvpValue(Opts, password),
	NvpValue(Opts, database),
	NvpValue(Opts, unix_socket),
	NvpValue(Opts, port),
	NvpValue(Opts, options),
};


MySQL::Connection::Connection(const std::string & str) :
	conn({})
{
	std::stringstream i(str);
	Opts o;
	NvpParse::parse(i, OptsTargetMap, o);
	mysql_init(&conn);
	if (o.options) {
		mysql_options(&conn, MYSQL_READ_DEFAULT_GROUP, ~o.options);
	}
	if (!mysql_real_connect(&conn, ~o.server, ~o.user, ~o.password, ~o.database,
				// NOLINTNEXTLINE(hicpp-signed-bitwise)
				o.port, ~o.unix_socket, CLIENT_LOCAL_FILES | CLIENT_MULTI_STATEMENTS)) {
		throw ConnectionError(&conn);
	}
	if (mysql_set_character_set(&conn, "utf8")) {
		throw ConnectionError(&conn);
	}
}

MySQL::Connection::~Connection()
{
	mysql_close(&conn);
}

void
MySQL::Connection::beginTxInt()
{
	if (mysql_autocommit(&conn, 0)) {
		throw Error(&conn);
	}
}

void
MySQL::Connection::commitTxInt()
{
	if (mysql_commit(&conn)) {
		throw Error(&conn);
	}
}

void
MySQL::Connection::rollbackTxInt()
{
	if (mysql_rollback(&conn)) {
		throw Error(&conn);
	}
}

DB::BulkDeleteStyle
MySQL::Connection::bulkDeleteStyle() const
{
	return DB::BulkDeleteUsingUsingAlias;
}

DB::BulkUpdateStyle
MySQL::Connection::bulkUpdateStyle() const
{
	return DB::BulkUpdateUsingJoin;
}

void
MySQL::Connection::ping() const
{
	if (mysql_ping(&conn)) {
		throw Error(&conn);
	}
}


DB::SelectCommandPtr
MySQL::Connection::select(const std::string & sql, const DB::CommandOptionsCPtr &)
{
	return std::make_shared<SelectCommand>(this, sql);
}

DB::ModifyCommandPtr
MySQL::Connection::modify(const std::string & sql, const DB::CommandOptionsCPtr &)
{
	return std::make_shared<ModifyCommand>(this, sql);
}

namespace MySQL {
	class LoadContext : public AdHoc::System::RuntimeContext {
		public:
			explicit LoadContext(MYSQL * c) :
				loadBuf(nullptr),
				loadBufLen(0),
				bufOff(0),
				conn(c),
				loadReturn(0)
			{
			}

			static int local_infile_init(void ** ptr, const char *, void * ctx) {
				*ptr = ctx;
				return 0;
			}

			static int local_infile_read(void * obj, char * buf, unsigned int bufSize) {
				auto ctx = static_cast<LoadContext *>(obj);
				if (ctx->loadBufLen - ctx->bufOff == 0) {
					ctx->swapContext();
					if (ctx->loadBufLen - ctx->bufOff <= 0) {
						// Nothing to do or error
						return ctx->bufOff;
					}
				}
				auto copy = std::min<size_t>(ctx->loadBufLen - ctx->bufOff, bufSize);
				memcpy(buf, ctx->loadBuf + ctx->bufOff, copy);
				ctx->bufOff += copy;
				return copy;
			}

			static void local_infile_end(void *) {
			}

			static int local_infile_error(void *, char*, unsigned int) {
				return 0;
			}

			void callback() override
			{
				loadReturn = mysql_read_query_result(conn);
			}

			const char * loadBuf;
			size_t loadBufLen;
			size_t bufOff;
			MYSQL * conn;
			int loadReturn;
	};
}

AdHocFormatter(MySQLConnectionLoadData, "LOAD DATA LOCAL INFILE 'any' INTO TABLE %? %?");
void
MySQL::Connection::beginBulkUpload(const char * table, const char * extra)
{
	auto sql = MySQLConnectionLoadData::get(table, extra);
	mysql_send_query(&conn, sql.c_str(), sql.length());

	ctx = std::make_unique<LoadContext>(&conn);

	mysql_set_local_infile_handler(&conn, LoadContext::local_infile_init, LoadContext::local_infile_read,
			LoadContext::local_infile_end, LoadContext::local_infile_error, ctx.get());

	ctx->swapContext();
}

void
MySQL::Connection::endBulkUpload(const char * msg)
{
	ctx->loadBuf = nullptr;
	ctx->loadBufLen = 0;
	ctx->bufOff = msg ? -1 : 0;
	// switch context with empty buffer fires finished
	ctx->swapContext();
	// Check result
	if (!msg) {
		if (ctx->loadReturn) {
			ctx.reset();
			throw Error(&conn);
		}
	}
	ctx.reset();
}

size_t
MySQL::Connection::bulkUploadData(const char * data, size_t len) const
{
	ctx->loadBuf = data;
	ctx->loadBufLen = len;
	ctx->bufOff = 0;
	// switch context to load the buffered data
	ctx->swapContext();
	return len;
}

int64_t
MySQL::Connection::insertId()
{
	return mysql_insert_id(&conn);
}