28#include <QItemSelectionModel>
33#include "moc_qgsdbimportvectorlayerdialog.cpp"
35using namespace Qt::StringLiterals;
39 , mConnection( connection )
42 setObjectName(
"QgsDbImportVectorLayerDialog" );
49 connect( mButtonBox, &QDialogButtonBox::rejected,
this, &QDialog::reject );
50 connect( mButtonBox, &QDialogButtonBox::accepted,
this, &QgsDbImportVectorLayerDialog::doImport );
52 Q_ASSERT( connection );
54 mFieldsView->setDestinationEditable(
true );
57 mFieldsView->setNativeTypes( connection->
nativeTypes() );
61 QgsDebugError( u
"Could not retrieve connection native types: %1"_s.arg( e.
what() ) );
63 connect( mResetButton, &QPushButton::clicked,
this, &QgsDbImportVectorLayerDialog::loadFieldsFromLayer );
64 connect( mAddButton, &QPushButton::clicked,
this, &QgsDbImportVectorLayerDialog::addField );
69 mEditButton->setPopupMode( QToolButton::InstantPopup );
72 QMenu *menu =
new QMenu( mEditButton );
75 menu->addAction( tr(
"Convert All Field Names to Lowercase" ),
this, [
this]() {
77 for (
int i = 0; i < model->
rowCount(); i++ )
80 const QString name = model->
data( index, Qt::EditRole ).toString();
81 model->
setData( index, name.toLower(), Qt::EditRole );
85 menu->addAction( tr(
"Convert All Field Names to Uppercase" ),
this, [
this]() {
87 for (
int i = 0; i < model->
rowCount(); i++ )
90 const QString name = model->
data( index, Qt::EditRole ).toString();
91 model->
setData( index, name.toUpper(), Qt::EditRole );
95 mEditButton->setMenu( menu );
98 if ( supportsSchemas )
100 std::unique_ptr<QgsAbstractDatabaseProviderConnection> schemeComboConn;
103 mLayoutSchemeCombo->addWidget( mSchemaCombo );
107 delete mLabelSchemas;
108 mLabelSchemas =
nullptr;
109 delete mLayoutSchemeCombo;
110 mLayoutSchemeCombo =
nullptr;
114 if ( !supportsPrimaryKeyName )
116 delete mLabelPrimaryKey;
117 mLabelPrimaryKey =
nullptr;
118 delete mEditPrimaryKey;
119 mEditPrimaryKey =
nullptr;
123 if ( !supportsGeomColumnName )
125 delete mLabelGeometryColumn;
126 mLabelGeometryColumn =
nullptr;
127 delete mEditGeometryColumnName;
128 mEditGeometryColumnName =
nullptr;
132 if ( !supportsTableComments )
134 delete mLabelComment;
135 mLabelComment =
nullptr;
137 mEditComment =
nullptr;
141 if ( !supportsStyles )
143 delete mChkSaveStyleToDatabase;
144 mChkSaveStyleToDatabase =
nullptr;
147 mExtentGroupBox->setTitleBase( tr(
"Filter by Extent" ) );
148 mExtentGroupBox->setCheckable(
true );
149 mExtentGroupBox->setChecked(
false );
150 mExtentGroupBox->setCollapsed(
true );
152 mFilterExpressionWidget->registerExpressionContextGenerator(
this );
155 sourceLayerComboChanged();
162 delete mSourceLayerComboBox;
163 mSourceLayerComboBox =
nullptr;
164 delete mFilterExpressionWidget;
165 mFilterExpressionWidget =
nullptr;
167 mFieldsView =
nullptr;
173 mSchemaCombo->setSchema(
schema );
178 mOwnedSource.reset();
179 mSourceLayer =
nullptr;
186 mOwnedSource.reset( vl );
187 mBlockSourceLayerChanges++;
188 mSourceLayerComboBox->setAdditionalLayers( { vl } );
189 mSourceLayerComboBox->setLayer( vl );
190 mBlockSourceLayerChanges--;
191 setSourceLayer( mOwnedSource.get() );
195 mBlockSourceLayerChanges++;
196 mSourceLayerComboBox->setLayer( vl );
197 mBlockSourceLayerChanges--;
198 setSourceLayer( vl );
202void QgsDbImportVectorLayerDialog::setSourceLayer(
QgsVectorLayer *layer )
204 mSourceLayer = layer;
205 if ( !mSourceLayer || !mSourceLayer->dataProvider() )
208 mEditTable->setText( layer->
name() );
210 const bool isSpatial = mSourceLayer->isSpatial();
211 if ( mEditGeometryColumnName )
212 mEditGeometryColumnName->setEnabled( isSpatial );
214 mCrsSelector->setEnabled( isSpatial );
216 mExtentGroupBox->setEnabled( isSpatial );
218 mExtentGroupBox->setChecked(
false );
220 const bool extentFilterEnabled = mExtentGroupBox->isChecked();
221 mExtentGroupBox->setOriginalExtent( mSourceLayer->extent(), mSourceLayer->crs() );
222 mExtentGroupBox->setOutputExtentFromOriginal();
223 mExtentGroupBox->setChecked( extentFilterEnabled );
224 mExtentGroupBox->setCollapsed( !extentFilterEnabled );
226 mFilterExpressionWidget->setLayer( mSourceLayer );
228 if ( mEditPrimaryKey )
232 const QgsAttributeList pkAttributes = mSourceLayer->dataProvider()->pkAttributeIndexes();
233 QString primaryKey = !pkAttributes.isEmpty() ? mSourceLayer->dataProvider()->fields().at( pkAttributes.at( 0 ) ).name() : QString();
234 if ( primaryKey.isEmpty() )
237 primaryKey = dsUri.keyColumn();
239 if ( primaryKey.isEmpty() )
241 primaryKey = mConnection->defaultPrimaryKeyColumnName();
244 mEditPrimaryKey->setText( primaryKey );
247 if ( mEditGeometryColumnName )
251 QString geomColumn = mSourceLayer->dataProvider()->geometryColumnName();
252 if ( geomColumn.isEmpty() )
254 QgsDataSourceUri dsUri( mSourceLayer->source() );
255 geomColumn = dsUri.geometryColumn();
257 if ( geomColumn.isEmpty() )
259 geomColumn = mConnection->defaultGeometryColumnName();
262 mEditGeometryColumnName->setText( geomColumn );
267 mCrsSelector->setCrs( mSourceLayer->crs() );
272 mEditComment->setPlainText( mSourceLayer->metadata().abstract() );
275 mFieldsView->setSourceLayer( mSourceLayer );
276 mFieldsView->setSourceFields( mSourceLayer->fields() );
277 mFieldsView->setDestinationFields( mSourceLayer->fields() );
279 const bool selectedFeatures = mSourceLayer->selectedFeatureCount() > 0;
280 mSourceLayerOnlySelected->setEnabled( selectedFeatures );
283void QgsDbImportVectorLayerDialog::loadFieldsFromLayer()
287 mFieldsView->setSourceFields( mSourceLayer->fields() );
288 mFieldsView->setDestinationFields( mSourceLayer->fields() );
292void QgsDbImportVectorLayerDialog::addField()
294 const int rowCount = mFieldsView->model()->rowCount();
295 mFieldsView->appendField( QgsField( u
"new_field"_s ), u
"NULL"_s );
296 const QModelIndex index = mFieldsView->model()->index( rowCount, 0 );
297 mFieldsView->selectionModel()->select( index, QItemSelectionModel::SelectionFlags( QItemSelectionModel::Clear | QItemSelectionModel::Select | QItemSelectionModel::Current | QItemSelectionModel::Rows ) );
298 mFieldsView->scrollTo( index );
303 return mSchemaCombo ? mSchemaCombo->currentSchema() : QString();
308 return mEditTable->text();
313 return mEditComment ? mEditComment->toPlainText() : QString();
318 return mChkSaveStyleToDatabase && mChkSaveStyleToDatabase->isChecked();
328 return mEditGeometryColumnName ? mEditGeometryColumnName->text() : QString();
336 mExtentGroupBox->setMapCanvas( canvas,
false );
340void QgsDbImportVectorLayerDialog::doImport()
349 if ( !mSourceLayer || !mSourceLayer->dataProvider() )
352 QString destinationUri;
353 QVariantMap providerOptions;
356 exporterOptions.
layerName = mEditTable->text();
358 exporterOptions.
schema = mSchemaCombo->currentSchema();
359 exporterOptions.
wkbType = mSourceLayer->wkbType();
360 if ( mEditPrimaryKey && !mEditPrimaryKey->text().trimmed().isEmpty() )
362 if ( mEditGeometryColumnName )
367 destinationUri = mConnection->createVectorLayerExporterDestinationUri( exporterOptions, providerOptions );
375 QVariantMap allProviderOptions = extraProviderOptions;
376 for (
auto it = providerOptions.constBegin(); it != providerOptions.constEnd(); ++it )
378 allProviderOptions.insert( it.key(), it.value() );
382 if ( mChkDropTable->isChecked() )
384 allProviderOptions.insert( u
"overwrite"_s,
true );
390 allProviderOptions.insert( u
"skipConvertFields"_s,
true );
398 if ( !mFilterExpressionWidget->expression().isEmpty() )
404 if ( mExtentGroupBox->isEnabled() && mExtentGroupBox->isChecked() )
409 if ( mSourceLayerOnlySelected->isEnabled() && mSourceLayerOnlySelected->isChecked() )
414 const QList<QgsFieldMappingModel::Field> fieldMapping = mFieldsView->mapping();
415 QList<QgsVectorLayerExporter::OutputField> outputFields;
416 outputFields.reserve( fieldMapping.size() );
423 return std::make_unique<QgsVectorLayerExporterTask>( mSourceLayer->clone(), destinationUri, mConnection->providerKey(), exportOptions, allProviderOptions,
true );
433void QgsDbImportVectorLayerDialog::sourceLayerComboChanged()
435 if ( mBlockSourceLayerChanges )
438 if ( mSourceLayerComboBox->currentLayer() == mSourceLayer )
441 setSourceLayer( qobject_cast< QgsVectorLayer * >( mSourceLayerComboBox->currentLayer() ) );
@ SetPrimaryKeyName
Can set the name of the primary key column.
@ SetGeometryColumnName
Can set the name of the geometry column.
@ SetTableComment
Can set comments for tables via setTableComment().
@ StyleStorage
Can save/load styles to/from the database.
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.
QgsVectorLayer * sourceLayer() const
Returns the source layer, or nullptr if no source layer is set.
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.
bool saveStyleToDatabase() const
Returns true if the style should be saved to the database after import.
void setMapCanvas(QgsMapCanvas *canvas)
Sets a map canvas to associate with the dialog.
QString geometryColumn() const
Returns the geometry column name for the destination table.
~QgsDbImportVectorLayerDialog() override
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.
static std::vector< std::unique_ptr< 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.
@ DestinationName
Destination field name.
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
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...
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.
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.
Custom exception class for provider connection related exceptions.
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
#define QgsDebugError(str)
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...
QString layerName
Name for the new layer.
Qgis::WkbType wkbType
WKB type for destination layer geometry.
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.