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
|
/*
* csvutils.cpp
*
* (c) 2002-2003,2008-2010 by Jeremy Bowman <jmbowman@alum.mit.edu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
/** @file csvutils.cpp
* Source file for CSVUtils
*/
#include <QFile>
#include <QFileInfo>
#include <QObject>
#include <QRegExp>
#include <QTextStream>
#include "csvutils.h"
#include "database.h"
#include "formatting.h"
/**
* Constructor.
*/
CSVUtils::CSVUtils() : m_textquote('"'), m_delimiter(','), colCount(0),
endStringCount(0), rowNum(1), calcCount(0)
{
}
/**
* Destructor.
*/
CSVUtils::~CSVUtils()
{
for (int i = 0; i < calcCount; i++) {
delete calcs[i];
}
}
/**
* Parse records from the specified CSV file, using the named text encoding,
* into the given database.
*
* @param filename The file to be parsed
* @param encoding "Latin-1" for that encoding, anything else for UTF-8
* @param db The database to load the data into
* @return Empty if no error occurred. Otherwise, an error message optionally
* followed by the text of the record imported that triggered that
* error
*/
QStringList CSVUtils::parseFile(const QString &filename,
const QString &encoding, Database *db)
{
initialize(db, filename);
QFile f(filename);
QStringList returnVal;
if (!f.open(QFile::ReadOnly)) {
returnVal.append(QObject::tr("Unable to open file"));
return returnVal;
}
QTextStream input(&f);
if (encoding == "Latin-1") {
input.setCodec("latin1");
}
else {
input.setCodec("UTF-8");
}
rowNum = 1;
message = "";
enum { S_START, S_QUOTED_FIELD, S_MAYBE_END_OF_QUOTED_FIELD,
S_END_OF_QUOTED_FIELD, S_MAYBE_NORMAL_FIELD,
S_NORMAL_FIELD } state = S_START;
QChar x;
rowString = "";
row.clear();
QString field = "";
// store IDs of added rows; if there's an error, delete them
addedIds.clear();
bool crLast = false;
while (!input.atEnd()) {
input >> x; // read one char
if (x == '\r') {
// treat as '\n', and watch for a following real '\n'
crLast = true;
x = '\n';
}
else if (crLast && x == '\n') {
crLast = false;
continue;
}
else {
crLast = false;
}
rowString += x;
switch (state)
{
case S_START :
if (x == m_textquote) {
state = S_QUOTED_FIELD;
}
else if (x == m_delimiter) {
row.append("");
}
else if (x == '\n') {
if (row.count() == 0) {
// blank line, ignore it
continue;
}
else {
// row ended on a delimiter (empty cell)
row.append("");
field = "";
if (!addRow(db)) {
break;
}
}
}
else {
field += x;
state = S_MAYBE_NORMAL_FIELD;
}
break;
case S_QUOTED_FIELD :
if (x == m_textquote) {
state = S_MAYBE_END_OF_QUOTED_FIELD;
}
else {
field += x;
}
break;
case S_MAYBE_END_OF_QUOTED_FIELD :
if (x == m_textquote) {
field += x;
state = S_QUOTED_FIELD;
}
else if (x == m_delimiter || x == '\n') {
row.append(field);
field = "";
if (x == '\n') {
if (!addRow(db)) {
break;
}
}
state = S_START;
}
else {
state = S_END_OF_QUOTED_FIELD;
}
break;
case S_END_OF_QUOTED_FIELD :
if (x == m_delimiter || x == '\n') {
row.append(field);
field = "";
if (x == '\n') {
if (!addRow(db)) {
break;
}
}
state = S_START;
}
else {
state = S_END_OF_QUOTED_FIELD;
}
break;
case S_MAYBE_NORMAL_FIELD :
if (x == m_textquote) {
field = "";
state = S_QUOTED_FIELD;
break;
}
case S_NORMAL_FIELD :
if (x == m_delimiter) {
row.append(field);
field = "";
state = S_START;
}
else if (x == '\n') {
row.append(field);
field = "";
if (!addRow(db)) {
break;
}
}
else {
field += x;
}
}
if (!message.isEmpty()) {
break;
}
}
if (message.isEmpty() && row.count() > 0) {
// last line doesn't end with '\n'
row.append(field);
addRow(db);
}
if (!message.isEmpty()) {
// an error was encountered; delete any rows that were added
int count = addedIds.count();
for (int i = count - 1; i > -1; i--) {
db->deleteRow(addedIds[i]);
}
returnVal.append(message);
returnVal.append(rowString);
}
f.close();
return returnVal;
}
/**
* Convert the provided row into a text line suitable for inclusion in a
* CSV file.
*
* @param row A row of database fields in text form
* @return A CSV record
*/
QString CSVUtils::encodeRow(QStringList row)
{
QString result;
int count = (int)row.count();
for (int i = 0; i < count; i++) {
result += encodeCell(row[i]);
if (i < count - 1) {
result += m_delimiter;
}
}
return result + "\n";
}
/**
* Encode the given string into text usable as a CSV field. This is
* typically the same as the input value unless it contains newlines,
* the quoting character, or the field delimiting character.
*
* @param content The text to be converted
* @return A CSV field string
*/
QString CSVUtils::encodeCell(QString content)
{
if (content.contains('"') == 0 && content.contains(',') == 0
&& content.contains('\n') == 0) {
return content;
}
QString result("\"");
result += content.replace(QRegExp("\""), "\"\"");
return result + "\"";
}
/**
* Prepare to import content into the specified database from the named file.
*
* @param db The database to import data into
* @param filename Path to the file to be imported from
*/
void CSVUtils::initialize(Database *db, const QString &filename)
{
colNames = db->listColumns();
types = db->listTypes();
colCount = colNames.count();
endStringCount = 0;
int i;
for (i = colCount - 1; i > -1; i--) {
int type = types[i];
if (type != STRING && type != NOTE) {
break;
}
endStringCount++;
}
for (i = 0; i < calcCount; i++) {
delete calcs[i];
}
calcs.clear();
calcDecimals.clear();
for (i = 0; i < colCount; i++) {
if (types[i] == CALC) {
int decimals = 2;
calcs.append(db->loadCalc(colNames[i], &decimals));
calcDecimals.append(decimals);
}
}
calcCount = calcs.count();
QFileInfo info(filename);
db->setImportBasePath(info.absolutePath() + "/");
}
/**
* Add the last parsed row of CSV data to the specified database.
*
* @param db The database to import data into
* @return True if successful, false if an error occurred
*/
bool CSVUtils::addRow(Database *db)
{
int countDiff = colCount - row.count();
int i;
if (countDiff > 0 && countDiff <= endStringCount) {
// last columns may have been blank in Excel or whatever...
for (i = 0; i < countDiff; i++) {
row.append("");
}
}
int rowId = 0;
if (calcCount > 0) {
// calculate the derived values in the added row
int calcIndex = 0;
for (i = 0; i < colCount; i++) {
if (types[i] == CALC) {
double value = calcs[calcIndex]->value(row, colNames);
int decimals = calcDecimals[calcIndex];
row[i] = Formatting::formatDouble(value, decimals);
calcIndex++;
}
}
}
message = db->addRow(row, &rowId, false, true);
if (!message.isEmpty()) {
message = QObject::tr("Error in row %1").arg(rowNum) + "\n" + message;
return false;
}
addedIds.append(rowId);
row.clear();
rowString = "";
rowNum++;
return true;
}
|