src/SqlHandler.h
branchv_0
changeset 12 0b38339b871b
parent 11 ccf19c7e7adf
child 14 eacacf060755
--- a/src/SqlHandler.h	Tue Oct 22 16:04:23 2019 +0200
+++ b/src/SqlHandler.h	Tue Oct 22 16:04:56 2019 +0200
@@ -24,6 +24,7 @@
 #include <codecvt>
 #include <unistd.h>
 #include <cassert>
+#include <sys/stat.h>
 
 #include <sqlite3.h>
 
@@ -140,6 +141,7 @@
 class SqlHandler : public RelationalReaderValueHandler {
 private:
 	Configuration configuration;
+	boolean_t fileAlreadyExisted = false;
 	writer::RelationalWriter* relationalWriter;
 	std::wstring_convert<codecvt_utf8<wchar_t>> convertor; // TODO: support also other encodings
 	vector<AttributeMetadata> currentReaderMetadata;
@@ -186,7 +188,17 @@
 public:
 
 	SqlHandler(writer::RelationalWriter* relationalWriter, Configuration& configuration) : relationalWriter(relationalWriter), configuration(configuration) {
-		std::string file = configuration.file.size() ? convertor.to_bytes(configuration.file) : ":memory:";
+		std::string file;
+		if (configuration.file.size()) {
+			file = convertor.to_bytes(configuration.file);
+
+			// in C++17 we can use: std::filesystem::exists()
+			struct stat fileStat;
+			fileAlreadyExisted = (stat(file.c_str(), &fileStat) == 0);
+		} else {
+			file = ":memory:";
+		}
+
 		connection.reset(new Connection(file.c_str()));
 	}
 
@@ -255,7 +267,7 @@
 			default:
 				throw SqlException(L"Unsupported type in attribute()");
 		}
-		
+
 		if (currentAttributeIndex % currentReaderMetadata.size() == 0) {
 			currentInsert->next();
 			currentInsert->reset();
@@ -264,12 +276,17 @@
 	}
 
 	void endOfPipe() {
+		// run the transformation – process all statements:
 		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.");
-		}
+		// delete or keep the file:
+		if (configuration.file.size()) {
+			if (configuration.keepFile == KeepFile::Never || (configuration.keepFile == KeepFile::Automatic && !fileAlreadyExisted)) {
+				std::wcerr << L"will unlink file" << std::endl;
+				int result = unlink(convertor.to_bytes(configuration.file).c_str());
+				if (result) throw SqlException(L"Unable to delete SQLite file.");
+			}
+		} // else: we had no file, everything was in memory
 	}
 
 };