create table for each relation v_0
authorFrantišek Kučera <franta-hg@frantovo.cz>
Tue, 30 Jul 2019 18:40:35 +0200
branchv_0
changeset 6 32b4293307f4
parent 5 cbc7817a3346
child 7 9119b29d1e7c
create table for each relation
src/SqlHandler.h
--- a/src/SqlHandler.h	Tue Jul 30 17:06:41 2019 +0200
+++ b/src/SqlHandler.h	Tue Jul 30 18:40:35 2019 +0200
@@ -19,6 +19,7 @@
 
 #include <memory>
 #include <string>
+#include <sstream>
 #include <vector>
 #include <locale>
 #include <codecvt>
@@ -127,6 +128,7 @@
 	writer::RelationalWriter* relationalWriter;
 	std::wstring_convert<codecvt_utf8<wchar_t>> convertor; // TODO: support also other encodings
 	std::unique_ptr<Connection> connection;
+	relpipe::writer::string_t currentInsert;
 
 	void processStatement(const Statement& statement) {
 		PreparedStatement prepared = connection->prepareStatement(convertor.to_bytes(statement.sql).c_str());
@@ -149,6 +151,19 @@
 		}
 	}
 
+	relpipe::writer::string_t toSQLType(relpipe::reader::TypeId typeId) {
+		if (typeId == relpipe::reader::TypeId::BOOLEAN) return L"boolean";
+		else if (typeId == relpipe::reader::TypeId::INTEGER) return L"integer";
+		else return L"text";
+	}
+
+	void writeIdentifier(std::wstringstream& output, relpipe::writer::string_t identifier) {
+		for (auto & ch : identifier) {
+			if (ch == L'"') output << L"\"\"";
+			else output << ch;
+		}
+	}
+
 public:
 
 	SqlHandler(writer::RelationalWriter* relationalWriter, Configuration& configuration) : relationalWriter(relationalWriter), configuration(configuration) {
@@ -160,7 +175,20 @@
 	}
 
 	void startRelation(string_t name, vector<AttributeMetadata> attributes) override {
+		std::wstringstream sql;
+		sql << L"CREATE TABLE ";
+		writeIdentifier(sql, name);
+		sql << L" (\n";
+		for (int i = 0; i < attributes.size(); i++) {
+			sql << L"\t";
+			writeIdentifier(sql, attributes[i].getAttributeName());
+			sql << L" " << toSQLType(attributes[i].getTypeId());
+			if (i < attributes.size() - 1) sql << L",\n";
+		}
+		sql << L"\n)";
 
+		PreparedStatement createTable = connection->prepareStatement(convertor.to_bytes(sql.str()).c_str());
+		createTable.next();
 	}
 
 	void attribute(const string_t& value) override {
@@ -169,7 +197,7 @@
 
 	void endOfPipe() {
 		for (const Statement& statement : configuration.statements) processStatement(statement);
-		
+
 		if (configuration.file.size() && !configuration.keepFile) {
 			int result = unlink(convertor.to_bytes(configuration.file).c_str());
 			if (result) throw SqlException(L"Unable to delete SQLite file.");