diff --git a/.idea/QtSettings.xml b/.idea/QtSettings.xml
deleted file mode 100644
index 0248d0c..0000000
--- a/.idea/QtSettings.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/misc.xml b/.idea/misc.xml
deleted file mode 100644
index 0b76fe5..0000000
--- a/.idea/misc.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/pgLab.iml b/.idea/pgLab.iml
index 4c94235..6102194 100644
--- a/.idea/pgLab.iml
+++ b/.idea/pgLab.iml
@@ -1,2 +1,8 @@
-
\ No newline at end of file
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/pglab/CMakeLists.txt b/pglab/CMakeLists.txt
index fb3d3f2..ab4dda5 100644
--- a/pglab/CMakeLists.txt
+++ b/pglab/CMakeLists.txt
@@ -30,9 +30,9 @@ set(PGLAB_SOURCES
codeeditor/GutterPainter.cpp
crud/CrudModel.cpp
crud/CrudTab.cpp
- crud/DataGridWidget.cpp
querytool/QueryExplainModel.cpp
querytool/QueryParamListController.cpp
+ querytool/QueryResultModel.cpp
querytool/QueryTool.cpp
serverinspector/DatabasesPage.cpp
serverinspector/RolesPage.cpp
diff --git a/pglab/crud/CrudModel.cpp b/pglab/crud/CrudModel.cpp
index c30a1bc..8367f32 100644
--- a/pglab/crud/CrudModel.cpp
+++ b/pglab/crud/CrudModel.cpp
@@ -4,13 +4,11 @@
#include "catalog/PgAttribute.h"
#include "catalog/PgAttributeContainer.h"
#include "catalog/PgConstraintContainer.h"
-#include "catalog/PgClassContainer.h"
#include "SqlFormattingUtils.h"
#include "Pgsql_oids.h"
#include "CustomDataRole.h"
#include
#include
-#include
#include
#include "Pgsql_oids.h"
#include "Pgsql_PgException.h"
@@ -41,23 +39,12 @@ void CrudModel::setConfig(std::shared_ptr db, const PgClass &table
{
m_database = db;
m_table = table;
- m_wholeTable = true;
+ m_primaryKey = db->catalog()->constraints()->getPrimaryForRelation(table.oid());
callLoadData = true;
auto dbconfig = m_database->config();
m_dbConn.setupConnection(dbconfig);
}
-void CrudModel::setResult(std::shared_ptr db, std::shared_ptr result)
-{
- m_database = db;
- m_table.reset();
- m_wholeTable = false;
- callLoadData = false;
- auto dbconfig = m_database->config();
- m_dbConn.setupConnection(dbconfig);
- loadIntoModel(result);
-}
-
QVariant CrudModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (section == 0)
@@ -218,8 +205,6 @@ QVariant CrudModel::data(const QModelIndex &index, int role) const
if (value)
return StringToVariant(value->c_str(), typ);
}
- else if (role == Qt::ForegroundRole && !m_wholeTable && columnIsReadOnly(index.column()))
- return QBrush(Qt::gray);
return {};
}
@@ -244,18 +229,13 @@ void CrudModel::loadData()
void CrudModel::loadIntoModel(std::shared_ptr data)
{
beginResetModel();
- bool was_dirty = hasPendingChanges();
m_pendingRowList.clear();
m_roData = data;
initializeColumnList();
- m_mapping.emplace(createResultSourceMapping(*m_roData, *m_database->catalog()));
lastRowKey = data->rows() - 1;
initRowMapping();
- if (m_wholeTable)
- appendNewRowInternal();
+ appendNewRowInternal();
endResetModel();
- if (was_dirty)
- emit pendingChangesChanged(false);
}
void CrudModel::initRowMapping()
@@ -297,7 +277,7 @@ Qt::ItemFlags CrudModel::flags(const QModelIndex &index) const
if (index.column() < PreColumnCount)
return flags;
- if (!columnIsReadOnly(index.column()))
+ if (m_primaryKey && !columnIsReadOnly(index.column()))
flags |= Qt::ItemIsEditable;
return flags;
@@ -324,10 +304,7 @@ bool CrudModel::setData(const QModelIndex &index, const QVariant &value, int rol
s.clear();
val = s;
}
- bool was_dirty = hasPendingChanges();
m_pendingRowList.setValue(col, row_mapping.rowKey, val);
- if (!was_dirty)
- emit pendingChangesChanged(true);
emit dataChanged(index, index, QVector() << role);
return true;
@@ -335,17 +312,22 @@ bool CrudModel::setData(const QModelIndex &index, const QVariant &value, int rol
return false;
}
-std::tuple> CrudModel::saveRow(const PendingRow &pending_row, const RowMapping &row_mapping)
+std::tuple> CrudModel::saveRow(const PendingRow &pending_row)
{
auto data = pending_row.data();
- if (data.empty())
- return { true, {} };
+ RowMapping& rowmapping = m_rowMapping[pending_row.row()];
- if (row_mapping.isNew())
+ if (!data.empty())
{
QString buffer;
Pgsql::Params params;
- std::tie(buffer, params) = createInsertQuery(pending_row);
+ if (rowmapping.isNew())
+ std::tie(buffer, params) = createInsertQuery(pending_row);
+ else
+ {
+ Pgsql::Params pkey_params = getPKeyParamsForRow(pending_row.row());
+ std::tie(buffer, params) = createUpdateQuery(pkey_params, pending_row);
+ }
Pgsql::Connection db_update_conn;
auto dbconfig = m_database->config();
@@ -374,120 +356,59 @@ std::tuple> CrudModel::saveRow(const Pending
msgBox.setText(ex.what());
msgBox.exec();
}
- return { false, {} };
- }
-
- return saveUpdate(pending_row, row_mapping);
-}
-
-std::tuple> CrudModel::saveUpdate(const PendingRow &pending_row, const RowMapping &row_mapping)
-{
- std::set tables;
- for (const auto &e : pending_row.data())
- tables.insert(m_mapping->tableOid(e.first));
-
- try
- {
- Pgsql::Connection db_update_conn;
- auto dbconfig = m_database->config();
- db_update_conn.connect(dbconfig.connectionString());
- auto tx = Pgsql::Transaction::startTransaction(db_update_conn);
- for (Oid table_oid : tables)
- {
- QString buffer;
- Pgsql::Params params;
- std::tie(buffer, params) = createUpdateQuery(table_oid, pending_row, row_mapping);
- auto result = tx.queryParam(buffer, params);
- if (!result || result.tuplesAffected() != 1)
- {
- QMessageBox::warning(nullptr, tr("Update failed"), tr("The change did not update exactly one row in %1, the row may have changed or is no longer unique.").arg(tableName(table_oid)));
- return { false, {} };
- }
- }
- tx.commit();
-
- std::vector values;
- values.reserve(m_roData->cols());
- for (int col = 0; col < m_roData->cols(); ++col)
- {
- auto &&pending = pending_row.data();
- auto found = pending.find(col);
- values.push_back(found != pending.end() ? found->second : getSavedData(row_mapping, col));
- }
- return { true, values };
- }
- catch (const Pgsql::PgResultError &ex)
- {
- QMessageBox msgBox;
- msgBox.setText(ex.what());
- msgBox.exec();
}
return { false, {} };
}
-QString CrudModel::tableName(Oid table_oid) const
+Pgsql::Params CrudModel::getPKeyParamsForRow(int row) const
{
- auto table = m_database->catalog()->classes()->getByKey(table_oid);
- return table ? table->fullyQualifiedQuotedObjectName() : QString();
-}
-
-std::vector CrudModel::resultColumnsOfTable(Oid table_oid) const
-{
- std::vector cols;
- for (int col = 0; col < m_roData->cols(); ++col)
- if (m_roData->ftable(col) == table_oid && m_roData->ftableCol(col) > 0)
- cols.push_back(col);
- return cols;
-}
-
-QString CrudModel::attributeName(int col) const
-{
- if (col < static_cast(columnList.size()) && columnList[col])
- return columnList[col]->name;
- return QString::fromUtf8(m_roData->getColName(col));
-}
-
-Pgsql::Params CrudModel::getPKeyParamsForRow(const RowMapping &row_mapping, Oid table_oid) const
-{
- Pgsql::Params params;
- for (int col : m_mapping->primaryKeyColumns(table_oid))
+ Pgsql::Params params;
+ for (auto attnum : m_primaryKey->key)
{
- auto s = getSavedData(row_mapping, col);
- params.add(s, getType(col));
- }
- return params;
+ const int col = attNumToCol(attnum);
+ Oid t = getType(col);
+ auto s = getSavedData(col, row);
+ params.add(s, t);
+ }
+ return params;
}
-std::tuple CrudModel::createUpdateQuery(Oid table_oid, const PendingRow &pending_row, const RowMapping &row_mapping)
+QString CrudModel::columnName(int col) const
{
- Pgsql::Params params;
- QString table_name = tableName(table_oid);
- QString buffer;
- QTextStream q(&buffer);
- q << "UPDATE " << table_name << " AS d\n SET ";
- int param = 0;
- for (auto& e : pending_row.data())
- {
- if (m_mapping->tableOid(e.first) != table_oid)
- continue;
- if (param > 0)
- q << ",";
- q << quoteIdent(attributeName(e.first)) << "=$" << ++param;
- params.add(e.second, getType(e.first));
- }
+ return m_roData->getColName(col);
+}
- q << "\nWHERE ";
- int i = 0;
- for (int col : m_mapping->primaryKeyColumns(table_oid))
+std::tuple CrudModel::createUpdateQuery(const Pgsql::Params &pkey_params, const PendingRow &pending_row)
+{
+ Pgsql::Params params;
+ auto data = pending_row.data();
+ QString table_name = m_table->fullyQualifiedQuotedObjectName();
+ QString buffer;
+ QTextStream q(&buffer);
+ q << "UPDATE " << table_name << " AS d\n SET ";
+ int param = 0;
+ for (auto& e : data)
{
- if (i > 0)
- q << " AND ";
- q << quoteIdent(attributeName(col)) << "=$" << ++param;
- ++i;
- }
- params.addParams(getPKeyParamsForRow(row_mapping, table_oid));
- q.flush();
- return { buffer, params };
+ if (param > 0)
+ q << ",";
+ q << quoteIdent(columnName(e.first)) << "=$" << ++param;
+ params.add(e.second, getType(e.first));
+ }
+
+ q << "\nWHERE ";
+ int i = 0;
+ for (auto attnum : m_primaryKey->key)
+ {
+ int col = attNumToCol(attnum);
+ if (i > 0)
+ q << " AND ";
+ q << quoteIdent(columnName(col)) << "=$" << ++param;
+ ++i;
+ }
+ params.addParams(pkey_params);
+ q << "\nRETURNING *";
+ q.flush();
+ return { buffer, params };
}
std::tuple CrudModel::createInsertQuery(const PendingRow &pending_row)
@@ -503,11 +424,12 @@ std::tuple CrudModel::createInsertQuery(const PendingRow
for (const auto& e : data)
{
int num = e.first;
+ auto&& column = columnList[num];
if (first)
first = false;
else
q << ",";
- q << quoteIdent(attributeName(num));
+ q << quoteIdent(column.name);
}
q << ") VALUES ($1";
for (size_t p = 2; p <= data.size(); ++p)
@@ -520,6 +442,19 @@ std::tuple CrudModel::createInsertQuery(const PendingRow
return { buffer, params };
}
+std::tuple CrudModel::createDeleteStatement(const PKeyValues &pkey_values)
+{
+ Pgsql::Params params;
+ size_t i = 0;
+ for (auto attnum : m_primaryKey->key)
+ {
+ const int col = attNumToCol(attnum);
+ params.add(pkey_values[i].c_str(), getType(col));
+ ++i;
+ }
+
+ return { createDeleteStatement(), params };
+}
QString CrudModel::createDeleteStatement() const
{
@@ -530,11 +465,12 @@ QString CrudModel::createDeleteStatement() const
q << "DELETE FROM " << table_name;
q << "\nWHERE ";
int i = 0;
- for (int col : m_mapping->primaryKeyColumns(m_table->oid()))
+ for (auto attnum : m_primaryKey->key)
{
+ const int col = attNumToCol(attnum);
if (i > 0)
q << " AND ";
- q << quoteIdent(attributeName(col)) << "=$" << ++i;
+ q << quoteIdent(columnName(col)) << "=$" << ++i;
}
q.flush();
@@ -547,13 +483,7 @@ bool CrudModel::savePendingChanges()
while (!m_pendingRowList.m_rows.empty())
{
auto iter = m_pendingRowList.m_rows.begin();
- int pendingKey = iter->first;
- auto mapping_iter = std::find_if(m_rowMapping.begin(), m_rowMapping.end(),
- [pendingKey](const RowMapping &rhs) -> bool { return rhs.rowKey == pendingKey; });
- if (mapping_iter == m_rowMapping.end())
- return false;
-
- auto [ok, modified_row] = saveRow(iter->second, *mapping_iter);
+ auto [ok, modified_row] = saveRow(iter->second);
if (ok)
{
int rowKey = iter->first;
@@ -586,13 +516,9 @@ bool CrudModel::columnIsReadOnly(int column_index) const
if (m_roData == nullptr)
return true;
- int col = column_index - PreColumnCount;
- if (!m_mapping || !m_mapping->isEditable(col))
- return true;
-
- const auto &column = columnList[col];
- return !column || column->getIdentity() == PgAttribute::Identity::Always
- || column->getGenerated() != PgAttribute::Generated::None;
+ auto&& column = columnList[column_index - PreColumnCount];
+ return column.getIdentity() == PgAttribute::Identity::Always
+ || column.getGenerated() != PgAttribute::Generated::None;
}
void CrudModel::initializeColumnList()
@@ -600,51 +526,28 @@ void CrudModel::initializeColumnList()
columnList.clear();
columnList.reserve(m_roData->cols());
auto atts = m_database->catalog()->attributes();
+ auto columns = atts->getColumnsForRelation(m_table->oid());
for (int col = 0; col < m_roData->cols(); ++col)
{
int attnum = m_roData->ftableCol(col);
- if (attnum <= 0)
- {
- columnList.emplace_back();
- continue;
- }
- auto columns = atts->getColumnsForRelation(m_roData->ftable(col));
auto find_result = std::find_if(columns.begin(), columns.end(), [attnum](const PgAttribute &att) { return att.num == attnum; });
- if (find_result != columns.end())
- columnList.emplace_back(*find_result);
- else
- columnList.emplace_back();
+ assert(find_result != columns.end());
+ columnList.push_back(*find_result);
}
}
-bool CrudModel::saveChanges()
+bool CrudModel::submit()
{
- bool was_dirty = hasPendingChanges();
- bool ok = savePendingChanges();
- if (was_dirty != hasPendingChanges())
- emit pendingChangesChanged(hasPendingChanges());
- return ok;
+ return savePendingChanges();
}
-void CrudModel::revertChanges()
+void CrudModel::revert()
{
- if (!hasPendingChanges())
- return;
- m_pendingRowList.clear();
- for (auto &row_mapping : m_rowMapping)
- row_mapping.pending = false;
-
- if (rowCount() > 0)
- emit dataChanged(index(0, 0), index(rowCount() - 1, columnCount() - 1));
- emit pendingChangesChanged(false);
}
void CrudModel::appendNewRow()
{
- if (!m_wholeTable)
- return;
-
int row = static_cast(m_rowMapping.size());
beginInsertRows(QModelIndex(), row, row);
appendNewRowInternal();
@@ -662,8 +565,6 @@ std::tuple CrudModel::removeRows(const std::set
return { true, "" };
if (row_ranges.rbegin()->end() > static_cast(m_rowMapping.size()))
return { false, "Range error" };
- if (!m_wholeTable || !m_table || m_mapping->primaryKeyColumns(m_table->oid()).empty())
- return { false, "Rows can only be removed from a table with a primary key" };
// When removing rows there is no direct mapping anymore between the rows in the grid
// and the rows in m_roData
@@ -688,7 +589,7 @@ std::tuple CrudModel::removeRows(const std::set
for (int current_row = range.start(); current_row < range.end(); ++current_row)
{
auto&& mapping = m_rowMapping[static_cast(current_row)];
- auto params = getPKeyParamsForRow(mapping, m_table->oid());
+ auto params = getPKeyParamsForRow(mapping.rowKey);
if (!params.empty())
db_update_conn.queryParam(delete_statement, params);
}
@@ -697,10 +598,7 @@ std::tuple CrudModel::removeRows(const std::set
// If something goes wrong after this commit we should reload contents of model
}
// Then from model
- bool was_dirty = hasPendingChanges();
RemoveRangesOfRowsFromModel(row_ranges);
- if (was_dirty != hasPendingChanges())
- emit pendingChangesChanged(hasPendingChanges());
return { true, "" };
}
catch (const Pgsql::PgResultError &error)
@@ -735,8 +633,6 @@ void CrudModel::RemoveRangeOfRowsFromModel(IntegerRange range)
beginRemoveRows(QModelIndex(), range.start(), range.end() - 1);
SCOPE_EXIT { endRemoveRows(); };
auto first = m_rowMapping.begin() + range.start();
- for (auto iter = first; iter != first + range.length(); ++iter)
- m_pendingRowList.m_rows.erase(iter->rowKey);
m_rowMapping.erase(first, first + range.length());
}
diff --git a/pglab/crud/CrudModel.h b/pglab/crud/CrudModel.h
index 485b6c2..5a6beb3 100644
--- a/pglab/crud/CrudModel.h
+++ b/pglab/crud/CrudModel.h
@@ -5,10 +5,8 @@
#include "Pgsql_Connection.h"
#include "IntegerRange.h"
-#include "ResultSourceMapping.h"
#include "catalog/PgClass.h"
#include "catalog/PgConstraint.h"
-#include "catalog/PgAttribute.h"
#include
#include