17#include "moc_qgsqueryresultwidget.cpp"
43 mQueryResultsTableView->hide();
44 mQueryResultsTableView->setItemDelegate(
new QgsQueryResultItemDelegate( mQueryResultsTableView ) );
45 mQueryResultsTableView->setContextMenuPolicy( Qt::CustomContextMenu );
46 connect( mQueryResultsTableView, &QTableView::customContextMenuRequested,
this, &QgsQueryResultWidget::showCellContextMenu );
52 QVBoxLayout *vl =
new QVBoxLayout();
53 vl->setContentsMargins( 0, 0, 0, 0 );
54 vl->addWidget( mCodeEditorWidget );
55 mSqlEditorContainer->setLayout( vl );
57 connect( mExecuteButton, &QPushButton::pressed,
this, &QgsQueryResultWidget::executeQuery );
58 connect( mClearButton, &QPushButton::pressed,
this, [ = ]
60 mSqlEditor->setText( QString() );
62 connect( mLoadLayerPushButton, &QPushButton::pressed,
this, [ = ]
66 emit createSqlVectorLayer( mConnection->providerKey(), mConnection->uri(), sqlVectorLayerOptions() );
70 connect( mSqlEditor, &QgsCodeEditorSQL::textChanged,
this, &QgsQueryResultWidget::updateButtons );
71 connect( mSqlEditor, &QgsCodeEditorSQL::selectionChanged,
this, [ = ]
73 mExecuteButton->setText( mSqlEditor->selectedText().isEmpty() ? tr(
"Execute" ) : tr(
"Execute Selection" ) );
75 connect( mFilterToolButton, &QToolButton::pressed,
this, [ = ]
81 std::unique_ptr<QgsVectorLayer> vlayer { mConnection->createSqlVectorLayer( sqlVectorLayerOptions() ) };
83 if ( builder.exec() == QDialog::Accepted )
85 mFilterLineEdit->setText( builder.sql() );
90 mMessageBar->pushCritical( tr(
"Error opening filter dialog" ), tr(
"There was an error while preparing SQL filter dialog: %1." ).arg( ex.
what() ) );
97 mSqlErrorText->hide();
99 mLoadAsNewLayerGroupBox->setCollapsed(
true );
107 mPkColumnsCheckBox->setVisible( showPkConfig );
108 mPkColumnsComboBox->setVisible( showPkConfig );
111 mGeometryColumnCheckBox->setVisible( showGeometryColumnConfig );
112 mGeometryColumnComboBox->setVisible( showGeometryColumnConfig );
115 mFilterLabel->setVisible( showFilterConfig );
116 mFilterToolButton->setVisible( showFilterConfig );
117 mFilterLineEdit->setVisible( showFilterConfig );
120 mAvoidSelectingAsFeatureIdCheckBox->setVisible( showDisableSelectAtId );
125 QShortcut *copySelection =
new QShortcut( QKeySequence::Copy, mQueryResultsTableView );
126 connect( copySelection, &QShortcut::activated,
this, &QgsQueryResultWidget::copySelection );
128 setConnection( connection );
131QgsQueryResultWidget::~QgsQueryResultWidget()
134 cancelRunningQuery();
139 mSqlVectorLayerOptions = options;
140 if ( ! options.
sql.isEmpty() )
142 setQuery( options.
sql );
146 mPkColumnsComboBox->setCheckedItems( {} );
151 mGeometryColumnCheckBox->setChecked( ! options.
geometryColumn.isEmpty() );
152 mGeometryColumnComboBox->clear();
155 mGeometryColumnComboBox->setCurrentText( options.
geometryColumn );
157 mFilterLineEdit->setText( options.
filter );
158 mLayerNameLineEdit->setText( options.
layerName );
161void QgsQueryResultWidget::setWidgetMode( QueryWidgetMode widgetMode )
163 mQueryWidgetMode = widgetMode;
164 switch ( widgetMode )
166 case QueryWidgetMode::SqlQueryMode:
167 mLoadAsNewLayerGroupBox->setTitle( tr(
"Load as New Layer" ) );
168 mLoadLayerPushButton->setText( tr(
"Load Layer" ) );
169 mLoadAsNewLayerGroupBox->setCollapsed(
true );
171 case QueryWidgetMode::QueryLayerUpdateMode:
172 mLoadAsNewLayerGroupBox->setTitle( tr(
"Update Query Layer" ) );
173 mLoadLayerPushButton->setText( tr(
"Update Layer" ) );
174 mLoadAsNewLayerGroupBox->setCollapsed(
false );
179void QgsQueryResultWidget::executeQuery()
181 mQueryResultsTableView->hide();
182 mSqlErrorText->hide();
183 mFirstRowFetched =
false;
185 cancelRunningQuery();
188 const QString sql { mSqlEditor->selectedText().isEmpty() ? mSqlEditor->text() : mSqlEditor->selectedText() };
194 { QStringLiteral(
"query" ), sql },
195 { QStringLiteral(
"provider" ), mConnection->providerKey() },
196 { QStringLiteral(
"connection" ), mConnection->uri() },
200 mWasCanceled =
false;
201 mFeedback = std::make_unique<QgsFeedback>();
202 mStopButton->setEnabled(
true );
203 mStatusLabel->show();
204 mStatusLabel->setText( tr(
"Executing query…" ) );
205 mProgressBar->show();
206 mProgressBar->setRange( 0, 0 );
207 mSqlErrorMessage.clear();
209 connect( mStopButton, &QPushButton::pressed, mFeedback.get(), [ = ]
211 mStatusLabel->setText( tr(
"Stopped" ) );
213 mProgressBar->hide();
218 connect( &mQueryResultWatcher, &QFutureWatcher<QgsAbstractDatabaseProviderConnection::QueryResult>::finished,
this, &QgsQueryResultWidget::startFetching, Qt::ConnectionType::UniqueConnection );
224 return mConnection->execSql( sql, mFeedback.get() );
228 mSqlErrorMessage = ex.
what();
232 mQueryResultWatcher.setFuture( future );
236 showError( tr(
"Connection error" ), tr(
"Cannot execute query: connection to the database is not available." ) );
240void QgsQueryResultWidget::updateButtons()
242 mFilterLineEdit->setEnabled( mFirstRowFetched );
243 mFilterToolButton->setEnabled( mFirstRowFetched );
244 const bool isEmpty = mSqlEditor->text().isEmpty();
245 mExecuteButton->setEnabled( !isEmpty );
246 mClearButton->setEnabled( !isEmpty );
248 mLoadAsNewLayerGroupBox->setEnabled(
249 mSqlErrorMessage.isEmpty() &&
254void QgsQueryResultWidget::showCellContextMenu( QPoint point )
256 const QModelIndex modelIndex = mQueryResultsTableView->indexAt( point );
257 if ( modelIndex.isValid() )
259 QMenu *menu =
new QMenu();
260 menu->setAttribute( Qt::WA_DeleteOnClose );
265 }, QKeySequence::Copy );
267 menu->exec( mQueryResultsTableView->viewport()->mapToGlobal( point ) );
271void QgsQueryResultWidget::copySelection()
273 const QModelIndexList selection = mQueryResultsTableView->selectionModel()->selectedIndexes();
274 if ( selection.empty() )
281 for (
const QModelIndex &index : selection )
283 if ( minRow == -1 || index.row() < minRow )
284 minRow = index.row();
285 if ( maxRow == -1 || index.row() > maxRow )
286 maxRow = index.row();
287 if ( minCol == -1 || index.column() < minCol )
288 minCol = index.column();
289 if ( maxCol == -1 || index.column() > maxCol )
290 maxCol = index.column();
293 if ( minRow == maxRow && minCol == maxCol )
296 const QString text = mModel->data( selection.at( 0 ), Qt::DisplayRole ).toString();
297 QApplication::clipboard()->setText( text );
301 copyResults( minRow, maxRow, minCol, maxCol );
305void QgsQueryResultWidget::updateSqlLayerColumns( )
310 mFilterToolButton->setEnabled(
true );
311 mFilterLineEdit->setEnabled(
true );
312 mPkColumnsComboBox->clear();
313 mGeometryColumnComboBox->clear();
314 const bool hasPkInformation { ! mSqlVectorLayerOptions.primaryKeyColumns.isEmpty() };
315 const bool hasGeomColInformation { ! mSqlVectorLayerOptions.geometryColumn.isEmpty() };
316 static const QStringList geomColCandidates { QStringLiteral(
"geom" ), QStringLiteral(
"geometry" ), QStringLiteral(
"the_geom" ) };
317 const QStringList constCols { mModel->columns() };
318 for (
const QString &
c : constCols )
320 const bool pkCheckedState = hasPkInformation ? mSqlVectorLayerOptions.primaryKeyColumns.contains(
c ) :
c.contains( QStringLiteral(
"id" ), Qt::CaseSensitivity::CaseInsensitive );
322 mPkColumnsComboBox->addItemWithCheckState(
c, pkCheckedState && mPkColumnsComboBox->checkedItems().isEmpty() ? Qt::CheckState::Checked : Qt::CheckState::Unchecked );
323 mGeometryColumnComboBox->addItem(
c );
324 if ( ! hasGeomColInformation && geomColCandidates.contains(
c, Qt::CaseSensitivity::CaseInsensitive ) )
326 mGeometryColumnComboBox->setCurrentText(
c );
329 mPkColumnsCheckBox->setChecked( hasPkInformation );
330 mGeometryColumnCheckBox->setChecked( hasGeomColInformation );
331 if ( hasGeomColInformation )
333 mGeometryColumnComboBox->setCurrentText( mSqlVectorLayerOptions.geometryColumn );
337void QgsQueryResultWidget::cancelRunningQuery()
346 if ( mQueryResultWatcher.isRunning() )
348 mQueryResultWatcher.waitForFinished();
352void QgsQueryResultWidget::cancelApiFetcher()
356 mApiFetcher->stopFetching();
361void QgsQueryResultWidget::startFetching()
363 if ( ! mWasCanceled )
365 if ( ! mSqlErrorMessage.isEmpty() )
367 showError( tr(
"SQL error" ), mSqlErrorMessage,
true );
373 mStatusLabel->setText( QStringLiteral(
"Query executed successfully (%1 rows, %2 ms)" )
374 .arg( QLocale().toString( mQueryResultWatcher.result().rowCount() ),
375 QLocale().toString( mQueryResultWatcher.result().queryExecutionTime() ) ) );
379 mStatusLabel->setText( QStringLiteral(
"Query executed successfully (%1 s)" ).arg( QLocale().toString( mQueryResultWatcher.result().queryExecutionTime() ) ) );
381 mProgressBar->hide();
382 mModel = std::make_unique<QgsQueryResultModel>( mQueryResultWatcher.result() );
389 connect( mModel.get(), &QgsQueryResultModel::fetchMoreRows,
this, [ = ](
long long maxRows )
391 mFetchedRowsBatchCount = 0;
392 mProgressBar->setRange( 0, maxRows );
393 mProgressBar->show();
396 connect( mModel.get(), &QgsQueryResultModel::rowsInserted,
this, [ = ](
const QModelIndex &,
int first,
int last )
398 if ( ! mFirstRowFetched )
400 emit firstResultBatchFetched();
401 mFirstRowFetched = true;
402 mQueryResultsTableView->show();
404 updateSqlLayerColumns( );
405 mActualRowCount = mModel->queryResult().rowCount();
407 mStatusLabel->setText( tr(
"Fetched rows: %1/%2 %3 %4 ms" )
408 .arg( QLocale().toString( mModel->rowCount( mModel->index( -1, -1 ) ) ),
409 mActualRowCount != -1 ? QLocale().toString( mActualRowCount ) : tr(
"unknown" ),
410 mWasCanceled ? tr(
"(stopped)" ) : QString(),
411 QLocale().toString( mQueryResultWatcher.result().queryExecutionTime() ) ) );
412 mFetchedRowsBatchCount += last - first + 1;
413 mProgressBar->setValue( mFetchedRowsBatchCount );
416 mQueryResultsTableView->setModel( mModel.get() );
417 mQueryResultsTableView->show();
419 connect( mModel.get(), &QgsQueryResultModel::fetchingComplete, mStopButton, [ = ]
422 const QgsHistoryEntry currentHistoryEntry = QgsGui::historyProviderRegistry()->entry( mCurrentHistoryEntryId, ok );
423 QVariantMap entryDetails = currentHistoryEntry.entry;
424 entryDetails.insert( QStringLiteral(
"rows" ), mActualRowCount );
425 entryDetails.insert( QStringLiteral(
"time" ), mQueryResultWatcher.result().queryExecutionTime() );
427 QgsGui::historyProviderRegistry()->updateEntry( mCurrentHistoryEntryId,
429 mProgressBar->hide();
430 mStopButton->setEnabled( false );
436 mStatusLabel->setText( tr(
"SQL command aborted" ) );
437 mProgressBar->hide();
441void QgsQueryResultWidget::showError(
const QString &title,
const QString &message,
bool isSqlError )
443 mStatusLabel->show();
444 mStatusLabel->setText( tr(
"An error occurred while executing the query" ) );
445 mProgressBar->hide();
446 mQueryResultsTableView->hide();
449 mSqlErrorText->show();
450 mSqlErrorText->setText( message );
454 mMessageBar->pushCritical( title, message );
458void QgsQueryResultWidget::tokensReady(
const QStringList &tokens )
460 mSqlEditor->setExtraKeywords( mSqlEditor->extraKeywords() + tokens );
461 mSqlErrorText->setExtraKeywords( mSqlErrorText->extraKeywords() + tokens );
464void QgsQueryResultWidget::copyResults()
466 const int rowCount = mModel->rowCount( QModelIndex() );
467 const int columnCount = mModel->columnCount( QModelIndex() );
468 copyResults( 0, rowCount - 1, 0, columnCount - 1 );
471void QgsQueryResultWidget::copyResults(
int fromRow,
int toRow,
int fromColumn,
int toColumn )
473 QStringList rowStrings;
474 QStringList columnStrings;
476 const int rowCount = mModel->rowCount( QModelIndex() );
477 const int columnCount = mModel->columnCount( QModelIndex() );
479 toRow = std::min( toRow, rowCount - 1 );
480 toColumn = std::min( toColumn, columnCount - 1 );
482 rowStrings.reserve( toRow - fromRow );
485 for (
int col = fromColumn; col <= toColumn; col++ )
487 columnStrings += mModel->headerData( col, Qt::Horizontal, Qt::DisplayRole ).toString();
489 rowStrings += columnStrings.join( QLatin1Char(
'\t' ) );
490 columnStrings.clear();
492 for (
int row = fromRow; row <= toRow; row++ )
494 for (
int col = fromColumn; col <= toColumn; col++ )
496 columnStrings += mModel->data( mModel->index( row, col ), Qt::DisplayRole ).toString();
498 rowStrings += columnStrings.join( QLatin1Char(
'\t' ) );
499 columnStrings.clear();
502 if ( !rowStrings.isEmpty() )
504 const QString text = rowStrings.join( QLatin1Char(
'\n' ) );
505 QString html = QStringLiteral(
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"><html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"/></head><body><table border=\"1\"><tr><td>%1</td></tr></table></body></html>" ).arg( text );
506 html.replace( QLatin1String(
"\t" ), QLatin1String(
"</td><td>" ) ).replace( QLatin1String(
"\n" ), QLatin1String(
"</td></tr><tr><td>" ) );
508 QMimeData *mdata =
new QMimeData();
509 mdata->setData( QStringLiteral(
"text/html" ), html.toUtf8() );
510 if ( !text.isEmpty() )
512 mdata->setText( text );
516 QApplication::clipboard()->setMimeData( mdata, QClipboard::Selection );
518 QApplication::clipboard()->setMimeData( mdata, QClipboard::Clipboard );
524 mSqlVectorLayerOptions.
sql = mSqlEditor->text();
525 mSqlVectorLayerOptions.filter = mFilterLineEdit->text();
526 mSqlVectorLayerOptions.primaryKeyColumns = mPkColumnsComboBox->checkedItems();
527 mSqlVectorLayerOptions.geometryColumn = mGeometryColumnComboBox->currentText();
528 mSqlVectorLayerOptions.layerName = mLayerNameLineEdit->text();
529 mSqlVectorLayerOptions.disableSelectAtId = mAvoidSelectingAsFeatureIdCheckBox->isChecked();
532 if ( ! mPkColumnsCheckBox->isChecked() )
536 if ( ! mGeometryColumnCheckBox->isChecked() )
545 mConnection.reset( connection );
553 const QMultiMap<Qgis::SqlKeywordCategory, QStringList> keywordsDict { connection->
sqlDictionary() };
554 QStringList keywords;
555 for (
auto it = keywordsDict.constBegin(); it != keywordsDict.constEnd(); it++ )
557 keywords.append( it.value() );
561 mSqlEditor->setExtraKeywords( keywords );
562 mSqlErrorText->setExtraKeywords( keywords );
565 QThread *apiFetcherWorkerThread =
new QThread();
566 QgsConnectionsApiFetcher *apiFetcher =
new QgsConnectionsApiFetcher( mConnection->uri(), mConnection->providerKey() );
567 apiFetcher->moveToThread( apiFetcherWorkerThread );
568 connect( apiFetcherWorkerThread, &QThread::started, apiFetcher, &QgsConnectionsApiFetcher::fetchTokens );
569 connect( apiFetcher, &QgsConnectionsApiFetcher::tokensReady,
this, &QgsQueryResultWidget::tokensReady );
570 connect( apiFetcher, &QgsConnectionsApiFetcher::fetchingFinished, apiFetcherWorkerThread, [apiFetcher, apiFetcherWorkerThread]
572 apiFetcherWorkerThread->quit();
573 apiFetcherWorkerThread->wait();
574 apiFetcherWorkerThread->deleteLater();
575 apiFetcher->deleteLater();
578 mApiFetcher = apiFetcher;
579 apiFetcherWorkerThread->start();
586void QgsQueryResultWidget::setQuery(
const QString &sql )
588 mSqlEditor->setText( sql );
591void QgsQueryResultWidget::notify(
const QString &title,
const QString &text,
Qgis::MessageLevel level )
593 mMessageBar->pushMessage( title, text, level );
599void QgsConnectionsApiFetcher::fetchTokens()
603 emit fetchingFinished();
611 emit fetchingFinished();
615 if ( ! mStopFetching && connection )
617 mFeedback = std::make_unique< QgsFeedback >();
623 schemas = connection->
schemas();
624 emit tokensReady( schemas );
633 schemas.push_back( QString() );
636 for (
const auto &schema : std::as_const( schemas ) )
642 emit fetchingFinished();
646 QStringList tableNames;
655 emit fetchingFinished();
658 tableNames.push_back( table.tableName() );
660 emit tokensReady( tableNames );
668 for (
const auto &table : std::as_const( tableNames ) )
674 emit fetchingFinished();
678 QStringList fieldNames;
681 const QgsFields fields( connection->
fields( schema, table, mFeedback.get() ) );
685 emit fetchingFinished();
689 for (
const auto &field : std::as_const( fields ) )
691 fieldNames.push_back( field.name() );
695 emit fetchingFinished();
699 emit tokensReady( fieldNames );
710 emit fetchingFinished();
713void QgsConnectionsApiFetcher::stopFetching()
720QgsQueryResultItemDelegate::QgsQueryResultItemDelegate( QObject *parent )
721 : QStyledItemDelegate( parent )
725QString QgsQueryResultItemDelegate::displayText(
const QVariant &value,
const QLocale &locale )
const
728 QString result { QgsExpressionUtils::toLocalizedString( value ) };
730 if ( result.length() > 255 )
732 result.truncate( 255 );
733 result.append( QStringLiteral(
"…" ) );
MessageLevel
Level for messages This will be used both for message log and message bar in application.
@ Warning
Warning message.
@ UnstableFeatureIds
SQL layer definition supports disabling select at id.
@ SubsetStringFilter
SQL layer definition supports subset string filter.
@ PrimaryKeys
SQL layer definition supports primary keys.
@ GeometryColumn
SQL layer definition supports geometry column.
The QgsAbstractDatabaseProviderConnection class provides common functionality for DB based connection...
virtual QList< QgsAbstractDatabaseProviderConnection::TableProperty > tables(const QString &schema=QString(), const QgsAbstractDatabaseProviderConnection::TableFlags &flags=QgsAbstractDatabaseProviderConnection::TableFlags(), QgsFeedback *feedback=nullptr) const
Returns information on the tables in the given schema.
QFlags< TableFlag > TableFlags
@ SqlLayers
Can create vector layers from SQL SELECT queries.
@ Schemas
Can list schemas (if not set, the connection does not support schemas)
virtual Qgis::SqlLayerDefinitionCapabilities sqlLayerDefinitionCapabilities()
Returns SQL layer definition capabilities (Filters, GeometryColumn, PrimaryKeys).
virtual QMultiMap< Qgis::SqlKeywordCategory, QStringList > sqlDictionary()
Returns a dictionary of SQL keywords supported by the provider.
virtual QStringList schemas() const
Returns information about the existing schemas.
Capabilities capabilities() const
Returns connection capabilities.
virtual QgsFields fields(const QString &schema, const QString &table, QgsFeedback *feedback=nullptr) const
Returns the fields of a table and schema.
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
A SQL editor based on QScintilla2.
void collapsedStateChanged(bool collapsed)
Signal emitted when groupbox collapsed/expanded state is changed, and when first shown.
void canceled()
Internal routines can connect to this signal if they use event loop.
Container of fields for a vector layer.
static QgsHistoryProviderRegistry * historyProviderRegistry()
Returns the global history provider registry, used for tracking history providers.
long long addEntry(const QString &providerId, const QVariantMap &entry, bool &ok, QgsHistoryProviderRegistry::HistoryEntryOptions options=QgsHistoryProviderRegistry::HistoryEntryOptions())
Adds an entry to the history logs.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
Custom exception class for provider connection related exceptions.
static QgsProviderRegistry * instance(const QString &pluginPath=QString())
Means of accessing canonical single instance.
QgsProviderMetadata * providerMetadata(const QString &providerKey) const
Returns metadata of the provider or nullptr if not found.
Query Builder for layers.
@ UnknownCount
Provider returned an unknown feature count.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
The QueryResult class represents the result of a query executed by execSql()
The SqlVectorLayerOptions stores all information required to create a SQL (query) layer.
QString sql
The SQL expression that defines the SQL (query) layer.
QStringList primaryKeyColumns
List of primary key column names.
QString filter
Additional subset string (provider-side filter), not all data providers support this feature: check s...
QString layerName
Optional name for the new layer.
bool disableSelectAtId
If SelectAtId is disabled (default is false), not all data providers support this feature: check supp...
QString geometryColumn
Name of the geometry column.
The TableProperty class represents a database table or view.