QGIS API Documentation 3.99.0-Master (09f76ad7019)
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( "Exports a vector layer to a SpatiaLite database, creating "
59 "a new table.\n\n"
60 "Prior to this a connection between QGIS and the SpatiaLite "
61 "database has to be created (for example through the QGIS "
62 "Browser panel)." );
63}
64
65QString QgsExportToRegisteredSpatialiteAlgorithm::shortDescription() const
66{
67 return QObject::tr( "Exports a vector layer to a registered SpatiaLite database, creating a new table." );
68}
69
70Qgis::ProcessingAlgorithmFlags QgsExportToRegisteredSpatialiteAlgorithm::flags() const
71{
73}
74
75QgsExportToRegisteredSpatialiteAlgorithm *QgsExportToRegisteredSpatialiteAlgorithm::createInstance() const
76{
77 return new QgsExportToRegisteredSpatialiteAlgorithm();
78}
79
80void QgsExportToRegisteredSpatialiteAlgorithm::initAlgorithm( const QVariantMap & )
81{
82 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Layer to export" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::Vector ) ) );
83 addParameter( new QgsProcessingParameterProviderConnection( u"DATABASE"_s, QObject::tr( "Database (connection name)" ), u"spatialite"_s ) );
84 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 ) );
85 addParameter( new QgsProcessingParameterField( u"PRIMARY_KEY"_s, QObject::tr( "Primary key field" ), QVariant(), u"INPUT"_s, Qgis::ProcessingFieldParameterDataType::Any, false, true ) );
86 addParameter( new QgsProcessingParameterString( u"GEOMETRY_COLUMN"_s, QObject::tr( "Geometry column" ), u"geom"_s ) );
87 addParameter( new QgsProcessingParameterString( u"ENCODING"_s, QObject::tr( "Encoding" ), u"UTF-8"_s, false, true ) );
88 addParameter( new QgsProcessingParameterBoolean( u"OVERWRITE"_s, QObject::tr( "Overwrite" ), true ) );
89 addParameter( new QgsProcessingParameterBoolean( u"CREATEINDEX"_s, QObject::tr( "Create spatial index" ), true ) );
90 addParameter( new QgsProcessingParameterBoolean( u"LOWERCASE_NAMES"_s, QObject::tr( "Convert field names to lowercase" ), true ) );
91 addParameter( new QgsProcessingParameterBoolean( u"DROP_STRING_LENGTH"_s, QObject::tr( "Drop length constraints on character fields" ), false ) );
92 addParameter( new QgsProcessingParameterBoolean( u"FORCE_SINGLEPART"_s, QObject::tr( "Create single-part geometries instead of multipart" ), false ) );
93}
94
95QVariantMap QgsExportToRegisteredSpatialiteAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
96{
97 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, u"INPUT"_s, context ) );
98 if ( !source )
99 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
100
101 const QString connectionName = parameterAsConnectionName( parameters, u"DATABASE"_s, context );
102
103 std::unique_ptr<QgsAbstractDatabaseProviderConnection> conn;
104 try
105 {
107 conn.reset( static_cast<QgsAbstractDatabaseProviderConnection *>( md->createConnection( connectionName ) ) );
108 }
110 {
111 QgsProcessingException( QObject::tr( "Could not retrieve connection details for %1" ).arg( connectionName ) );
112 }
113
114 const QString primaryKeyField = parameterAsString( parameters, u"PRIMARY_KEY"_s, context );
115 const QString encoding = parameterAsString( parameters, u"ENCODING"_s, context );
116 const bool overwrite = parameterAsBoolean( parameters, u"OVERWRITE"_s, context );
117
118 QString tableName = parameterAsDatabaseTableName( parameters, u"TABLENAME"_s, context ).trimmed();
119 if ( tableName.isEmpty() )
120 {
121 tableName = source->sourceName();
122 tableName = tableName.replace( '.', '_' );
123 }
124 tableName = tableName.replace( ' ', QString() ).right( 63 );
125
126 QString geometryColumn = parameterAsString( parameters, u"GEOMETRY_COLUMN"_s, context );
127 if ( geometryColumn.isEmpty() )
128 {
129 geometryColumn = u"geom"_s;
130 }
131 if ( source->wkbType() == Qgis::WkbType::NoGeometry )
132 {
133 geometryColumn.clear();
134 }
135
136 const bool createSpatialIndex = parameterAsBoolean( parameters, u"CREATEINDEX"_s, context );
137
138 QMap<QString, QVariant> options;
139 if ( overwrite )
140 {
141 options[u"overwrite"_s] = true;
142 }
143 if ( parameterAsBoolean( parameters, u"LOWERCASE_NAMES"_s, context ) )
144 {
145 options[u"lowercaseFieldNames"_s] = true;
146 geometryColumn = geometryColumn.toLower();
147 }
148 if ( parameterAsBoolean( parameters, u"DROP_STRING_LENGTH"_s, context ) )
149 {
150 options[u"dropStringConstraints"_s] = true;
151 }
152 if ( parameterAsBoolean( parameters, u"FORCE_SINGLEPART"_s, context ) )
153 {
154 options[u"forceSinglePartGeometryType"_s] = true;
155 }
156 if ( !encoding.isEmpty() )
157 {
158 options[u"fileEncoding"_s] = encoding;
159 }
160
161 QgsDataSourceUri uri = QgsDataSourceUri( conn->uri() );
162 uri.setTable( tableName );
163 uri.setKeyColumn( primaryKeyField );
164 uri.setGeometryColumn( geometryColumn );
165
166 auto exporter = std::make_unique<QgsVectorLayerExporter>( uri.uri(), u"spatialite"_s, source->fields(), source->wkbType(), source->sourceCrs(), overwrite, options );
167
168 if ( exporter->errorCode() != Qgis::VectorExportResult::Success )
169 throw QgsProcessingException( QObject::tr( "Error exporting to SpatiaLite\n%1" ).arg( exporter->errorMessage() ) );
170
171 QgsFeatureIterator featureIterator = source->getFeatures();
172
173 const double step = source->featureCount() > 0 ? 100.0 / source->featureCount() : 0.0;
174
175 long long i = 0;
176 QgsFeature f;
177 while ( featureIterator.nextFeature( f ) )
178 {
179 if ( feedback->isCanceled() )
180 {
181 break;
182 }
183
184 if ( !exporter->addFeature( f, QgsFeatureSink::FastInsert ) )
185 {
186 feedback->reportError( exporter->errorMessage() );
187 }
188
189 feedback->setProgress( i * step );
190 i++;
191 }
192 exporter->flushBuffer();
193
194 if ( exporter->errorCode() != Qgis::VectorExportResult::Success )
195 throw QgsProcessingException( QObject::tr( "Error exporting to SpatiaLite\n%1" ).arg( exporter->errorMessage() ) );
196
197 exporter.reset();
198
199 if ( !geometryColumn.isEmpty() && createSpatialIndex )
200 {
201 try
202 {
204 opt.geometryColumnName = geometryColumn;
205 conn->createSpatialIndex( "", tableName, opt );
206 }
208 {
209 throw QgsProcessingException( QObject::tr( "Error creating spatial index:\n%1" ).arg( e.what() ) );
210 }
211 }
212
213 try
214 {
215 conn->vacuum( "", tableName );
216 }
218 {
219 feedback->reportError( QObject::tr( "Error vacuuming table:\n%1" ).arg( e.what() ) );
220 }
221
222 QVariantMap outputs;
223 return outputs;
224}
225
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
Definition qgis.h:3610
@ Success
No errors were encountered.
Definition qgis.h:1072
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3680
@ NoGeometry
No geometry.
Definition qgis.h:298
@ NoThreading
Algorithm is not thread safe and cannot be run in a background thread, e.g. for algorithms which mani...
Definition qgis.h:3659
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:55
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:63
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.