Explore Enterprise Education Gitee Premium Gitee AI AI teammates
Fetch the repository succeeded.
Create your Gitee Account
Explore and code with more than 14 million developers,Free private repositories !:)
Sign up
Already have an account? Sign in
文件
master
Branches (16)
Tags (31)
master
coverity_scan
v3.11.x
issue1831_v1
qdarkstyle
no_savepoints_ro_db
v3.10.x
v3.9.x
v3.6.x
v3.5.x
v3.4.x
v3.3.x
utf8grammar
sqlb-3.2.x
sqlb-3.1.x
sqlb-3.x
continuous
v3.11.2
v3.11.1v2
v3.11.1
v3.11.0
v3.11.0-beta3
v3.11.0-beta2
v3.11.0-beta1
v3.11.0-alpha1
v3.10.1
v3.10.0
v3.10.0-beta2
v3.10.0-beta1
v3.9.1
v3.9.0
v3.9.0-beta1
v3.8.0
v3.7.0
v3.6.0
v3.5.1
master
Branches (16)
Tags (31)
master
coverity_scan
v3.11.x
issue1831_v1
qdarkstyle
no_savepoints_ro_db
v3.10.x
v3.9.x
v3.6.x
v3.5.x
v3.4.x
v3.3.x
utf8grammar
sqlb-3.2.x
sqlb-3.1.x
sqlb-3.x
continuous
v3.11.2
v3.11.1v2
v3.11.1
v3.11.0
v3.11.0-beta3
v3.11.0-beta2
v3.11.0-beta1
v3.11.0-alpha1
v3.10.1
v3.10.0
v3.10.0-beta2
v3.10.0-beta1
v3.9.1
v3.9.0
v3.9.0-beta1
v3.8.0
v3.7.0
v3.6.0
v3.5.1
Clone or Download
Clone/Download
Prompt
To download the code, please copy the following command and execute it in the terminal
To ensure that your submitted code identity is correctly recognized by Gitee, please execute the following command.
When using the SSH protocol for the first time to clone or push code, follow the prompts below to complete the SSH configuration.
1 Generate RSA keys.
2 Obtain the content of the RSA public key and configure it in SSH Public Keys
To use SVN on Gitee, please visit the usage guide
When using the HTTPS protocol, the command line will prompt for account and password verification as follows. For security reasons, Gitee recommends configure and use personal access tokens instead of login passwords for cloning, pushing, and other operations.
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # Private Token
master
Branches (16)
Tags (31)
master
coverity_scan
v3.11.x
issue1831_v1
qdarkstyle
no_savepoints_ro_db
v3.10.x
v3.9.x
v3.6.x
v3.5.x
v3.4.x
v3.3.x
utf8grammar
sqlb-3.2.x
sqlb-3.1.x
sqlb-3.x
continuous
v3.11.2
v3.11.1v2
v3.11.1
v3.11.0
v3.11.0-beta3
v3.11.0-beta2
v3.11.0-beta1
v3.11.0-alpha1
v3.10.1
v3.10.0
v3.10.0-beta2
v3.10.0-beta1
v3.9.1
v3.9.0
v3.9.0-beta1
v3.8.0
v3.7.0
v3.6.0
v3.5.1
sqlitebrowser
/
src
/
ExportDataDialog.cpp
sqlitebrowser
/
src
/
ExportDataDialog.cpp
ExportDataDialog.cpp 20.52 KB
Copy Edit Raw Blame History
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 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
#include "ExportDataDialog.h"
#include "ui_ExportDataDialog.h"
#include "sqlitedb.h"
#include "Settings.h"
#include "sqlite.h"
#include "FileDialog.h"
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <QTextCodec>
#include <json.hpp>
using json = nlohmann::json;
ExportDataDialog::ExportDataDialog(DBBrowserDB& db, ExportFormats format, QWidget* parent, const QString& query, const sqlb::ObjectIdentifier& selection)
: QDialog(parent),
ui(new Ui::ExportDataDialog),
pdb(db),
m_format(format),
m_sQuery(query)
{
// Create UI
ui->setupUi(this);
// Show different option widgets depending on the export format
ui->stackFormat->setCurrentIndex(format);
if(format == ExportFormatJson) {
setWindowTitle(tr("Export data as JSON"));
}
// Retrieve the saved dialog preferences
ui->checkHeader->setChecked(Settings::getValue("exportcsv", "firstrowheader").toBool());
setSeparatorChar(Settings::getValue("exportcsv", "separator").toInt());
setQuoteChar(Settings::getValue("exportcsv", "quotecharacter").toInt());
setNewLineString(Settings::getValue("exportcsv", "newlinecharacters").toString());
ui->checkPrettyPrint->setChecked(Settings::getValue("exportjson", "prettyprint").toBool());
// Update the visible/hidden status of the "Other" line edit fields
showCustomCharEdits();
// If a SQL query was specified hide the table combo box. If not fill it with tables to export
if(query.isEmpty())
{
// Get list of tables to export
for(const auto& it : pdb.schemata)
{
const auto tables = it.second.equal_range("table");
const auto views = it.second.equal_range("view");
std::map<std::string, sqlb::ObjectPtr> objects;
for(auto jt=tables.first;jt!=tables.second;++jt)
objects.insert({jt->second->name(), jt->second});
for(auto jt=views.first;jt!=views.second;++jt)
objects.insert({jt->second->name(), jt->second});
for(const auto& jt : objects)
{
sqlb::ObjectIdentifier obj(it.first, jt.second->name());
QListWidgetItem* item = new QListWidgetItem(QIcon(QString(":icons/%1").arg(QString::fromStdString(sqlb::Object::typeToString(jt.second->type())))), QString::fromStdString(obj.toDisplayString()));
item->setData(Qt::UserRole, QString::fromStdString(obj.toSerialised()));
ui->listTables->addItem(item);
}
}
// Sort list of tables and select the table specified in the selection parameter or alternatively the first one
ui->listTables->model()->sort(0);
if(selection.isEmpty())
{
ui->listTables->setCurrentItem(ui->listTables->item(0));
} else {
for(int i=0;i<ui->listTables->count();i++)
{
if(sqlb::ObjectIdentifier(ui->listTables->item(i)->data(Qt::UserRole).toString().toStdString()) == selection)
{
ui->listTables->setCurrentRow(i);
break;
}
}
}
} else {
// Hide table combo box
ui->labelTable->setVisible(false);
ui->listTables->setVisible(false);
resize(minimumSize());
}
}
ExportDataDialog::~ExportDataDialog()
{
delete ui;
}
bool ExportDataDialog::exportQuery(const QString& sQuery, const QString& sFilename)
{
switch(m_format)
{
case ExportFormatCsv:
return exportQueryCsv(sQuery, sFilename);
case ExportFormatJson:
return exportQueryJson(sQuery, sFilename);
}
return false;
}
bool ExportDataDialog::exportQueryCsv(const QString& sQuery, const QString& sFilename)
{
// Prepare the quote and separating characters
QChar quoteChar = currentQuoteChar();
QString quotequoteChar = QString(quoteChar) + quoteChar;
QChar sepChar = currentSeparatorChar();
QString newlineStr = currentNewLineString();
// Chars that require escaping
std::string special_chars = newlineStr.toStdString() + sepChar.toLatin1() + quoteChar.toLatin1();
// Open file
QFile file(sFilename);
if(file.open(QIODevice::WriteOnly))
{
// Open text stream to the file
QTextStream stream(&file);
QByteArray utf8Query = sQuery.toUtf8();
sqlite3_stmt *stmt;
auto pDb = pdb.get(tr("exporting CSV"));
int status = sqlite3_prepare_v2(pDb.get(), utf8Query.data(), utf8Query.size(), &stmt, nullptr);
if(SQLITE_OK == status)
{
if(ui->checkHeader->isChecked())
{
int columns = sqlite3_column_count(stmt);
for (int i = 0; i < columns; ++i)
{
QString content = QString::fromUtf8(sqlite3_column_name(stmt, i));
if(content.toStdString().find_first_of(special_chars) != std::string::npos)
stream << quoteChar << content.replace(quoteChar, quotequoteChar) << quoteChar;
else
stream << content;
if(i != columns - 1)
// Only output the separator value if sepChar isn't 0,
// as that's used to indicate no separator character
// should be used
if(!sepChar.isNull())
stream << sepChar;
}
stream << newlineStr;
}
QApplication::setOverrideCursor(Qt::WaitCursor);
int columns = sqlite3_column_count(stmt);
size_t counter = 0;
while(sqlite3_step(stmt) == SQLITE_ROW)
{
for (int i = 0; i < columns; ++i)
{
QString content = QString::fromUtf8(
reinterpret_cast<const char*>(sqlite3_column_blob(stmt, i)),
sqlite3_column_bytes(stmt, i));
// If no quote char is set but the content contains a line break, we enforce some quote characters. This probably isn't entirely correct
// but still better than having the line breaks unquoted and effectively outputting a garbage file.
if(quoteChar.isNull() && content.contains(newlineStr))
stream << '"' << content.replace('"', "\"\"") << '"';
// If the content needs to be quoted, quote it. But only if a quote char has been specified
else if(!quoteChar.isNull() && content.toStdString().find_first_of(special_chars) != std::string::npos)
stream << quoteChar << content.replace(quoteChar, quotequoteChar) << quoteChar;
// If it doesn't need to be quoted, don't quote it
else
stream << content;
if(i != columns - 1)
// Only output the separator value if sepChar isn't 0,
// as that's used to indicate no separator character
// should be used
if(!sepChar.isNull())
stream << sepChar;
}
stream << newlineStr;
if(counter % 1000 == 0)
qApp->processEvents();
counter++;
}
}
sqlite3_finalize(stmt);
QApplication::restoreOverrideCursor();
qApp->processEvents();
// Done writing the file
file.close();
} else {
QMessageBox::warning(this, QApplication::applicationName(),
tr("Could not open output file: %1").arg(sFilename));
return false;
}
return true;
}
bool ExportDataDialog::exportQueryJson(const QString& sQuery, const QString& sFilename)
{
// Open file
QFile file(sFilename);
if(file.open(QIODevice::WriteOnly))
{
QByteArray utf8Query = sQuery.toUtf8();
sqlite3_stmt *stmt;
auto pDb = pdb.get(tr("exporting JSON"));
int status = sqlite3_prepare_v2(pDb.get(), utf8Query.data(), utf8Query.size(), &stmt, nullptr);
json json_table;
if(SQLITE_OK == status)
{
QApplication::setOverrideCursor(Qt::WaitCursor);
int columns = sqlite3_column_count(stmt);
size_t counter = 0;
std::vector<std::string> column_names;
while(sqlite3_step(stmt) == SQLITE_ROW)
{
// Get column names if we didn't do so before
if(!column_names.size())
{
for(int i=0;i<columns;++i)
column_names.push_back(sqlite3_column_name(stmt, i));
}
json json_row;
for(int i=0;i<columns;++i)
{
int type = sqlite3_column_type(stmt, i);
std::string column_name = column_names[static_cast<size_t>(i)];
switch (type) {
case SQLITE_INTEGER: {
qint64 content = sqlite3_column_int64(stmt, i);
json_row[column_name] = content;
break;
}
case SQLITE_FLOAT: {
double content = sqlite3_column_double(stmt, i);
json_row[column_name] = content;
break;
}
case SQLITE_NULL: {
json_row[column_name] = nullptr;
break;
}
case SQLITE_TEXT: {
QString content = QString::fromUtf8(
reinterpret_cast<const char*>(sqlite3_column_text(stmt, i)),
sqlite3_column_bytes(stmt, i));
json_row[column_name] = content.toStdString();
break;
}
case SQLITE_BLOB: {
QByteArray content(reinterpret_cast<const char*>(sqlite3_column_blob(stmt, i)),
sqlite3_column_bytes(stmt, i));
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
QString string = codec->toUnicode(content.toBase64(QByteArray::Base64Encoding));
json_row[column_name] = string.toStdString();
break;
}
}
}
json_table.push_back(json_row);
if(counter % 1000 == 0)
qApp->processEvents();
counter++;
}
}
sqlite3_finalize(stmt);
// Create JSON document
file.write(json_table.dump(ui->checkPrettyPrint->isChecked() ? 4 : -1).c_str());
QApplication::restoreOverrideCursor();
qApp->processEvents();
// Done writing the file
file.close();
} else {
QMessageBox::warning(this, QApplication::applicationName(),
tr("Could not open output file: %1").arg(sFilename));
return false;
}
return true;
}
void ExportDataDialog::accept()
{
QStringList file_dialog_filter;
QString default_file_extension;
switch(m_format)
{
case ExportFormatCsv:
file_dialog_filter << FILE_FILTER_CSV
<< FILE_FILTER_TSV
<< FILE_FILTER_DSV
<< FILE_FILTER_TXT
<< FILE_FILTER_ALL;
default_file_extension = FILE_EXT_CSV_DEFAULT;
break;
case ExportFormatJson:
file_dialog_filter << FILE_FILTER_JSON
<< FILE_FILTER_TXT
<< FILE_FILTER_ALL;
default_file_extension = FILE_EXT_JSON_DEFAULT;
break;
}
if(!m_sQuery.isEmpty())
{
// called from sqlexecute query tab
QString sFilename = FileDialog::getSaveFileName(
CreateDataFile,
this,
tr("Choose a filename to export data"),
file_dialog_filter.join(";;"));
if(sFilename.isEmpty())
{
close();
return;
}
exportQuery(m_sQuery, sFilename);
} else {
// called from the File export menu
QList<QListWidgetItem*> selectedItems = ui->listTables->selectedItems();
if(selectedItems.isEmpty())
{
QMessageBox::warning(this, QApplication::applicationName(),
tr("Please select at least 1 table."));
return;
}
// Get filename
QStringList filenames;
if(selectedItems.size() == 1)
{
QString fileName = FileDialog::getSaveFileName(
CreateDataFile,
this,
tr("Choose a filename to export data"),
file_dialog_filter.join(";;"),
selectedItems.at(0)->text() + default_file_extension);
if(fileName.isEmpty())
{
close();
return;
}
filenames << fileName;
} else {
// ask for folder
QString exportfolder = FileDialog::getExistingDirectory(
CreateDataFile,
this,
tr("Choose a directory"),
QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if(exportfolder.isEmpty())
{
close();
return;
}
for(const QListWidgetItem* item : selectedItems)
filenames << QDir(exportfolder).filePath(item->text() + default_file_extension);
}
// Only if the user hasn't clicked the cancel button
for(int i = 0; i < selectedItems.size(); ++i)
{
// if we are called from execute sql tab, query is already set
// and we only export 1 select
QString sQuery = QString("SELECT * FROM %1;").arg(QString::fromStdString(sqlb::ObjectIdentifier(selectedItems.at(i)->data(Qt::UserRole).toString().toStdString()).toString()));
exportQuery(sQuery, filenames.at(i));
}
}
// Save the dialog preferences for future use
Settings::setValue("exportcsv", "firstrowheader", ui->checkHeader->isChecked());
Settings::setValue("exportjson", "prettyprint", ui->checkPrettyPrint->isChecked());
Settings::setValue("exportcsv", "separator", currentSeparatorChar());
Settings::setValue("exportcsv", "quotecharacter", currentQuoteChar());
Settings::setValue("exportcsv", "newlinecharacters", currentNewLineString());
// Notify the user the export has completed
QMessageBox::information(this, QApplication::applicationName(), tr("Export completed."));
QDialog::accept();
}
void ExportDataDialog::showCustomCharEdits()
{
// Retrieve selection info for the quote, separator, and newline widgets
int quoteIndex = ui->comboQuoteCharacter->currentIndex();
int quoteCount = ui->comboQuoteCharacter->count();
int sepIndex = ui->comboFieldSeparator->currentIndex();
int sepCount = ui->comboFieldSeparator->count();
int newLineIndex = ui->comboNewLineString->currentIndex();
int newLineCount = ui->comboNewLineString->count();
// Determine which will have their 'Other' line edit widget visible
bool quoteVisible = quoteIndex == (quoteCount - 1);
bool sepVisible = sepIndex == (sepCount - 1);
bool newLineVisible = newLineIndex == (newLineCount - 1);
// Update the visibility of the 'Other' line edit widgets
ui->editCustomQuote->setVisible(quoteVisible);
ui->editCustomSeparator->setVisible(sepVisible);
ui->editCustomNewLine->setVisible(newLineVisible);
}
void ExportDataDialog::setQuoteChar(const QChar& c)
{
QComboBox* combo = ui->comboQuoteCharacter;
// Set the combo and/or Other box to the correct selection
switch (c.toLatin1()) {
case '"':
combo->setCurrentIndex(0); // First option is a quote character
break;
case '\'':
combo->setCurrentIndex(1); // Second option is a single quote character
break;
case 0:
combo->setCurrentIndex(2); // Third option is blank (no character)
break;
default:
// For everything else, set the combo box to option 3 ('Other') and
// place the desired string into the matching edit line box
combo->setCurrentIndex(3);
if(!c.isNull())
{
// Don't set it if/when it's the 0 flag value
ui->editCustomQuote->setText(c);
}
break;
}
}
char ExportDataDialog::currentQuoteChar() const
{
QComboBox* combo = ui->comboQuoteCharacter;
switch (combo->currentIndex()) {
case 0:
return '"'; // First option is a quote character
case 1:
return '\''; // Second option is a single quote character
case 2:
return 0; // Third option is a blank (no character)
default:
// The 'Other' option was selected, so check if the matching edit
// line widget contains something
int customQuoteLength = ui->editCustomQuote->text().length();
if (customQuoteLength > 0) {
// Yes it does. Return its first character
char customQuoteChar = ui->editCustomQuote->text().at(0).toLatin1();
return customQuoteChar;
} else {
// No it doesn't, so return 0 to indicate it was empty
return 0;
}
}
}
void ExportDataDialog::setSeparatorChar(const QChar& c)
{
QComboBox* combo = ui->comboFieldSeparator;
// Set the combo and/or Other box to the correct selection
switch (c.toLatin1()) {
case ',':
combo->setCurrentIndex(0); // First option is a comma character
break;
case ';':
combo->setCurrentIndex(1); // Second option is a semi-colon character
break;
case '\t':
combo->setCurrentIndex(2); // Third option is a tab character
break;
case '|':
combo->setCurrentIndex(3); // Fourth option is a pipe symbol
break;
default:
// For everything else, set the combo box to option 3 ('Other') and
// place the desired string into the matching edit line box
combo->setCurrentIndex(4);
// Only put the separator character in the matching line edit box if
// it's not the flag value of 0, which is for indicating its empty
if(!c.isNull())
ui->editCustomSeparator->setText(c);
break;
}
}
char ExportDataDialog::currentSeparatorChar() const
{
QComboBox* combo = ui->comboFieldSeparator;
switch (combo->currentIndex()) {
case 0:
return ','; // First option is a comma character
case 1:
return ';'; // Second option is a semi-colon character
case 2:
return '\t'; // Third option is a tab character
case 3:
return '|'; // Fourth option is a pipe character
default:
// The 'Other' option was selected, so check if the matching edit
// line widget contains something
int customSeparatorLength = ui->editCustomSeparator->text().length();
if (customSeparatorLength > 0) {
// Yes it does. Return its first character
char customSeparatorChar = ui->editCustomSeparator->text().at(0).toLatin1();
return customSeparatorChar;
} else {
// No it doesn't, so return 0 to indicate it was empty
return 0;
}
}
}
void ExportDataDialog::setNewLineString(const QString& s)
{
QComboBox* combo = ui->comboNewLineString;
// Set the combo and/or Other box to the correct selection
if (s == "\r\n") {
// For Windows style newlines, set the combo box to option 0
combo->setCurrentIndex(0);
} else if (s == "\n") {
// For Unix style newlines, set the combo box to option 1
combo->setCurrentIndex(1);
} else {
// For everything else, set the combo box to option 2 ('Other') and
// place the desired string into the matching edit line box
combo->setCurrentIndex(2);
ui->editCustomNewLine->setText(s);
}
}
QString ExportDataDialog::currentNewLineString() const
{
QComboBox* combo = ui->comboNewLineString;
switch (combo->currentIndex()) {
case 0:
// Windows style newlines
return QString("\r\n");
case 1:
// Unix style newlines
return QString("\n");
default:
// Return the text from the 'Other' box
return QString(ui->editCustomNewLine->text().toLatin1());
}
}
Loading...
Report
Report success
We will send you the feedback within 2 working days through the letter!
Please fill in the reason for the report carefully. Provide as detailed a description as possible.
Please select a report type
Cancel
Send
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

About

Official home of the DB Browser for SQLite (DB4S) project. Previously known as "SQLite Database Browser" and "Database Browser for SQLite". Website at:
Cancel

Releases

No release

Contributors

All

Activities

can not load any more
Edit
About
Homepage
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/ax4688/sqlitebrowser.git
git@gitee.com:ax4688/sqlitebrowser.git
ax4688
sqlitebrowser
sqlitebrowser
master
Going to Help Center

Search

Comment
Repository Report
Back to the top
Login prompt
This operation requires login to the code cloud account. Please log in before operating.
Go to login
No account. Register

AltStyle によって変換されたページ (->オリジナル) /