Skip to content

Commit

Permalink
[expressions] Allow conversion of features/geometries to bool
Browse files Browse the repository at this point in the history
Where geometry = false if empty, feature = false if not valid.
Allows expressions like "case when $geometry then ... else ..."
and "case when get_feature(...) then ... else ... "
  • Loading branch information
nyalldawson committed Nov 10, 2015
1 parent 719ff40 commit 0853076
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/core/qgsexpression.cpp
Expand Up @@ -371,6 +371,20 @@ static TVL getTVLValue( const QVariant& value, QgsExpression* parent )
if ( value.isNull() )
return Unknown;

//handle some special cases
if ( value.canConvert<QgsGeometry>() )
{
//geom is false if empty
QgsGeometry geom = value.value<QgsGeometry>();
return geom.isEmpty() ? False : True;
}
else if ( value.canConvert<QgsFeature>() )
{
//feat is false if non-valid
QgsFeature feat = value.value<QgsFeature>();
return feat.isValid() ? True : False;
}

if ( value.type() == QVariant::Int )
return value.toInt() != 0 ? True : False;

Expand Down
6 changes: 6 additions & 0 deletions tests/src/core/testqgsexpression.cpp
Expand Up @@ -630,6 +630,12 @@ class TestQgsExpression: public QObject
QTest::newRow( "layer_property type" ) << QString( "layer_property('%1','type')" ).arg( mPointsLayer->name() ) << false << QVariant( "Vector" );
QTest::newRow( "layer_property storage_type" ) << QString( "layer_property('%1','storage_type')" ).arg( mPointsLayer->name() ) << false << QVariant( "ESRI Shapefile" );
QTest::newRow( "layer_property geometry_type" ) << QString( "layer_property('%1','geometry_type')" ).arg( mPointsLayer->name() ) << false << QVariant( "Point" );

//test conversions to bool
QTest::newRow( "feature to bool false" ) << QString( "case when get_feature('none','none',499) then true else false end" ) << false << QVariant( false );
QTest::newRow( "feature to bool true" ) << QString( "case when get_feature('test','col1',10) then true else false end" ) << false << QVariant( true );
QTest::newRow( "geometry to bool false" ) << QString( "case when geom_from_wkt('') then true else false end" ) << false << QVariant( false );
QTest::newRow( "geometry to bool true" ) << QString( "case when geom_from_wkt('Point(3 4)') then true else false end" ) << false << QVariant( true );
}

void run_evaluation_test( QgsExpression& exp, bool evalError, QVariant& result )
Expand Down

0 comments on commit 0853076

Please sign in to comment.