kexicsvexport.cpp
1/* This file is part of the KDE project
2 Copyright (C) 2005,2006 Jaroslaw Staniek <js@iidea.pl>
3
4 This library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Library General Public
6 License as published by the Free Software Foundation; either
7 version 2 of the License, or (at your option) any later version.
8
9 This library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Library General Public License for more details.
13
14 You should have received a copy of the GNU Library General Public License
15 along with this library; see the file COPYING.LIB. If not, write to
16 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
17 * Boston, MA 02110-1301, USA.
18*/
19
20#include "kexicsvexport.h"
21#include "kexicsvwidgets.h"
22#include <main/startup/KexiStartupFileDialog.h>
23#include <kexidb/cursor.h>
24#include <kexidb/utils.h>
25#include <core/keximainwindow.h>
26#include <core/kexiproject.h>
27#include <core/kexipartinfo.h>
28#include <core/kexipartmanager.h>
29#include <core/kexiguimsghandler.h>
30#include <kexiutils/utils.h>
31#include <widget/kexicharencodingcombobox.h>
32
33#include <tqcheckbox.h>
34#include <tqgroupbox.h>
35#include <tqclipboard.h>
36#include <tdeapplication.h>
37#include <tdelocale.h>
38#include <kiconloader.h>
39#include <kactivelabel.h>
40#include <kpushbutton.h>
41#include <tdeapplication.h>
42#include <kdebug.h>
43#include <ksavefile.h>
44
45
46using namespace KexiCSVExport;
47
48Options::Options()
49 : mode(File), itemId(0), addColumnNames(true)
50{
51}
52
53bool Options::assign( TQMap<TQString,TQString>& args )
54{
55 mode = (args["destinationType"]=="file")
56 ? KexiCSVExport::File : KexiCSVExport::Clipboard;
57
58 if (args.contains("delimiter"))
59 delimiter = args["delimiter"];
60 else
61 delimiter = (mode==File) ? KEXICSV_DEFAULT_FILE_DELIMITER : KEXICSV_DEFAULT_CLIPBOARD_DELIMITER;
62
63 if (args.contains("textQuote"))
64 textQuote = args["textQuote"];
65 else
66 textQuote = (mode==File) ? KEXICSV_DEFAULT_FILE_TEXT_QUOTE : KEXICSV_DEFAULT_CLIPBOARD_TEXT_QUOTE;
67
68 bool ok;
69 itemId = args["itemId"].toInt(&ok);
70 if (!ok || itemId<=0)
71 return false;
72 if (args.contains("forceDelimiter"))
73 forceDelimiter = args["forceDelimiter"];
74 if (args.contains("addColumnNames"))
75 addColumnNames = (args["addColumnNames"]=="1");
76 return true;
77}
78
79//------------------------------------
80
81bool KexiCSVExport::exportData(KexiDB::TableOrQuerySchema& tableOrQuery,
82 const Options& options, int rowCount, TQTextStream *predefinedTextStream)
83{
84 KexiDB::Connection* conn = tableOrQuery.connection();
85 if (!conn)
86 return false;
87
88 if (rowCount == -1)
89 rowCount = KexiDB::rowCount(tableOrQuery);
90 if (rowCount == -1)
91 return false;
92
97
100
101 KexiDB::QuerySchema* query = tableOrQuery.query();
102 if (!query)
103 query = tableOrQuery.table()->query();
104
105 KexiDB::QueryColumnInfo::Vector fields( query->fieldsExpanded( KexiDB::QuerySchema::WithInternalFields ) );
106 TQString buffer;
107
108 KSaveFile *kSaveFile = 0;
109 TQTextStream *stream = 0;
110
111 const bool copyToClipboard = options.mode==Clipboard;
112 if (copyToClipboard) {
114 uint bufSize = TQMIN((rowCount<0 ? 10 : rowCount) * fields.count() * 20, 128000);
115 buffer.reserve( bufSize );
116 if (buffer.capacity() < bufSize) {
117 kdWarning() << "KexiCSVExportWizard::exportData() cannot allocate memory for " << bufSize
118 << " characters" << endl;
119 return false;
120 }
121 }
122 else {
123 if (predefinedTextStream) {
124 stream = predefinedTextStream;
125 }
126 else {
127 if (options.fileName.isEmpty()) {//sanity
128 kdWarning() << "KexiCSVExportWizard::exportData(): fname is empty" << endl;
129 return false;
130 }
131 kSaveFile = new KSaveFile(options.fileName);
132 if (0 == kSaveFile->status())
133 stream = kSaveFile->textStream();
134 if (0 != kSaveFile->status() || !stream) {//sanity
135 kdWarning() << "KexiCSVExportWizard::exportData(): status != 0 or stream == 0" << endl;
136 delete kSaveFile;
137 return false;
138 }
139 }
140 }
141
143
144#define _ERR \
145 delete [] isText; \
146 if (kSaveFile) { kSaveFile->abort(); delete kSaveFile; } \
147 return false
148
149#define APPEND(what) \
150 if (copyToClipboard) buffer.append(what); else (*stream) << (what)
151
152// line endings should be as in RFC 4180
153#define CSV_EOLN "\r\n"
154
155 // 0. Cache information
156 const uint fieldsCount = query->fieldsExpanded().count(); //real fields count without internals
157 const TQCString delimiter( options.delimiter.left(1).latin1() );
158 const bool hasTextQuote = !options.textQuote.isEmpty();
159 const TQString textQuote( options.textQuote.left(1) );
160 const TQCString escapedTextQuote( (textQuote + textQuote).latin1() ); //ok?
161 //cache for faster checks
162 bool *isText = new bool[fieldsCount];
163 bool *isDateTime = new bool[fieldsCount];
164 bool *isTime = new bool[fieldsCount];
165 bool *isBLOB = new bool[fieldsCount];
166 uint *visibleFieldIndex = new uint[fieldsCount];
167// bool isInteger[fieldsCount]; //cache for faster checks
168// bool isFloatingPoint[fieldsCount]; //cache for faster checks
169 for (uint i=0; i<fieldsCount; i++) {
171 const int indexForVisibleLookupValue = fields[i]->indexForVisibleLookupValue();
172 if (-1 != indexForVisibleLookupValue) {
173 ci = query->expandedOrInternalField( indexForVisibleLookupValue );
174 visibleFieldIndex[i] = indexForVisibleLookupValue;
175 }
176 else {
177 ci = fields[i];
178 visibleFieldIndex[i] = i;
179 }
180
181 isText[i] = ci->field->isTextType();
182 isDateTime[i] = ci->field->type()==KexiDB::Field::DateTime;
183 isTime[i] = ci->field->type()==KexiDB::Field::Time;
184 isBLOB[i] = ci->field->type()==KexiDB::Field::BLOB;
185// isInteger[i] = fields[i]->field->isIntegerType()
186// || fields[i]->field->type()==KexiDB::Field::Boolean;
187// isFloatingPoint[i] = fields[i]->field->isFPNumericType();
188 }
189
190 // 1. Output column names
191 if (options.addColumnNames) {
192 for (uint i=0; i<fieldsCount; i++) {
193 if (i>0)
194 APPEND( delimiter );
195 if (hasTextQuote){
196 APPEND( textQuote + fields[i]->captionOrAliasOrName().replace(textQuote, escapedTextQuote) + textQuote );
197 }
198 else {
199 APPEND( fields[i]->captionOrAliasOrName() );
200 }
201 }
202 APPEND(CSV_EOLN);
203 }
204
205 KexiGUIMessageHandler handler;
206 KexiDB::Cursor *cursor = conn->executeQuery(*query);
207 if (!cursor) {
208 handler.showErrorMessage(conn);
209 _ERR;
210 }
211 for (cursor->moveFirst(); !cursor->eof() && !cursor->error(); cursor->moveNext()) {
212 const uint realFieldCount = TQMIN(cursor->fieldCount(), fieldsCount);
213 for (uint i=0; i<realFieldCount; i++) {
214 const uint real_i = visibleFieldIndex[i];
215 if (i>0)
216 APPEND( delimiter );
217 if (cursor->value(real_i).isNull())
218 continue;
219 if (isText[real_i]) {
220 if (hasTextQuote)
221 APPEND( textQuote + TQString(cursor->value(real_i).toString()).replace(textQuote, escapedTextQuote) + textQuote );
222 else
223 APPEND( cursor->value(real_i).toString() );
224 }
225 else if (isDateTime[real_i]) { //avoid "T" in ISO DateTime
226 APPEND( cursor->value(real_i).toDateTime().date().toString(TQt::ISODate)+" "
227 + cursor->value(real_i).toDateTime().time().toString(TQt::ISODate) );
228 }
229 else if (isTime[real_i]) { //time is temporarily stored as null date + time...
230 APPEND( cursor->value(real_i).toTime().toString(TQt::ISODate) );
231 }
232 else if (isBLOB[real_i]) { //BLOB is escaped in a special way
233 if (hasTextQuote)
235 APPEND( textQuote + KexiDB::escapeBLOB(cursor->value(real_i).toByteArray(), KexiDB::BLOBEscapeHex) + textQuote );
236 else
237 APPEND( KexiDB::escapeBLOB(cursor->value(real_i).toByteArray(), KexiDB::BLOBEscapeHex) );
238 }
239 else {//other types
240 APPEND( cursor->value(real_i).toString() );
241 }
242 }
243 APPEND(CSV_EOLN);
244 }
245
246 if (copyToClipboard)
247 buffer.squeeze();
248
249 if (!conn->deleteCursor(cursor)) {
250 handler.showErrorMessage(conn);
251 _ERR;
252 }
253
254 if (copyToClipboard)
255 kapp->clipboard()->setText(buffer, TQClipboard::Clipboard);
256
257 delete [] isText;
258 delete [] isDateTime;
259 delete [] isTime;
260 delete [] isBLOB;
261 delete [] visibleFieldIndex;
262
263 if (kSaveFile) {
264 if (!kSaveFile->close()) {
265 kdWarning() << "KexiCSVExportWizard::exportData(): error close(); status == "
266 << kSaveFile->status() << endl;
267 }
268 delete kSaveFile;
269 }
270 return true;
271}
Options used in KexiCSVExportWizard contructor.
bool assign(TQMap< TQString, TQString > &args)
Assigns args.
int itemId
Table or query ID.
TQString forceDelimiter
Used for "clipboard" mode.
Provides database connection, allowing queries and data modification.
Definition connection.h:62
bool deleteCursor(Cursor *cursor)
Cursor * executeQuery(const TQString &statement, uint cursor_options=0)
Provides database cursor functionality.
Definition cursor.h:67
virtual bool moveNext()
Definition cursor.cpp:292
virtual TQVariant value(uint i)=0
bool eof() const
Definition cursor.cpp:339
uint fieldCount() const
Definition cursor.h:165
bool moveFirst()
Definition cursor.cpp:205
Type type() const
Definition field.cpp:134
bool isTextType() const
Definition field.h:280
bool error() const
Definition object.h:38
Helper class that assigns additional information for the column in a query.
Definition queryschema.h:49
int indexForVisibleLookupValue() const
Definition queryschema.h:75
KexiDB::QuerySchema provides information about database query.
@ WithInternalFields
Like Default but internal fields (for lookup) are appended.
QueryColumnInfo::Vector fieldsExpanded(FieldsExpandedOptions options=Default)
QueryColumnInfo * expandedOrInternalField(uint index)
QuerySchema * query() const
TableSchema * table() const
Connection * connection() const
QuerySchema * query()
int rowCount(Connection &conn, const TQString &sql)
KEXI_DB_EXPORT TQString escapeBLOB(const TQByteArray &array, BLOBEscapingType type)
@ BLOBEscapeHex
escaping like 1FAD without quotes or prefixes