Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ target_sources(${PROJECT_NAME}
src/sql/sqlitetypes.h
src/sql/Query.h
src/sql/ObjectIdentifier.h
src/sql/DropOrder.h
src/csvparser.h
src/sqlite.h
src/Data.h
Expand Down Expand Up @@ -185,6 +186,7 @@ target_sources(${PROJECT_NAME}
src/sql/sqlitetypes.cpp
src/sql/Query.cpp
src/sql/ObjectIdentifier.cpp
src/sql/DropOrder.cpp
src/sqltextedit.cpp
src/docktextedit.cpp
src/csvparser.cpp
Expand Down
81 changes: 81 additions & 0 deletions src/MainWindow.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -913,8 +913,89 @@ void MainWindow::compact()
dialog.exec();
}

// Collect all tables, views, indexes and triggers which are selected in the Database Structure tree
static std::vector<sqlb::DropItem> selectedDropItems(const QTreeView& view)
{
std::vector<sqlb::DropItem> items;
QSet<QModelIndex> seen;
const QModelIndexList selected = view.selectionModel()->selectedIndexes();
for(const QModelIndex& index : selected)
{
// Every selected row has one selected index per column. Only look at each row once.
const QModelIndex nameIndex = index.sibling(index.row(), DbStructureModel::ColumnName);
if(seen.contains(nameIndex))
continue;
seen.insert(nameIndex);

const QString type = nameIndex.sibling(nameIndex.row(), DbStructureModel::ColumnObjectType).data(Qt::EditRole).toString();
if(type != "table" && type != "view" && type != "trigger" && type != "index")
continue;

items.push_back({type.toStdString(), sqlb::ObjectIdentifier(
nameIndex.sibling(nameIndex.row(), DbStructureModel::ColumnSchema).data(Qt::EditRole).toString().toStdString(),
nameIndex.data(Qt::EditRole).toString().toStdString())});
}
return items;
}

void MainWindow::deleteObjects(const std::vector<sqlb::DropItem>& items)
{
// List all objects in the confirmation, but keep the dialog at a sensible size
const size_t maxListed = 15;
QString list;
for(size_t i = 0; i < items.size() && i < maxListed; ++i)
list += QString("\n%1 '%2'").arg(QString::fromStdString(items[i].type), QString::fromStdString(items[i].object.toDisplayString()));
if(items.size() > maxListed)
list += "\n" + tr("... and %n more", nullptr, static_cast<int>(items.size() - maxListed));

const QString message = tr("Are you sure you want to delete the following %n objects?\nAll data associated with deleted tables will be lost.", nullptr, static_cast<int>(items.size())) + "\n" + list;
if(QMessageBox::warning(this, QApplication::applicationName(), message,
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
return;

// Delete everything in one savepoint so that either all or none of the objects are removed
// The restore point makes sure the changes are not written to disk before the user saves them.
const bool wasDirty = db.getDirty();
const std::string savepoint = db.generateSavepointName("deleteobjects");
if(!db.setSavepoint() || !db.setSavepoint(savepoint))
{
QMessageBox::warning(this, QApplication::applicationName(), tr("Error: could not delete the selected objects.") + " " +
tr("Message from database engine:\n%1").arg(db.lastError()));
return;
}
for(const sqlb::DropItem& item : items)
{
if(!db.executeSQL(sqlb::dropStatement(item), false, true))
{
const QString error = tr("Message from database engine:\n%1").arg(db.lastError());
db.revertToSavepoint(savepoint);
if(!wasDirty)
db.revertToSavepoint(); // Nothing changed, so don't leave the database marked as modified
QMessageBox::warning(this, QApplication::applicationName(),
tr("Error: could not delete the selected objects. No objects were deleted.") + " " + error);
return;
}
}
db.releaseSavepoint(savepoint);

refreshTableBrowsers();
changeObjectSelection();
}

void MainWindow::deleteObject()
{
// If more than one object is selected in the Database Structure tab, delete all of them with a single confirmation
if(ui->mainTab->currentWidget() == ui->structure)
{
// Ordering also removes duplicates, e.g. a table which is selected in both the Tables and the Browsables branch
const std::vector<sqlb::DropItem> items = sqlb::orderForDrop(selectedDropItems(*ui->dbTreeWidget));
if(items.size() > 1)
{
deleteObjects(items);
return;
}
}

// Get name and type of object to delete
sqlb::ObjectIdentifier obj;
QString type;
Expand Down
2 changes: 2 additions & 0 deletions src/MainWindow.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

#include "dbstructureqitemviewfacade.h"
#include "sqlitedb.h"
#include "sql/DropOrder.h"

#include <memory>
#include <vector>
Expand Down Expand Up @@ -152,6 +153,7 @@ friend TableBrowserDock;

QList<TableBrowserDock*> allTableBrowserDocks() const;
void getSelectedObject(QString &type, sqlb::ObjectIdentifier& obj);
void deleteObjects(const std::vector<sqlb::DropItem>& items); // Expects items in the order of sqlb::orderForDrop()

protected:
void closeEvent(QCloseEvent *) override;
Expand Down
32 changes: 32 additions & 0 deletions src/sql/DropOrder.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#include "DropOrder.h"

#include <algorithm>
#include <cctype>

namespace sqlb {

std::vector<DropItem> orderForDrop(const std::vector<DropItem>& items)
{
// Objects which depend on others must be dropped first
static const char* const type_order[] = {"trigger", "index", "view", "table"};

std::vector<DropItem> result;
for(const char* type : type_order)
{
for(const DropItem& item : items)
{
if(item.type == type && std::find(result.begin(), result.end(), item) == result.end())
result.push_back(item);
}
}
return result;
}

std::string dropStatement(const DropItem& item)
{
std::string type = item.type;
std::transform(type.begin(), type.end(), type.begin(), [](unsigned char c) { return static_cast<char>(std::toupper(c)); });
return "DROP " + type + " " + item.object.toString() + ";";
}

}
34 changes: 34 additions & 0 deletions src/sql/DropOrder.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#ifndef DROPORDER_H
#define DROPORDER_H

#include "ObjectIdentifier.h"

#include <string>
#include <vector>

namespace sqlb {

// A database object which is going to be dropped. The type is one of "table", "view", "index" and "trigger".
struct DropItem
{
std::string type;
ObjectIdentifier object;

bool operator==(const DropItem& rhs) const
{
return type == rhs.type && object == rhs.object;
}
};

// Return the items in an order in which they can safely be dropped one after the other: triggers first, then indexes,
// then views and finally tables. This way no object is dropped before the objects which depend on it, and dropping a
// table never makes the later DROP of one of its own indexes or triggers fail. Duplicates and items of unknown type are
// removed. The relative order of items of the same type is preserved.
std::vector<DropItem> orderForDrop(const std::vector<DropItem>& items);

// Build the statement which drops a single item
std::string dropStatement(const DropItem& item);

}

#endif
9 changes: 7 additions & 2 deletions src/sqlitetablemodel.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -226,10 +226,10 @@ static QString toSuperScript(T number)

QVariant SqliteTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole && role != Qt::EditRole && role != Qt::FontRole)
if (role != Qt::DisplayRole && role != Qt::EditRole && role != Qt::FontRole && role != Qt::ToolTipRole)
return QVariant();

if (orientation == Qt::Vertical && role == Qt::FontRole)
if (orientation == Qt::Vertical && (role == Qt::FontRole || role == Qt::ToolTipRole))
return QVariant();

if (orientation == Qt::Horizontal)
Expand All @@ -242,6 +242,11 @@ QVariant SqliteTableModel::headerData(int section, Qt::Orientation orientation,
switch (role) {
case Qt::EditRole:
return QString::fromStdString(plainHeader);
case Qt::ToolTipRole:
// When browsing a table the first header is the hidden row id column, so the sections already are 1-based column numbers there
if(m_table_of_query)
return section > 0 ? tr("Column %1: %2").arg(section).arg(QString::fromStdString(plainHeader)) : QVariant();
return tr("Column %1: %2").arg(section + 1).arg(QString::fromStdString(plainHeader));
case Qt::FontRole: {
bool is_pk = false;
bool is_fk = getForeignKeyClause(column-1) != nullptr;
Expand Down
39 changes: 39 additions & 0 deletions src/tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,45 @@ if(WIN32)
set_tests_properties(test-global-filter PROPERTIES ENVIRONMENT "PATH=${TESTGLOBALFILTER_PATH}")
endif()

# test drop order

set(TESTDROPORDER_SRC
TestDropOrder.cpp
../sql/DropOrder.cpp
../sql/ObjectIdentifier.cpp
)

set(TESTDROPORDER_HDR
TestDropOrder.h
../sql/DropOrder.h
../sql/ObjectIdentifier.h
)

add_executable(test-drop-order ${TESTDROPORDER_HDR} ${TESTDROPORDER_SRC})
if(QT_MAJOR STREQUAL "Qt6")
set_target_properties(test-drop-order PROPERTIES
AUTOUIC_OPTIONS "--connections=string"
)
endif()
target_link_libraries(test-drop-order ${QT_MAJOR}::Test ${LIBSQLITE_NAME})
add_test(NAME test-drop-order COMMAND $<TARGET_FILE:test-drop-order>)
set_tests_properties(test-drop-order PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
if(WIN32)
set(_do_extra_paths "")
foreach(_p IN LISTS CMAKE_PREFIX_PATH)
list(APPEND _do_extra_paths "${_p}" "${_p}/bin")
# OpenSSL 3 Universal installer layout: bin/x86, bin/x64
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
list(APPEND _do_extra_paths "${_p}/bin/x64")
else()
list(APPEND _do_extra_paths "${_p}/bin/x86")
endif()
endforeach()
# SQLite and SQLCipher are built as DLLs in the CMake prefix by the Windows CI jobs.
string(REPLACE ";" "\\;" TESTDROPORDER_PATH "${_do_extra_paths};$ENV{PATH}")
set_tests_properties(test-drop-order PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen;PATH=${TESTDROPORDER_PATH}")
endif()

# test cache

set(TESTCACHE_SRC
Expand Down
Loading
Loading