summaryrefslogtreecommitdiff
path: root/sqliteutil.cpp
blob: 93b91debde632f7cb71e57c47b0445940f84444f (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
#include <sstream>
#include <cstring>
#include "sqliteutil.h"


namespace sqlite {
	std::vector<std::vector<std::string>> parseCSV(std::string output) {
		std::istringstream ss{output};
		std::vector<std::vector<std::string>> table;

		std::string line;
		while (std::getline(ss, line)) {
			while (!line.empty() && strchr("\r\n", line.back()) != nullptr)
				line.pop_back();

			table.emplace_back();

			if (line.empty()) continue;

			std::vector<std::string> &row = table.back();
			row.emplace_back();
			bool inString = false;
			for (size_t i = 0; i < line.size(); i++) {
				switch (line[i]) {
					case '"':
						if (inString) {
							if (i + 1 < line.size() && line[i+1] == '"') {
								row.back().push_back('"');
								i++;
							} else {
								inString = false;
							}
						} else {
							inString = true;
						}
						break;

					case ',':
						if (inString) {
							row.back().push_back(',');
						} else {
							row.emplace_back();
						}
						break;

					default:
						row.back().push_back(line[i]);
						break;
				}
			}
		}

		return table;
	}
}