QGIS API Documentation 4.3.0-Master (d3b565c628d)
Loading...
Searching...
No Matches
qgsalgorithmexecuteandloadpostgisquery.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmexecuteandloadpostgisquery.cpp
3 ---------------------
4 begin : December 2025
5 copyright : (C) 2025 by Alexander Bruy
6 email : alexander dot bruy at gmail dot com
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17
19
21#include "qgsprovidermetadata.h"
22#include "qgsproviderregistry.h"
23#include "qgsvectorlayer.h"
24
25#include <QString>
26
27using namespace Qt::StringLiterals;
28
30
31QString QgsExecuteAndLoadPostgisQueryAlgorithm::name() const
32{
33 return u"postgisexecuteandloadsql"_s;
34}
35
36QString QgsExecuteAndLoadPostgisQueryAlgorithm::displayName() const
37{
38 return QObject::tr( "PostgreSQL execute and load SQL" );
39}
40
41QStringList QgsExecuteAndLoadPostgisQueryAlgorithm::tags() const
42{
43 return QObject::tr( "database,sql,postgresql,postgis,execute,load,layer,table" ).split( ',' );
44}
45
46QString QgsExecuteAndLoadPostgisQueryAlgorithm::group() const
47{
48 return QObject::tr( "Database" );
49}
50
51QString QgsExecuteAndLoadPostgisQueryAlgorithm::groupId() const
52{
53 return u"database"_s;
54}
55
56QString QgsExecuteAndLoadPostgisQueryAlgorithm::shortHelpString() const
57{
58 return QObject::tr( "This algorithm performs a SQL database query on a PostgreSQL database connected to QGIS and loads the query results as a new layer." );
59}
60
61QString QgsExecuteAndLoadPostgisQueryAlgorithm::shortDescription() const
62{
63 return QObject::tr( "Executes a SQL command on a PostgreSQL database and loads the result as a layer." );
64}
65
66Qgis::ProcessingAlgorithmFlags QgsExecuteAndLoadPostgisQueryAlgorithm::flags() const
67{
69}
70
71QgsExecuteAndLoadPostgisQueryAlgorithm *QgsExecuteAndLoadPostgisQueryAlgorithm::createInstance() const
72{
73 return new QgsExecuteAndLoadPostgisQueryAlgorithm();
74}
75
76void QgsExecuteAndLoadPostgisQueryAlgorithm::initAlgorithm( const QVariantMap & )
77{
78 addParameter( new QgsProcessingParameterProviderConnection( u"DATABASE"_s, QObject::tr( "Database (connection name)" ), u"postgres"_s ) );
79 addParameter( new QgsProcessingParameterString( u"SQL"_s, QObject::tr( "SQL query" ), QVariant(), true ) );
80 addParameter( new QgsProcessingParameterString( u"ID_FIELD"_s, QObject::tr( "Unique ID field name" ), u"id"_s ) );
81 addParameter( new QgsProcessingParameterString( u"GEOMETRY_FIELD"_s, QObject::tr( "Geometry field name" ), u"geom"_s, false, true ) );
82 addOutput( new QgsProcessingOutputVectorLayer( u"OUTPUT"_s, QObject::tr( "Output layer" ) ) );
83}
84
85QVariantMap QgsExecuteAndLoadPostgisQueryAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
86{
87 QGS_MARK_ALGORITHM_SOURCE
88
89 Q_UNUSED( feedback );
90
91 const QString connName = parameterAsConnectionName( parameters, u"DATABASE"_s, context );
92
93 std::unique_ptr<QgsAbstractDatabaseProviderConnection> conn;
94 try
95 {
97 conn.reset( static_cast<QgsAbstractDatabaseProviderConnection *>( md->createConnection( connName ) ) );
98 }
100 {
101 throw QgsProcessingException( QObject::tr( "Could not retrieve connection details for %1" ).arg( connName ) );
102 }
103
104 QString sql = parameterAsString( parameters, u"SQL"_s, context ).replace( '\n', ' ' );
105 if ( sql.endsWith( ';' ) )
106 {
107 sql.chop( 1 );
108 }
109 const QString idField = parameterAsString( parameters, u"ID_FIELD"_s, context );
110 const QString geomField = parameterAsString( parameters, u"GEOMETRY_FIELD"_s, context );
111
112 QgsDataSourceUri uri( conn->uri() );
113 uri.setDataSource( QString(), u"(%1)"_s.arg( sql ), geomField, QString(), idField );
114
115 auto layer = std::make_unique<QgsVectorLayer>( uri.uri(), u"layername"_s, u"postgres"_s );
116 if ( !layer->isValid() )
117 {
118 throw QgsProcessingException( QObject::tr( "This layer is invalid! Please check the PostGIS log for error messages." ) );
119 }
120
121 const QString layerId = layer->id();
122 const QgsProcessingContext::LayerDetails details( u"SQL layer"_s, context.project(), u"OUTPUT"_s, QgsProcessingUtils::LayerHint::Vector );
123 context.addLayerToLoadOnCompletion( layerId, details );
124 context.temporaryLayerStore()->addMapLayer( layer.release() );
125
126 QVariantMap outputs;
127 outputs.insert( u"OUTPUT"_s, layerId );
128 return outputs;
129}
130
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3826
@ NotAvailableInStandaloneTool
Algorithm should not be available from the standalone "qgis_process" tool. Used to flag algorithms wh...
Definition qgis.h:3812
@ RequiresProject
The algorithm requires that a valid QgsProject is available from the processing context in order to e...
Definition qgis.h:3813
Provides common functionality for database based connections.
Stores the component parts of a data source URI (e.g.
QgsMapLayer * addMapLayer(QgsMapLayer *layer, bool takeOwnership=true)
Add a layer to the store.
virtual Qgis::ProcessingAlgorithmFlags flags() const
Returns the flags indicating how and when the algorithm operates and should be exposed to users.
Details for layers to load into projects.
Contains information about the context in which a processing algorithm is executed.
void addLayerToLoadOnCompletion(const QString &layer, const QgsProcessingContext::LayerDetails &details)
Adds a layer to load (by ID or datasource) into the canvas upon completion of the algorithm or model.
QgsProject * project() const
Returns the project in which the algorithm is being executed.
QgsMapLayerStore * temporaryLayerStore()
Returns a reference to the layer store used for storing temporary layers during algorithm execution.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
A vector layer output for processing algorithms.
A data provider connection parameter for processing algorithms, allowing users to select from availab...
A string parameter for processing algorithms.
Custom exception class for provider connection related exceptions.
Holds data provider key, description, and associated shared library file or function pointer informat...
virtual QgsAbstractProviderConnection * createConnection(const QString &uri, const QVariantMap &configuration)
Creates a new connection from uri and configuration, the newly created connection is not automaticall...
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.