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 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
|
#include "indexdialog.h"
#include "ui_indexdialog.h"
#include "schemaresolver.h"
#include "services/notifymanager.h"
#include "common/utils_sql.h"
#include "db/chainexecutor.h"
#include "dbtree/dbtree.h"
#include "ddlpreviewdialog.h"
#include "uiconfig.h"
#include "services/config.h"
#include "uiutils.h"
#include "db/sqlite3.h"
#include "indexexprcolumndialog.h"
#include "windows/editorwindow.h"
#include "services/codeformatter.h"
#include "common/dialogsizehandler.h"
#include <QDebug>
#include <QGridLayout>
#include <QSignalMapper>
#include <QScrollBar>
#include <QPushButton>
#include <QMessageBox>
IndexDialog::IndexDialog(Db* db, QWidget *parent) :
QDialog(parent),
db(db),
ui(new Ui::IndexDialog)
{
init();
}
IndexDialog::IndexDialog(Db* db, const QString& index, QWidget* parent) :
QDialog(parent),
db(db),
index(index),
ui(new Ui::IndexDialog)
{
existingIndex = true;
init();
bool sysIdx = isSystemIndex(index);
ui->indexTab->setDisabled(sysIdx);
ui->ddlTab->setDisabled(sysIdx);
}
IndexDialog::~IndexDialog()
{
clearColumns();
delete ui;
}
void IndexDialog::changeEvent(QEvent *e)
{
QDialog::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void IndexDialog::init()
{
ui->setupUi(this);
limitDialogWidth(this);
DialogSizeHandler::applyFor(this);
if (!db || !db->isOpen())
{
qCritical() << "Created IndexDialog for null or closed database.";
notifyError(tr("Tried to open index dialog for closed or inexisting database."));
preReject();
return;
}
ui->moveUpButton->setIcon(ICONS.MOVE_UP);
ui->moveDownButton->setIcon(ICONS.MOVE_DOWN);
ui->addExprColumnButton->setIcon(ICONS.INDEX_EXPR_ADD);
ui->editExprColumnButton->setIcon(ICONS.INDEX_EXPR_EDIT);
ui->delExprColumnButton->setIcon(ICONS.INDEX_EXPR_DEL);
connect(ui->moveUpButton, SIGNAL(clicked()), this, SLOT(moveColumnUp()));
connect(ui->moveDownButton, SIGNAL(clicked()), this, SLOT(moveColumnDown()));
connect(ui->addExprColumnButton, SIGNAL(clicked()), this, SLOT(addExprColumn()));
connect(ui->editExprColumnButton, SIGNAL(clicked()), this, SLOT(editExprColumn()));
connect(ui->delExprColumnButton, SIGNAL(clicked()), this, SLOT(delExprColumn()));
connect(ui->columnsTable, SIGNAL(cellDoubleClicked(int,int)), this, SLOT(editExprColumn(int)));
ui->columnsTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
connect(ui->columnsTable->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), this, SLOT(updateToolBarButtons(QModelIndex)));
ui->partialIndexEdit->setDb(db);
connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabChanged(int)));
columnStateSignalMapping = new QSignalMapper(this);
connect(columnStateSignalMapping, SIGNAL(mapped(QString)), this, SLOT(updateColumnState(QString)));
SchemaResolver resolver(db);
ui->tableCombo->addItem(QString());
ui->tableCombo->addItems(resolver.getTables());
connect(ui->tableCombo, SIGNAL(currentTextChanged(QString)), this, SLOT(updateTable(QString)));
connect(ui->tableCombo, SIGNAL(currentTextChanged(QString)), this, SLOT(updateValidation()));
connect(ui->uniqueCheck, SIGNAL(toggled(bool)), this, SLOT(updateValidation()));
if (existingIndex)
ui->tableCombo->setEnabled(false);
connect(ui->partialIndexCheck, SIGNAL(toggled(bool)), this, SLOT(updatePartialConditionState()));
connect(ui->partialIndexEdit, SIGNAL(errorsChecked(bool)), this, SLOT(updateValidation()));
connect(ui->partialIndexEdit, SIGNAL(textChanged()), this, SLOT(updateValidation()));
ui->partialIndexEdit->setVirtualSqlExpression("SELECT %1");
updatePartialConditionState();
ui->columnsTable->setColumnHidden(2, false);
readCollations();
if (index.isNull())
createIndex = SqliteCreateIndexPtr::create();
else
readIndex();
originalCreateIndex = SqliteCreateIndexPtr::create(*createIndex);
ui->nameEdit->setText(index);
setTable(createIndex->table);
if (!index.isNull())
applyIndex();
updateValidation();
ui->nameEdit->setFocus();
}
void IndexDialog::readIndex()
{
SchemaResolver resolver(db);
SqliteQueryPtr parsedObject = resolver.getParsedObject(index, SchemaResolver::INDEX);
if (!parsedObject.dynamicCast<SqliteCreateIndex>())
{
createIndex = SqliteCreateIndexPtr::create();
notifyError(tr("Could not process index %1 correctly. Unable to open an index dialog.").arg(index));
preReject();
return;
}
createIndex = parsedObject.dynamicCast<SqliteCreateIndex>();
}
void IndexDialog::buildColumns()
{
// Clean up
clearColumns();
ui->columnsTable->setRowCount(0);
int row = 0;
for (const QString& column : tableColumns)
buildColumn(column, row++);
updateToolBarButtons();
}
void IndexDialog::updateTable(const QString& value)
{
table = value;
SchemaResolver resolver(db);
tableColumns = resolver.getTableColumns(table);
buildColumns();
}
void IndexDialog::updateValidation()
{
bool tableOk = ui->tableCombo->currentIndex() > 0;
bool colSelected = false;
bool hasExprColumn = false;
if (tableOk)
{
for (Column* col : columns.values())
{
if (col->getCheck()->isChecked())
{
colSelected = true;
hasExprColumn |= col->isExpr();
}
}
}
bool partialConditionOk = (!ui->partialIndexCheck->isChecked() ||
(ui->partialIndexEdit->isSyntaxChecked() && !ui->partialIndexEdit->haveErrors()));
bool uniqueAndExprOk = !(ui->uniqueCheck->isChecked() && hasExprColumn);
setValidState(ui->uniqueCheck, uniqueAndExprOk, tr("Unique index cannot have indexed expressions. Either remove expressions from list below, or uncheck this option."));
setValidState(ui->tableCombo, tableOk, tr("Pick the table for the index."));
setValidState(ui->columnsTable, colSelected, tr("Select at least one column."));
setValidState(ui->partialIndexCheck, partialConditionOk, tr("Enter a valid condition."));
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(colSelected && partialConditionOk && uniqueAndExprOk);
}
void IndexDialog::setTable(const QString& value)
{
ui->tableCombo->setCurrentText(value);
}
void IndexDialog::readCollations()
{
SchemaResolver resolver(db);
QStringList collList = resolver.getCollations();
if (collList.size() > 0)
collList.prepend("");
collations.setStringList(collList);
}
void IndexDialog::buildColumn(const QString& name, int row)
{
Column* column = new Column(name, ui->columnsTable);
buildColumn(column, row);
}
IndexDialog::Column* IndexDialog::buildColumn(SqliteOrderBy* orderBy, int row)
{
Column* column = orderBy->isSimpleColumn() ?
new Column(orderBy->getColumnName(), ui->columnsTable) :
new Column(dynamic_cast<SqliteExpr*>(orderBy->expr->clone()), ui->columnsTable);
buildColumn(column, row);
return column;
}
IndexDialog::Column* IndexDialog::buildColumn(SqliteExpr* expr, int row)
{
Column* column = new Column(expr, ui->columnsTable);
buildColumn(column, row);
return column;
}
void IndexDialog::buildColumn(Column* column, int row)
{
totalColumns++;
ui->columnsTable->setRowCount(totalColumns);
QString key = column->getKey();
columns[key] = column;
columnsByRow << column;
column->setCheckParent(new QWidget());
QHBoxLayout* layout = new QHBoxLayout();
QMargins margins = layout->contentsMargins();
margins.setTop(0);
margins.setBottom(0);
margins.setLeft(4);
margins.setRight(4);
layout->setContentsMargins(margins);
column->getCheckParent()->setLayout(layout);
column->setCheck(new QCheckBox(column->getKey()));
column->getCheckParent()->layout()->addWidget(column->getCheck());
columnStateSignalMapping->setMapping(column->getCheck(), key);
connect(column->getCheck(), SIGNAL(toggled(bool)), columnStateSignalMapping, SLOT(map()));
connect(column->getCheck(), SIGNAL(toggled(bool)), this, SLOT(updateValidation()));
column->setCollation(new QComboBox());
column->getCollation()->setEditable(true);
column->getCollation()->lineEdit()->setPlaceholderText(tr("default", "index dialog"));
column->getCollation()->setModel(&collations);
column->setSort(new QComboBox());
column->getSort()->setToolTip(tr("Sort order", "table constraints"));
QStringList sortList = {"", sqliteSortOrder(SqliteSortOrder::ASC), sqliteSortOrder(SqliteSortOrder::DESC)};
column->getSort()->addItems(sortList);
column->prepareForNewRow();
column->assignToNewRow(row);
updateColumnState(key);
}
void IndexDialog::updateColumnState(const QString& columnKey)
{
Column* col = columns[columnKey];
bool enabled = col->getCheck()->isChecked();
col->getSort()->setEnabled(enabled);
col->getCollation()->setEnabled(enabled);
}
void IndexDialog::updatePartialConditionState()
{
ui->partialIndexEdit->setEnabled(ui->partialIndexCheck->isChecked());
updateValidation();
}
void IndexDialog::updateDdl()
{
rebuildCreateIndex();
QString formatted = FORMATTER->format("sql", createIndex->detokenize(), db);
ui->ddlEdit->setPlainText(formatted);
}
void IndexDialog::tabChanged(int tab)
{
if (tab == 1)
updateDdl();
}
void IndexDialog::moveColumnUp()
{
QModelIndex idx = ui->columnsTable->selectionModel()->currentIndex();
if (!idx.isValid())
return;
int row = idx.row();
if (row <= 0)
return;
columnsByRow.move(row, row - 1);
rebuildColumnsByNewOrder();
idx = ui->columnsTable->model()->index(row - 1, 0);
ui->columnsTable->selectionModel()->setCurrentIndex(idx, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
}
void IndexDialog::moveColumnDown()
{
QModelIndex idx = ui->columnsTable->selectionModel()->currentIndex();
if (!idx.isValid())
return;
int row = idx.row();
int cols = tableColumns.size();
if ((row + 1) >= cols)
return;
columnsByRow.move(row, row + 1);
rebuildColumnsByNewOrder();
idx = ui->columnsTable->model()->index(row + 1, 0);
ui->columnsTable->selectionModel()->setCurrentIndex(idx, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
}
void IndexDialog::updateToolBarButtons(const QModelIndex& idx)
{
if (!idx.isValid())
{
ui->editExprColumnButton->setEnabled(false);
ui->delExprColumnButton->setEnabled(false);
ui->moveUpButton->setEnabled(false);
ui->moveDownButton->setEnabled(false);
return;
}
int row = idx.row();
int cols = tableColumns.size();
ui->moveUpButton->setEnabled(row > 0);
ui->moveDownButton->setEnabled((row + 1) < cols);
bool isExpr = columnsByRow[row]->isExpr();
ui->editExprColumnButton->setEnabled(isExpr);
ui->delExprColumnButton->setEnabled(isExpr);
}
void IndexDialog::addExprColumn()
{
IndexExprColumnDialog dialog(db, this);
dialog.setExistingExprColumnKeys(getExistingColumnExprs());
dialog.setTableColumns(getTableColumns());
if (!dialog.exec())
return;
SqliteExpr* expr = dialog.getColumn();
if (!expr)
{
qCritical() << "Null expr in IndexDialog::addExprColumn(). Aborting.";
return;
}
int row = columnsByRow.size();
ui->columnsTable->insertRow(row);
Column* col = buildColumn(expr, row);
col->getCheck()->setChecked(true);
rebuildColumnsByNewOrder();
ui->columnsTable->scrollToBottom();
updateValidation();
}
void IndexDialog::editExprColumn(int row)
{
if (row < 0)
row = ui->columnsTable->currentRow();
if (row < 0 || row >= columnsByRow.size())
{
qWarning() << "IndexDialog::editExprColumn() called for row out of bounds:" << row << "while there are" << columnsByRow.size() << "rows.";
return;
}
Column* col = columnsByRow[row];
if (!col->isExpr())
{
qWarning() << "IndexDialog::editExprColumn() called for non-expr index column.";
return;
}
IndexExprColumnDialog dialog(db, col->getExpr(), this);
dialog.setExistingExprColumnKeys(getExistingColumnExprs(col->getKey()));
dialog.setTableColumns(getTableColumns());
if (!dialog.exec())
return;
SqliteExpr* expr = dialog.getColumn();
if (!expr)
{
qCritical() << "Null expr in IndexDialog::editExprColumn(). Aborting.";
return;
}
QString oldKey = col->getKey();
col->setExpr(expr);
QString newKey = col->getKey();
columns.remove(oldKey);
columns[newKey] = col;
col->getCheck()->setText(newKey);
col->getCheck()->setChecked(true);
rebuildColumnsByNewOrder();
updateValidation();
}
void IndexDialog::delExprColumn()
{
int row = ui->columnsTable->currentRow();
if (row < 0 || row >= columnsByRow.size())
{
qWarning() << "IndexDialog::delExprColumn() called for row out of bounds:" << row << "while there are" << columnsByRow.size() << "rows.";
return;
}
Column* col = columnsByRow[row];
if (!col->isExpr())
{
qWarning() << "IndexDialog::delExprColumn() called for non-expr index column.";
return;
}
// Removes all widgets in the row
ui->columnsTable->removeRow(row);
columnsByRow.removeOne(col);
columns.remove(col->getKey());
delete col;
rebuildColumnsByNewOrder();
updateValidation();
}
void IndexDialog::applyColumnValues()
{
Column* column = nullptr;
QString key;
int row = 0;
int totalRows = tableColumns.size();
bool orderChanged = false;
QStringList orderedIndexKeys;
for (SqliteOrderBy* idxCol : createIndex->indexedColumns)
{
key = getKey(idxCol);
orderedIndexKeys << key;
if (idxCol->isSimpleColumn())
{
column = columns[key];
if (!column)
{
qCritical() << "Cannot find column by name or expression! Column name/expression:" << key
<< ", available columns:" << columns.keys() << ", index name:" << index;
continue;
}
}
else
column = buildColumn(idxCol, totalRows++);
column->getCheck()->setChecked(true);
updateColumnState(key);
column->getSort()->setCurrentText(sqliteSortOrder(idxCol->order));
column->getCollation()->setCurrentText(idxCol->getCollation());
// Setting proper order
int intendedRow = columnsByRow.indexOf(column);
if (intendedRow != row)
{
columnsByRow.move(intendedRow, row);
orderChanged = true;
}
row++;
}
if (orderChanged)
rebuildColumnsByNewOrder();
}
void IndexDialog::applyIndex()
{
applyColumnValues();
ui->uniqueCheck->setChecked(createIndex->uniqueKw);
ui->partialIndexCheck->setChecked(createIndex->where != nullptr);
if (createIndex->where)
ui->partialIndexEdit->setPlainText(createIndex->where->detokenize());
}
SqliteOrderBy* IndexDialog::addIndexedColumn(const QString& name)
{
SqliteOrderBy* idxCol = new SqliteOrderBy();
idxCol->setParent(createIndex.data());
SqliteExpr* expr = new SqliteExpr();
expr->initId(name);
idxCol->expr = expr;
expr->setParent(idxCol);
createIndex->indexedColumns << idxCol;
return idxCol;
}
SqliteOrderBy* IndexDialog::addIndexedColumn(SqliteExpr* expr)
{
SqliteOrderBy* idxCol = new SqliteOrderBy();
idxCol->setParent(createIndex.data());
SqliteExpr* clonedExpr = dynamic_cast<SqliteExpr*>(expr->clone());
idxCol->expr = clonedExpr;
clonedExpr->setParent(idxCol);
createIndex->indexedColumns << idxCol;
return idxCol;
}
void IndexDialog::addCollation(SqliteOrderBy* col, const QString& name)
{
SqliteExpr* expr = new SqliteExpr();
col->expr->setParent(expr);
expr->initCollate(col->expr, name);
expr->setParent(col);
col->expr = expr;
}
void IndexDialog::rebuildCreateIndex()
{
createIndex = SqliteCreateIndexPtr::create();
createIndex->index = ui->nameEdit->text();
if (ui->tableCombo->currentIndex() > -1)
createIndex->table = ui->tableCombo->currentText();
createIndex->uniqueKw = ui->uniqueCheck->isChecked();
SqliteOrderBy* idxCol = nullptr;
for (Column* column : columnsByRow)
{
if (!column->getCheck()->isChecked())
continue;
if (column->isExpr())
idxCol = addIndexedColumn(column->getExpr());
else
idxCol = addIndexedColumn(column->getName());
if (!column->getCollation()->currentText().isEmpty())
addCollation(idxCol, column->getCollation()->currentText());
if (column->getSort()->currentIndex() > 0)
idxCol->order = sqliteSortOrder(column->getSort()->currentText());
}
if (ui->partialIndexCheck->isChecked())
{
if (createIndex->where)
delete createIndex->where;
Parser parser;
SqliteExpr* expr = parser.parseExpr(ui->partialIndexEdit->toPlainText());
if (expr)
{
expr->setParent(createIndex.data());
createIndex->where = expr;
}
else
{
qCritical() << "Could not parse expression from partial index condition: " << ui->partialIndexEdit->toPlainText()
<< ", the CREATE INDEX statement will be incomplete.";
}
}
createIndex->rebuildTokens();
}
void IndexDialog::queryDuplicates()
{
static QString queryTpl = QStringLiteral("SELECT %1 FROM %2 GROUP BY %3 HAVING %4;\n");
static QString countTpl = QStringLiteral("count(%1) AS %2");
static QString countColNameTpl = QStringLiteral("count(%1)");
static QString countConditionTpl = QStringLiteral("count(%1) > 1");
QStringList cols;
QStringList grpCols;
QStringList countCols;
QString wrappedCol;
QString countColName;
for (const QString& column : tableColumns)
{
if (!columns[column]->getCheck()->isChecked())
continue;
wrappedCol = wrapObjIfNeeded(column);
cols << wrappedCol;
grpCols << wrappedCol;
countColName = wrapObjIfNeeded(countColNameTpl.arg(column));
cols << countTpl.arg(wrappedCol, countColName);
countCols << countConditionTpl.arg(wrappedCol);
}
EditorWindow* editor = MAINWINDOW->openSqlEditor();
editor->setCurrentDb(db);
QString sqlCols = cols.join(", ");
QString sqlGrpCols = grpCols.join(", ");
QString sqlCntCols = countCols.join(" AND ");
QString sqlTable = wrapObjIfNeeded(ui->tableCombo->currentText());
editor->setContents(queryTpl.arg(sqlCols, sqlTable, sqlGrpCols, sqlCntCols));
editor->execute();
}
void IndexDialog::clearColumns()
{
for (Column* c : columns.values())
delete c;
columns.clear();
columnsByRow.clear();
}
void IndexDialog::rebuildColumnsByNewOrder()
{
int row = 0;
for (Column* column : columnsByRow)
{
column->prepareForNewRow();
column->assignToNewRow(row++);
}
}
QString IndexDialog::getKey(SqliteOrderBy* col) const
{
if (col->isSimpleColumn())
return col->getColumnName();
return buildKey(col->expr);
}
QString IndexDialog::buildKey(SqliteExpr* expr)
{
if (expr->mode == SqliteExpr::Mode::COLLATE && expr->expr1)
return expr->expr1->tokens.filterWhiteSpaces(false).detokenize().trimmed();
return expr->tokens.filterWhiteSpaces(false).detokenize().trimmed();
}
QStringList IndexDialog::getExistingColumnExprs(const QString& exceptThis) const
{
QString key;
QStringList exprs;
for (Column* col : columnsByRow)
{
if (col->isExpr())
{
key = col->getKey();
if (!exceptThis.isNull() && key == exceptThis)
continue;
exprs << key;
}
}
return exprs;
}
QStringList IndexDialog::getTableColumns() const
{
QStringList cols;
for (Column* col : columnsByRow)
{
if (!col->isExpr())
cols << col->getKey();
}
return cols;
}
void IndexDialog::preReject()
{
preRejected = true;
}
QString IndexDialog::getOriginalDdl() const
{
SqliteCreateIndex* initialCreateIndex = originalCreateIndex->typeClone<SqliteCreateIndex>();
initialCreateIndex->rebuildTokens();
QString initialDdl = initialCreateIndex->detokenize();
delete initialCreateIndex;
return initialDdl;
}
void IndexDialog::accept()
{
QString initialDdl = getOriginalDdl();
rebuildCreateIndex();
QString ddl = createIndex->detokenize();
if (initialDdl == ddl)
{
// Nothing changed. Just close.
QDialog::accept();
return;
}
QStringList sqls;
if (existingIndex)
sqls << QString("DROP INDEX %1").arg(wrapObjIfNeeded(originalCreateIndex->index));
sqls << ddl;
if (!CFG_UI.General.DontShowDdlPreview.get())
{
DdlPreviewDialog dialog(db, this);
dialog.setDdl(sqls);
if (dialog.exec() != QDialog::Accepted)
return;
}
ChainExecutor executor;
executor.setDb(db);
executor.setAsync(false);
executor.setQueries(sqls);
executor.exec();
if (executor.getSuccessfulExecution())
{
CFG->addDdlHistory(sqls.join("\n"), db->getName(), db->getPath());
QDialog::accept();
DBTREE->refreshSchema(db);
return;
}
if (executor.getErrors().size() == 1 && executor.getErrors().first().first == SQLITE_CONSTRAINT)
{
int res = QMessageBox::critical(this,
tr("Error", "index dialog"),
tr("Cannot create unique index, because values in selected columns are not unique. "
"Would you like to execute SELECT query to see problematic values?"),
QMessageBox::Yes,
QMessageBox::No);
if (res == QMessageBox::Yes)
{
QDialog::reject();
queryDuplicates();
}
}
else
{
QMessageBox::critical(this, tr("Error", "index dialog"), tr("An error occurred while executing SQL statements:\n%1")
.arg(executor.getErrorsMessages().join(",\n")), QMessageBox::Ok);
}
}
int IndexDialog::exec()
{
if (preRejected)
return Rejected;
return QDialog::exec();
}
IndexDialog::Column::Column(const QString& name, QTableWidget* table)
{
this->name = name;
this->table = table;
}
IndexDialog::Column::Column(SqliteExpr* expr, QTableWidget* table)
{
this->expr = expr;
this->table = table;
}
IndexDialog::Column::~Column()
{
safe_delete(expr);
}
void IndexDialog::Column::assignToNewRow(int row)
{
table->setCellWidget(row, 0, column1Contrainer);
table->setCellWidget(row, 1, column2Contrainer);
table->setCellWidget(row, 2, column3Contrainer);
}
void IndexDialog::Column::prepareForNewRow()
{
column1Contrainer = defineContainer(checkParent);
column2Contrainer = defineContainer(sort);
column3Contrainer = defineContainer(collation);
}
QCheckBox* IndexDialog::Column::getCheck() const
{
return check;
}
void IndexDialog::Column::setCheck(QCheckBox* cb)
{
check = cb;
}
QWidget* IndexDialog::Column::getCheckParent() const
{
return checkParent;
}
void IndexDialog::Column::setCheckParent(QWidget* w)
{
checkParent = w;
}
QComboBox* IndexDialog::Column::getSort() const
{
return sort;
}
void IndexDialog::Column::setSort(QComboBox* cb)
{
sort = cb;
}
QComboBox* IndexDialog::Column::getCollation() const
{
return collation;
}
void IndexDialog::Column::setCollation(QComboBox* cb)
{
collation = cb;
}
QString IndexDialog::Column::getName() const
{
return name;
}
SqliteExpr* IndexDialog::Column::getExpr() const
{
// If column's expression contains collation at top level,
// the EXPR for processing is inner expr of collation.
if (expr->mode == SqliteExpr::Mode::COLLATE)
return expr->expr1;
return expr;
}
void IndexDialog::Column::setExpr(SqliteExpr* expr)
{
safe_delete(this->expr);
this->expr = expr;
}
bool IndexDialog::Column::isExpr() const
{
return expr != nullptr;
}
QString IndexDialog::Column::getKey() const
{
if (expr)
return IndexDialog::buildKey(expr);
else
return name;
}
QWidget* IndexDialog::Column::defineContainer(QWidget* w)
{
QHBoxLayout* layout = new QHBoxLayout();
QMargins margins = layout->contentsMargins();
margins.setTop(0);
margins.setBottom(0);
margins.setLeft(0);
margins.setRight(0);
layout->setContentsMargins(margins);
QWidget* container = new QWidget();
container->setLayout(layout);
container->layout()->addWidget(w);
return container;
}
|