summaryrefslogtreecommitdiff
path: root/lib/output/pq/updateDatabase.cpp
blob: 232e8f9fa0dc5f63055bc5651f05fb0977d0ba8a (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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
#include "updateDatabase.h"
#include "pqConn.h"
#include "typeMapper.h"
#include <compileTimeFormatter.h>
#include <cstdint>
#include <dbRecordSet.h>
#include <eventSourceBase.h>
#include <helpers.h>
#include <input/mysqlConn.h>
#include <input/mysqlRecordSet.h>
#include <input/replStream.h>
#include <input/sql/selectColumns.h>
#include <input/sql/showMasterStatus.h>
#include <memory>
#include <mysql_types.h>
#include <output/pq/sql/insertColumn.h>
#include <output/pq/sql/insertSource.h>
#include <output/pq/sql/insertTable.h>
#include <output/pq/sql/selectColumns.h>
#include <output/pq/sql/selectSource.h>
#include <output/pq/sql/selectSourceSchema.h>
#include <output/pq/sql/selectTables.h>
#include <output/pq/sql/updateSourcePosition.h>
#include <output/pq/sql/updateSourceRotate.h>
#include <row.h>
#include <stdexcept>
#include <streamSupport.h>

namespace MyGrate::Output::Pq {
#ifndef __cpp_aggregate_paren_init
	ColumnDef::ColumnDef(std::string n, std::size_t o, bool p) : name {std::move(n)}, ordinal(o), is_pk(p) { }
#endif

	UpdateDatabase::UpdateDatabase(const char * const str, uint64_t s) : UpdateDatabase {PqConn {str}, s} { }

	UpdateDatabase::UpdateDatabase(PqConn && conn, uint64_t s) :
		UpdateDatabase {std::forward<PqConn>(conn), s, output::pq::sql::selectSourceSchema::execute(&conn, s)}
	{
	}

	UpdateDatabase::UpdateDatabase(PqConn && conn, uint64_t s, RecordSetPtr cfg) :
		PqConn {std::move(conn)}, source {s}, schema(cfg->at(0, 0)),
		database(cfg->at(0, 1)), selected {tables.end()}, table_map {nullptr, nullptr}
	{
		auto trecs = output::pq::sql::selectTables::execute(this, source);
		auto crecs = output::pq::sql::selectColumns::execute(this, source);
		for (auto t {0U}; t < trecs->rows(); t++) {
			tables.emplace(trecs->at(t, 0), std::make_unique<TableOutput>(*crecs, trecs->at(t, 0)));
		}
	}

	EventSourceBasePtr
	UpdateDatabase::getSource()
	{
		auto srcrec = output::pq::sql::selectSource::execute(this, source);
		verify<ConfigError>(srcrec->rows() == 1, "Wrong number of source config rows");
		return (*srcrec)[0].create<Input::ReplicationStream, 7>();
	}

	TableOutput::TableOutput(const RecordSet & crecs, std::string_view name) : keys {0}
	{
		for (auto c {0U}; c < crecs.rows(); c++) {
			if (crecs.at(c, 0) == name) {
				const auto & cd = columns.emplace_back(crecs[c].create<ColumnDef, 3, 1>());
				if (cd->is_pk) {
					keys += 1;
				}
			}
		}
	}

	UpdateDatabase
	UpdateDatabase::createNew(PqConn * pq, const char * host, const char * username, const char * password,
			unsigned short port, const char * db, int sid, const char * schema)
	{
		Input::MySQLConn my {host, username, password, port};
		auto ms = input::sql::showMasterStatus::execute(&my);
		auto source_id = Tx {pq}([&]() {
			pq->query(scprintf<"CREATE SCHEMA IF NOT EXISTS %?">(schema).c_str());
			return **output::pq::sql::insertSource::execute(
					pq, host, username, password, port, db, ms->at(0, 0), ms->at(0, 1), sid, schema);
		});
		return UpdateDatabase(pq->connstr.c_str(), source_id);
	}

	void
	UpdateDatabase::addTable(Input::MySQLConn * conn, const char * tableName)
	{
		// Assumes a readonly or transaction supporting table
		conn->query("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ");
		conn->query(scprintf<"LOCK TABLE %? READ">(tableName).c_str());
		Tx {conn}([&] {
			auto pos = *(*input::sql::showMasterStatus::execute(conn))[0].create<MySQL::ReplicationPosition, 2>();
			conn->query("UNLOCK TABLES");
			// Consistent unlocked view of table during transaction
			auto cols = input::sql::selectColumns::execute(conn, tableName);
			verify<std::logic_error>(cols->rows() > 0, "Table has no rows");
			auto tableDef {std::make_unique<TableOutput>()};
			Tx {this}([&] {
				const auto table_id
						= **output::pq::sql::insertTable::execute(this, tableName, source, pos.filename, pos.position);
				std::stringstream ct;
				scprintf<"CREATE TABLE %?.%?(">(ct, schema, tableName);
				TypeMapper tm;
				for (auto col : *cols) {
					output::pq::sql::insertColumn::execute(this, col[0], col.currentRow(), table_id);
					if (col.currentRow()) {
						ct << ',';
					}
					scprintf<"%? %?">(ct, col[0], tm.map(col[2], scprintf<"%?.%?">(tableName, col[0])));
					if (!col[1]) {
						ct << " not null";
					}
					if (col[3]) {
						ct << " primary key";
						tableDef->keys += 1;
					}
					tableDef->columns.push_back(
							std::make_unique<ColumnDef>(col[0], tableDef->columns.size() + 1, col[3]));
				}
				ct << ")";
				this->query(ct.str().c_str());
				this->copyTableContent(conn, tableName, tableDef);
			});
			tables.emplace(tableName, std::move(tableDef));
		});
	}

	struct WritePqCopyStream {
		explicit WritePqCopyStream(FILE * o) : out {o} { }
		WritePqCopyStream(const WritePqCopyStream &) = delete;
		WritePqCopyStream(WritePqCopyStream &&) = delete;
		WritePqCopyStream & operator=(const WritePqCopyStream &) = delete;
		WritePqCopyStream & operator=(WritePqCopyStream &&) = delete;

		~WritePqCopyStream()
		{
			fputc('\n', out);
		}

		void
		nextField()
		{
			fputc('\t', out);
		}

		void operator()(std::nullptr_t) const
		{
			fputs("\\N", out);
		}
#define BASIC_PRINT(T, fmt) \
	void operator()(T v) const \
	{ \
		fprintf(out, fmt, v); \
	}
		BASIC_PRINT(double, "%f")
		BASIC_PRINT(float, "%f")
		BASIC_PRINT(int8_t, "%hhd")
		BASIC_PRINT(uint8_t, "%hhu")
		BASIC_PRINT(int16_t, "%hd")
		BASIC_PRINT(uint16_t, "%hu")
		BASIC_PRINT(int32_t, "%d")
		BASIC_PRINT(uint32_t, "%u")
		BASIC_PRINT(int64_t, "%ld")
		BASIC_PRINT(uint64_t, "%lu")
#undef BASIC_PRINT
		void operator()(timespec) const
		{
			throw std::logic_error("timespec not implemented");
		}
		void
		operator()(Date v) const
		{
			fprintf(out, "%d-%d-%d", v.year, v.month, v.day);
		}
		void
		operator()(Time v) const
		{
			fprintf(out, "%d:%d:%d", v.hour, v.minute, v.second);
		}
		void
		operator()(DateTime v) const
		{
			operator()(static_cast<Date &>(v));
			fputc('T', out);
			operator()(static_cast<Time &>(v));
		}
		void
		operator()(std::string_view v) const
		{
			auto pos {v.begin()};
			while (pos != v.end()) {
				auto esc = std::find_if(pos, v.end(), [](unsigned char c) {
					return std::iscntrl(c);
				});
				if (esc != pos) {
					fwrite(pos, esc - pos, 1, out);
					pos = esc;
				}
				while (pos != v.end()) {
					fprintf(out, "\\%03o", *pos);
					pos++;
				}
			}
		}
		void operator()(BitSet) const
		{
			throw std::logic_error("bitset not implemented");
		}
		void
		operator()(Blob v) const
		{
			fputs("\\\\x", out);
			std::for_each(v.begin(), v.end(), [this](auto b) {
				fprintf(out, "%02hhx", (uint8_t)b);
			});
		}

		FILE * out;
	};

	void
	UpdateDatabase::copyTableContent(Input::MySQLConn * conn, const char * table, const TableDefPtr & tableDef)
	{
		auto out = beginBulkUpload(schema.c_str(), table);
		auto sourceSelect = [&tableDef](auto table) {
			std::stringstream sf;
			unsigned int ordinal {0};
			for (const auto & col : tableDef->columns) {
				scprintf<"%? %?">(sf, !ordinal++ ? "SELECT " : ", ", col->name);
			}
			sf << " FROM " << table;
			return sf.str();
		};
		auto stmt {conn->prepare(sourceSelect(table).c_str(), 0)};
		stmt->execute({});
		auto sourceCursor {stmt->cursor()};

		const auto cols = sourceCursor->columns();
		while (sourceCursor->fetch()) {
			WritePqCopyStream cs {out};
			for (auto ordinal {0U}; ordinal < cols; ordinal += 1) {
				if (ordinal) {
					cs.nextField();
				}
				sourceCursor->at(ordinal).visit(cs);
			}
		}

		fclose(out);
	}

	void
	UpdateDatabase::tableMap(MariaDB_Event_Ptr e)
	{
		if (*e->event.table_map.database == database) {
			selected = tables.find(*e->event.table_map.table);
			table_map = std::move(e);
		}
		else {
			selected = tables.end();
			table_map.reset();
		}
	}

	void
	UpdateDatabase::beforeEvent(const MariaDB_Event_Ptr &)
	{
		beginTx();
	}

	void
	UpdateDatabase::afterEvent(const MariaDB_Event_Ptr & e)
	{
		output::pq::sql::updateSourcePosition::execute(this, e->next_event_pos, source);
		commitTx();
	}

	void
	UpdateDatabase::verifyRow(const MariaDB_Event_Ptr & e, const TableDefPtr & out)
	{
		verify<std::runtime_error>(
				e->event.rows.column_count == out->columns.size(), "Incorrect number of columns in row data");
	}

	void
	UpdateDatabase::copyKeys(const Row & r, const TableDefPtr & td, std::back_insert_iterator<Row> && out)
	{
		std::copy_if(r.begin(), r.end(), out, [c = td->columns.begin()](auto &&) mutable {
			return (c++)->get()->is_pk;
		});
	}

	void
	UpdateDatabase::updateRow(MariaDB_Event_Ptr e)
	{
		if (selected != tables.end()) {
			auto & out = selected->second;
			verifyRow(e, out);
			if (!out->update) {
				std::stringstream ou;
				std::size_t ordinal {0}, kordinal {out->columns.size()};

				scprintf<"UPDATE %?.%? ">(ou, schema, selected->first);
				for (const auto & col : out->columns) {
					scprintf<"%? %? = $%?">(ou, !ordinal ? " SET " : ", ", col->name, ordinal + 1);
					ordinal++;
				}
				for (const auto & col : out->columns) {
					if (col->is_pk) {
						scprintf<"%? %? = $%?">(
								ou, kordinal == out->columns.size() ? " WHERE " : " AND ", col->name, kordinal + 1);
						kordinal++;
					}
				}

				out->update = prepare(ou.str().c_str(), kordinal);
			}
			beforeEvent(e);
			auto rows {Row::fromRowsEvent(e->event.rows, table_map->event.table_map)};
			verify<ReplicationError>(rows.size() % 2 == 0, "Odd number of update rows");
			for (auto rp = rows.begin(); rp != rows.end(); rp++) {
				copyKeys(*rp, out, std::back_inserter(*rp));
				out->update->execute(*rp);
				verify<ReplicationError>(out->update->rows() == 1, "Wrong number of rows updated.");
			}
			afterEvent(e);
		}
	}

	void
	UpdateDatabase::deleteRow(MariaDB_Event_Ptr e)
	{
		if (selected != tables.end()) {
			auto & out = selected->second;
			verifyRow(e, out);
			if (!out->deleteFrom) {
				std::stringstream ou;
				std::size_t kordinal {0};

				scprintf<"DELETE FROM %?.%? ">(ou, schema, selected->first);
				for (const auto & col : out->columns) {
					if (col->is_pk) {
						scprintf<"%? %? = $%?">(ou, !kordinal ? " WHERE " : " AND ", col->name, kordinal + 1);
						kordinal++;
					}
				}

				out->deleteFrom = prepare(ou.str().c_str(), kordinal);
			}
			beforeEvent(e);
			for (auto & r : Row::fromRowsEvent(e->event.rows, table_map->event.table_map)) {
				Row keys;
				copyKeys(r, out, std::back_inserter(keys));
				out->deleteFrom->execute(keys);
				verify<ReplicationError>(out->deleteFrom->rows() == 1, "Wrong number of rows deleted.");
			}
			afterEvent(e);
		}
	}

	void
	UpdateDatabase::insertRow(MariaDB_Event_Ptr e)
	{
		if (selected != tables.end()) {
			auto & out = selected->second;
			verifyRow(e, out);
			if (!out->insertInto) {
				std::stringstream ou;
				std::size_t ordinal {0}, vordinal {0};

				scprintf<"INSERT INTO %?.%? ">(ou, schema, selected->first);
				for (const auto & col : out->columns) {
					scprintf<"%? %?">(ou, !ordinal++ ? "(" : ", ", col->name);
				}
				ou << ") VALUES";
				for (const auto & col : out->columns) {
					scprintf<"%? $%?">(ou, !vordinal++ ? "(" : ", ", vordinal);
					(void)col;
				}
				ou << ")";

				out->insertInto = prepare(ou.str().c_str(), out->columns.size());
			}
			beforeEvent(e);
			for (const auto & r : Row::fromRowsEvent(e->event.rows, table_map->event.table_map)) {
				out->insertInto->execute(r);
				verify<ReplicationError>(out->insertInto->rows() == 1, "Wrong number of rows updated.");
			}
			afterEvent(e);
		}
	}

	void
	UpdateDatabase::rotate(MariaDB_Event_Ptr e)
	{
		if ((e->flags & LOG_EVENT_ARTIFICIAL_F) == 0) {
			beforeEvent(e);
			output::pq::sql::updateSourceRotate::execute(
					this, *e->event.rotate.filename, e->event.rotate.position, source);
			afterEvent(e);
		}
	}
}