27#include <QItemSelectionModel>
31#include "moc_qgsdbimportvectorlayerdialog.cpp"
35 , mConnection( connection )
38 setObjectName(
"QgsDbImportVectorLayerDialog" );
44 mExtentGroupBox->setOutputCrs( crs );
47 connect( mButtonBox, &QDialogButtonBox::rejected,
this, &QDialog::reject );
48 connect( mButtonBox, &QDialogButtonBox::accepted,
this, &QgsDbImportVectorLayerDialog::doImport );
50 Q_ASSERT( connection );
52 mFieldsView->setDestinationEditable(
true );
55 mFieldsView->setNativeTypes( connection->
nativeTypes() );
59 QgsDebugError( QStringLiteral(
"Could not retrieve connection native types: %1" ).arg( e.
what() ) );
61 connect( mResetButton, &QPushButton::clicked,
this, &QgsDbImportVectorLayerDialog::loadFieldsFromLayer );
62 connect( mAddButton, &QPushButton::clicked,
this, &QgsDbImportVectorLayerDialog::addField );
67 mEditButton->setPopupMode( QToolButton::InstantPopup );
70 QMenu *menu =
new QMenu( mEditButton );
73 menu->addAction( tr(
"Convert All Field Names to Lowercase" ),
this, [
this]() {
75 for (
int i = 0; i < model->
rowCount(); i++ )
78 const QString name = model->
data( index, Qt::EditRole ).toString();
79 model->
setData( index, name.toLower(), Qt::EditRole );
83 menu->addAction( tr(
"Convert All Field Names to Uppercase" ),
this, [
this]() {
85 for (
int i = 0; i < model->
rowCount(); i++ )
88 const QString name = model->
data( index, Qt::EditRole ).toString();
89 model->
setData( index, name.toUpper(), Qt::EditRole );
93 mEditButton->setMenu( menu );
96 if ( supportsSchemas )
98 std::unique_ptr<QgsAbstractDatabaseProviderConnection> schemeComboConn;
101 mLayoutSchemeCombo->addWidget( mSchemaCombo );
105 delete mLabelSchemas;
106 mLabelSchemas =
nullptr;
107 delete mLayoutSchemeCombo;
108 mLayoutSchemeCombo =
nullptr;
112 if ( !supportsPrimaryKeyName )
114 delete mLabelPrimaryKey;
115 mLabelPrimaryKey =
nullptr;
116 delete mEditPrimaryKey;
117 mEditPrimaryKey =
nullptr;
121 if ( !supportsGeomColumnName )
123 delete mLabelGeometryColumn;
124 mLabelGeometryColumn =
nullptr;
125 delete mEditGeometryColumnName;
126 mEditGeometryColumnName =
nullptr;
130 if ( !supportsTableComments )
132 delete mLabelComment;
133 mLabelComment =
nullptr;
135 mEditComment =
nullptr;
138 mExtentGroupBox->setTitleBase( tr(
"Filter by Extent" ) );
139 mExtentGroupBox->setCheckable(
true );
140 mExtentGroupBox->setChecked(
false );
141 mExtentGroupBox->setCollapsed(
true );
143 mFilterExpressionWidget->registerExpressionContextGenerator(
this );
146 sourceLayerComboChanged();
153 delete mSourceLayerComboBox;
154 mSourceLayerComboBox =
nullptr;
155 delete mFilterExpressionWidget;
156 mFilterExpressionWidget =
nullptr;
158 mFieldsView =
nullptr;
164 mSchemaCombo->setSchema(
schema );
169 mOwnedSource.reset();
170 mSourceLayer =
nullptr;
177 mOwnedSource.reset( vl );
178 mBlockSourceLayerChanges++;
179 mSourceLayerComboBox->setAdditionalLayers( { vl } );
180 mSourceLayerComboBox->setLayer( vl );
181 mBlockSourceLayerChanges--;
182 setSourceLayer( mOwnedSource.get() );
186 mBlockSourceLayerChanges++;
187 mSourceLayerComboBox->setLayer( vl );
188 mBlockSourceLayerChanges--;
189 setSourceLayer( vl );
193void QgsDbImportVectorLayerDialog::setSourceLayer(
QgsVectorLayer *layer )
195 mSourceLayer = layer;
196 if ( !mSourceLayer || !mSourceLayer->dataProvider() )
199 mEditTable->setText( layer->
name() );
201 const bool isSpatial = mSourceLayer->isSpatial();
202 if ( mEditGeometryColumnName )
203 mEditGeometryColumnName->setEnabled( isSpatial );
205 mCrsSelector->setEnabled( isSpatial );
207 mExtentGroupBox->setEnabled( isSpatial );
209 mExtentGroupBox->setChecked(
false );
211 const bool extentFilterEnabled = mExtentGroupBox->isChecked();
212 mExtentGroupBox->setOriginalExtent( mSourceLayer->extent(), mSourceLayer->crs() );
213 mExtentGroupBox->setOutputExtentFromOriginal();
214 mExtentGroupBox->setChecked( extentFilterEnabled );
215 mExtentGroupBox->setCollapsed( !extentFilterEnabled );
217 mFilterExpressionWidget->setLayer( mSourceLayer );
219 if ( mEditPrimaryKey )
223 const QgsAttributeList pkAttributes = mSourceLayer->dataProvider()->pkAttributeIndexes();
224 QString primaryKey = !pkAttributes.isEmpty() ? mSourceLayer->dataProvider()->fields().at( pkAttributes.at( 0 ) ).name() : QString();
225 if ( primaryKey.isEmpty() )
228 primaryKey = dsUri.keyColumn();
230 if ( primaryKey.isEmpty() )
232 primaryKey = mConnection->defaultPrimaryKeyColumnName();
235 mEditPrimaryKey->setText( primaryKey );
238 if ( mEditGeometryColumnName )
242 QString geomColumn = mSourceLayer->dataProvider()->geometryColumnName();
243 if ( geomColumn.isEmpty() )
245 QgsDataSourceUri dsUri( mSourceLayer->source() );
246 geomColumn = dsUri.geometryColumn();
248 if ( geomColumn.isEmpty() )
250 geomColumn = mConnection->defaultGeometryColumnName();
253 mEditGeometryColumnName->setText( geomColumn );
258 mCrsSelector->setCrs( mSourceLayer->crs() );
263 mEditComment->setPlainText( mSourceLayer->metadata().abstract() );
266 mFieldsView->setSourceLayer( mSourceLayer );
267 mFieldsView->setSourceFields( mSourceLayer->fields() );
268 mFieldsView->setDestinationFields( mSourceLayer->fields() );
270 const bool selectedFeatures = mSourceLayer->selectedFeatureCount() > 0;
271 mSourceLayerOnlySelected->setEnabled( selectedFeatures );
274void QgsDbImportVectorLayerDialog::loadFieldsFromLayer()
278 mFieldsView->setSourceFields( mSourceLayer->fields() );
279 mFieldsView->setDestinationFields( mSourceLayer->fields() );
283void QgsDbImportVectorLayerDialog::addField()
285 const int rowCount = mFieldsView->model()->rowCount();
286 mFieldsView->appendField( QgsField( QStringLiteral(
"new_field" ) ), QStringLiteral(
"NULL" ) );
287 const QModelIndex index = mFieldsView->model()->index( rowCount, 0 );
288 mFieldsView->selectionModel()->select(
290 QItemSelectionModel::SelectionFlags(
291 QItemSelectionModel::Clear | QItemSelectionModel::Select | QItemSelectionModel::Current | QItemSelectionModel::Rows
294 mFieldsView->scrollTo( index );
299 return mSchemaCombo ? mSchemaCombo->currentSchema() : QString();
304 return mEditTable->text();
309 return mEditComment ? mEditComment->toPlainText() : QString();
317 mExtentGroupBox->setMapCanvas( canvas,
false );
321void QgsDbImportVectorLayerDialog::doImport()
330 if ( !mSourceLayer || !mSourceLayer->dataProvider() )
333 QString destinationUri;
334 QVariantMap providerOptions;
337 exporterOptions.
layerName = mEditTable->text();
339 exporterOptions.
schema = mSchemaCombo->currentSchema();
340 exporterOptions.
wkbType = mSourceLayer->wkbType();
341 if ( mEditPrimaryKey && !mEditPrimaryKey->text().trimmed().isEmpty() )
343 if ( mEditGeometryColumnName )
348 destinationUri = mConnection->createVectorLayerExporterDestinationUri( exporterOptions, providerOptions );
356 QVariantMap allProviderOptions = extraProviderOptions;
357 for (
auto it = providerOptions.constBegin(); it != providerOptions.constEnd(); ++it )
359 allProviderOptions.insert( it.key(), it.value() );
363 if ( mChkDropTable->isChecked() )
365 allProviderOptions.insert( QStringLiteral(
"overwrite" ),
true );
371 allProviderOptions.insert( QStringLiteral(
"skipConvertFields" ),
true );
379 if ( !mFilterExpressionWidget->expression().isEmpty() )
385 if ( mExtentGroupBox->isEnabled() && mExtentGroupBox->isChecked() )
390 if ( mSourceLayerOnlySelected->isEnabled() && mSourceLayerOnlySelected->isChecked() )
395 const QList<QgsFieldMappingModel::Field> fieldMapping = mFieldsView->mapping();
396 QList<QgsVectorLayerExporter::OutputField> outputFields;
397 outputFields.reserve( fieldMapping.size() );
404 return std::make_unique<QgsVectorLayerExporterTask>( mSourceLayer->clone(), destinationUri, mConnection->providerKey(), exportOptions, allProviderOptions,
true );
414void QgsDbImportVectorLayerDialog::sourceLayerComboChanged()
416 if ( mBlockSourceLayerChanges )
419 if ( mSourceLayerComboBox->currentLayer() == mSourceLayer )
422 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().
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.
~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 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.
@ 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.
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.
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.