summaryrefslogtreecommitdiff
path: root/lib/output/pq/updateDatabase.cpp
blob: 6a0f4191882c5854a6b12ab495ac7bdc2df1a0bf (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
#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 <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 <stdexcept>
#include <streamSupport.h>

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

	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))
	{
		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)
	{
		for (auto c {0U}; c < crecs.rows(); c++) {
			if (crecs.at(c, 0) == name) {
				columns.emplace_back(crecs[c].create<ColumnDef, 3, 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)
	{
		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);
			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->columns.push_back(std::make_unique<ColumnDef>(col[0], tableDef->columns.size() + 1, col[3]));
			}
			ct << ")";
			this->query(ct.str().c_str());
		});
		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)
	{
		auto out = beginBulkUpload(schema.c_str(), table);
		auto sourceSelect = [this](auto table) {
			std::stringstream sf;
			unsigned int ordinal {0};
			for (const auto & col : tables.at(table)->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);
	}
}