Esempio n. 1
0
QString QgsOracleConn::toPoolName( const QgsDataSourceUri &uri )
{
  QString conninfo = uri.connectionInfo();
  if ( uri.hasParam( "dbworkspace" ) )
    conninfo += " dbworkspace=" + uri.param( "dbworkspace" );
  return conninfo;
}
Esempio n. 2
0
void QgsPGConnectionItem::createSchema()
{
  QString schemaName = QInputDialog::getText( nullptr, tr( "Create Schema" ), tr( "Schema name:" ) );
  if ( schemaName.isEmpty() )
    return;

  QgsDataSourceUri uri = QgsPostgresConn::connUri( mName );
  QgsPostgresConn *conn = QgsPostgresConn::connectDb( uri.connectionInfo( false ), false );
  if ( !conn )
  {
    QMessageBox::warning( nullptr, tr( "Create Schema" ), tr( "Unable to create schema." ) );
    return;
  }

  //create the schema
  QString sql = QStringLiteral( "CREATE SCHEMA %1" ).arg( QgsPostgresConn::quotedIdentifier( schemaName ) );

  QgsPostgresResult result( conn->PQexec( sql ) );
  if ( result.PQresultStatus() != PGRES_COMMAND_OK )
  {
    QMessageBox::warning( nullptr, tr( "Create Schema" ), tr( "Unable to create schema %1\n%2" ).arg( schemaName,
                          result.PQresultErrorMessage() ) );
    conn->unref();
    return;
  }

  conn->unref();
  refresh();
  // the parent should be updated
  if ( mParent )
    mParent->refreshConnections();
}
void QgsOracleNewConnection::on_btnConnect_clicked()
{
  QgsDataSourceUri uri;
  uri.setConnection( txtHost->text(), txtPort->text(), txtDatabase->text(), txtUsername->text(), txtPassword->text() );
  if ( !txtOptions->text().isEmpty() )
    uri.setParam( "dboptions", txtOptions->text() );
  if ( !txtWorkspace->text().isEmpty() )
    uri.setParam( "dbworkspace", txtWorkspace->text() );

  QgsOracleConn *conn = QgsOracleConnPool::instance()->acquireConnection( QgsOracleConn::toPoolName( uri ) );

  if ( conn )
  {
    // Database successfully opened; we can now issue SQL commands.
    QMessageBox::information( this,
                              tr( "Test connection" ),
                              tr( "Connection to %1 was successful" ).arg( txtDatabase->text() ) );

    // free connection resources
    QgsOracleConnPool::instance()->releaseConnection( conn );
  }
  else
  {
    QMessageBox::information( this,
                              tr( "Test connection" ),
                              tr( "Connection failed - consult message log for details.\n\n" ) );
  }
}
Esempio n. 4
0
void QgsPgNewConnection::testConnection()
{
  QgsDataSourceUri uri;
  if ( !txtService->text().isEmpty() )
  {
    uri.setConnection( txtService->text(), txtDatabase->text(),
                       txtUsername->text(), txtPassword->text(),
                       ( QgsDataSourceUri::SslMode ) cbxSSLmode->currentData().toInt(),
                       mAuthConfigSelect->configId() );
  }
  else
  {
    uri.setConnection( txtHost->text(), txtPort->text(), txtDatabase->text(),
                       txtUsername->text(), txtPassword->text(),
                       ( QgsDataSourceUri::SslMode ) cbxSSLmode->currentData().toInt(),
                       mAuthConfigSelect->configId() );
  }

  QgsPostgresConn *conn = QgsPostgresConn::connectDb( uri.connectionInfo( false ), true );

  if ( conn )
  {
    // Database successfully opened; we can now issue SQL commands.
    bar->pushMessage( tr( "Connection to %1 was successful" ).arg( txtDatabase->text() ),
                      QgsMessageBar::INFO );

    // free pg connection resources
    conn->unref();
  }
  else
  {
    bar->pushMessage( tr( "Connection failed - consult message log for details." ),
                      QgsMessageBar::WARNING );
  }
}
Esempio n. 5
0
void QgsPGSchemaItem::renameSchema()
{
  QgsNewNameDialog dlg( tr( "schema '%1'" ).arg( mName ), mName );
  dlg.setWindowTitle( tr( "Rename Schema" ) );
  if ( dlg.exec() != QDialog::Accepted || dlg.name() == mName )
    return;

  QString schemaName = QgsPostgresConn::quotedIdentifier( mName );
  QgsDataSourceUri uri = QgsPostgresConn::connUri( mConnectionName );
  QgsPostgresConn *conn = QgsPostgresConn::connectDb( uri.connectionInfo( false ), false );
  if ( !conn )
  {
    QMessageBox::warning( nullptr, tr( "Rename Schema" ), tr( "Unable to rename schema." ) );
    return;
  }

  //rename the schema
  QString sql = QStringLiteral( "ALTER SCHEMA %1 RENAME TO %2" )
                .arg( schemaName, QgsPostgresConn::quotedIdentifier( dlg.name() ) );

  QgsPostgresResult result( conn->PQexec( sql ) );
  if ( result.PQresultStatus() != PGRES_COMMAND_OK )
  {
    QMessageBox::warning( nullptr, tr( "Rename Schema" ), tr( "Unable to rename schema %1\n%2" ).arg( schemaName,
                          result.PQresultErrorMessage() ) );
    conn->unref();
    return;
  }

  conn->unref();
  QMessageBox::information( nullptr, tr( "Rename Schema" ), tr( "Schema renamed successfully." ) );
  if ( mParent )
    mParent->refresh();
}
void QgsOracleNewConnection::testConnection()
{
  QgsDataSourceUri uri;
  uri.setConnection( txtHost->text(), txtPort->text(), txtDatabase->text(), txtUsername->text(), txtPassword->text() );
  if ( !txtOptions->text().isEmpty() )
    uri.setParam( QStringLiteral( "dboptions" ), txtOptions->text() );
  if ( !txtWorkspace->text().isEmpty() )
    uri.setParam( QStringLiteral( "dbworkspace" ), txtWorkspace->text() );

  QgsOracleConn *conn = QgsOracleConnPool::instance()->acquireConnection( QgsOracleConn::toPoolName( uri ) );

  if ( conn )
  {
    // Database successfully opened; we can now issue SQL commands.
    bar->pushMessage( tr( "Connection to %1 was successful." ).arg( txtName->text() ),
                      Qgis::Info );
    // free connection resources
    QgsOracleConnPool::instance()->releaseConnection( conn );
  }
  else
  {
    bar->pushMessage( tr( "Connection failed - consult message log for details." ),
                      Qgis::Warning );
  }
}
Esempio n. 7
0
QgsDataSourceUri QgsAuxiliaryStorage::parseOgrUri( const QgsDataSourceUri &uri )
{
  QgsDataSourceUri newUri;

  // parsing for ogr style uri :
  // " filePath|layername='tableName' table="" sql="
  QStringList uriParts = uri.uri().split( '|' );
  if ( uriParts.count() < 2 )
    return newUri;

  const QString databasePath = uriParts[0].replace( ' ', "" );

  const QString table = uriParts[1];
  QStringList tableParts = table.split( ' ' );

  if ( tableParts.count() < 1 )
    return newUri;

  const QString tableName = tableParts[0].replace( QStringLiteral( "layername=" ), QString() );

  newUri.setDataSource( QString(), tableName, QString() );
  newUri.setDatabase( databasePath );

  return newUri;
}
Esempio n. 8
0
QVector<QgsDataItem*> QgsPGConnectionItem::createChildren()
{

  QVector<QgsDataItem*>items;

  QgsDataSourceUri uri = QgsPostgresConn::connUri( mName );
  // TODO: wee need to cancel somehow acquireConnection() if deleteLater() was called on this item to avoid later credential dialog if connection failed
  QgsPostgresConn *conn = QgsPostgresConnPool::instance()->acquireConnection( uri.connectionInfo( false ) );
  if ( !conn )
  {
    items.append( new QgsErrorItem( this, tr( "Connection failed" ), mPath + "/error" ) );
    QgsDebugMsg( "Connection failed - " + uri.connectionInfo( false ) );
    return items;
  }

  QList<QgsPostgresSchemaProperty> schemas;
  bool ok = conn->getSchemas( schemas );
  QgsPostgresConnPool::instance()->releaseConnection( conn );

  if ( !ok )
  {
    items.append( new QgsErrorItem( this, tr( "Failed to get schemas" ), mPath + "/error" ) );
    return items;
  }

  Q_FOREACH ( const QgsPostgresSchemaProperty& schema, schemas )
  {
    QgsPGSchemaItem * schemaItem = new QgsPGSchemaItem( this, mName, schema.name, mPath + '/' + schema.name );
    if ( !schema.description.isEmpty() )
    {
      schemaItem->setToolTip( schema.description );
    }
    items.append( schemaItem );
  }
Esempio n. 9
0
void QgsAfsSourceSelect::buildQuery( const QgsOwsConnection &connection, const QModelIndex& index )
{
  if ( !index.isValid() )
  {
    return;
  }
  QModelIndex filterIndex = index.sibling( index.row(), 4 );
  QString id = index.sibling( index.row(), 0 ).data().toString();

  // Query available fields
  QgsDataSourceUri ds = connection.uri();
  QString url = ds.param( "url" ) + "/" + id;
  ds.removeParam( "url" );
  ds.setParam( "url", url );
  QgsAfsProvider provider( ds.uri() );
  if ( !provider.isValid() )
  {
    return;
  }

  //show expression builder
  QgsExpressionBuilderDialog d( 0, filterIndex.data().toString() );

  //add available attributes to expression builder
  QgsExpressionBuilderWidget* w = d.expressionBuilder();
  w->loadFieldNames( provider.fields() );

  if ( d.exec() == QDialog::Accepted )
  {
    QgsDebugMsg( "Expression text = " + w->expressionText() );
    mModelProxy->setData( filterIndex, QVariant( w->expressionText() ) );
  }
}
Esempio n. 10
0
void QgsWCSSourceSelect::populateLayerList()
{

  mLayersTreeWidget->clear();


  QgsDataSourceUri uri = mUri;
  QString cache = QgsNetworkAccessManager::cacheLoadControlName( selectedCacheLoadControl() );
  uri.setParam( QStringLiteral( "cache" ), cache );

  mCapabilities.setUri( uri );

  if ( !mCapabilities.lastError().isEmpty() )
  {
    showError( mCapabilities.lastErrorTitle(), mCapabilities.lastErrorFormat(), mCapabilities.lastError() );
    return;
  }

  QVector<QgsWcsCoverageSummary> coverages;
  if ( !mCapabilities.supportedCoverages( coverages ) )
    return;

  QMap<int, QgsTreeWidgetItem *> items;
  QMap<int, int> coverageParents;
  QMap<int, QStringList> coverageParentNames;
  mCapabilities.coverageParents( coverageParents, coverageParentNames );

  mLayersTreeWidget->setSortingEnabled( true );

  int coverageAndStyleCount = -1;

  for ( QVector<QgsWcsCoverageSummary>::iterator coverage = coverages.begin();
        coverage != coverages.end();
        ++coverage )
  {
    QgsDebugMsg( QString( "coverage orderId = %1 identifier = %2" ).arg( coverage->orderId ).arg( coverage->identifier ) );

    QgsTreeWidgetItem *lItem = createItem( coverage->orderId, QStringList() << coverage->identifier << coverage->title << coverage->abstract, items, coverageAndStyleCount, coverageParents, coverageParentNames );

    lItem->setData( 0, Qt::UserRole + 0, coverage->identifier );
    lItem->setData( 0, Qt::UserRole + 1, "" );

    // Make only leaves selectable
    if ( !coverageParents.keys( coverage->orderId ).isEmpty() )
    {
      lItem->setFlags( Qt::ItemIsEnabled );
    }
  }

  mLayersTreeWidget->sortByColumn( 0, Qt::AscendingOrder );

  // If we got some coverages, let the user add them to the map
  if ( mLayersTreeWidget->topLevelItemCount() == 1 )
  {
    mLayersTreeWidget->expandItem( mLayersTreeWidget->topLevelItem( 0 ) );
  }
}
Esempio n. 11
0
void QgsOSMExportDialog::onOK()
{
  if ( !openDatabase() )
    return;

  QgsOSMDatabase::ExportType type;
  if ( radPoints->isChecked() )
    type = QgsOSMDatabase::Point;
  else if ( radPolylines->isChecked() )
    type = QgsOSMDatabase::Polyline;
  else
    type = QgsOSMDatabase::Polygon;

  buttonBox->setEnabled( false );
  QApplication::setOverrideCursor( Qt::WaitCursor );

  QStringList tagKeys;
  QStringList notNullTagKeys;

  for ( int i = 0; i < mTagsModel->rowCount(); ++i )
  {
    QStandardItem* item = mTagsModel->item( i, 0 );
    if ( item->checkState() == Qt::Checked )
      tagKeys << item->text();

    QStandardItem* item2 = mTagsModel->item( i, 2 );
    if ( item2->checkState() == Qt::Checked )
      notNullTagKeys << item->text();
  }

  bool res = mDatabase->exportSpatiaLite( type, editLayerName->text(), tagKeys, notNullTagKeys );

  // load the layer into canvas if that was requested
  if ( chkLoadWhenFinished->isChecked() )
  {
    QgsDataSourceUri uri;
    uri.setDatabase( editDbFileName->text() );
    uri.setDataSource( QString(), editLayerName->text(), "geometry" );
    QgsVectorLayer* vlayer = new QgsVectorLayer( uri.uri(), editLayerName->text(), "spatialite" );
    if ( vlayer->isValid() )
      QgsMapLayerRegistry::instance()->addMapLayer( vlayer );
  }

  QApplication::restoreOverrideCursor();
  buttonBox->setEnabled( true );

  if ( res )
  {
    QMessageBox::information( this, tr( "OpenStreetMap export" ), tr( "Export has been successful." ) );
  }
  else
  {
    QMessageBox::critical( this, tr( "OpenStreetMap export" ), tr( "Failed to export OSM data:\n%1" ).arg( mDatabase->errorString() ) );
  }

  mDatabase->close();
}
Esempio n. 12
0
bool QgsDb2Provider::setSubsetString( const QString& theSQL, bool )
{
  QString prevWhere = mSqlWhereClause;
  QgsDebugMsg( theSQL );
  mSqlWhereClause = theSQL.trimmed();

  QString sql = QString( "SELECT COUNT(*) FROM " );

  sql += QString( "%1.%2" ).arg( mSchemaName, mTableName );

  if ( !mSqlWhereClause.isEmpty() )
  {
    sql += QString( " WHERE %1" ).arg( mSqlWhereClause );
  }

  if ( !openDatabase( mDatabase ) )
  {
    return false;
  }

  QSqlQuery query = QSqlQuery( mDatabase );
  query.setForwardOnly( true );
  QgsDebugMsg( sql );
  if ( !query.exec( sql ) )
  {
    pushError( query.lastError().text() );
    mSqlWhereClause = prevWhere;
    QgsDebugMsg( query.lastError().text() );
    return false;
  }

  if ( query.isActive() && query.next() )
  {
    mNumberFeatures = query.value( 0 ).toInt();
    QgsDebugMsg( QString( "count: %1" ).arg( mNumberFeatures ) );
  }
  else
  {
    pushError( query.lastError().text() );
    mSqlWhereClause = prevWhere;
    QgsDebugMsg( query.lastError().text() );
    return false;
  }

  QgsDataSourceUri anUri = QgsDataSourceUri( dataSourceUri() );
  anUri.setSql( mSqlWhereClause );

  setDataSourceUri( anUri.uri() );

  mExtent.setMinimal();

  emit dataChanged();

  return true;
}
Esempio n. 13
0
QVector<QgsDataItem*> QgsWMSConnectionItem::createChildren()
{
  QVector<QgsDataItem*> children;

  QgsDataSourceUri uri;
  uri.setEncodedUri( mUri );

  QgsDebugMsg( "mUri = " + mUri );

  QgsWmsSettings wmsSettings;
  if ( !wmsSettings.parseUri( mUri ) )
  {
    children.append( new QgsErrorItem( this, tr( "Failed to parse WMS URI" ), mPath + "/error" ) );
    return children;
  }

  bool res = mCapabilitiesDownload->downloadCapabilities( wmsSettings.baseUrl(), wmsSettings.authorization() );

  if ( !res )
  {
    children.append( new QgsErrorItem( this, tr( "Failed to download capabilities" ), mPath + "/error" ) );
    return children;
  }

  QgsWmsCapabilities caps;
  if ( !caps.parseResponse( mCapabilitiesDownload->response(), wmsSettings.parserSettings() ) )
  {
    children.append( new QgsErrorItem( this, tr( "Failed to parse capabilities" ), mPath + "/error" ) );
    return children;
  }

  // Attention: supportedLayers() gives tree leafs, not top level
  QVector<QgsWmsLayerProperty> layerProperties = caps.supportedLayers();
  if ( !layerProperties.isEmpty() )
  {
    QgsWmsCapabilitiesProperty capabilitiesProperty = caps.capabilitiesProperty();
    const QgsWmsCapabilityProperty& capabilityProperty = capabilitiesProperty.capability;

    // If we have several top-level layers, or if we just have one single top-level layer,
    // then use those top-level layers directly
    if ( capabilityProperty.layers.size() > 1 ||
         ( capabilityProperty.layers.size() == 1 && capabilityProperty.layers[0].layer.size() == 0 ) )
    {
      Q_FOREACH ( const QgsWmsLayerProperty& layerProperty, capabilityProperty.layers )
      {
        // Attention, the name may be empty
        QgsDebugMsg( QString::number( layerProperty.orderId ) + ' ' + layerProperty.name + ' ' + layerProperty.title );
        QString pathName = layerProperty.name.isEmpty() ? QString::number( layerProperty.orderId ) : layerProperty.name;

        QgsWMSLayerItem *layer = new QgsWMSLayerItem( this, layerProperty.title, mPath + '/' + pathName, capabilitiesProperty, uri, layerProperty );

        children << layer;
      }
    }
Esempio n. 14
0
QString QgsAmsSourceSelect::getLayerURI( const QgsOwsConnection &connection,
    const QString &layerTitle, const QString & /*layerName*/,
    const QString &crs,
    const QString & /*filter*/,
    const QgsRectangle & /*bBox*/ ) const
{
  QgsDataSourceUri ds = connection.uri();
  ds.setParam( QStringLiteral( "layer" ), layerTitle );
  ds.setParam( QStringLiteral( "crs" ), crs );
  ds.setParam( QStringLiteral( "format" ), getSelectedImageEncoding() );
  return ds.uri();
}
Esempio n. 15
0
void QgsOwsConnection::addCommonConnectionSettings( QgsDataSourceUri &uri, const QString &key )
{
  QgsSettings settings;

  if ( settings.value( key + QStringLiteral( "/ignoreAxisOrientation" ), false ).toBool() )
  {
    uri.setParam( QStringLiteral( "IgnoreAxisOrientation" ), QStringLiteral( "1" ) );
  }
  if ( settings.value( key + QStringLiteral( "/invertAxisOrientation" ), false ).toBool() )
  {
    uri.setParam( QStringLiteral( "InvertAxisOrientation" ), QStringLiteral( "1" ) );
  }
}
Esempio n. 16
0
QVector<QgsDataItem *> QgsWmsDataItemProvider::createDataItems( const QString &path, QgsDataItem *parentItem )
{
  QVector<QgsDataItem *> items;
  if ( path.startsWith( QLatin1String( "geonode:/" ) ) )
  {
    QString connectionName = path.split( '/' ).last();
    if ( QgsGeoNodeConnectionUtils::connectionList().contains( connectionName ) )
    {
      QgsGeoNodeConnection connection( connectionName );

      QString url = connection.uri().param( QStringLiteral( "url" ) );
      QgsGeoNodeRequest geonodeRequest( url, true );

      const QStringList encodedUris( geonodeRequest.fetchServiceUrlsBlocking( QStringLiteral( "WMS" ) ) );

      if ( !encodedUris.isEmpty() )
      {
        for ( const QString &encodedUri : encodedUris )
        {
          QgsDebugMsg( encodedUri );
          QgsDataSourceUri uri;
          QgsSettings settings;
          QString key( QgsGeoNodeConnectionUtils::pathGeoNodeConnection() + "/" + connectionName );

          QString dpiMode = settings.value( key + "/wms/dpiMode", "all" ).toString();
          uri.setParam( QStringLiteral( "url" ), encodedUri );
          if ( !dpiMode.isEmpty() )
          {
            uri.setParam( QStringLiteral( "dpiMode" ), dpiMode );
          }

          QgsDebugMsg( QStringLiteral( "WMS full uri: '%1'." ).arg( QString( uri.encodedUri() ) ) );

          QgsDataItem *item = new QgsWMSConnectionItem( parentItem, QStringLiteral( "WMS" ), path, uri.encodedUri() );
          if ( item )
          {
            items.append( item );
          }
        }
      }
    }
  }

  return items;
}
Esempio n. 17
0
QgsDataSourceUri QgsOracleConn::connUri( QString theConnName )
{
  QgsDebugMsgLevel( "theConnName = " + theConnName, 3 );

  QSettings settings;

  QString key = "/Oracle/connections/" + theConnName;

  QString database = settings.value( key + "/database" ).toString();

  QString host = settings.value( key + "/host" ).toString();
  QString port = settings.value( key + "/port" ).toString();
  if ( port.length() == 0 )
  {
    port = "1521";
  }

  bool useEstimatedMetadata = settings.value( key + "/estimatedMetadata", false ).toBool();

  QString username;
  QString password;
  if ( settings.value( key + "/saveUsername" ).toString() == "true" )
  {
    username = settings.value( key + "/username" ).toString();
  }

  if ( settings.value( key + "/savePassword" ).toString() == "true" )
  {
    password = settings.value( key + "/password" ).toString();
  }

  QgsDataSourceUri uri;
  uri.setConnection( host, port, database, username, password );
  uri.setUseEstimatedMetadata( useEstimatedMetadata );
  if ( !settings.value( key + "/dboptions" ).toString().isEmpty() )
  {
    uri.setParam( "dboptions", settings.value( key + "/dboptions" ).toString() );
  }
  if ( !settings.value( key + "/dbworkspace" ).toString().isEmpty() )
  {
    uri.setParam( "dbworkspace", settings.value( key + "/dbworkspace" ).toString() );
  }

  return uri;
}
Esempio n. 18
0
bool QgsAuxiliaryStorage::duplicateTable( const QgsDataSourceUri &ogrUri, const QString &newTable )
{
  QgsDataSourceUri uri = parseOgrUri( ogrUri );
  bool rc = false;

  if ( !uri.table().isEmpty() && !uri.database().isEmpty() )
  {
    spatialite_database_unique_ptr database;
    database = openDB( uri.database() );

    if ( database )
    {
      QString sql = QStringLiteral( "CREATE TABLE %1 AS SELECT * FROM %2" ).arg( newTable, uri.table() );
      rc = exec( sql, database.get() );
    }
  }

  return rc;
}
Esempio n. 19
0
bool QgsAuxiliaryStorage::deleteTable( const QgsDataSourceUri &ogrUri )
{
  bool rc = false;
  QgsDataSourceUri uri = parseOgrUri( ogrUri );

  if ( !uri.database().isEmpty() && !uri.table().isEmpty() )
  {
    spatialite_database_unique_ptr database;
    database = openDB( uri.database() );

    if ( database )
    {
      QString sql = QString( "DROP TABLE %1" ).arg( uri.table() );
      rc = exec( sql, database.get() );

      sql = QStringLiteral( "VACUUM" );
      rc = exec( sql, database.get() );
    }
  }

  return rc;
}
Esempio n. 20
0
QVector<QgsDataItem *> QgsXyzTileDataItemProvider::createDataItems( const QString &path, QgsDataItem *parentItem )
{
  QVector<QgsDataItem *> items;
  if ( path.startsWith( QLatin1String( "geonode:/" ) ) )
  {
    QString connectionName = path.split( '/' ).last();
    if ( QgsGeoNodeConnectionUtils::connectionList().contains( connectionName ) )
    {
      QgsGeoNodeConnection connection( connectionName );

      QString url = connection.uri().param( QStringLiteral( "url" ) );
      QgsGeoNodeRequest geonodeRequest( url, true );

      const QgsStringMap urlData( geonodeRequest.fetchServiceUrlDataBlocking( QStringLiteral( "XYZ" ) ) );

      if ( !urlData.isEmpty() )
      {
        auto urlDataIt = urlData.constBegin();
        for ( ; urlDataIt != urlData.constEnd(); ++urlDataIt )
        {
          const QString layerName = urlDataIt.key();
          QgsDebugMsg( urlDataIt.value() );
          QgsDataSourceUri uri;
          uri.setParam( QStringLiteral( "type" ), QStringLiteral( "xyz" ) );
          uri.setParam( QStringLiteral( "url" ), urlDataIt.value() );

          QgsDataItem *item = new QgsXyzLayerItem( parentItem, layerName, path, uri.encodedUri() );
          if ( item )
          {
            items.append( item );
          }
        }
      }
    }
  }

  return items;
}
Esempio n. 21
0
void QgsPgNewConnection::testConnection()
{
  QgsTemporaryCursorOverride cursorOverride( Qt::WaitCursor );

  QgsDataSourceUri uri;
  if ( !txtService->text().isEmpty() )
  {
    uri.setConnection( txtService->text(), txtDatabase->text(),
                       mAuthSettings->username(), mAuthSettings->password(),
                       ( QgsDataSourceUri::SslMode ) cbxSSLmode->currentData().toInt(),
                       mAuthSettings->configId() );
  }
  else
  {
    uri.setConnection( txtHost->text(), txtPort->text(), txtDatabase->text(),
                       mAuthSettings->username(), mAuthSettings->password(),
                       ( QgsDataSourceUri::SslMode ) cbxSSLmode->currentData().toInt(),
                       mAuthSettings->configId() );
  }

  QgsPostgresConn *conn = QgsPostgresConn::connectDb( uri.connectionInfo( false ), true );

  if ( conn )
  {
    // Database successfully opened; we can now issue SQL commands.
    bar->pushMessage( tr( "Connection to %1 was successful." ).arg( txtDatabase->text() ),
                      Qgis::Info );

    // free pg connection resources
    conn->unref();
  }
  else
  {
    bar->pushMessage( tr( "Connection failed - consult message log for details." ),
                      Qgis::Warning );
  }
}
Esempio n. 22
0
QString QgsAfsSourceSelect::getLayerURI( const QgsOwsConnection& connection,
    const QString& layerTitle, const QString& /*layerName*/,
    const QString& crs,
    const QString& filter,
    const QgsRectangle& bBox ) const
{
  QgsDataSourceUri ds = connection.uri();
  QString url = ds.param( "url" ) + "/" + layerTitle;
  ds.removeParam( "url" );
  ds.setParam( "url", url );
  ds.setParam( "filter", filter );
  ds.setParam( "crs", crs );
  if ( !bBox.isEmpty() )
  {
    ds.setParam( "bbox", QString( "%1,%2,%3,%4" ).arg( bBox.xMinimum() ).arg( bBox.yMinimum() ).arg( bBox.xMaximum() ).arg( bBox.yMaximum() ) );
  }
  return ds.uri();
}
Esempio n. 23
0
QString QgsAmsSourceSelect::getLayerURI( const QgsOwsConnection &connection,
    const QString &layerTitle, const QString & /*layerName*/,
    const QString &crs,
    const QString & /*filter*/,
    const QgsRectangle & /*bBox*/, const QString &layerId ) const
{
  QgsDataSourceUri ds = connection.uri();
  QString url = layerTitle;
  QString trimmedUrl = layerId.isEmpty() ? url : url.left( url.length() - 1 - layerId.length() ); // trim '/0' from end of url -- AMS provider requires this omitted
  ds.removeParam( QStringLiteral( "url" ) );
  ds.setParam( QStringLiteral( "url" ), trimmedUrl );
  ds.setParam( QStringLiteral( "layer" ), layerId );
  ds.setParam( QStringLiteral( "crs" ), crs );
  ds.setParam( QStringLiteral( "format" ), getSelectedImageEncoding() );
  return ds.uri();
}
Esempio n. 24
0
void QgsWCSSourceSelect::addButtonClicked()
{
  QgsDataSourceUri uri = mUri;

  QString identifier = selectedIdentifier();
  if ( identifier.isEmpty() ) { return; }

  uri.setParam( QStringLiteral( "identifier" ), identifier );

  // Set crs only if necessary (multiple offered), so that we can decide in the
  // provider if WCS 1.0 with RESPONSE_CRS has to be used.  Not perfect, they can
  // add more CRS in future and URI will be saved in project without any.
  // TODO: consider again, currently if crs in url is used to set WCS coverage CRS,
  //       without that param user is asked for CRS
  //if ( selectedLayersCRSs().size() > 1 )
  //{
  uri.setParam( QStringLiteral( "crs" ), selectedCrs() );
  //}

  QgsDebugMsg( "selectedFormat = " +  selectedFormat() );
  if ( !selectedFormat().isEmpty() )
  {
    uri.setParam( QStringLiteral( "format" ), selectedFormat() );
  }

  QgsDebugMsg( "selectedTime = " +  selectedTime() );
  if ( !selectedTime().isEmpty() )
  {
    uri.setParam( QStringLiteral( "time" ), selectedTime() );
  }

  QString cache;
  QgsDebugMsg( QString( "selectedCacheLoadControl = %1" ).arg( selectedCacheLoadControl() ) );
  cache = QgsNetworkAccessManager::cacheLoadControlName( selectedCacheLoadControl() );
  uri.setParam( QStringLiteral( "cache" ), cache );

  emit addRasterLayer( uri.encodedUri(), identifier, QStringLiteral( "wcs" ) );
}
Esempio n. 25
0
bool QgsPGConnectionItem::handleDrop( const QMimeData *data, const QString &toSchema )
{
  if ( !QgsMimeDataUtils::isUriList( data ) )
    return false;

  // TODO: probably should show a GUI with settings etc
  QgsDataSourceUri uri = QgsPostgresConn::connUri( mName );

  QStringList importResults;
  bool hasError = false;

  QgsMimeDataUtils::UriList lst = QgsMimeDataUtils::decodeUriList( data );
  const auto constLst = lst;
  for ( const QgsMimeDataUtils::Uri &u : constLst )
  {
    // open the source layer
    bool owner;
    QString error;
    QgsVectorLayer *srcLayer = u.vectorLayer( owner, error );
    if ( !srcLayer )
    {
      importResults.append( tr( "%1: %2" ).arg( u.name, error ) );
      hasError = true;
      continue;
    }

    if ( srcLayer->isValid() )
    {
      uri.setDataSource( QString(), u.name,  srcLayer->geometryType() != QgsWkbTypes::NullGeometry ? QStringLiteral( "geom" ) : QString() );
      QgsDebugMsg( "URI " + uri.uri( false ) );

      if ( !toSchema.isNull() )
      {
        uri.setSchema( toSchema );
      }

      QVariantMap options;
      options.insert( QStringLiteral( "forceSinglePartGeometryType" ), true );
      std::unique_ptr< QgsVectorLayerExporterTask > exportTask( new QgsVectorLayerExporterTask( srcLayer, uri.uri( false ), QStringLiteral( "postgres" ), srcLayer->crs(), options, owner ) );

      // when export is successful:
      connect( exportTask.get(), &QgsVectorLayerExporterTask::exportComplete, this, [ = ]()
      {
        // this is gross - TODO - find a way to get access to messageBar from data items
        QMessageBox::information( nullptr, tr( "Import to PostGIS database" ), tr( "Import was successful." ) );
        refreshSchema( toSchema );
      } );

      // when an error occurs:
      connect( exportTask.get(), &QgsVectorLayerExporterTask::errorOccurred, this, [ = ]( int error, const QString & errorMessage )
      {
        if ( error != QgsVectorLayerExporter::ErrUserCanceled )
        {
          QgsMessageOutput *output = QgsMessageOutput::createMessageOutput();
          output->setTitle( tr( "Import to PostGIS database" ) );
          output->setMessage( tr( "Failed to import some layers!\n\n" ) + errorMessage, QgsMessageOutput::MessageText );
          output->showMessage();
        }
        refreshSchema( toSchema );
      } );

      QgsApplication::taskManager()->addTask( exportTask.release() );
    }
    else
    {
      importResults.append( tr( "%1: Not a valid layer!" ).arg( u.name ) );
      hasError = true;
    }
  }

  if ( hasError )
  {
    QgsMessageOutput *output = QgsMessageOutput::createMessageOutput();
    output->setTitle( tr( "Import to PostGIS database" ) );
    output->setMessage( tr( "Failed to import some layers!\n\n" ) + importResults.join( QStringLiteral( "\n" ) ), QgsMessageOutput::MessageText );
    output->showMessage();
  }

  return true;
}
Esempio n. 26
0
void QgsGeomColumnTypeThread::run()
{
  QgsDataSourceUri uri = QgsPostgresConn::connUri( mName );
  mConn = QgsPostgresConnPool::instance()->acquireConnection( uri.connectionInfo( false ) );
  if ( !mConn )
  {
    QgsDebugMsg( "Connection failed - " + uri.connectionInfo( false ) );
    return;
  }

  mStopped = false;

  bool dontResolveType = QgsPostgresConn::dontResolveType( mName );

  emit progressMessage( tr( "Retrieving tables of %1…" ).arg( mName ) );
  QVector<QgsPostgresLayerProperty> layerProperties;
  if ( !mConn->supportedLayers( layerProperties,
                                QgsPostgresConn::geometryColumnsOnly( mName ),
                                QgsPostgresConn::publicSchemaOnly( mName ),
                                mAllowGeometrylessTables ) ||
       layerProperties.isEmpty() )
  {
    QgsPostgresConnPool::instance()->releaseConnection( mConn );
    mConn = nullptr;
    return;
  }

  int i = 0, n = layerProperties.size();
  for ( QVector<QgsPostgresLayerProperty>::iterator it = layerProperties.begin(),
        end = layerProperties.end();
        it != end; ++it )
  {
    QgsPostgresLayerProperty &layerProperty = *it;
    if ( !mStopped )
    {
      emit progress( i++, n );
      emit progressMessage( tr( "Scanning column %1.%2.%3…" )
                            .arg( layerProperty.schemaName,
                                  layerProperty.tableName,
                                  layerProperty.geometryColName ) );

      if ( !layerProperty.geometryColName.isNull() &&
           ( layerProperty.types.value( 0, QgsWkbTypes::Unknown ) == QgsWkbTypes::Unknown ||
             layerProperty.srids.value( 0, std::numeric_limits<int>::min() ) == std::numeric_limits<int>::min() ) )
      {
        if ( dontResolveType )
        {
          QgsDebugMsg( QStringLiteral( "skipping column %1.%2 without type constraint" ).arg( layerProperty.schemaName, layerProperty.tableName ) );
          continue;
        }

        mConn->retrieveLayerTypes( layerProperty, mUseEstimatedMetadata );
      }
    }

    if ( mStopped )
    {
      layerProperty.types.clear();
      layerProperty.srids.clear();
      break;
    }

    // Now tell the layer list dialog box...
    emit setLayerType( layerProperty );
  }

  emit progress( 0, 0 );
  emit progressMessage( mStopped ? tr( "Table retrieval stopped." ) : tr( "Table retrieval finished." ) );

  QgsPostgresConnPool::instance()->releaseConnection( mConn );
  mConn = nullptr;
}
Esempio n. 27
0
QVector<QgsDataItem *> QgsWMSConnectionItem::createChildren()
{
  QVector<QgsDataItem *> children;

  QgsDataSourceUri uri;
  uri.setEncodedUri( mUri );

  QgsDebugMsg( "mUri = " + mUri );

  QgsWmsSettings wmsSettings;
  if ( !wmsSettings.parseUri( mUri ) )
  {
    children.append( new QgsErrorItem( this, tr( "Failed to parse WMS URI" ), mPath + "/error" ) );
    return children;
  }

  bool res = mCapabilitiesDownload->downloadCapabilities( wmsSettings.baseUrl(), wmsSettings.authorization() );

  if ( !res )
  {
    children.append( new QgsErrorItem( this, tr( "Failed to download capabilities" ), mPath + "/error" ) );
    return children;
  }

  QgsWmsCapabilities caps;
  if ( !caps.parseResponse( mCapabilitiesDownload->response(), wmsSettings.parserSettings() ) )
  {
    children.append( new QgsErrorItem( this, tr( "Failed to parse capabilities" ), mPath + "/error" ) );
    return children;
  }

  // Attention: supportedLayers() gives tree leafs, not top level
  QVector<QgsWmsLayerProperty> layerProperties = caps.supportedLayers();
  if ( !layerProperties.isEmpty() )
  {
    QgsWmsCapabilitiesProperty capabilitiesProperty = caps.capabilitiesProperty();
    const QgsWmsCapabilityProperty &capabilityProperty = capabilitiesProperty.capability;

    for ( const QgsWmsLayerProperty &layerProperty : qgis::as_const( capabilityProperty.layers ) )
    {
      // Attention, the name may be empty
      QgsDebugMsg( QString::number( layerProperty.orderId ) + ' ' + layerProperty.name + ' ' + layerProperty.title );
      QString pathName = layerProperty.name.isEmpty() ? QString::number( layerProperty.orderId ) : layerProperty.name;

      QgsWMSLayerItem *layer = new QgsWMSLayerItem( this, layerProperty.title, mPath + '/' + pathName, capabilitiesProperty, uri, layerProperty );

      children << layer;
    }
  }

  QList<QgsWmtsTileLayer> tileLayers = caps.supportedTileLayers();
  if ( !tileLayers.isEmpty() )
  {
    QHash<QString, QgsWmtsTileMatrixSet> tileMatrixSets = caps.supportedTileMatrixSets();

    const auto constTileLayers = tileLayers;
    for ( const QgsWmtsTileLayer &l : constTileLayers )
    {
      QString title = l.title.isEmpty() ? l.identifier : l.title;
      QgsDataItem *layerItem = l.styles.size() == 1 ? this : new QgsDataCollectionItem( this, title, mPath + '/' + l.identifier );
      if ( layerItem != this )
      {
        layerItem->setCapabilities( layerItem->capabilities2() & ~QgsDataItem::Fertile );
        layerItem->setState( QgsDataItem::Populated );
        layerItem->setToolTip( title );
        children << layerItem;
      }

      for ( const QgsWmtsStyle &style : qgis::as_const( l.styles ) )
      {
        QString styleName = style.title.isEmpty() ? style.identifier : style.title;
        if ( layerItem == this )
          styleName = title;  // just one style so no need to display it

        QgsDataItem *styleItem = l.setLinks.size() == 1 ? layerItem : new QgsDataCollectionItem( layerItem, styleName, layerItem->path() + '/' + style.identifier );
        if ( styleItem != layerItem )
        {
          styleItem->setCapabilities( styleItem->capabilities2() & ~QgsDataItem::Fertile );
          styleItem->setState( QgsDataItem::Populated );
          styleItem->setToolTip( styleName );
          if ( layerItem == this )
            children << styleItem;
          else
            layerItem->addChildItem( styleItem );
        }

        for ( const QgsWmtsTileMatrixSetLink &setLink : qgis::as_const( l.setLinks ) )
        {
          QString linkName = setLink.tileMatrixSet;
          if ( styleItem == layerItem )
            linkName = styleName;  // just one link so no need to display it

          QgsDataItem *linkItem = l.formats.size() == 1 ? styleItem : new QgsDataCollectionItem( styleItem, linkName, styleItem->path() + '/' + setLink.tileMatrixSet );
          if ( linkItem != styleItem )
          {
            linkItem->setCapabilities( linkItem->capabilities2() & ~QgsDataItem::Fertile );
            linkItem->setState( QgsDataItem::Populated );
            linkItem->setToolTip( linkName );
            if ( styleItem == this )
              children << linkItem;
            else
              styleItem->addChildItem( linkItem );
          }

          for ( const QString &format : qgis::as_const( l.formats ) )
          {
            QString name = format;
            if ( linkItem == styleItem )
              name = linkName;  // just one format so no need to display it

            QgsDataItem *tileLayerItem = new QgsWMTSLayerItem( linkItem, name, linkItem->path() + '/' + name, uri,
                l.identifier, format, style.identifier, setLink.tileMatrixSet, tileMatrixSets[ setLink.tileMatrixSet ].crs, title );
            tileLayerItem->setToolTip( name );
            if ( linkItem == this )
              children << tileLayerItem;
            else
              linkItem->addChildItem( tileLayerItem );
          }
        }
      }
    }
  }

  return children;
}
Esempio n. 28
0
QgsDataSourceUri QgsGeoPackageConnection::uri()
{
  QgsDataSourceUri uri;
  uri.setEncodedUri( mPath );
  return uri;
}
Esempio n. 29
0
void QgsPGSchemaItem::deleteSchema()
{
  // check if schema contains tables/views
  QgsDataSourceUri uri = QgsPostgresConn::connUri( mConnectionName );
  QgsPostgresConn *conn = QgsPostgresConn::connectDb( uri.connectionInfo( false ), false );
  if ( !conn )
  {
    QMessageBox::warning( nullptr, tr( "Delete Schema" ), tr( "Unable to delete schema." ) );
    return;
  }

  QString sql = QStringLiteral( "SELECT table_name FROM information_schema.tables WHERE table_schema='%1'" ).arg( mName );
  QgsPostgresResult result( conn->PQexec( sql ) );
  if ( result.PQresultStatus() != PGRES_TUPLES_OK )
  {
    QMessageBox::warning( nullptr, tr( "Delete Schema" ), tr( "Unable to delete schema." ) );
    conn->unref();
    return;
  }

  QStringList childObjects;
  int maxListed = 10;
  for ( int idx = 0; idx < result.PQntuples(); idx++ )
  {
    childObjects << result.PQgetvalue( idx, 0 );
    QgsPostgresSchemaProperty schema;
    if ( idx == maxListed - 1 )
      break;
  }

  int count = result.PQntuples();
  if ( count > 0 )
  {
    QString objects = childObjects.join( QStringLiteral( "\n" ) );
    if ( count > maxListed )
    {
      objects += QStringLiteral( "\n[%1 additional objects not listed]" ).arg( count - maxListed );
    }
    if ( QMessageBox::question( nullptr, QObject::tr( "Delete Schema" ),
                                QObject::tr( "Schema '%1' contains objects:\n\n%2\n\nAre you sure you want to delete the schema and all these objects?" ).arg( mName, objects ),
                                QMessageBox::Yes | QMessageBox::No, QMessageBox::No ) != QMessageBox::Yes )
    {
      conn->unref();
      return;
    }
  }
  else
  {
    if ( QMessageBox::question( nullptr, QObject::tr( "Delete Schema" ),
                                QObject::tr( "Are you sure you want to delete the schema '%1'?" ).arg( mName ),
                                QMessageBox::Yes | QMessageBox::No, QMessageBox::No ) != QMessageBox::Yes )
      return;
  }

  QString errCause;
  bool res = ::deleteSchema( mName, uri, errCause, count > 0 );
  if ( !res )
  {
    QMessageBox::warning( nullptr, tr( "Delete Schema" ), errCause );
  }
  else
  {
    QMessageBox::information( nullptr, tr( "Delete Schema" ), tr( "Schema deleted successfully." ) );
    if ( mParent )
      mParent->refresh();
  }
}
Esempio n. 30
0
QVector<QgsDataItem *> QgsPGSchemaItem::createChildren()
{
  QVector<QgsDataItem *>items;

  QgsDataSourceUri uri = QgsPostgresConn::connUri( mConnectionName );
  QgsPostgresConn *conn = QgsPostgresConnPool::instance()->acquireConnection( uri.connectionInfo( false ) );

  if ( !conn )
  {
    items.append( new QgsErrorItem( this, tr( "Connection failed" ), mPath + "/error" ) );
    QgsDebugMsg( "Connection failed - " + uri.connectionInfo( false ) );
    return items;
  }

  QVector<QgsPostgresLayerProperty> layerProperties;
  bool ok = conn->supportedLayers( layerProperties,
                                   QgsPostgresConn::geometryColumnsOnly( mConnectionName ),
                                   QgsPostgresConn::publicSchemaOnly( mConnectionName ),
                                   QgsPostgresConn::allowGeometrylessTables( mConnectionName ), mName );

  if ( !ok )
  {
    items.append( new QgsErrorItem( this, tr( "Failed to get layers" ), mPath + "/error" ) );
    QgsPostgresConnPool::instance()->releaseConnection( conn );
    return items;
  }

  bool dontResolveType = QgsPostgresConn::dontResolveType( mConnectionName );
  const auto constLayerProperties = layerProperties;
  for ( QgsPostgresLayerProperty layerProperty : constLayerProperties )
  {
    if ( layerProperty.schemaName != mName )
      continue;

    if ( !layerProperty.geometryColName.isNull() &&
         ( layerProperty.types.value( 0, QgsWkbTypes::Unknown ) == QgsWkbTypes::Unknown ||
           layerProperty.srids.value( 0, std::numeric_limits<int>::min() ) == std::numeric_limits<int>::min() ) )
    {
      if ( dontResolveType )
      {
        //QgsDebugMsg( QStringLiteral( "skipping column %1.%2 without type constraint" ).arg( layerProperty.schemaName ).arg( layerProperty.tableName ) );
        continue;
      }

      conn->retrieveLayerTypes( layerProperty, true /* useEstimatedMetadata */ );
    }

    for ( int i = 0; i < layerProperty.size(); i++ )
    {
      QgsPGLayerItem *layerItem = createLayer( layerProperty.at( i ) );
      if ( layerItem )
        items.append( layerItem );
    }
  }

  QgsPostgresConnPool::instance()->releaseConnection( conn );

  QgsProjectStorage *storage = QgsApplication::projectStorageRegistry()->projectStorageFromType( "postgresql" );
  if ( QgsPostgresConn::allowProjectsInDatabase( mConnectionName ) && storage )
  {
    QgsPostgresProjectUri postUri;
    postUri.connInfo = uri;
    postUri.schemaName = mName;
    QString schemaUri = QgsPostgresProjectStorage::encodeUri( postUri );
    const QStringList projectNames = storage->listProjects( schemaUri );
    for ( const QString &projectName : projectNames )
    {
      QgsPostgresProjectUri projectUri( postUri );
      projectUri.projectName = projectName;
      items.append( new QgsProjectItem( this, projectName, QgsPostgresProjectStorage::encodeUri( projectUri ) ) );
    }
  }

  return items;
}