void QgsOgrFeatureIterator::getFeatureAttribute( OGRFeatureH ogrFet, QgsFeature & f, int attindex ) { OGRFieldDefnH fldDef = OGR_F_GetFieldDefnRef( ogrFet, attindex ); if ( ! fldDef ) { QgsDebugMsg( "ogrFet->GetFieldDefnRef(attindex) returns NULL" ); return; } QVariant value; if ( OGR_F_IsFieldSet( ogrFet, attindex ) ) { switch ( P->mAttributeFields[attindex].type() ) { case QVariant::String: value = QVariant( P->mEncoding->toUnicode( OGR_F_GetFieldAsString( ogrFet, attindex ) ) ); break; case QVariant::Int: value = QVariant( OGR_F_GetFieldAsInteger( ogrFet, attindex ) ); break; case QVariant::Double: value = QVariant( OGR_F_GetFieldAsDouble( ogrFet, attindex ) ); break; //case QVariant::DateTime: value = QVariant(QDateTime::fromString(str)); break; default: assert( NULL && "unsupported field type" ); } } else { value = QVariant( QString::null ); } f.setAttribute( attindex, value ); }
void GDALWPrintRecords(GDALWConnection conn) { char * wkt; int i; OGRFeatureH feature; OGRGeometryH geometry; OGRFeatureDefnH featureDefn; featureDefn = OGR_L_GetLayerDefn(conn.layer); OGR_L_ResetReading(conn.layer); while( (feature = OGR_L_GetNextFeature(conn.layer)) != NULL ) { for(i = 0; i < OGR_FD_GetFieldCount(featureDefn); i++ ) { OGRFieldDefnH hFieldDefn = OGR_FD_GetFieldDefn( featureDefn, i ); if( OGR_Fld_GetType(hFieldDefn) == OFTInteger ) printf( "%d,", OGR_F_GetFieldAsInteger( feature, i ) ); else if( OGR_Fld_GetType(hFieldDefn) == OFTReal ) printf( "%.3f,", OGR_F_GetFieldAsDouble( feature, i) ); else printf( "%s,", OGR_F_GetFieldAsString( feature, i) ); } geometry = OGR_F_GetGeometryRef(feature); OGR_G_ExportToWkt(geometry, &wkt); printf("%s", wkt); printf("\n"); CPLFree(wkt); OGR_F_Destroy(feature); } }
void QgsOgrFeatureIterator::getFeatureAttribute( OGRFeatureH ogrFet, QgsFeature & f, int attindex ) { OGRFieldDefnH fldDef = OGR_F_GetFieldDefnRef( ogrFet, attindex ); if ( ! fldDef ) { QgsDebugMsg( "ogrFet->GetFieldDefnRef(attindex) returns NULL" ); return; } QVariant value; if ( OGR_F_IsFieldSet( ogrFet, attindex ) ) { switch ( mSource->mFields.at( attindex ).type() ) { case QVariant::String: value = QVariant( mSource->mEncoding->toUnicode( OGR_F_GetFieldAsString( ogrFet, attindex ) ) ); break; case QVariant::Int: value = QVariant( OGR_F_GetFieldAsInteger( ogrFet, attindex ) ); break; #if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM >= 2000000 case QVariant::LongLong: value = QVariant( OGR_F_GetFieldAsInteger64( ogrFet, attindex ) ); break; #endif case QVariant::Double: value = QVariant( OGR_F_GetFieldAsDouble( ogrFet, attindex ) ); break; case QVariant::Date: case QVariant::DateTime: { int year, month, day, hour, minute, second, tzf; OGR_F_GetFieldAsDateTime( ogrFet, attindex, &year, &month, &day, &hour, &minute, &second, &tzf ); if ( mSource->mFields.at( attindex ).type() == QVariant::Date ) value = QDate( year, month, day ); else value = QDateTime( QDate( year, month, day ), QTime( hour, minute, second ) ); } break; default: assert( 0 && "unsupported field type" ); } } else { value = QVariant( QString::null ); } f.setAttribute( attindex, value ); }
/* {ok, DataSource} = lgeo_ogr:open("test/polygon.shp"), {ok, Layer} = lgeo_ogr:ds_get_layer(DataSource, 0), {ok, Feature} = lgeo_ogr:l_get_feature(Layer, 0), {ok, Fields} = lgeo_ogr:f_get_fields(Feature). {1,"first"} */ static ERL_NIF_TERM f_get_fields(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { EnvFeature_t **feature; ERL_NIF_TERM eterm; if (argc != 1) { return enif_make_badarg(env); } if(!enif_get_resource(env, argv[0], OGR_F_RESOURCE, (void**)&feature)) { return enif_make_badarg(env); } OGRFeatureDefnH feature_defn = OGR_F_GetDefnRef((**feature).obj); int count = OGR_FD_GetFieldCount(feature_defn); ERL_NIF_TERM *arr = (ERL_NIF_TERM *) malloc(sizeof(ERL_NIF_TERM)*count); int index; for(index=0; index<count; index++) { OGRFieldDefnH field_defn = OGR_FD_GetFieldDefn(feature_defn, index); if(OGR_Fld_GetType(field_defn) == OFTInteger) { arr[index] = enif_make_int(env, OGR_F_GetFieldAsInteger((**feature).obj, index)); } else if(OGR_Fld_GetType(field_defn) == OFTReal) { arr[index] = enif_make_double(env, OGR_F_GetFieldAsDouble((**feature).obj, index)); } else if(OGR_Fld_GetType(field_defn) == OFTString) { arr[index] = enif_make_string(env, OGR_F_GetFieldAsString((**feature).obj, index), ERL_NIF_LATIN1); } else { arr[index] = enif_make_string(env, OGR_F_GetFieldAsString((**feature).obj, index), ERL_NIF_LATIN1); } } eterm = enif_make_tuple_from_array(env, arr, index); free(arr); return enif_make_tuple2(env, enif_make_atom(env, "ok"), eterm); }
/* What we need: specific condition, is walk in , tactic, distance elevation * minsteps, maxsteps, waterdrops, pump/roll, fwa id. */ int main( int argc, char *argv[] ) { GDALAllRegister(); OGRRegisterAll(); const char *pszInputfile = NULL; const char *pszOutputfile = NULL; const char *pszOutputFormat = "CSV"; char **papszCreateOptions = NULL; const char *pszDataPath = NULL; const char *pszFpuCode = NULL; int nLimit = 0; int bProgress = TRUE; double dfMaxX, dfMinX, dfMaxY, dfMinY; int bLimit = FALSE; double dfBuffer = 0.0; int i = 1; while( i < argc ) { if( EQUAL( argv[i], "-p" ) ) { bProgress = TRUE; } else if( EQUAL( argv[i], "-d" ) ) { pszDataPath = argv[++i]; } else if( EQUAL( argv[i], "-of" ) ) { pszOutputFormat = argv[++i]; } else if( EQUAL( argv[i], "-co" ) ) { papszCreateOptions = CSLAddString( papszCreateOptions, argv[++i] ); } else if( EQUAL( argv[i], "-sl" ) ) { dfMaxX = atof(argv[++i]); dfMinX = atof(argv[++i]); dfMaxY = atof(argv[++i]); dfMinY = atof(argv[++i]); bLimit = TRUE; } else if( EQUAL( argv[i], "-fpu" ) ) { pszFpuCode = argv[++i]; } else if( EQUAL( argv[i], "-b" ) ) { dfBuffer = atof( argv[++i] ); } else if( EQUAL( argv[i], "-l" ) ) { nLimit = atoi( argv[++i] ); } else if( EQUAL( argv[i], "-h" ) ) { Usage(); } else if( pszInputfile == NULL ) { pszInputfile = argv[i]; } else if( pszOutputfile == NULL ) { pszOutputfile = argv[i]; } else { Usage(); } i++; } if( pszInputfile == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "No input file provided\n"); Usage(); } if( pszOutputfile == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Invalid output selected, " "use database and table or output file\n" ); Usage(); } pszDataPath = CPLGetConfigOption( "OMFFR_DATA", NULL ); OGRDataSourceH hInputDS = OGROpen( pszInputfile, FALSE, NULL ); if( hInputDS == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Cannot open input file\n" ); Usage(); } int year, num, day; const char *dow, *disc_time; int bi; double ros; int fuel; const char *spec_cond; int slope, walkin; const char *tactic; double dist; int elev; double ltow; int minsteps = 250; int maxsteps = 10000; const char *sunrise, *sunset; int waterdrops, pumproll; char *abyFwa; const char *fwaid; double lon, lat; OGRLayerH hInputLayer; hInputLayer = OGR_DS_GetLayerByName( hInputDS, CPLGetBasename( pszInputfile ) ); OGRFeatureDefnH hInputFeatureDefn; OGRFeatureH hInputFeature; OGRGeometryH hGeometry; hInputFeatureDefn = OGR_L_GetLayerDefn( hInputLayer ); const char *pszTmpFilename =CPLFormFilename( pszDataPath, "irs/FWA", ".dat" ); std::vector<CFWA>fwas = LoadFwas( pszTmpFilename ); int nFeatures = OGR_L_GetFeatureCount( hInputLayer, TRUE ); FILE *fout = fopen( pszOutputfile, "w" ); //CFWA *fwa; Random random; char pszDb[8192]; sprintf( pszDb, "%s/omffr.sqlite", pszDataPath ); IRSDataAccess *poDA = IRSDataAccess::Create( 0, pszDb ); int rc; sqlite3 *db; rc = sqlite3_open_v2( pszDb, &db, SQLITE_OPEN_READONLY, NULL ); rc = sqlite3_enable_load_extension( db, 1 ); rc = sqlite3_load_extension( db, "/usr/local/lib/libspatialite.so", 0, NULL ); sqlite3_stmt *stmt; rc = sqlite3_prepare_v2( db, "SELECT * from fwa join fwa_bndry USING(fwa_gis_id) " \ "WHERE ST_Contains(fwa_bndry.geometry, MakePoint(?, ?, 4269))", -1, &stmt, NULL ); if(rc) { CPLError( CE_Failure, CPLE_AppDefined, "Could not open DB"); } GDALTermProgress( 0.0, NULL, NULL ); OGR_L_ResetReading( hInputLayer ); const char *pszFwaName; int nDone = 0; while( ( hInputFeature = OGR_L_GetNextFeature( hInputLayer ) ) != NULL ) { /* fwaid = OGR_F_GetFieldAsString( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "fwa_name" ) ); abyFwa = CPLStrdup( fwaid ); LaunderFwaName( abyFwa ); fwa = FindFwa( fwas, abyFwa ); if( fwa == NULL ) { CPLError( CE_Warning, CPLE_FileIO, "Could not load fwa (%s)from file, missing\n", abyFwa ); continue; } */ /* Get fwa by point */ hGeometry = OGR_F_GetGeometryRef( hInputFeature ); /* Try to handle non-geometry types (csv) */ if( hGeometry != NULL ) { lat = OGR_G_GetY( hGeometry, 0 ); lon = OGR_G_GetX( hGeometry, 0 ); } else { lat = OGR_F_GetFieldAsDouble( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "Y") ); lon = OGR_F_GetFieldAsDouble( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "X") ); } std::string oFwaName = poDA->PointQuery( "fwa_bndry", "fwa_lndr_name", lon, lat ); rc = sqlite3_bind_double( stmt, 1, lon ); rc = sqlite3_bind_double( stmt, 2, lat ); //sqlite3_bind_text( stmt, 1, oFwaName.c_str(), -1, SQLITE_TRANSIENT); rc = sqlite3_step( stmt ); if( rc != SQLITE_ROW && rc != SQLITE_DONE ) { CPLError( CE_Warning, CPLE_FileIO, "Could not load fwa (%s)from file, missing\n", oFwaName.c_str() ); sqlite3_reset(stmt); continue; } int nFwaWalkIn, nFwaHead, nFwaTail, nFwaPara, nFwaAttackD; int nFwaWaterDrop, nFwaPumpRoll; nFwaWalkIn = sqlite3_column_int( stmt, 4 ); nFwaHead = sqlite3_column_int( stmt, 6 ); nFwaTail = sqlite3_column_int( stmt, 7 ); nFwaPara = sqlite3_column_int( stmt, 8 ); nFwaAttackD = sqlite3_column_int( stmt, 9 ); nFwaWaterDrop = sqlite3_column_int( stmt, 10 ); nFwaPumpRoll = sqlite3_column_int( stmt, 5 ); year = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "year" ) ); num = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "fire_num" ) ); day = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "day" ) ); dow = OGR_F_GetFieldAsString( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "week_day" ) ); disc_time = OGR_F_GetFieldAsString( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "disc_time" ) ); bi = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "bi" ) ); ros = OGR_F_GetFieldAsDouble( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "ros" ) ); fuel = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "fuel" ) ); spec_cond = OGR_F_GetFieldAsString( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "spec_cond" ) ); slope = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "slope_perc" ) ); //if( random.rand3() * 100 > fwa->GetWalkInPct() ) if( random.rand3() * 100 > nFwaWalkIn ) walkin = 0; else walkin = 1; //if( fwa->GetHead() == 100 ) if( nFwaHead == 100 ) tactic = "HEAD\0"; //else if( fwa->GetTail() == 100 ) else if( nFwaTail == 100 ) tactic = "TAIL\0"; //else if( fwa->GetParallel() == 100 ) else if( nFwaTail == 100 ) tactic = "PARALLEL\0"; else { int r = (int)(random.rand3() * 100 ); int total = 0; if( r < nFwaHead ) tactic = "HEAD\0"; else if( r < nFwaTail + nFwaTail ) tactic = "TAIL\0"; else tactic = "PARALLEL\0"; } //dist = fwa->GetAttackDist(); dist = nFwaAttackD; elev = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "elev" ) ); ltow = OGR_F_GetFieldAsDouble( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "ratio" ) ); sunrise = OGR_F_GetFieldAsString( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "sunrise" ) ); sunset = OGR_F_GetFieldAsString( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "sunset" ) ); //if( fwa->GetWaterDrops() ) if( nFwaWaterDrop ) waterdrops = TRUE; else waterdrops = FALSE; //if( fwa->GetPumpnRoll() ) if( nFwaPumpRoll ) pumproll = TRUE; else pumproll = FALSE; fprintf( fout, "%d %d %d %s %s " "%d %lf %d %s %d " "%d %s %lf %d %lf " "%d %d %s %s %d " "%d %s %lf %lf\n", year, num, day, dow, disc_time, bi, ros, fuel, spec_cond, slope, walkin, tactic, dist, elev, ltow, minsteps, maxsteps, sunrise, sunset, waterdrops, pumproll, /* abyFwa */ oFwaName.c_str(), lat, lon ); sqlite3_reset(stmt); nDone++; GDALTermProgress( (float)nDone / (float)nFeatures, NULL, NULL ); } GDALTermProgress( 1.0, NULL, NULL ); fclose( fout ); OGR_DS_Destroy( hInputDS ); return 0; }
QVariant QgsOgrUtils::getOgrFeatureAttribute( OGRFeatureH ogrFet, const QgsFields& fields, int attIndex, QTextCodec* encoding , bool* ok ) { if ( !ogrFet || attIndex < 0 || attIndex >= fields.count() ) { if ( ok ) *ok = false; return QVariant(); } OGRFieldDefnH fldDef = OGR_F_GetFieldDefnRef( ogrFet, attIndex ); if ( ! fldDef ) { if ( ok ) *ok = false; QgsDebugMsg( "ogrFet->GetFieldDefnRef(attindex) returns NULL" ); return QVariant(); } QVariant value; if ( ok ) *ok = true; if ( OGR_F_IsFieldSet( ogrFet, attIndex ) ) { switch ( fields.at( attIndex ).type() ) { case QVariant::String: { if ( encoding ) value = QVariant( encoding->toUnicode( OGR_F_GetFieldAsString( ogrFet, attIndex ) ) ); else value = QVariant( QString::fromUtf8( OGR_F_GetFieldAsString( ogrFet, attIndex ) ) ); break; } case QVariant::Int: value = QVariant( OGR_F_GetFieldAsInteger( ogrFet, attIndex ) ); break; #if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM >= 2000000 case QVariant::LongLong: value = QVariant( OGR_F_GetFieldAsInteger64( ogrFet, attIndex ) ); break; #endif case QVariant::Double: value = QVariant( OGR_F_GetFieldAsDouble( ogrFet, attIndex ) ); break; case QVariant::Date: case QVariant::DateTime: case QVariant::Time: { int year, month, day, hour, minute, second, tzf; OGR_F_GetFieldAsDateTime( ogrFet, attIndex, &year, &month, &day, &hour, &minute, &second, &tzf ); if ( fields.at( attIndex ).type() == QVariant::Date ) value = QDate( year, month, day ); else if ( fields.at( attIndex ).type() == QVariant::Time ) value = QTime( hour, minute, second ); else value = QDateTime( QDate( year, month, day ), QTime( hour, minute, second ) ); } break; default: Q_ASSERT_X( false, "QgsOgrUtils::getOgrFeatureAttribute", "unsupported field type" ); if ( ok ) *ok = false; } } else { value = QVariant( QString::null ); } return value; }
static CPLErr ProcessLayer( OGRLayerH hSrcLayer, int bSRSIsSet, GDALDatasetH hDstDS, std::vector<int> anBandList, const std::vector<double> &adfBurnValues, int b3D, int bInverse, const char *pszBurnAttribute, char **papszRasterizeOptions, GDALProgressFunc pfnProgress, void* pProgressData ) { /* -------------------------------------------------------------------- */ /* Checkout that SRS are the same. */ /* If -a_srs is specified, skip the test */ /* -------------------------------------------------------------------- */ OGRCoordinateTransformationH hCT = NULL; if (!bSRSIsSet) { OGRSpatialReferenceH hDstSRS = NULL; if( GDALGetProjectionRef( hDstDS ) != NULL ) { char *pszProjection; pszProjection = (char *) GDALGetProjectionRef( hDstDS ); hDstSRS = OSRNewSpatialReference(NULL); if( OSRImportFromWkt( hDstSRS, &pszProjection ) != OGRERR_NONE ) { OSRDestroySpatialReference(hDstSRS); hDstSRS = NULL; } } OGRSpatialReferenceH hSrcSRS = OGR_L_GetSpatialRef(hSrcLayer); if( hDstSRS != NULL && hSrcSRS != NULL ) { if( OSRIsSame(hSrcSRS, hDstSRS) == FALSE ) { hCT = OCTNewCoordinateTransformation(hSrcSRS, hDstSRS); if( hCT == NULL ) { CPLError(CE_Warning, CPLE_AppDefined, "The output raster dataset and the input vector layer do not have the same SRS.\n" "And reprojection of input data did not work. Results might be incorrect."); } } } else if( hDstSRS != NULL && hSrcSRS == NULL ) { CPLError(CE_Warning, CPLE_AppDefined, "The output raster dataset has a SRS, but the input vector layer SRS is unknown.\n" "Ensure input vector has the same SRS, otherwise results might be incorrect."); } else if( hDstSRS == NULL && hSrcSRS != NULL ) { CPLError(CE_Warning, CPLE_AppDefined, "The input vector layer has a SRS, but the output raster dataset SRS is unknown.\n" "Ensure output raster dataset has the same SRS, otherwise results might be incorrect."); } if( hDstSRS != NULL ) { OSRDestroySpatialReference(hDstSRS); } } /* -------------------------------------------------------------------- */ /* Get field index, and check. */ /* -------------------------------------------------------------------- */ int iBurnField = -1; if( pszBurnAttribute ) { iBurnField = OGR_FD_GetFieldIndex( OGR_L_GetLayerDefn( hSrcLayer ), pszBurnAttribute ); if( iBurnField == -1 ) { CPLError(CE_Failure, CPLE_AppDefined, "Failed to find field %s on layer %s, skipping.", pszBurnAttribute, OGR_FD_GetName( OGR_L_GetLayerDefn( hSrcLayer ) ) ); if( hCT != NULL ) OCTDestroyCoordinateTransformation(hCT); return CE_Failure; } } /* -------------------------------------------------------------------- */ /* Collect the geometries from this layer, and build list of */ /* burn values. */ /* -------------------------------------------------------------------- */ OGRFeatureH hFeat; std::vector<OGRGeometryH> ahGeometries; std::vector<double> adfFullBurnValues; OGR_L_ResetReading( hSrcLayer ); while( (hFeat = OGR_L_GetNextFeature( hSrcLayer )) != NULL ) { OGRGeometryH hGeom; if( OGR_F_GetGeometryRef( hFeat ) == NULL ) { OGR_F_Destroy( hFeat ); continue; } hGeom = OGR_G_Clone( OGR_F_GetGeometryRef( hFeat ) ); if( hCT != NULL ) { if( OGR_G_Transform(hGeom, hCT) != OGRERR_NONE ) { OGR_F_Destroy( hFeat ); OGR_G_DestroyGeometry(hGeom); continue; } } ahGeometries.push_back( hGeom ); for( unsigned int iBand = 0; iBand < anBandList.size(); iBand++ ) { if( adfBurnValues.size() > 0 ) adfFullBurnValues.push_back( adfBurnValues[MIN(iBand,adfBurnValues.size()-1)] ); else if( pszBurnAttribute ) { adfFullBurnValues.push_back( OGR_F_GetFieldAsDouble( hFeat, iBurnField ) ); } /* I have made the 3D option exclusive to other options since it can be used to modify the value from "-burn value" or "-a attribute_name" */ if( b3D ) { // TODO: get geometry "z" value /* Points and Lines will have their "z" values collected at the point and line levels respectively. However filled polygons (GDALdllImageFilledPolygon) can use some help by getting their "z" values here. */ adfFullBurnValues.push_back( 0.0 ); } } OGR_F_Destroy( hFeat ); } if( hCT != NULL ) OCTDestroyCoordinateTransformation(hCT); /* -------------------------------------------------------------------- */ /* If we are in inverse mode, we add one extra ring around the */ /* whole dataset to invert the concept of insideness and then */ /* merge everything into one geometry collection. */ /* -------------------------------------------------------------------- */ if( bInverse ) { if( ahGeometries.size() == 0 ) { for( unsigned int iBand = 0; iBand < anBandList.size(); iBand++ ) { if( adfBurnValues.size() > 0 ) adfFullBurnValues.push_back( adfBurnValues[MIN(iBand,adfBurnValues.size()-1)] ); else /* FIXME? Not sure what to do exactly in the else case, but we must insert a value */ adfFullBurnValues.push_back( 0.0 ); } } InvertGeometries( hDstDS, ahGeometries ); } /* -------------------------------------------------------------------- */ /* Perform the burn. */ /* -------------------------------------------------------------------- */ CPLErr eErr = GDALRasterizeGeometries( hDstDS, static_cast<int>(anBandList.size()), &(anBandList[0]), static_cast<int>(ahGeometries.size()), &(ahGeometries[0]), NULL, NULL, &(adfFullBurnValues[0]), papszRasterizeOptions, pfnProgress, pProgressData ); /* -------------------------------------------------------------------- */ /* Cleanup geometries. */ /* -------------------------------------------------------------------- */ int iGeom; for( iGeom = static_cast<int>(ahGeometries.size())-1; iGeom >= 0; iGeom-- ) OGR_G_DestroyGeometry( ahGeometries[iGeom] ); return eErr; }
CPLErr RasterliteDataset::ReloadOverviews() { if (nLevel != 0) return CE_Failure; /* -------------------------------------------------------------------- */ /* Fetch resolutions */ /* -------------------------------------------------------------------- */ CPLString osSQL; OGRLayerH hRasterPyramidsLyr = OGR_DS_GetLayerByName(hDS, "raster_pyramids"); if (hRasterPyramidsLyr) { osSQL.Printf("SELECT pixel_x_size, pixel_y_size " "FROM raster_pyramids WHERE table_prefix = '%s' " "ORDER BY pixel_x_size ASC", osTableName.c_str()); } else { osSQL.Printf("SELECT DISTINCT(pixel_x_size), pixel_y_size " "FROM \"%s_metadata\" WHERE pixel_x_size != 0 " "ORDER BY pixel_x_size ASC", osTableName.c_str()); } OGRLayerH hSQLLyr = OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL); if (hSQLLyr == NULL) { if (hRasterPyramidsLyr == NULL) return CE_Failure; osSQL.Printf("SELECT DISTINCT(pixel_x_size), pixel_y_size " "FROM \"%s_metadata\" WHERE pixel_x_size != 0 " "ORDER BY pixel_x_size ASC", osTableName.c_str()); hSQLLyr = OGR_DS_ExecuteSQL(hDS, osSQL.c_str(), NULL, NULL); if (hSQLLyr == NULL) return CE_Failure; } /* -------------------------------------------------------------------- */ /* Cleanup */ /* -------------------------------------------------------------------- */ int i; for(i=1;i<nResolutions;i++) delete papoOverviews[i-1]; CPLFree(papoOverviews); papoOverviews = NULL; CPLFree(padfXResolutions); padfXResolutions = NULL; CPLFree(padfYResolutions); padfYResolutions = NULL; /* -------------------------------------------------------------------- */ /* Rebuild arrays */ /* -------------------------------------------------------------------- */ nResolutions = OGR_L_GetFeatureCount(hSQLLyr, TRUE); padfXResolutions = (double*)CPLMalloc(sizeof(double) * nResolutions); padfYResolutions = (double*)CPLMalloc(sizeof(double) * nResolutions); i = 0; OGRFeatureH hFeat; while((hFeat = OGR_L_GetNextFeature(hSQLLyr)) != NULL) { padfXResolutions[i] = OGR_F_GetFieldAsDouble(hFeat, 0); padfYResolutions[i] = OGR_F_GetFieldAsDouble(hFeat, 1); OGR_F_Destroy(hFeat); i ++; } OGR_DS_ReleaseResultSet(hDS, hSQLLyr); hSQLLyr = NULL; /* -------------------------------------------------------------------- */ /* Add overview levels as internal datasets */ /* -------------------------------------------------------------------- */ if (nResolutions > 1) { CPLString osRasterTableName = osTableName; osRasterTableName += "_rasters"; OGRLayerH hRasterLyr = OGR_DS_GetLayerByName(hDS, osRasterTableName.c_str()); papoOverviews = (RasterliteDataset**) CPLCalloc(nResolutions - 1, sizeof(RasterliteDataset*)); int nLev; for(nLev=1;nLev<nResolutions;nLev++) { int nOvrBands; GDALDataType eOvrDataType; int nBlockXSize, nBlockYSize; if (GetBlockParams(hRasterLyr, nLev, &nOvrBands, &eOvrDataType, &nBlockXSize, &nBlockYSize)) { if (eOvrDataType == GDT_Byte && nOvrBands == 1 && nBands == 3) nOvrBands = 3; papoOverviews[nLev-1] = new RasterliteDataset(this, nLev); int iBand; for(iBand=0;iBand<nBands;iBand++) { papoOverviews[nLev-1]->SetBand(iBand+1, new RasterliteBand(papoOverviews[nLev-1], iBand+1, eOvrDataType, nBlockXSize, nBlockYSize)); } } else { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find block characteristics for overview %d", nLev); papoOverviews[nLev-1] = NULL; } } } return CE_None; }
bool QgsShapeFile::insertLayer( QString dbname, QString schema, QString primary_key, QString geom_col, QString srid, PGconn * conn, QProgressDialog& pro, bool &fin, QString& errorText ) { connect( &pro, SIGNAL( canceled() ), this, SLOT( cancelImport() ) ); import_canceled = false; bool result = true; QString query = QString( "CREATE TABLE %1.%2(%3 int4 PRIMARY KEY" ) .arg( QgsPgUtil::quotedIdentifier( schema ) ) .arg( QgsPgUtil::quotedIdentifier( table_name ) ) .arg( QgsPgUtil::quotedIdentifier( primary_key ) ); for ( uint n = 0; n < column_names.size() && result; n++ ) { query += QString( ",%1 %2" ) .arg( QgsPgUtil::quotedIdentifier( column_names[n] ) ) .arg( column_types[n] ); } query += " )"; QgsDebugMsg( "Query string is: " + query ); PGresult *res = PQexec( conn, query.toUtf8() ); if ( PQresultStatus( res ) != PGRES_COMMAND_OK ) { // flag error and send query and error message to stdout on debug errorText += tr( "The database gave an error while executing this SQL:" ) + "\n"; errorText += query + '\n'; errorText += tr( "The error was:" ) + "\n"; errorText += PQresultErrorMessage( res ) + '\n'; PQclear( res ); return false; } else { PQclear( res ); } query = QString( "SELECT AddGeometryColumn(%1,%2,%3,%4,%5,2)" ) .arg( QgsPgUtil::quotedValue( schema ) ) .arg( QgsPgUtil::quotedValue( table_name ) ) .arg( QgsPgUtil::quotedValue( geom_col ) ) .arg( srid ) .arg( QgsPgUtil::quotedValue( geom_type ) ); res = PQexec( conn, query.toUtf8() ); if ( PQresultStatus( res ) != PGRES_TUPLES_OK ) { errorText += tr( "The database gave an error while executing this SQL:" ) + "\n"; errorText += query + '\n'; errorText += tr( "The error was:" ) + "\n"; errorText += PQresultErrorMessage( res ) + '\n'; PQclear( res ); return false; } else { PQclear( res ); } if ( isMulti ) { query = QString( "select constraint_name from information_schema.table_constraints where table_schema=%1 and table_name=%2 and constraint_name in ('$2','enforce_geotype_the_geom')" ) .arg( QgsPgUtil::quotedValue( schema ) ) .arg( QgsPgUtil::quotedValue( table_name ) ); QStringList constraints; res = PQexec( conn, query.toUtf8() ); if ( PQresultStatus( res ) == PGRES_TUPLES_OK ) { for ( int i = 0; i < PQntuples( res ); i++ ) constraints.append( PQgetvalue( res, i, 0 ) ); } PQclear( res ); if ( constraints.size() > 0 ) { // drop the check constraint // TODO This whole concept needs to be changed to either // convert the geometries to the same type or allow // multiple types in the check constraint. For now, we // just drop the constraint... query = QString( "alter table %1 drop constraint %2" ) .arg( QgsPgUtil::quotedIdentifier( table_name ) ) .arg( QgsPgUtil::quotedIdentifier( constraints[0] ) ); res = PQexec( conn, query.toUtf8() ); if ( PQresultStatus( res ) != PGRES_COMMAND_OK ) { errorText += tr( "The database gave an error while executing this SQL:" ) + "\n"; errorText += query + '\n'; errorText += tr( "The error was:" ) + "\n"; errorText += PQresultErrorMessage( res ) + '\n'; PQclear( res ); return false; } PQclear( res ); } } //adding the data into the table for ( int m = 0; m < features && result; m++ ) { if ( import_canceled ) { fin = true; break; } OGRFeatureH feat = OGR_L_GetNextFeature( ogrLayer ); if ( feat ) { OGRGeometryH geom = OGR_F_GetGeometryRef( feat ); if ( geom ) { query = QString( "INSERT INTO %1.%2 VALUES(%3" ) .arg( QgsPgUtil::quotedIdentifier( schema ) ) .arg( QgsPgUtil::quotedIdentifier( table_name ) ) .arg( m ); char *geo_temp; // 'GeometryFromText' supports only 2D coordinates // TODO for proper 2.5D support we would need to use 'GeomFromEWkt' if ( hasMoreDimensions ) OGR_G_SetCoordinateDimension( geom, 2 ); OGR_G_ExportToWkt( geom, &geo_temp ); QString geometry( geo_temp ); CPLFree( geo_temp ); for ( uint n = 0; n < column_types.size(); n++ ) { QString val; // FIXME: OGR_F_GetFieldAsString returns junk when called with a 8.255 float field if ( column_types[n] == "float" ) val = QString::number( OGR_F_GetFieldAsDouble( feat, n ) ); else val = codec->toUnicode( OGR_F_GetFieldAsString( feat, n ) ); if ( val.isEmpty() ) val = "NULL"; else val = QgsPgUtil::quotedValue( val ); query += "," + val; } query += QString( ",GeometryFromText(%1,%2))" ) .arg( QgsPgUtil::quotedValue( geometry ) ) .arg( srid ); if ( result ) res = PQexec( conn, query.toUtf8() ); if ( PQresultStatus( res ) != PGRES_COMMAND_OK ) { // flag error and send query and error message to stdout on debug result = false; errorText += tr( "The database gave an error while executing this SQL:" ) + "\n"; // the query string can be quite long. Trim if necessary... if ( query.count() > 100 ) errorText += query.left( 150 ) + tr( "... (rest of SQL trimmed)", "is appended to a truncated SQL statement" ) + "\n"; else errorText += query + '\n'; errorText += tr( "The error was:" ) + "\n"; errorText += PQresultErrorMessage( res ); errorText += '\n'; } else { PQclear( res ); } pro.setValue( pro.value() + 1 ); qApp->processEvents(); } OGR_F_Destroy( feat ); } } // create the GIST index if the the load was successful if ( result ) { // prompt user to see if they want to build the index and warn // them about the potential time-cost } OGR_L_ResetReading( ogrLayer ); return result; }
/*! \brief Fetch record \param cn pointer to dbCursor \param position position indicator (DB_NEXT, DB_FIRST, DB_LAST, etc) \param[out] more 0 for no record fetched otherwise 1 \return DB_OK on success \return DB_FAILED on error */ int db__driver_fetch(dbCursor * cn, int position, int *more) { int i, col; int ogrType, sqlType; dbToken token; dbTable *table; dbColumn *column; dbValue *value; cursor *c; G_debug(3, "db_driver_fetch()"); /* get cursor token */ token = db_get_cursor_token(cn); /* get the cursor by its token */ if (!(c = (cursor *) db_find_token(token))) { append_error(_("Cursor not found")); report_error(); return DB_FAILED; } /* fetch on position */ switch (position) { case DB_NEXT: G_debug(4, "DB_NEXT:"); if (c->hFeature) OGR_F_Destroy(c->hFeature); c->hFeature = OGR_L_GetNextFeature(c->hLayer); break; case DB_CURRENT: break; case DB_PREVIOUS: append_error(_("DB_PREVIOUS not supported")); report_error(); return DB_FAILED; break; case DB_FIRST: OGR_L_ResetReading(c->hLayer); if (c->hFeature) OGR_F_Destroy(c->hFeature); c->hFeature = OGR_L_GetNextFeature(c->hLayer); break; case DB_LAST: append_error(_("DB_LAST not supported")); report_error(); return DB_FAILED; break; }; if (c->hFeature == NULL) { *more = 0; return DB_OK; } *more = 1; /* get the data out of the descriptor into the table */ table = db_get_cursor_table(cn); /* check fid column */ if (strlen(OGR_L_GetFIDColumn(c->hLayer)) > 0) { column = db_get_table_column(table, 0); ogrType = db_get_column_host_type(column); sqlType = db_get_column_sqltype(column); value = db_get_column_value(column); value->i = OGR_F_GetFID(c->hFeature); G_debug(3, "fidcol '%s': ogrType %d, sqlType %d: val = %d", db_get_column_name(column), ogrType, sqlType, value->i); col = 0; } else { col = -1; } /* loop attributes */ for (i = 0; i < c->ncols; i++) { if (!(c->cols[i])) { continue; } /* unknown type */ col++; column = db_get_table_column(table, col); ogrType = db_get_column_host_type(column); sqlType = db_get_column_sqltype(column); value = db_get_column_value(column); db_zero_string(&value->s); /* Is null? */ if (OGR_F_IsFieldSet(c->hFeature, i)) { value->isNull = 0; } else { value->isNull = 1; continue; } G_debug(3, "col %d, ogrType %d, sqlType %d: val = '%s'", col, ogrType, sqlType, OGR_F_GetFieldAsString(c->hFeature, i)); switch (ogrType) { case OFTInteger: value->i = OGR_F_GetFieldAsInteger(c->hFeature, i); break; case OFTReal: value->d = OGR_F_GetFieldAsDouble(c->hFeature, i); break; case OFTString: case OFTDate: case OFTTime: case OFTDateTime: db_set_string(&(value->s), (char *)OGR_F_GetFieldAsString(c->hFeature, i)); break; default: G_warning(_("Unknown type")); break; } } G_debug(4, "Row fetched"); return DB_OK; }