QGIS API Documentation 4.3.0-Master (35968c35f7e)
Loading...
Searching...
No Matches
qgsdbimportvectorlayerdialog.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsdbimportvectorlayerdialog.cpp
3 --------------------------------------
4 Date : March 2025
5 Copyright : (C) 2025 by Nyall Dawson
6 Email : nyall dot dawson at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
17
21#include "qgsgui.h"
22#include "qgsmapcanvas.h"
23#include "qgsproject.h"
24#include "qgsproviderregistry.h"
25#include "qgsvectorlayer.h"
27
28#include <QItemSelectionModel>
29#include <QMenu>
30#include <QPushButton>
31#include <QString>
32
33#include "moc_qgsdbimportvectorlayerdialog.cpp"
34
35using namespace Qt::StringLiterals;
36
38 : QDialog( parent )
39 , mConnection( connection )
40{
41 setupUi( this );
42 setObjectName( "QgsDbImportVectorLayerDialog" );
44
45 mSourceLayerComboBox->setFilters( Qgis::LayerFilter::VectorLayer );
46 connect( mSourceLayerComboBox, &QgsMapLayerComboBox::layerChanged, this, &QgsDbImportVectorLayerDialog::sourceLayerComboChanged );
47 connect( mCrsSelector, &QgsProjectionSelectionWidget::crsChanged, this, [this]( const QgsCoordinateReferenceSystem &crs ) { mExtentGroupBox->setOutputCrs( crs ); } );
48
49 connect( mButtonBox, &QDialogButtonBox::rejected, this, &QDialog::reject );
50 connect( mButtonBox, &QDialogButtonBox::accepted, this, &QgsDbImportVectorLayerDialog::doImport );
51
52 Q_ASSERT( connection );
53
54 mFieldsView->setDestinationEditable( true );
55 try
56 {
57 mFieldsView->setNativeTypes( connection->nativeTypes() );
58 }
60 {
61 QgsDebugError( u"Could not retrieve connection native types: %1"_s.arg( e.what() ) );
62 }
63 connect( mResetButton, &QPushButton::clicked, this, &QgsDbImportVectorLayerDialog::loadFieldsFromLayer );
64 connect( mAddButton, &QPushButton::clicked, this, &QgsDbImportVectorLayerDialog::addField );
65 connect( mDeleteButton, &QPushButton::clicked, mFieldsView, &QgsFieldMappingWidget::removeSelectedFields );
66 connect( mUpButton, &QPushButton::clicked, mFieldsView, &QgsFieldMappingWidget::moveSelectedFieldsUp );
67 connect( mDownButton, &QPushButton::clicked, mFieldsView, &QgsFieldMappingWidget::moveSelectedFieldsDown );
68
69 mEditButton->setPopupMode( QToolButton::InstantPopup ); // Show menu on button click
70
71 // Create a menu for the dropdown
72 QMenu *menu = new QMenu( mEditButton );
73
74 // Add menu items
75 menu->addAction( tr( "Convert All Field Names to Lowercase" ), this, [this]() {
76 QgsFieldMappingModel *model = mFieldsView->model();
77 for ( int i = 0; i < model->rowCount(); i++ )
78 {
79 const QModelIndex index = model->index( i, static_cast<int>( QgsFieldMappingModel::ColumnDataIndex::DestinationName ) );
80 const QString name = model->data( index, Qt::EditRole ).toString();
81 model->setData( index, name.toLower(), Qt::EditRole );
82 }
83 } );
84
85 menu->addAction( tr( "Convert All Field Names to Uppercase" ), this, [this]() {
86 QgsFieldMappingModel *model = mFieldsView->model();
87 for ( int i = 0; i < model->rowCount(); i++ )
88 {
89 const QModelIndex index = model->index( i, static_cast<int>( QgsFieldMappingModel::ColumnDataIndex::DestinationName ) );
90 const QString name = model->data( index, Qt::EditRole ).toString();
91 model->setData( index, name.toUpper(), Qt::EditRole );
92 }
93 } );
94
95 mEditButton->setMenu( menu );
96
97 const bool supportsSchemas = mConnection->capabilities().testFlag( QgsAbstractDatabaseProviderConnection::Schemas );
98 if ( supportsSchemas )
99 {
100 std::unique_ptr<QgsAbstractDatabaseProviderConnection> schemeComboConn;
101 QgsProviderMetadata *md = QgsProviderRegistry::instance()->providerMetadata( mConnection->providerKey() );
102 mSchemaCombo = new QgsDatabaseSchemaComboBox( static_cast<QgsAbstractDatabaseProviderConnection *>( md->createConnection( mConnection->uri(), QVariantMap() ) ) );
103 mLayoutSchemeCombo->addWidget( mSchemaCombo );
104 }
105 else
106 {
107 delete mLabelSchemas;
108 mLabelSchemas = nullptr;
109 delete mLayoutSchemeCombo;
110 mLayoutSchemeCombo = nullptr;
111 }
112
113 const bool supportsPrimaryKeyName = mConnection->tableImportCapabilities().testFlag( Qgis::DatabaseProviderTableImportCapability::SetPrimaryKeyName );
114 if ( !supportsPrimaryKeyName )
115 {
116 delete mLabelPrimaryKey;
117 mLabelPrimaryKey = nullptr;
118 delete mEditPrimaryKey;
119 mEditPrimaryKey = nullptr;
120 }
121
122 const bool supportsGeomColumnName = mConnection->tableImportCapabilities().testFlag( Qgis::DatabaseProviderTableImportCapability::SetGeometryColumnName );
123 if ( !supportsGeomColumnName )
124 {
125 delete mLabelGeometryColumn;
126 mLabelGeometryColumn = nullptr;
127 delete mEditGeometryColumnName;
128 mEditGeometryColumnName = nullptr;
129 }
130
131 const bool supportsTableComments = mConnection->capabilities2().testFlag( Qgis::DatabaseProviderConnectionCapability2::SetTableComment );
132 if ( !supportsTableComments )
133 {
134 delete mLabelComment;
135 mLabelComment = nullptr;
136 delete mEditComment;
137 mEditComment = nullptr;
138 }
139
140 mExtentGroupBox->setTitleBase( tr( "Filter by Extent" ) );
141 mExtentGroupBox->setCheckable( true );
142 mExtentGroupBox->setChecked( false );
143 mExtentGroupBox->setCollapsed( true );
144
145 mFilterExpressionWidget->registerExpressionContextGenerator( this );
146
147 // populate initial layer
148 sourceLayerComboChanged();
149}
150
152{
153 // these widgets all potentially access mOwnedSource, so we need to force
154 // them to be deleted BEFORE the layer
155 delete mSourceLayerComboBox;
156 mSourceLayerComboBox = nullptr;
157 delete mFilterExpressionWidget;
158 mFilterExpressionWidget = nullptr;
159 delete mFieldsView;
160 mFieldsView = nullptr;
161}
162
164{
165 if ( mSchemaCombo )
166 mSchemaCombo->setSchema( schema );
167}
168
170{
171 mOwnedSource.reset();
172 mSourceLayer = nullptr;
173
174 bool owner = false;
175 QString error;
176 QgsVectorLayer *vl = uri.vectorLayer( owner, error, QgsProject::instance() );
177 if ( owner )
178 {
179 mOwnedSource.reset( vl );
180 mBlockSourceLayerChanges++;
181 mSourceLayerComboBox->setAdditionalLayers( { vl } );
182 mSourceLayerComboBox->setLayer( vl );
183 mBlockSourceLayerChanges--;
184 setSourceLayer( mOwnedSource.get() );
185 }
186 else if ( vl )
187 {
188 mBlockSourceLayerChanges++;
189 mSourceLayerComboBox->setLayer( vl );
190 mBlockSourceLayerChanges--;
191 setSourceLayer( vl );
192 }
193}
194
195void QgsDbImportVectorLayerDialog::setSourceLayer( QgsVectorLayer *layer )
196{
197 mSourceLayer = layer;
198 if ( !mSourceLayer || !mSourceLayer->dataProvider() )
199 return;
200
201 mEditTable->setText( layer->name() );
202
203 const bool isSpatial = mSourceLayer->isSpatial();
204 if ( mEditGeometryColumnName )
205 mEditGeometryColumnName->setEnabled( isSpatial );
206 if ( mCrsSelector )
207 mCrsSelector->setEnabled( isSpatial );
208
209 mExtentGroupBox->setEnabled( isSpatial );
210 if ( !isSpatial )
211 mExtentGroupBox->setChecked( false );
212
213 const bool extentFilterEnabled = mExtentGroupBox->isChecked();
214 mExtentGroupBox->setOriginalExtent( mSourceLayer->extent(), mSourceLayer->crs() );
215 mExtentGroupBox->setOutputExtentFromOriginal();
216 mExtentGroupBox->setChecked( extentFilterEnabled );
217 mExtentGroupBox->setCollapsed( !extentFilterEnabled );
218
219 mFilterExpressionWidget->setLayer( mSourceLayer );
220
221 if ( mEditPrimaryKey )
222 {
223 // set initial geometry column name. We use the source layer's primary key column name if available,
224 // else fallback to a default value given by the connection
225 const QgsAttributeList pkAttributes = mSourceLayer->dataProvider()->pkAttributeIndexes();
226 QString primaryKey = !pkAttributes.isEmpty() ? mSourceLayer->dataProvider()->fields().at( pkAttributes.at( 0 ) ).name() : QString();
227 if ( primaryKey.isEmpty() )
228 {
229 QgsDataSourceUri dsUri( mSourceLayer->source() );
230 primaryKey = dsUri.keyColumn();
231 }
232 if ( primaryKey.isEmpty() )
233 {
234 primaryKey = mConnection->defaultPrimaryKeyColumnName();
235 }
236
237 mEditPrimaryKey->setText( primaryKey );
238 }
239
240 if ( mEditGeometryColumnName )
241 {
242 // set initial geometry column name. We use the source layer's geometry name if available,
243 // else fallback to a default value given by the connection
244 QString geomColumn = mSourceLayer->dataProvider()->geometryColumnName();
245 if ( geomColumn.isEmpty() )
246 {
247 QgsDataSourceUri dsUri( mSourceLayer->source() );
248 geomColumn = dsUri.geometryColumn();
249 }
250 if ( geomColumn.isEmpty() )
251 {
252 geomColumn = mConnection->defaultGeometryColumnName();
253 }
254
255 mEditGeometryColumnName->setText( geomColumn );
256 }
257
258 if ( mCrsSelector )
259 {
260 mCrsSelector->setCrs( mSourceLayer->crs() );
261 }
262
263 if ( mEditComment )
264 {
265 mEditComment->setPlainText( mSourceLayer->metadata().abstract() );
266 }
267
268 mFieldsView->setSourceLayer( mSourceLayer );
269 mFieldsView->setSourceFields( mSourceLayer->fields() );
270 mFieldsView->setDestinationFields( mSourceLayer->fields() );
271
272 const bool selectedFeatures = mSourceLayer->selectedFeatureCount() > 0;
273 mSourceLayerOnlySelected->setEnabled( selectedFeatures );
274}
275
276void QgsDbImportVectorLayerDialog::loadFieldsFromLayer()
277{
278 if ( mSourceLayer )
279 {
280 mFieldsView->setSourceFields( mSourceLayer->fields() );
281 mFieldsView->setDestinationFields( mSourceLayer->fields() );
282 }
283}
284
285void QgsDbImportVectorLayerDialog::addField()
286{
287 const int rowCount = mFieldsView->model()->rowCount();
288 mFieldsView->appendField( QgsField( u"new_field"_s ), u"NULL"_s );
289 const QModelIndex index = mFieldsView->model()->index( rowCount, 0 );
290 mFieldsView->selectionModel()->select( index, QItemSelectionModel::SelectionFlags( QItemSelectionModel::Clear | QItemSelectionModel::Select | QItemSelectionModel::Current | QItemSelectionModel::Rows ) );
291 mFieldsView->scrollTo( index );
292}
293
295{
296 return mSchemaCombo ? mSchemaCombo->currentSchema() : QString();
297}
298
300{
301 return mEditTable->text();
302}
303
305{
306 return mEditComment ? mEditComment->toPlainText() : QString();
307}
308
310{
311 if ( canvas )
312 {
313 mExtentGroupBox->setCurrentExtent( canvas->mapSettings().visibleExtent(), canvas->mapSettings().destinationCrs() );
314 mExtentGroupBox->setMapCanvas( canvas, false );
315 }
316}
317
318void QgsDbImportVectorLayerDialog::doImport()
319{
320 // TODO -- validate
321
322 accept();
323}
324
325std::unique_ptr<QgsVectorLayerExporterTask> QgsDbImportVectorLayerDialog::createExporterTask( const QVariantMap &extraProviderOptions )
326{
327 if ( !mSourceLayer || !mSourceLayer->dataProvider() )
328 return nullptr;
329
330 QString destinationUri;
331 QVariantMap providerOptions;
332
334 exporterOptions.layerName = mEditTable->text();
335 if ( mSchemaCombo )
336 exporterOptions.schema = mSchemaCombo->currentSchema();
337 exporterOptions.wkbType = mSourceLayer->wkbType();
338 if ( mEditPrimaryKey && !mEditPrimaryKey->text().trimmed().isEmpty() )
339 exporterOptions.primaryKeyColumns << mEditPrimaryKey->text();
340 if ( mEditGeometryColumnName )
341 exporterOptions.geometryColumn = mEditGeometryColumnName->text();
342
343 try
344 {
345 destinationUri = mConnection->createVectorLayerExporterDestinationUri( exporterOptions, providerOptions );
346 }
348 {
349 return nullptr;
350 }
351
352 // options given to us by createVectorLayerExporterDestinationUri above should overwrite generic ones passed to this method
353 QVariantMap allProviderOptions = extraProviderOptions;
354 for ( auto it = providerOptions.constBegin(); it != providerOptions.constEnd(); ++it )
355 {
356 allProviderOptions.insert( it.key(), it.value() );
357 }
358
359 // overwrite?
360 if ( mChkDropTable->isChecked() )
361 {
362 allProviderOptions.insert( u"overwrite"_s, true );
363 }
364
365 // This flag tells to the provider that field types do not need conversion -- we have already
366 // explicitly set all fields to provider-specific field types and we do not need to treat
367 // them as generic/different provider fields
368 allProviderOptions.insert( u"skipConvertFields"_s, true );
369
371 if ( mCrsSelector )
372 {
373 exportOptions.setDestinationCrs( mCrsSelector->crs() );
374 }
375 exportOptions.setTransformContext( mSourceLayer->transformContext() );
376 if ( !mFilterExpressionWidget->expression().isEmpty() )
377 {
378 exportOptions.setFilterExpression( mFilterExpressionWidget->expression() );
380 }
381
382 if ( mExtentGroupBox->isEnabled() && mExtentGroupBox->isChecked() )
383 {
384 exportOptions.setExtent( QgsReferencedRectangle( mExtentGroupBox->outputExtent(), mExtentGroupBox->outputCrs() ) );
385 }
386
387 if ( mSourceLayerOnlySelected->isEnabled() && mSourceLayerOnlySelected->isChecked() )
388 {
389 exportOptions.setSelectedOnly( true );
390 }
391
392 const QList<QgsFieldMappingModel::Field> fieldMapping = mFieldsView->mapping();
393 QList<QgsVectorLayerExporter::OutputField> outputFields;
394 outputFields.reserve( fieldMapping.size() );
395 for ( const QgsFieldMappingModel::Field &field : fieldMapping )
396 {
397 outputFields.append( QgsVectorLayerExporter::OutputField( field.field, field.expression ) );
398 }
399 exportOptions.setOutputFields( outputFields );
400
401 return std::make_unique<QgsVectorLayerExporterTask>( mSourceLayer->clone(), destinationUri, mConnection->providerKey(), exportOptions, allProviderOptions, true );
402}
403
410
411void QgsDbImportVectorLayerDialog::sourceLayerComboChanged()
412{
413 if ( mBlockSourceLayerChanges )
414 return;
415
416 if ( mSourceLayerComboBox->currentLayer() == mSourceLayer )
417 return;
418
419 setSourceLayer( qobject_cast< QgsVectorLayer * >( mSourceLayerComboBox->currentLayer() ) );
420}
@ SetPrimaryKeyName
Can set the name of the primary key column.
Definition qgis.h:6229
@ SetGeometryColumnName
Can set the name of the geometry column.
Definition qgis.h:6228
@ SetTableComment
Can set comments for tables via setTableComment().
Definition qgis.h:6213
Provides common functionality for database based connections.
@ Schemas
Can list schemas (if not set, the connection does not support schemas).
virtual QList< QgsVectorDataProvider::NativeType > nativeTypes() const =0
Returns a list of native types supported by the connection.
Represents a coordinate reference system (CRS).
Stores the component parts of a data source URI (e.g.
A combo box which displays the list of schemas for a specific database connection.
void setDestinationSchema(const QString &schema)
Sets the destination schema for the new table.
QgsExpressionContext createExpressionContext() const override
This method needs to be reimplemented in all classes which implement this interface and return an exp...
std::unique_ptr< QgsVectorLayerExporterTask > createExporterTask(const QVariantMap &extraProviderOptions=QVariantMap())
Creates a new exporter task to match the settings defined in the dialog.
void setMapCanvas(QgsMapCanvas *canvas)
Sets a map canvas to associate with the dialog.
void setSourceUri(const QgsMimeDataUtils::Uri &uri)
Sets the source table uri.
QString schema() const
Returns the destination schema.
QString tableName() const
Returns the destination table name.
QString tableComment() const
Returns the optional comment to use for the new table.
QgsDbImportVectorLayerDialog(QgsAbstractDatabaseProviderConnection *connection, QWidget *parent=nullptr)
Constructor for QgsDbImportVectorLayerDialog.
QString what() const
static QList< QgsExpressionContextScope * > globalProjectLayerScopes(const QgsMapLayer *layer)
Creates a list of three scopes: global, layer's project and layer.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void appendScopes(const QList< QgsExpressionContextScope * > &scopes)
Appends a list of scopes to the end of the context.
Holds mapping information for mapping from one set of QgsFields to another.
int rowCount(const QModelIndex &parent=QModelIndex()) const override
QVariant data(const QModelIndex &index, int role) const override
bool setData(const QModelIndex &index, const QVariant &value, int role) override
bool removeSelectedFields()
Removes the currently selected field from the model.
bool moveSelectedFieldsDown()
Moves down the currently selected field.
bool moveSelectedFieldsUp()
Moves up currently selected field.
static void enableAutoGeometryRestore(QWidget *widget, const QString &key=QString())
Register the widget to allow its position to be automatically saved and restored when open and closed...
Definition qgsgui.cpp:225
Map canvas is a class for displaying all GIS data types on a canvas.
const QgsMapSettings & mapSettings() const
Gets access to properties used for map rendering.
void layerChanged(QgsMapLayer *layer)
Emitted whenever the currently selected layer changes.
QString name
Definition qgsmaplayer.h:87
QgsRectangle visibleExtent() const
Returns the actual extent derived from requested extent that takes output image size into account.
QgsCoordinateReferenceSystem destinationCrs() const
Returns the destination coordinate reference system for the map render.
static QgsProject * instance()
Returns the QgsProject singleton instance.
void crsChanged(const QgsCoordinateReferenceSystem &crs)
Emitted when the selected CRS is changed.
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.
A QgsRectangle with associated coordinate reference system.
Encapsulates options for use with QgsVectorLayerExporter.
void setExtent(const QgsReferencedRectangle &extent)
Sets an extent filter for the features to export.
void setOutputFields(const QList< QgsVectorLayerExporter::OutputField > &fields)
Sets the output field definitions for the destination table.
void setSelectedOnly(bool selected)
Sets whether the export should only include selected features.
void setDestinationCrs(const QgsCoordinateReferenceSystem &crs)
Sets the destination coordinate reference system to use for exported features.
void setFilterExpression(const QString &expression)
Set the filter expression for the features to export.
void setExpressionContext(const QgsExpressionContext &context)
Sets the expression context to use when a filterExpression() is set.
void setTransformContext(const QgsCoordinateTransformContext &context)
Sets the coordinate transform context to use when transforming exported features.
Represents a vector layer which manages a vector based dataset.
QList< int > QgsAttributeList
Definition qgsfield.h:30
#define QgsDebugError(str)
Definition qgslogger.h:71
Stores all information required to create a QgsVectorLayerExporter for the backend.
QStringList primaryKeyColumns
List of primary key column names. Note that some providers may ignore this if not supported.
QString schema
Optional schema for the new layer. May not be supported by all providers.
QString geometryColumn
Preferred name for the geometry column, if required. Note that some providers may ignore this if a sp...
The Field struct holds information about a mapped field.
Q_DECL_DEPRECATED QgsVectorLayer * vectorLayer(bool &owner, QString &error) const
Gets vector layer from uri if possible, otherwise returns nullptr and error is set.
Encapsulates output field definition.