QGIS API Documentation 4.3.0-Master (ffcfc20b9b4)
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 QGS_MARK_ALGORITHM_SOURCE
100
101 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, u"INPUT"_s, context ) );
102 if ( !source )
103 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
104
105 const QString connectionName = parameterAsConnectionName( parameters, u"DATABASE"_s, context );
106
107 std::unique_ptr<QgsAbstractDatabaseProviderConnection> conn;
108 try
109 {
111 conn.reset( static_cast<QgsAbstractDatabaseProviderConnection *>( md->createConnection( connectionName ) ) );
112 }
114 {
115 QgsProcessingException( QObject::tr( "Could not retrieve connection details for %1" ).arg( connectionName ) );
116 }
117
118 const QString primaryKeyField = parameterAsString( parameters, u"PRIMARY_KEY"_s, context );
119 const QString encoding = parameterAsString( parameters, u"ENCODING"_s, context );
120 const bool overwrite = parameterAsBoolean( parameters, u"OVERWRITE"_s, context );
121
122 QString tableName = parameterAsDatabaseTableName( parameters, u"TABLENAME"_s, context ).trimmed();
123 if ( tableName.isEmpty() )
124 {
125 tableName = source->sourceName();
126 tableName = tableName.replace( '.', '_' );
127 }
128 tableName = tableName.replace( ' ', QString() ).right( 63 );
129
130 QString geometryColumn = parameterAsString( parameters, u"GEOMETRY_COLUMN"_s, context );
131 if ( geometryColumn.isEmpty() )
132 {
133 geometryColumn = u"geom"_s;
134 }
135 if ( source->wkbType() == Qgis::WkbType::NoGeometry )
136 {
137 geometryColumn.clear();
138 }
139
140 const bool createSpatialIndex = parameterAsBoolean( parameters, u"CREATEINDEX"_s, context );
141
142 QMap<QString, QVariant> options;
143 if ( overwrite )
144 {
145 options[u"overwrite"_s] = true;
146 }
147 if ( parameterAsBoolean( parameters, u"LOWERCASE_NAMES"_s, context ) )
148 {
149 options[u"lowercaseFieldNames"_s] = true;
150 geometryColumn = geometryColumn.toLower();
151 }
152 if ( parameterAsBoolean( parameters, u"DROP_STRING_LENGTH"_s, context ) )
153 {
154 options[u"dropStringConstraints"_s] = true;
155 }
156 if ( parameterAsBoolean( parameters, u"FORCE_SINGLEPART"_s, context ) )
157 {
158 options[u"forceSinglePartGeometryType"_s] = true;
159 }
160 if ( !encoding.isEmpty() )
161 {
162 options[u"fileEncoding"_s] = encoding;
163 }
164
165 QgsDataSourceUri uri = QgsDataSourceUri( conn->uri() );
166 uri.setTable( tableName );
167 uri.setKeyColumn( primaryKeyField );
168 uri.setGeometryColumn( geometryColumn );
169
170 auto exporter = std::make_unique<QgsVectorLayerExporter>( uri.uri(), u"spatialite"_s, source->fields(), source->wkbType(), source->sourceCrs(), overwrite, options );
171
172 if ( exporter->errorCode() != Qgis::VectorExportResult::Success )
173 throw QgsProcessingException( QObject::tr( "Error exporting to SpatiaLite\n%1" ).arg( exporter->errorMessage() ) );
174
175 QgsFeatureIterator featureIterator = source->getFeatures();
176
177 const double step = source->featureCount() > 0 ? 100.0 / source->featureCount() : 0.0;
178
179 long long i = 0;
180 QgsFeature f;
181 while ( featureIterator.nextFeature( f ) )
182 {
183 if ( feedback->isCanceled() )
184 {
185 break;
186 }
187
188 if ( !exporter->addFeature( f, QgsFeatureSink::FastInsert ) )
189 {
190 feedback->reportError( exporter->errorMessage() );
191 }
192
193 feedback->setProgress( i * step );
194 i++;
195 }
196 exporter->flushBuffer();
197
198 if ( exporter->errorCode() != Qgis::VectorExportResult::Success )
199 throw QgsProcessingException( QObject::tr( "Error exporting to SpatiaLite\n%1" ).arg( exporter->errorMessage() ) );
200
201 exporter.reset();
202
203 if ( !geometryColumn.isEmpty() && createSpatialIndex )
204 {
205 try
206 {
208 opt.geometryColumnName = geometryColumn;
209 conn->createSpatialIndex( "", tableName, opt );
210 }
212 {
213 throw QgsProcessingException( QObject::tr( "Error creating spatial index:\n%1" ).arg( e.what() ) );
214 }
215 }
216
217 try
218 {
219 conn->vacuum( "", tableName );
220 }
222 {
223 feedback->reportError( QObject::tr( "Error vacuuming table:\n%1" ).arg( e.what() ) );
224 }
225
226 QVariantMap outputs;
227 return outputs;
228}
229
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
Definition qgis.h:3755
@ Success
No errors were encountered.
Definition qgis.h:1134
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3826
@ 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:3805
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.