QGIS API Documentation 4.1.0-Master (5bf3c20f3c9)
Loading...
Searching...
No Matches
qgsalgorithmexporttospatialiteregistered.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmexporttospatialiteregistered.cpp
3 ---------------------
4 begin : April 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"
24
25#include <QString>
26
27using namespace Qt::StringLiterals;
28
30
31QString QgsExportToRegisteredSpatialiteAlgorithm::name() const
32{
33 return u"importintospatialiteregistered"_s;
34}
35
36QString QgsExportToRegisteredSpatialiteAlgorithm::displayName() const
37{
38 return QObject::tr( "Export to SpatiaLite (registered)" );
39}
40
41QStringList QgsExportToRegisteredSpatialiteAlgorithm::tags() const
42{
43 return QObject::tr( "export,import,spatialite,table,layer,into,copy" ).split( ',' );
44}
45
46QString QgsExportToRegisteredSpatialiteAlgorithm::group() const
47{
48 return QObject::tr( "Database" );
49}
50
51QString QgsExportToRegisteredSpatialiteAlgorithm::groupId() const
52{
53 return u"database"_s;
54}
55
56QString QgsExportToRegisteredSpatialiteAlgorithm::shortHelpString() const
57{
58 return QObject::tr(
59 "Exports a vector layer to a SpatiaLite database, creating "
60 "a new table.\n\n"
61 "Prior to this a connection between QGIS and the SpatiaLite "
62 "database has to be created (for example through the QGIS "
63 "Browser panel)."
64 );
65}
66
67QString QgsExportToRegisteredSpatialiteAlgorithm::shortDescription() const
68{
69 return QObject::tr( "Exports a vector layer to a registered SpatiaLite database, creating a new table." );
70}
71
72Qgis::ProcessingAlgorithmFlags QgsExportToRegisteredSpatialiteAlgorithm::flags() const
73{
75}
76
77QgsExportToRegisteredSpatialiteAlgorithm *QgsExportToRegisteredSpatialiteAlgorithm::createInstance() const
78{
79 return new QgsExportToRegisteredSpatialiteAlgorithm();
80}
81
82void QgsExportToRegisteredSpatialiteAlgorithm::initAlgorithm( const QVariantMap & )
83{
84 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Layer to export" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::Vector ) ) );
85 addParameter( new QgsProcessingParameterProviderConnection( u"DATABASE"_s, QObject::tr( "Database (connection name)" ), u"spatialite"_s ) );
86 addParameter( new QgsProcessingParameterDatabaseTable( u"TABLENAME"_s, QObject::tr( "Table to export to (leave blank to use layer name)" ), u"DATABASE"_s, QString(), QVariant(), true, true ) );
87 addParameter( new QgsProcessingParameterField( u"PRIMARY_KEY"_s, QObject::tr( "Primary key field" ), QVariant(), u"INPUT"_s, Qgis::ProcessingFieldParameterDataType::Any, false, true ) );
88 addParameter( new QgsProcessingParameterString( u"GEOMETRY_COLUMN"_s, QObject::tr( "Geometry column" ), u"geom"_s ) );
89 addParameter( new QgsProcessingParameterString( u"ENCODING"_s, QObject::tr( "Encoding" ), u"UTF-8"_s, false, true ) );
90 addParameter( new QgsProcessingParameterBoolean( u"OVERWRITE"_s, QObject::tr( "Overwrite" ), true ) );
91 addParameter( new QgsProcessingParameterBoolean( u"CREATEINDEX"_s, QObject::tr( "Create spatial index" ), true ) );
92 addParameter( new QgsProcessingParameterBoolean( u"LOWERCASE_NAMES"_s, QObject::tr( "Convert field names to lowercase" ), true ) );
93 addParameter( new QgsProcessingParameterBoolean( u"DROP_STRING_LENGTH"_s, QObject::tr( "Drop length constraints on character fields" ), false ) );
94 addParameter( new QgsProcessingParameterBoolean( u"FORCE_SINGLEPART"_s, QObject::tr( "Create single-part geometries instead of multipart" ), false ) );
95}
96
97QVariantMap QgsExportToRegisteredSpatialiteAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
98{
99 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, u"INPUT"_s, context ) );
100 if ( !source )
101 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
102
103 const QString connectionName = parameterAsConnectionName( parameters, u"DATABASE"_s, context );
104
105 std::unique_ptr<QgsAbstractDatabaseProviderConnection> conn;
106 try
107 {
109 conn.reset( static_cast<QgsAbstractDatabaseProviderConnection *>( md->createConnection( connectionName ) ) );
110 }
112 {
113 QgsProcessingException( QObject::tr( "Could not retrieve connection details for %1" ).arg( connectionName ) );
114 }
115
116 const QString primaryKeyField = parameterAsString( parameters, u"PRIMARY_KEY"_s, context );
117 const QString encoding = parameterAsString( parameters, u"ENCODING"_s, context );
118 const bool overwrite = parameterAsBoolean( parameters, u"OVERWRITE"_s, context );
119
120 QString tableName = parameterAsDatabaseTableName( parameters, u"TABLENAME"_s, context ).trimmed();
121 if ( tableName.isEmpty() )
122 {
123 tableName = source->sourceName();
124 tableName = tableName.replace( '.', '_' );
125 }
126 tableName = tableName.replace( ' ', QString() ).right( 63 );
127
128 QString geometryColumn = parameterAsString( parameters, u"GEOMETRY_COLUMN"_s, context );
129 if ( geometryColumn.isEmpty() )
130 {
131 geometryColumn = u"geom"_s;
132 }
133 if ( source->wkbType() == Qgis::WkbType::NoGeometry )
134 {
135 geometryColumn.clear();
136 }
137
138 const bool createSpatialIndex = parameterAsBoolean( parameters, u"CREATEINDEX"_s, context );
139
140 QMap<QString, QVariant> options;
141 if ( overwrite )
142 {
143 options[u"overwrite"_s] = true;
144 }
145 if ( parameterAsBoolean( parameters, u"LOWERCASE_NAMES"_s, context ) )
146 {
147 options[u"lowercaseFieldNames"_s] = true;
148 geometryColumn = geometryColumn.toLower();
149 }
150 if ( parameterAsBoolean( parameters, u"DROP_STRING_LENGTH"_s, context ) )
151 {
152 options[u"dropStringConstraints"_s] = true;
153 }
154 if ( parameterAsBoolean( parameters, u"FORCE_SINGLEPART"_s, context ) )
155 {
156 options[u"forceSinglePartGeometryType"_s] = true;
157 }
158 if ( !encoding.isEmpty() )
159 {
160 options[u"fileEncoding"_s] = encoding;
161 }
162
163 QgsDataSourceUri uri = QgsDataSourceUri( conn->uri() );
164 uri.setTable( tableName );
165 uri.setKeyColumn( primaryKeyField );
166 uri.setGeometryColumn( geometryColumn );
167
168 auto exporter = std::make_unique<QgsVectorLayerExporter>( uri.uri(), u"spatialite"_s, source->fields(), source->wkbType(), source->sourceCrs(), overwrite, options );
169
170 if ( exporter->errorCode() != Qgis::VectorExportResult::Success )
171 throw QgsProcessingException( QObject::tr( "Error exporting to SpatiaLite\n%1" ).arg( exporter->errorMessage() ) );
172
173 QgsFeatureIterator featureIterator = source->getFeatures();
174
175 const double step = source->featureCount() > 0 ? 100.0 / source->featureCount() : 0.0;
176
177 long long i = 0;
178 QgsFeature f;
179 while ( featureIterator.nextFeature( f ) )
180 {
181 if ( feedback->isCanceled() )
182 {
183 break;
184 }
185
186 if ( !exporter->addFeature( f, QgsFeatureSink::FastInsert ) )
187 {
188 feedback->reportError( exporter->errorMessage() );
189 }
190
191 feedback->setProgress( i * step );
192 i++;
193 }
194 exporter->flushBuffer();
195
196 if ( exporter->errorCode() != Qgis::VectorExportResult::Success )
197 throw QgsProcessingException( QObject::tr( "Error exporting to SpatiaLite\n%1" ).arg( exporter->errorMessage() ) );
198
199 exporter.reset();
200
201 if ( !geometryColumn.isEmpty() && createSpatialIndex )
202 {
203 try
204 {
206 opt.geometryColumnName = geometryColumn;
207 conn->createSpatialIndex( "", tableName, opt );
208 }
210 {
211 throw QgsProcessingException( QObject::tr( "Error creating spatial index:\n%1" ).arg( e.what() ) );
212 }
213 }
214
215 try
216 {
217 conn->vacuum( "", tableName );
218 }
220 {
221 feedback->reportError( QObject::tr( "Error vacuuming table:\n%1" ).arg( e.what() ) );
222 }
223
224 QVariantMap outputs;
225 return outputs;
226}
227
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
Definition qgis.h:3653
@ Success
No errors were encountered.
Definition qgis.h:1079
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3724
@ NoGeometry
No geometry.
Definition qgis.h:312
@ NoThreading
Algorithm is not thread safe and cannot be run in a background thread, e.g. for algorithms which mani...
Definition qgis.h:3703
Provides common functionality for database based connections.
Stores the component parts of a data source URI (e.g.
void setTable(const QString &table)
Sets table to table.
void setGeometryColumn(const QString &geometryColumn)
Sets geometry column name to geometryColumn.
QString uri(bool expandAuthConfig=true) const
Returns the complete URI as a string.
void setKeyColumn(const QString &column)
Sets the name of the (primary) key column.
QString what() const
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:56
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:65
virtual Qgis::ProcessingAlgorithmFlags flags() const
Returns the flags indicating how and when the algorithm operates and should be exposed to users.
Contains information about the context in which a processing algorithm is executed.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
A boolean parameter for processing algorithms.
A database table name parameter for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A vector layer or feature source field parameter 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.
The SpatialIndexOptions contains extra options relating to spatial index creation.
QString geometryColumnName
Specifies the name of the geometry column to create the index for.