/*!
  \brief Create index

  If creating unique index fails, then non-unique index is created instead.

  \param name index name
  \param table table name
  \param column column(s) name
  \param unique TRUE to create unique index
*/
void VFKReaderSQLite::CreateIndex(const char *name, const char *table, const char *column,
                                  bool unique)
{
    CPLString   osSQL;

    if (unique) {
        osSQL.Printf("CREATE UNIQUE INDEX %s ON %s (%s)",
                     name, table, column);
        if (ExecuteSQL(osSQL.c_str()) == OGRERR_NONE) {
            return;
        }
    }

    osSQL.Printf("CREATE INDEX %s ON %s (%s)",
                 name, table, column);
    ExecuteSQL(osSQL.c_str());
}
示例#2
0
void GDALRegister_EPSILON()

{
    if( !GDAL_CHECK_VERSION( "EPSILON driver" ) )
        return;

    if( GDALGetDriverByName( "EPSILON" ) != NULL )
        return;

    GDALDriver *poDriver = new GDALDriver();

    poDriver->SetDescription( "EPSILON" );
    poDriver->SetMetadataItem( GDAL_DCAP_RASTER, "YES" );

    poDriver->SetMetadataItem( GDAL_DMD_LONGNAME, "Epsilon wavelets" );
    poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC, "frmt_epsilon.html" );
    poDriver->SetMetadataItem( GDAL_DMD_CREATIONDATATYPES, "Byte" );

    CPLString osMethods;
    char** papszFBID = eps_get_fb_info(EPS_FB_ID);
    char** papszFBIDIter = papszFBID;
    while(papszFBIDIter && *papszFBIDIter)
    {
        osMethods += "       <Value>";
        osMethods += *papszFBIDIter;
        osMethods += "</Value>\n";
        papszFBIDIter ++;
    }
    eps_free_fb_info(papszFBID);

    CPLString osOptionList;
    osOptionList.Printf(
"<CreationOptionList>"
"   <Option name='TARGET' type='int' description='target size reduction as a percentage of the original (0-100)' default='75'/>"
"   <Option name='FILTER' type='string-select' description='Filter ID' default='daub97lift'>"
"%s"
"   </Option>"
"   <Option name='BLOCKXSIZE' type='int' description='Tile Width. Between 32 and 1024' default='256'/>"
"   <Option name='BLOCKYSIZE' type='int' description='Tile Height. Between 32 and 1024' default='256'/>"
"   <Option name='MODE' type='string-select' default='OTLPF'>"
"       <Value>NORMAL</Value>"
"       <Value>OTLPF</Value>"
"   </Option>"
"   <Option name='RGB_RESAMPLE' type='boolean' description='if RGB must be resampled to 4:2:0' default='YES'/>"
"   <Option name='RASTERLITE_OUTPUT' type='boolean' description='if Rasterlite header and footers must be inserted' default='FALSE'/>"
"</CreationOptionList>", osMethods.c_str()  );

    poDriver->SetMetadataItem( GDAL_DMD_CREATIONOPTIONLIST,
                               osOptionList.c_str() );

    poDriver->pfnOpen = EpsilonDataset::Open;
    poDriver->pfnIdentify = EpsilonDataset::Identify;
    poDriver->pfnCreateCopy = EpsilonDatasetCreateCopy;

    poDriver->SetMetadataItem( GDAL_DCAP_VIRTUALIO, "YES" );

    GetGDALDriverManager()->RegisterDriver( poDriver );
}
OGRErr OGRWritableDWGLayer::CreateFeature( OGRFeature *poFeature )

{
    OGRGeometry *poGeom = poFeature->GetGeometryRef();
    OGRErr eErr;

    if( poGeom == NULL )
        return OGRERR_FAILURE;

/* -------------------------------------------------------------------- */
/*      Keep track of file extents.                                     */
/* -------------------------------------------------------------------- */
    poDS->ExtendExtent( poGeom );

/* -------------------------------------------------------------------- */
/*      Translate geometry.                                             */
/* -------------------------------------------------------------------- */
    OdDbObjectPtr pObject;

    eErr = WriteEntity( poGeom, &pObject );
    if( eErr != OGRERR_NONE )
        return eErr;

/* -------------------------------------------------------------------- */
/*      Append attributes.                                              */
/* -------------------------------------------------------------------- */
    OdResBufPtr xIter = OdResBuf::newRb( 1001 ); 
    xIter->setString( "ACAD" );

    OdResBufPtr temp = xIter;
        
    for( int iField = 0; iField < poFeature->GetFieldCount(); iField++ )
    {
        if( !poFeature->IsFieldSet( iField ) )
            continue;

        CPLString sNameValue;
        const char *pszValue = poFeature->GetFieldAsString( iField );
        
        while( *pszValue == ' ' )
            pszValue++;

        sNameValue.Printf( "%s=%s", 
                           poFeature->GetFieldDefnRef( iField )->GetNameRef(),
                           pszValue );

        OdResBufPtr newRB = OdResBuf::newRb( 1000 );
        newRB->setString( sNameValue.c_str() );

        temp->setNext( newRB );
        temp = temp->next();
    }
    
    if( pObject != (const void *) NULL )
        pObject->setXData( xIter );

    return OGRERR_NONE;
}
示例#4
0
CPLXMLNode *
PamHistogramToXMLTree( double dfMin, double dfMax,
                       int nBuckets, GUIntBig * panHistogram,
                       int bIncludeOutOfRange, int bApprox )

{
    if( nBuckets > (INT_MAX - 10) / 12 )
        return nullptr;

    const size_t nLen = 22 * static_cast<size_t>(nBuckets) + 10;
    char *pszHistCounts = static_cast<char *>( VSIMalloc(nLen) );
    if( pszHistCounts == nullptr )
        return nullptr;

    CPLXMLNode *psXMLHist = CPLCreateXMLNode( nullptr, CXT_Element, "HistItem" );

    CPLString oFmt;
    CPLSetXMLValue( psXMLHist, "HistMin",
                    oFmt.Printf( "%.16g", dfMin ));
    CPLSetXMLValue( psXMLHist, "HistMax",
                    oFmt.Printf( "%.16g", dfMax ));
    CPLSetXMLValue( psXMLHist, "BucketCount",
                    oFmt.Printf( "%d", nBuckets ));
    CPLSetXMLValue( psXMLHist, "IncludeOutOfRange",
                    oFmt.Printf( "%d", bIncludeOutOfRange ));
    CPLSetXMLValue( psXMLHist, "Approximate",
                    oFmt.Printf( "%d", bApprox ));

    size_t iHistOffset = 0;
    pszHistCounts[0] = '\0';
    for( int iBucket = 0; iBucket < nBuckets; iBucket++ )
    {
        snprintf( pszHistCounts + iHistOffset,
                  nLen - iHistOffset,
                  CPL_FRMT_GUIB, panHistogram[iBucket] );
        if( iBucket < nBuckets-1 )
            strcat( pszHistCounts + iHistOffset, "|" );
        iHistOffset += strlen(pszHistCounts+iHistOffset);
    }

    CPLSetXMLValue( psXMLHist, "HistCounts", pszHistCounts );
    CPLFree( pszHistCounts );

    return psXMLHist;
}
示例#5
0
/*!
  \brief VFKReaderSQLite constructor
*/
VFKReaderSQLite::VFKReaderSQLite(const char *pszFilename) : VFKReader(pszFilename)
{
    const char *pszDbNameConf;
    CPLString   pszDbName;
    CPLString   osCommand;
    VSIStatBufL sStatBuf;
    bool        bNewDb;
    
    /* open tmp SQLite DB (re-use DB file if already exists) */
    pszDbNameConf = CPLGetConfigOption("OGR_VFK_DB_NAME", NULL);
    if (pszDbNameConf) {
	pszDbName = pszDbNameConf;
    }
    else {
	pszDbName.Printf("%s.db", m_pszFilename);
    }
    
    if (CSLTestBoolean(CPLGetConfigOption("OGR_VFK_DB_SPATIAL", "YES")))
	m_bSpatial = TRUE;    /* build geometry from DB */
    else
	m_bSpatial = FALSE;   /* store also geometry in DB */
    
    bNewDb = TRUE;
    if (VSIStatL(pszDbName, &sStatBuf ) == 0) {
	if (CSLTestBoolean(CPLGetConfigOption("OGR_VFK_DB_OVERWRITE", "NO"))) {
	    bNewDb = TRUE;     /* overwrite existing DB */
	    VSIUnlink(pszDbName);
	}
	else {
	    bNewDb = FALSE;    /* re-use exising DB */
	}
    }
    else {
      	CPLError(CE_Warning, CPLE_AppDefined, 
                 "SQLite DB not found. Reading VFK data may take some time...");
    }
    CPLDebug("OGR-VFK", "New DB: %s Spatial: %s",
	     bNewDb ? "yes" : "no", m_bSpatial ? "yes" : "no");

    if (SQLITE_OK != sqlite3_open(pszDbName, &m_poDB)) {
        CPLError(CE_Failure, CPLE_AppDefined, 
                 "Creating SQLite DB failed");
    }
    else {
        char* pszErrMsg = NULL;
        sqlite3_exec(m_poDB, "PRAGMA synchronous = OFF", NULL, NULL, &pszErrMsg);
        sqlite3_free(pszErrMsg);
    }
    
    if (bNewDb) {
        /* new DB, create support metadata tables */
        osCommand = "CREATE TABLE 'vfk_blocks' "
	  "(file_name text, table_name text, num_records integer, "
	    "num_geometries integer, table_defn text)";
        ExecuteSQL(osCommand.c_str());
    }
}
示例#6
0
void GTIFFBuildOverviewMetadata( const char *pszResampling,
                                 GDALDataset *poBaseDS,
                                 CPLString &osMetadata )

{
    osMetadata = "<GDALMetadata>";

    if( pszResampling && STARTS_WITH_CI(pszResampling, "AVERAGE_BIT2") )
        osMetadata +=
            "<Item name=\"RESAMPLING\" sample=\"0\">"
            "AVERAGE_BIT2GRAYSCALE</Item>";

    if( poBaseDS->GetMetadataItem( "INTERNAL_MASK_FLAGS_1" ) )
    {
        for( int iBand = 0; iBand < 200; iBand++ )
        {
            CPLString osItem;
            CPLString osName;

            osName.Printf( "INTERNAL_MASK_FLAGS_%d", iBand + 1 );
            if( poBaseDS->GetMetadataItem( osName ) )
            {
                osItem.Printf( "<Item name=\"%s\">%s</Item>",
                               osName.c_str(),
                               poBaseDS->GetMetadataItem( osName ) );
                osMetadata += osItem;
            }
        }
    }

    const char* pszNoDataValues = poBaseDS->GetMetadataItem("NODATA_VALUES");
    if( pszNoDataValues )
    {
        CPLString osItem;
        osItem.Printf( "<Item name=\"NODATA_VALUES\">%s</Item>",
                       pszNoDataValues );
        osMetadata += osItem;
    }

    if( !EQUAL(osMetadata,"<GDALMetadata>") )
        osMetadata += "</GDALMetadata>";
    else
        osMetadata = "";
}
示例#7
0
int OGRDXFWriterLayer::WriteValue( int nCode, int nValue )

{
    CPLString osLinePair;

    osLinePair.Printf( "%3d\n%d\n", nCode, nValue );

    return VSIFWriteL( osLinePair.c_str(),
                       1, osLinePair.size(), fp ) == osLinePair.size();
}
CPLErr RasterliteDataset::CleanOverviews()
{
    CPLString osSQL;
    
    if (nLevel != 0)
        return CE_Failure;
        
    osSQL.Printf("BEGIN");
    OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL);
    
    CPLString osResolutionCond =
        "NOT " + RasterliteGetPixelSizeCond(padfXResolutions[0], padfYResolutions[0]);

    osSQL.Printf("DELETE FROM \"%s_rasters\" WHERE id "
                 "IN(SELECT id FROM \"%s_metadata\" WHERE %s)",
                  osTableName.c_str(), osTableName.c_str(),
                  osResolutionCond.c_str());
    OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL);

    osSQL.Printf("DELETE FROM \"%s_metadata\" WHERE %s",
                  osTableName.c_str(), osResolutionCond.c_str());
    OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL);
    
    OGRLayerH hRasterPyramidsLyr = OGR_DS_GetLayerByName(hDS, "raster_pyramids");
    if (hRasterPyramidsLyr)
    {
        osSQL.Printf("DELETE FROM raster_pyramids WHERE table_prefix = '%s' AND %s",
                      osTableName.c_str(), osResolutionCond.c_str());
        OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL);
    }
    
    osSQL.Printf("COMMIT");
    OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL);
    
    int i;
    for(i=1;i<nResolutions;i++)
        delete papoOverviews[i-1];
    CPLFree(papoOverviews);
    papoOverviews = NULL;
    nResolutions = 1;
    
    return CE_None;
}
示例#9
0
OGRFeature *OGRIDBTableLayer::GetFeature( GIntBig nFeatureId )

{
    if( pszFIDColumn == NULL )
        return OGRIDBLayer::GetFeature( nFeatureId );

    ClearQuery();

    iNextShapeId = nFeatureId;

    poCurr = new ITCursor( *poDS->GetConnection() );

    // Create list of fields
    CPLString osFields;

    if ( poFeatureDefn->GetFieldIndex( pszFIDColumn ) == -1 )
        osFields += pszFIDColumn;

    if ( pszGeomColumn )
    {
        if ( ! osFields.empty() )
            osFields += ",";

        osFields += "st_asbinary(";
        osFields += pszGeomColumn;
        osFields += ") as ";
        osFields += pszGeomColumn;
    }

    for( int i = 0; i < poFeatureDefn->GetFieldCount(); i++ )
    {
        if ( ! osFields.empty() )
            osFields += ",";

        osFields += poFeatureDefn->GetFieldDefn(i)->GetNameRef();
    }

    CPLString sql;

    sql.Printf( "SELECT %s FROM %s WHERE %s = %d",
                osFields.c_str(), poFeatureDefn->GetName(),
                pszFIDColumn, nFeatureId );

    CPLDebug( "OGR_IDB", "ExecuteSQL(%s)", sql.c_str() );
    if( !poCurr->Prepare( sql.c_str() ) ||
        !poCurr->Open(ITCursor::ReadOnly) )
    {
        delete poCurr;
        poCurr = NULL;
        return NULL;
    }

    return GetNextRawFeature();
}
示例#10
0
/*!
  \brief Load geometry (point layers)

  \return number of invalid features
*/
int VFKDataBlockSQLite::LoadGeometryPoint()
{
    if (LoadGeometryFromDB()) /* try to load geometry from DB */
        return 0;

    const bool bSkipInvalid =
        EQUAL(m_pszName, "OB") || EQUAL(m_pszName, "OP") ||
        EQUAL(m_pszName, "OBBP");

    CPLString osSQL;
    osSQL.Printf("SELECT SOURADNICE_Y,SOURADNICE_X,%s,rowid FROM %s",
                 FID_COLUMN, m_pszName);

    VFKReaderSQLite *poReader = (VFKReaderSQLite*) m_poReader;
    sqlite3_stmt *hStmt = poReader->PrepareStatement(osSQL.c_str());

    if (poReader->IsSpatial())
        poReader->ExecuteSQL("BEGIN");

    int nGeometries = 0;
    int nInvalid = 0;
    while(poReader->ExecuteSQL(hStmt) == OGRERR_NONE) {
        /* read values */
        const double x = -1.0 * sqlite3_column_double(hStmt, 0); /* S-JTSK coordinate system expected */
        const double y = -1.0 * sqlite3_column_double(hStmt, 1);
#ifdef DEBUG
        const GIntBig iFID = sqlite3_column_int64(hStmt, 2);
#endif
        const int rowId = sqlite3_column_int(hStmt, 3);

        VFKFeatureSQLite *poFeature = (VFKFeatureSQLite *) GetFeatureByIndex(rowId - 1);
        CPLAssert(NULL != poFeature && poFeature->GetFID() == iFID);

        /* create geometry */
        OGRPoint pt(x, y);
        if (!poFeature->SetGeometry(&pt)) {
            nInvalid++;
            continue;
        }

        /* store also geometry in DB */
        if (poReader->IsSpatial() &&
            SaveGeometryToDB(&pt, rowId) != OGRERR_FAILURE)
            nGeometries++;
    }

    /* update number of geometries in VFK_DB_TABLE table */
    UpdateVfkBlocks(nGeometries);

    if (poReader->IsSpatial())
        poReader->ExecuteSQL("COMMIT");

    return bSkipInvalid ? 0 : nInvalid;
}
示例#11
0
CPLString OGRCARTODBTableLayer::GetSRS_SQL(const char* pszGeomCol)
{
    CPLString osSQL;

    osSQL.Printf("SELECT srid, srtext FROM spatial_ref_sys WHERE srid IN "
                "(SELECT Find_SRID('%s', '%s', '%s'))",
                OGRCARTODBEscapeLiteral(poDS->GetCurrentSchema()).c_str(),
                OGRCARTODBEscapeLiteral(osName).c_str(),
                OGRCARTODBEscapeLiteral(pszGeomCol).c_str());

    return osSQL;
}
示例#12
0
OGRErr OGROCIDataSource::DeleteLayer( int iLayer )

{
/* -------------------------------------------------------------------- */
/*      Blow away our OGR structures related to the layer.  This is     */
/*      pretty dangerous if anything has a reference to this layer!     */
/* -------------------------------------------------------------------- */
    CPLString osLayerName =
        papoLayers[iLayer]->GetLayerDefn()->GetName();

    CPLDebug( "OCI", "DeleteLayer(%s)", osLayerName.c_str() );

    delete papoLayers[iLayer];
    memmove( papoLayers + iLayer, papoLayers + iLayer + 1,
             sizeof(void *) * (nLayers - iLayer - 1) );
    nLayers--;

/* -------------------------------------------------------------------- */
/*      Remove from the database.                                       */
/* -------------------------------------------------------------------- */
    OGROCIStatement oCommand( poSession );
    CPLString       osCommand;
    int             nFailures = 0;

    osCommand.Printf( "DROP TABLE \"%s\"", osLayerName.c_str() );
    if( oCommand.Execute( osCommand ) != CE_None )
        nFailures++;

    osCommand.Printf(
        "DELETE FROM USER_SDO_GEOM_METADATA WHERE TABLE_NAME = UPPER('%s')",
        osLayerName.c_str() );

    if( oCommand.Execute( osCommand ) != CE_None )
        nFailures++;

    if( nFailures == 0 )
        return OGRERR_NONE;
    else
        return OGRERR_FAILURE;
}
示例#13
0
OGRFeature *OGRSQLiteViewLayer::GetFeature( long nFeatureId )

{
    if (HasLayerDefnError())
        return NULL;

/* -------------------------------------------------------------------- */
/*      If we don't have an explicit FID column, just read through      */
/*      the result set iteratively to find our target.                  */
/* -------------------------------------------------------------------- */
    if( pszFIDColumn == NULL )
        return OGRSQLiteLayer::GetFeature( nFeatureId );

/* -------------------------------------------------------------------- */
/*      Setup explicit query statement to fetch the record we want.     */
/* -------------------------------------------------------------------- */
    CPLString osSQL;
    int rc;

    ClearStatement();

    iNextShapeId = nFeatureId;

    osSQL.Printf( "SELECT \"%s\", * FROM '%s' WHERE \"%s\" = %d",
                  OGRSQLiteEscapeName(pszFIDColumn).c_str(),
                  pszEscapedTableName, 
                  OGRSQLiteEscapeName(pszFIDColumn).c_str(),
                  (int) nFeatureId );

    CPLDebug( "OGR_SQLITE", "exec(%s)", osSQL.c_str() );

    rc = sqlite3_prepare( poDS->GetDB(), osSQL, osSQL.size(), 
                          &hStmt, NULL );
    if( rc != SQLITE_OK )
    {
        CPLError( CE_Failure, CPLE_AppDefined, 
                  "In GetFeature(): sqlite3_prepare(%s):\n  %s", 
                  osSQL.c_str(), sqlite3_errmsg(poDS->GetDB()) );

        return NULL;
    }
/* -------------------------------------------------------------------- */
/*      Get the feature if possible.                                    */
/* -------------------------------------------------------------------- */
    OGRFeature *poFeature = NULL;

    poFeature = GetNextRawFeature();

    ResetReading();

    return poFeature;
}
示例#14
0
char *GOA2GetAuthorizationURL(const char *pszScope)

{
    CPLString osScope;
    CPLString osURL;

    osScope.Seize(CPLEscapeString(pszScope, -1, CPLES_URL));
    osURL.Printf( "%s/auth?scope=%s&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code&client_id=%s",
                  GOOGLE_AUTH_URL,
                  osScope.c_str(), 
                  CPLGetConfigOption("GOA2_CLIENT_ID", GDAL_CLIENT_ID));
    return CPLStrdup(osURL);
}
示例#15
0
CPLXMLNode *
PamHistogramToXMLTree( double dfMin, double dfMax,
                       int nBuckets, int * panHistogram,
                       int bIncludeOutOfRange, int bApprox )

{
    char *pszHistCounts = (char *) CPLMalloc(12 * nBuckets + 10);
    int iBucket, iHistOffset;
    CPLXMLNode *psXMLHist;
    CPLString oFmt;

    psXMLHist = CPLCreateXMLNode( NULL, CXT_Element, "HistItem" );

    CPLSetXMLValue( psXMLHist, "HistMin", 
                    oFmt.Printf( "%.16g", dfMin ));
    CPLSetXMLValue( psXMLHist, "HistMax", 
                    oFmt.Printf( "%.16g", dfMax ));
    CPLSetXMLValue( psXMLHist, "BucketCount", 
                    oFmt.Printf( "%d", nBuckets ));
    CPLSetXMLValue( psXMLHist, "IncludeOutOfRange", 
                    oFmt.Printf( "%d", bIncludeOutOfRange ));
    CPLSetXMLValue( psXMLHist, "Approximate", 
                    oFmt.Printf( "%d", bApprox ));

    iHistOffset = 0;
    pszHistCounts[0] = '\0';
    for( iBucket = 0; iBucket < nBuckets; iBucket++ )
    {
        sprintf( pszHistCounts + iHistOffset, "%d", panHistogram[iBucket] );
        if( iBucket < nBuckets-1 )
            strcat( pszHistCounts + iHistOffset, "|" );
        iHistOffset += strlen(pszHistCounts+iHistOffset);
    }
        
    CPLSetXMLValue( psXMLHist, "HistCounts", pszHistCounts );
    CPLFree( pszHistCounts );

    return psXMLHist;
}
示例#16
0
OGRErr OGRIngresTableLayer::PrepareNewStyleGeometry(
    OGRGeometry *poGeom, CPLString &osRetGeomText )

{
	OGRErr eErr = OGRERR_NONE;
    osRetGeomText = "";

    if( poGeom == NULL )
        return OGRERR_FAILURE;

/* -------------------------------------------------------------------- */
/*      Point                                                           */
/* -------------------------------------------------------------------- */
    if( wkbFlatten(poGeom->getGeometryType()) == wkbPoint )
    {
        osRetGeomText.Printf( "POINTFROMWKB( ~V )");
    }
/* -------------------------------------------------------------------- */
/*      Linestring                                                      */
/* -------------------------------------------------------------------- */
    else if( wkbFlatten(poGeom->getGeometryType()) == wkbLineString )
    {
        osRetGeomText.Printf("LINEFROMWKB( ~V )");
    }
/* -------------------------------------------------------------------- */
/*      Polygon                                                         */
/* -------------------------------------------------------------------- */
    else if( wkbFlatten(poGeom->getGeometryType()) == wkbPolygon )
    {
        osRetGeomText.Printf("POLYFROMWKB( ~V )");
    }
/* -------------------------------------------------------------------- */
/*      Multipoint                                                      */
/* -------------------------------------------------------------------- */
    else if( wkbFlatten(poGeom->getGeometryType()) == wkbMultiPoint )
    {
        osRetGeomText.Printf("MPOINTFROMWKB( ~V )");
    }
/* -------------------------------------------------------------------- */
/*      Multilinestring                                                 */
/* -------------------------------------------------------------------- */
    else if( wkbFlatten(poGeom->getGeometryType()) == wkbMultiLineString )
    {
    	osRetGeomText.Printf("MLINEFROMWKB( ~V )");
    }
/* -------------------------------------------------------------------- */
/*      Multipolygon                                                    */
/* -------------------------------------------------------------------- */
    else if( wkbFlatten(poGeom->getGeometryType()) == wkbMultiPolygon )
    {
    	osRetGeomText.Printf("MPOLYFROMWKB( ~V )");
    }
    else
    {
        eErr = OGRERR_FAILURE;
    }

    return eErr;
}
CPLErr RasterliteDataset::CleanOverviewLevel(int nOvrFactor)
{
    CPLString osSQL;
    
    if (nLevel != 0)
        return CE_Failure;
    
/* -------------------------------------------------------------------- */
/*      Find the index of the overview matching the overview factor     */
/* -------------------------------------------------------------------- */
    int iLev;
    for(iLev=1;iLev<nResolutions;iLev++)
    {
        if (fabs(padfXResolutions[0] * nOvrFactor - padfXResolutions[iLev]) < 1e-15 &&
            fabs(padfYResolutions[0] * nOvrFactor - padfYResolutions[iLev]) < 1e-15)
            break;
    }
    
    if (iLev == nResolutions)
        return CE_None;
        
/* -------------------------------------------------------------------- */
/*      Now clean existing overviews at that resolution                 */
/* -------------------------------------------------------------------- */

    osSQL.Printf("BEGIN");
    OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL);
    
    CPLString osResolutionCond;
    osResolutionCond.Printf(
                 "pixel_x_size >= %.15f AND pixel_x_size <= %.15f AND "
                 "pixel_y_size >= %.15f AND pixel_y_size <= %.15f",
                 padfXResolutions[iLev] - 1e-15, padfXResolutions[iLev] + 1e-15,
                 padfYResolutions[iLev] - 1e-15, padfYResolutions[iLev] + 1e-15);
    
    osSQL.Printf("DELETE FROM \"%s_rasters\" WHERE id "
                 "IN(SELECT id FROM \"%s_metadata\" WHERE %s)",
                  osTableName.c_str(), osTableName.c_str(),
                  osResolutionCond.c_str());
    OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL);

    osSQL.Printf("DELETE FROM \"%s_metadata\" WHERE %s",
                  osTableName.c_str(), osResolutionCond.c_str());
    OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL);
    
    OGRLayerH hRasterPyramidsLyr = OGR_DS_GetLayerByName(hDS, "raster_pyramids");
    if (hRasterPyramidsLyr)
    {
        osSQL.Printf("DELETE FROM raster_pyramids WHERE table_prefix = '%s' AND %s",
                      osTableName.c_str(), osResolutionCond.c_str());
        OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL);
    }
    
    osSQL.Printf("COMMIT");
    OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL);
    
    return CE_None;
}
示例#18
0
int CPLGetExecPath( char *pszPathBuf, int nMaxLength )
{
    long nPID = getpid();
    CPLString osExeLink;

    osExeLink.Printf( "/proc/%ld/exe", nPID );
    ssize_t nResultLen = readlink( osExeLink, pszPathBuf, nMaxLength );
    if( nResultLen >= 0 )
        pszPathBuf[nResultLen] = '\0';
    else
        pszPathBuf[0] = '\0';

    return nResultLen > 0;
}
示例#19
0
/*!
  \brief Save geometry to DB (as WKB)

  \param poGeom pointer to OGRGeometry to be saved
  \param iRowId row id to update

  \return OGRERR_NONE on success otherwise OGRERR_FAILURE
*/
OGRErr VFKDataBlockSQLite::SaveGeometryToDB(const OGRGeometry *poGeom, int iRowId)
{
    int        rc, nWKBLen;
    GByte     *pabyWKB;
    CPLString  osSQL;

    sqlite3_stmt *hStmt;

    VFKReaderSQLite  *poReader;

    poReader  = (VFKReaderSQLite*) m_poReader;

    if (poGeom) {
	nWKBLen = poGeom->WkbSize();
	pabyWKB = (GByte *) CPLMalloc(nWKBLen + 1);
	poGeom->exportToWkb(wkbNDR, pabyWKB);
        
	osSQL.Printf("UPDATE %s SET %s = ? WHERE rowid = %d",
		     m_pszName, GEOM_COLUMN, iRowId);
	hStmt = poReader->PrepareStatement(osSQL.c_str());
	
	rc = sqlite3_bind_blob(hStmt, 1, pabyWKB, nWKBLen, CPLFree);
	if (rc != SQLITE_OK) {
	    sqlite3_finalize(hStmt);
	    CPLError(CE_Failure, CPLE_AppDefined, 
		     "Storing geometry in DB failed");
	    return OGRERR_FAILURE;
	}
    }
    else { /* invalid */
	osSQL.Printf("UPDATE %s SET %s = NULL WHERE rowid = %d",
		     m_pszName, GEOM_COLUMN, iRowId);
	hStmt = poReader->PrepareStatement(osSQL.c_str());
    }

    return poReader->ExecuteSQL(hStmt); /* calls sqlite3_finalize() */
}
OGRErr OGRCARTODataSource::DeleteLayer(int iLayer)
{
    if (!bReadWrite)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Operation not available in read-only mode");
        return OGRERR_FAILURE;
    }

    if( iLayer < 0 || iLayer >= nLayers )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "Layer %d not in legal range of 0 to %d.",
                  iLayer, nLayers-1 );
        return OGRERR_FAILURE;
    }

/* -------------------------------------------------------------------- */
/*      Blow away our OGR structures related to the layer.  This is     */
/*      pretty dangerous if anything has a reference to this layer!     */
/* -------------------------------------------------------------------- */
    CPLString osLayerName = papoLayers[iLayer]->GetLayerDefn()->GetName();

    CPLDebug( "CARTO", "DeleteLayer(%s)", osLayerName.c_str() );

    int bDeferredCreation = papoLayers[iLayer]->GetDeferredCreation();
    papoLayers[iLayer]->CancelDeferredCreation();
    delete papoLayers[iLayer];
    memmove( papoLayers + iLayer, papoLayers + iLayer + 1,
             sizeof(void *) * (nLayers - iLayer - 1) );
    nLayers--;

    if (osLayerName.size() == 0)
        return OGRERR_NONE;

    if( !bDeferredCreation )
    {
        CPLString osSQL;
        osSQL.Printf("DROP TABLE %s",
                    OGRCARTOEscapeIdentifier(osLayerName).c_str());

        json_object* poObj = RunSQL(osSQL);
        if( poObj == NULL )
            return OGRERR_FAILURE;
        json_object_put(poObj);
    }

    return OGRERR_NONE;
}
示例#21
0
OGRErr OGRCARTODBTableLayer::CreateField( OGRFieldDefn *poFieldIn,
                                          CPL_UNUSED int bApproxOK )
{
    GetLayerDefn();

    if (!poDS->IsReadWrite())
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Operation not available in read-only mode");
        return OGRERR_FAILURE;
    }

    OGRFieldDefn oField(poFieldIn);
    if( bLaunderColumnNames )
    {
        char* pszName = OGRPGCommonLaunderName(oField.GetNameRef());
        oField.SetName(pszName);
        CPLFree(pszName);
    }

/* -------------------------------------------------------------------- */
/*      Create the new field.                                           */
/* -------------------------------------------------------------------- */

    if( !bDeferedCreation )
    {
        CPLString osSQL;
        osSQL.Printf( "ALTER TABLE %s ADD COLUMN %s %s",
                    OGRCARTODBEscapeIdentifier(osName).c_str(),
                    OGRCARTODBEscapeIdentifier(oField.GetNameRef()).c_str(),
                    OGRPGCommonLayerGetType(oField, FALSE, TRUE).c_str() );
        if( !oField.IsNullable() )
            osSQL += " NOT NULL";
        if( oField.GetDefault() != NULL && !oField.IsDefaultDriverSpecific() )
        {
            osSQL += " DEFAULT ";
            osSQL += OGRPGCommonLayerGetPGDefault(&oField);
        }

        json_object* poObj = poDS->RunSQL(osSQL);
        if( poObj == NULL )
            return OGRERR_FAILURE;
        json_object_put(poObj);
    }

    poFeatureDefn->AddFieldDefn( &oField );

    return OGRERR_NONE;
}
OGRErr OGRPGDumpLayer::CreateField( OGRFieldDefn *poFieldIn,
                                    int bApproxOK )
{
    CPLString           osCommand;
    CPLString           osFieldType;
    OGRFieldDefn        oField( poFieldIn );

    /* -------------------------------------------------------------------- */
    /*      Do we want to "launder" the column names into Postgres          */
    /*      friendly format?                                                */
    /* -------------------------------------------------------------------- */
    if( bLaunderColumnNames )
    {
        char    *pszSafeName = poDS->LaunderName( oField.GetNameRef() );

        oField.SetName( pszSafeName );
        CPLFree( pszSafeName );

        if( EQUAL(oField.GetNameRef(),"oid") )
        {
            CPLError( CE_Warning, CPLE_AppDefined,
                      "Renaming field 'oid' to 'oid_' to avoid conflict with internal oid field." );
            oField.SetName( "oid_" );
        }
    }

    const char* pszOverrideType = CSLFetchNameValue(papszOverrideColumnTypes, oField.GetNameRef());
    if( pszOverrideType != NULL )
        osFieldType = pszOverrideType;
    else
    {
        osFieldType = OGRPGTableLayerGetType(oField, bPreservePrecision, bApproxOK);
        if (osFieldType.size() == 0)
            return OGRERR_FAILURE;
    }

    /* -------------------------------------------------------------------- */
    /*      Create the new field.                                           */
    /* -------------------------------------------------------------------- */
    osCommand.Printf( "ALTER TABLE %s ADD COLUMN %s %s",
                      pszSqlTableName, OGRPGDumpEscapeColumnName(oField.GetNameRef()).c_str(),
                      osFieldType.c_str() );
    if (bCreateTable)
        poDS->Log(osCommand);

    poFeatureDefn->AddFieldDefn( &oField );

    return OGRERR_NONE;
}
示例#23
0
/*!
  \brief Read FID from DB
*/
OGRErr VFKFeatureSQLite::SetFIDFromDB()
{
    CPLString   osSQL;
    
    osSQL.Printf("SELECT %s FROM %s WHERE rowid = %d",
                 FID_COLUMN, m_poDataBlock->GetName(), m_iRowId);
    if (ExecuteSQL(osSQL.c_str()) != OGRERR_NONE)
        return OGRERR_FAILURE;

    m_nFID = sqlite3_column_int(m_hStmt, 0);
  
    FinalizeSQL();
    
    return OGRERR_NONE;
}
示例#24
0
/*!
  \brief Update VFK_DB_TABLE table

  \param nGeometries number of geometries to update
*/
void VFKDataBlockSQLite::UpdateVfkBlocks(int nGeometries) {
    CPLString osSQL;

    VFKReaderSQLite *poReader = (VFKReaderSQLite*) m_poReader;

    /* update number of features in VFK_DB_TABLE table */
    const int nFeatCount = (int)GetFeatureCount();
    if (nFeatCount > 0) {
        osSQL.Printf("UPDATE %s SET num_features = %d WHERE table_name = '%s'",
                     VFK_DB_TABLE, nFeatCount, m_pszName);
        poReader->ExecuteSQL(osSQL.c_str());
    }

    /* update number of geometries in VFK_DB_TABLE table */
    if (nGeometries > 0) {
        CPLDebug("OGR-VFK",
                 "VFKDataBlockSQLite::UpdateVfkBlocks(): name=%s -> "
                 "%d geometries saved to internal DB", m_pszName, nGeometries);

        osSQL.Printf("UPDATE %s SET num_geometries = %d WHERE table_name = '%s'",
                     VFK_DB_TABLE, nGeometries, m_pszName);
        poReader->ExecuteSQL(osSQL.c_str());
    }
}
示例#25
0
CPLErr
GDALDefaultOverviews::BuildOverviewsSubDataset(
    const char * pszPhysicalFile,
    const char * pszResampling,
    int nOverviews, int * panOverviewList,
    int nBands, int * panBandList,
    GDALProgressFunc pfnProgress, void * pProgressData)

{
    if( osOvrFilename.length() == 0 && nOverviews > 0 )
    {
        VSIStatBufL sStatBuf;

        int iSequence = 0;  // Used after for.
        for( iSequence = 0; iSequence < 100; iSequence++ )
        {
            osOvrFilename.Printf( "%s_%d.ovr", pszPhysicalFile, iSequence );
            if( VSIStatExL( osOvrFilename, &sStatBuf,
                            VSI_STAT_EXISTS_FLAG ) != 0 )
            {
                CPLString osAdjustedOvrFilename;

                if( poDS->GetMOFlags() & GMO_PAM_CLASS )
                {
                    osAdjustedOvrFilename.Printf(
                        ":::BASE:::%s_%d.ovr",
                        CPLGetFilename(pszPhysicalFile),
                        iSequence );
                }
                else
                {
                    osAdjustedOvrFilename = osOvrFilename;
                }

                poDS->SetMetadataItem( "OVERVIEW_FILE",
                                       osAdjustedOvrFilename,
                                       "OVERVIEWS" );
                break;
            }
        }

        if( iSequence == 100 )
            osOvrFilename = "";
    }

    return BuildOverviews( NULL, pszResampling, nOverviews, panOverviewList,
                           nBands, panBandList, pfnProgress, pProgressData );
}
示例#26
0
int OGRDXFWriterDS::FixupHANDSEED( VSILFILE *fp )

{
/* -------------------------------------------------------------------- */
/*      What is a good next handle seed?  Scan existing values.         */
/* -------------------------------------------------------------------- */
    unsigned int   nHighestHandle = 0;
    std::set<CPLString>::iterator it;

    for( it = aosUsedEntities.begin(); it != aosUsedEntities.end(); it++ ) 
    {
        unsigned int nHandle;
        if( sscanf( (*it).c_str(), "%x", &nHandle ) == 1 )
        {
            if( nHandle > nHighestHandle )
                nHighestHandle = nHandle;
        }
    }

/* -------------------------------------------------------------------- */
/*      Read the existing handseed value, replace it, and write back.   */
/* -------------------------------------------------------------------- */
    char szWorkBuf[30];
    int  i = 0;

    if( nHANDSEEDOffset == 0 )
        return FALSE;

    VSIFSeekL( fp, nHANDSEEDOffset, SEEK_SET );
    VSIFReadL( szWorkBuf, 1, sizeof(szWorkBuf), fp );
    
    while( szWorkBuf[i] != '\n' )
        i++;

    i++;
    if( szWorkBuf[i] == '\r' )
        i++;
    
    CPLString osNewValue;

    osNewValue.Printf( "%08X", nHighestHandle + 1 );
    strncpy( szWorkBuf + i, osNewValue.c_str(), osNewValue.size() );

    VSIFSeekL( fp, nHANDSEEDOffset, SEEK_SET );
    VSIFWriteL( szWorkBuf, 1, sizeof(szWorkBuf), fp );

    return TRUE;
}
示例#27
0
文件: Tif_band.cpp 项目: zjucsxxd/mrf
// Returns a string in /vsimem/ + prefix + count that doesn't exist when this function gets called
// It is not completely safe, open the result as soon as possible
CPLString uniq_memfname(const char *prefix)
{

// Define MRF_LOCAL_TMP to use local files instead of RAM
// #define MRF_LOCAL_TMP
#if defined(MRF_LOCAL_TMP)
    return CPLGenerateTempFilename(prefix);
#else
    CPLString fname;
    VSIStatBufL statb;
    static unsigned int cnt=0;
    do fname.Printf("/vsimem/%s_%08x",prefix, cnt++);
    while (!VSIStatL(fname, &statb));
    return fname;
#endif
}
示例#28
0
OGRErr OGRCARTODBTableLayer::DeleteFeature( GIntBig nFID )

{

    if( bDeferedCreation && RunDeferedCreationIfNecessary() != OGRERR_NONE )
        return OGRERR_FAILURE;
    FlushDeferedInsert();

    GetLayerDefn();

    if (!poDS->IsReadWrite())
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Operation not available in read-only mode");
        return OGRERR_FAILURE;
    }
    
    if( osFIDColName.size() == 0 )
        return OGRERR_FAILURE;
    
    CPLString osSQL;
    osSQL.Printf("DELETE FROM %s WHERE %s = " CPL_FRMT_GIB,
                    OGRCARTODBEscapeIdentifier(osName).c_str(),
                    OGRCARTODBEscapeIdentifier(osFIDColName).c_str(),
                    nFID);

    OGRErr eRet = OGRERR_FAILURE;
    json_object* poObj = poDS->RunSQL(osSQL);
    if( poObj != NULL )
    {
        json_object* poTotalRows = json_object_object_get(poObj, "total_rows");
        if( poTotalRows != NULL && json_object_get_type(poTotalRows) == json_type_int )
        {
            int nTotalRows = json_object_get_int(poTotalRows);
            if( nTotalRows > 0 )
            {
                eRet = OGRERR_NONE;
            }
            else
                eRet = OGRERR_NON_EXISTING_FEATURE;
        }
        json_object_put(poObj);
    }

    return eRet;
}
示例#29
0
OGRSpatialReference *OGRIDBTableLayer::GetSpatialRef()

{
    if( nSRSId == -2 )
    {
        nSRSId = -1;

        if ( ! pszGeomColumn )
            return NULL;

        CPLString osCmd;
        osCmd.Printf( " SELECT FIRST 1 srid, trim(srtext)"
                      " FROM spatial_ref_sys, %s"
                      " WHERE srid = ST_Srid(%s) ",
                      poFeatureDefn->GetName(), pszGeomColumn );

        ITCursor oSridCur( *poDS->GetConnection() );

        if( oSridCur.Prepare( osCmd.c_str() )&&
            oSridCur.Open( ITCursor::ReadOnly ) )
        {
            ITRow * row = static_cast<ITRow *>( oSridCur.NextRow() );
            if ( row && ! row->IsNull() )
            {
                nSRSId = atoi(row->Column(0)->Printable());
                const char * wkt = row->Column(1)->Printable();

                if ( poSRS )
                {
                    // Hmm ... it should be null
                    delete poSRS;
                }
                poSRS = new OGRSpatialReference();
                if ( poSRS->importFromWkt( (char **)&wkt ) != OGRERR_NONE )
                {
                    CPLError( CE_Warning, CPLE_AppDefined,
                              "Error parse srs wkt: %s", wkt );
                    delete poSRS;
                    poSRS = NULL;
                }
            }
        }
    }

    return OGRIDBLayer::GetSpatialRef();
}
示例#30
0
json_object* OGRCARTODBTableLayer::FetchNewFeatures(GIntBig iNext)
{
    if( osFIDColName.size() > 0 )
    {
        CPLString osSQL;
        osSQL.Printf("%s WHERE %s%s >= " CPL_FRMT_GIB " ORDER BY %s ASC LIMIT %d",
                     osSELECTWithoutWHERE.c_str(),
                     ( osWHERE.size() ) ? CPLSPrintf("%s AND ", osWHERE.c_str()) : "",
                     OGRCARTODBEscapeIdentifier(osFIDColName).c_str(),
                     iNext,
                     OGRCARTODBEscapeIdentifier(osFIDColName).c_str(),
                     GetFeaturesToFetch());
        return poDS->RunSQL(osSQL);
    }
    else
        return OGRCARTODBLayer::FetchNewFeatures(iNext);
}