17#include "moc_qgsdbimportvectorlayerdialog.cpp"
27#include <QItemSelectionModel>
32 , mConnection( connection )
35 setObjectName(
"QgsDbImportVectorLayerDialog" );
41 mExtentGroupBox->setOutputCrs(
crs );
44 connect( mButtonBox, &QDialogButtonBox::rejected,
this, &QDialog::reject );
45 connect( mButtonBox, &QDialogButtonBox::accepted,
this, &QgsDbImportVectorLayerDialog::doImport );
47 Q_ASSERT( connection );
49 mFieldsView->setDestinationEditable(
true );
52 mFieldsView->setNativeTypes( connection->
nativeTypes() );
56 QgsDebugError( QStringLiteral(
"Could not retrieve connection native types: %1" ).arg( e.
what() ) );
58 connect( mResetButton, &QPushButton::clicked,
this, &QgsDbImportVectorLayerDialog::loadFieldsFromLayer );
59 connect( mAddButton, &QPushButton::clicked,
this, &QgsDbImportVectorLayerDialog::addField );
64 mEditButton->setPopupMode( QToolButton::InstantPopup );
67 QMenu *menu =
new QMenu( mEditButton );
70 menu->addAction( tr(
"Convert All Field Names to Lowercase" ),
this, [=]() {
72 for (
int i = 0; i < model->
rowCount(); i++ )
75 const QString name = model->
data( index, Qt::EditRole ).toString();
76 model->
setData( index, name.toLower(), Qt::EditRole );
80 menu->addAction( tr(
"Convert All Field Names to Uppercase" ),
this, [=]() {
82 for (
int i = 0; i < model->
rowCount(); i++ )
85 const QString name = model->
data( index, Qt::EditRole ).toString();
86 model->
setData( index, name.toUpper(), Qt::EditRole );
90 mEditButton->setMenu( menu );
93 if ( supportsSchemas )
95 std::unique_ptr<QgsAbstractDatabaseProviderConnection> schemeComboConn;
98 mLayoutSchemeCombo->addWidget( mSchemaCombo );
102 delete mLabelSchemas;
103 mLabelSchemas =
nullptr;
104 delete mLayoutSchemeCombo;
105 mLayoutSchemeCombo =
nullptr;
109 if ( !supportsPrimaryKeyName )
111 delete mLabelPrimaryKey;
112 mLabelPrimaryKey =
nullptr;
113 delete mEditPrimaryKey;
114 mEditPrimaryKey =
nullptr;
118 if ( !supportsGeomColumnName )
120 delete mLabelGeometryColumn;
121 mLabelGeometryColumn =
nullptr;
122 delete mEditGeometryColumnName;
123 mEditGeometryColumnName =
nullptr;
127 if ( !supportsTableComments )
129 delete mLabelComment;
130 mLabelComment =
nullptr;
132 mEditComment =
nullptr;
135 mExtentGroupBox->setTitleBase( tr(
"Filter by Extent" ) );
136 mExtentGroupBox->setCheckable(
true );
137 mExtentGroupBox->setChecked(
false );
138 mExtentGroupBox->setCollapsed(
true );
140 mFilterExpressionWidget->registerExpressionContextGenerator(
this );
143 sourceLayerComboChanged();
150 delete mSourceLayerComboBox;
151 mSourceLayerComboBox =
nullptr;
152 delete mFilterExpressionWidget;
153 mFilterExpressionWidget =
nullptr;
155 mFieldsView =
nullptr;
166 mOwnedSource.reset();
167 mSourceLayer =
nullptr;
174 mOwnedSource.reset( vl );
175 mBlockSourceLayerChanges++;
176 mSourceLayerComboBox->setAdditionalLayers( { vl } );
177 mSourceLayerComboBox->setLayer( vl );
178 mBlockSourceLayerChanges--;
179 setSourceLayer( mOwnedSource.get() );
183 mBlockSourceLayerChanges++;
184 mSourceLayerComboBox->setLayer( vl );
185 mBlockSourceLayerChanges--;
186 setSourceLayer( vl );
190void QgsDbImportVectorLayerDialog::setSourceLayer(
QgsVectorLayer *layer )
192 mSourceLayer = layer;
193 if ( !mSourceLayer || !mSourceLayer->dataProvider() )
196 mEditTable->setText( layer->
name() );
198 const bool isSpatial = mSourceLayer->isSpatial();
199 if ( mEditGeometryColumnName )
200 mEditGeometryColumnName->setEnabled( isSpatial );
202 mCrsSelector->setEnabled( isSpatial );
204 mExtentGroupBox->setEnabled( isSpatial );
206 mExtentGroupBox->setChecked(
false );
208 const bool extentFilterEnabled = mExtentGroupBox->isChecked();
209 mExtentGroupBox->setOriginalExtent( mSourceLayer->extent(), mSourceLayer->crs() );
210 mExtentGroupBox->setOutputExtentFromOriginal();
211 mExtentGroupBox->setChecked( extentFilterEnabled );
212 mExtentGroupBox->setCollapsed( !extentFilterEnabled );
214 mFilterExpressionWidget->setLayer( mSourceLayer );
216 if ( mEditPrimaryKey )
220 const QgsAttributeList pkAttributes = mSourceLayer->dataProvider()->pkAttributeIndexes();
221 QString primaryKey = !pkAttributes.isEmpty() ? mSourceLayer->dataProvider()->fields().at( pkAttributes.at( 0 ) ).name() : QString();
222 if ( primaryKey.isEmpty() )
225 primaryKey = dsUri.keyColumn();
227 if ( primaryKey.isEmpty() )
229 primaryKey = mConnection->defaultPrimaryKeyColumnName();
232 mEditPrimaryKey->setText( primaryKey );
235 if ( mEditGeometryColumnName )
239 QString geomColumn = mSourceLayer->dataProvider()->geometryColumnName();
240 if ( geomColumn.isEmpty() )
243 geomColumn = dsUri.geometryColumn();
245 if ( geomColumn.isEmpty() )
247 geomColumn = mConnection->defaultGeometryColumnName();
250 mEditGeometryColumnName->setText( geomColumn );
255 mCrsSelector->setCrs( mSourceLayer->crs() );
260 mEditComment->setPlainText( mSourceLayer->metadata().abstract() );
263 mFieldsView->setSourceLayer( mSourceLayer );
264 mFieldsView->setSourceFields( mSourceLayer->fields() );
265 mFieldsView->setDestinationFields( mSourceLayer->fields() );
267 const bool selectedFeatures = mSourceLayer->selectedFeatureCount() > 0;
268 mSourceLayerOnlySelected->setEnabled( selectedFeatures );
271void QgsDbImportVectorLayerDialog::loadFieldsFromLayer()
275 mFieldsView->setSourceFields( mSourceLayer->fields() );
276 mFieldsView->setDestinationFields( mSourceLayer->fields() );
280void QgsDbImportVectorLayerDialog::addField()
282 const int rowCount = mFieldsView->model()->rowCount();
283 mFieldsView->appendField(
QgsField( QStringLiteral(
"new_field" ) ), QStringLiteral(
"NULL" ) );
284 const QModelIndex index = mFieldsView->model()->index( rowCount, 0 );
285 mFieldsView->selectionModel()->select(
287 QItemSelectionModel::SelectionFlags(
288 QItemSelectionModel::Clear | QItemSelectionModel::Select | QItemSelectionModel::Current | QItemSelectionModel::Rows
291 mFieldsView->scrollTo( index );
296 return mSchemaCombo ? mSchemaCombo->
currentSchema() : QString();
301 return mEditTable->text();
306 return mEditComment ? mEditComment->toPlainText() : QString();
314 mExtentGroupBox->setMapCanvas( canvas,
false );
318void QgsDbImportVectorLayerDialog::doImport()
327 if ( !mSourceLayer || !mSourceLayer->dataProvider() )
330 QString destinationUri;
331 QVariantMap providerOptions;
334 exporterOptions.
layerName = mEditTable->text();
337 exporterOptions.
wkbType = mSourceLayer->wkbType();
338 if ( mEditPrimaryKey && !mEditPrimaryKey->text().trimmed().isEmpty() )
340 if ( mEditGeometryColumnName )
345 destinationUri = mConnection->createVectorLayerExporterDestinationUri( exporterOptions, providerOptions );
353 QVariantMap allProviderOptions = extraProviderOptions;
354 for (
auto it = providerOptions.constBegin(); it != providerOptions.constEnd(); ++it )
356 allProviderOptions.insert( it.key(), it.value() );
360 if ( mChkDropTable->isChecked() )
362 allProviderOptions.insert( QStringLiteral(
"overwrite" ), true );
368 allProviderOptions.insert( QStringLiteral(
"skipConvertFields" ), true );
376 if ( !mFilterExpressionWidget->expression().isEmpty() )
382 if ( mExtentGroupBox->isEnabled() && mExtentGroupBox->isChecked() )
387 if ( mSourceLayerOnlySelected->isEnabled() && mSourceLayerOnlySelected->isChecked() )
392 const QList<QgsFieldMappingModel::Field> fieldMapping = mFieldsView->mapping();
393 QList<QgsVectorLayerExporter::OutputField> outputFields;
394 outputFields.reserve( fieldMapping.size() );
401 return std::make_unique<QgsVectorLayerExporterTask>( mSourceLayer->clone(), destinationUri, mConnection->providerKey(), exportOptions, allProviderOptions,
true );
411void QgsDbImportVectorLayerDialog::sourceLayerComboChanged()
413 if ( mBlockSourceLayerChanges )
416 if ( mSourceLayerComboBox->currentLayer() == mSourceLayer )
419 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 setSchema(const QString &schema)
Sets the current schema selected in the combo box.
QString currentSchema() const
Returns the name of the current schema selected in the combo box.
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
Encapsulate a field in an attribute table or data source.
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)
const QgsCoordinateReferenceSystem & crs
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.