QGIS API Documentation  master-59fd5e0
QgsExpression Class Reference

Class for parsing and evaluation of expressions (formerly called "search strings"). More...

#include <qgsexpression.h>

+ Collaboration diagram for QgsExpression:

List of all members.

Classes

class  Function
 A abstract base class for defining QgsExpression functions. More...
class  Interval
class  Node
class  NodeBinaryOperator
class  NodeColumnRef
class  NodeCondition
class  NodeFunction
class  NodeInOperator
class  NodeList
class  NodeLiteral
class  NodeUnaryOperator
class  StaticFunction
class  Visitor
 support for visitor pattern - algorithms dealing with the expressions may be implemented without modifying the Node classes More...
class  WhenThen

Public Types

enum  BinaryOperator {
  boOr, boAnd, boEQ, boNE,
  boLE, boGE, boLT, boGT,
  boRegexp, boLike, boNotLike, boILike,
  boNotILike, boIs, boIsNot, boPlus,
  boMinus, boMul, boDiv, boMod,
  boPow, boConcat
}
typedef QVariant(* FcnEval )(const QVariantList &values, const QgsFeature *f, QgsExpression *parent)
enum  NodeType {
  ntUnaryOperator, ntBinaryOperator, ntInOperator, ntFunction,
  ntLiteral, ntColumnRef, ntCondition
}
enum  SpatialOperator {
  soBbox, soIntersects, soContains, soCrosses,
  soEquals, soDisjoint, soOverlaps, soTouches,
  soWithin
}
enum  UnaryOperator { uoNot, uoMinus }
typedef QList< WhenThen * > WhenThenList

Public Member Functions

 QgsExpression (const QString &expr)
 ~QgsExpression ()
void acceptVisitor (Visitor &v) const
 entry function for the visitor pattern
int currentRowNumber ()
 Return the number used for $rownum special column.
QString dump () const
 Return the parsed expression as a string - useful for debugging.
QString evalErrorString () const
 Returns evaluation error.
QVariant evaluate (const QgsFeature *f=NULL)
 Evaluate the feature and return the result.
QVariant evaluate (const QgsFeature &f)
 Evaluate the feature and return the result.
QVariant evaluate (const QgsFeature *f, const QgsFields &fields)
 Evaluate the feature and return the result.
QVariant evaluate (const QgsFeature &f, const QgsFields &fields)
 Evaluate the feature and return the result.
const QString & expression () const
QgsDistanceAreageomCalculator ()
 Return calculator used for distance and area calculations (used by internal functions)
bool hasEvalError () const
 Returns true if an error occurred when evaluating last input.
bool hasParserError () const
 Returns true if an error occurred when parsing the input expression.
bool needsGeometry ()
 Returns true if the expression uses feature geometry for some computation.
QString parserErrorString () const
 Returns parser error.
bool prepare (const QgsFields &fields)
 Get the expression ready for evaluation - find out column indexes.
QStringList referencedColumns ()
 Get list of columns referenced by the expression.
const NoderootNode () const
 Returns root node of the expression. Root node is null is parsing has failed.
int scale ()
void setCurrentRowNumber (int rowNumber)
 Set the number for $rownum special column.
void setEvalErrorString (QString str)
 Set evaluation error (used internally by evaluation functions)
void setGeomCalculator (QgsDistanceArea &calc)
 Sets the geometry calculator used in evaluation of expressions,.
void setScale (double scale)

Static Public Member Functions

static const QStringList & BuiltinFunctions ()
static int functionCount ()
 Returns the number of functions defined in the parser.
static int functionIndex (QString name)
static const QList< Function * > & Functions ()
static QString group (QString group)
static QString helptext (QString name)
static bool isFunctionName (QString name)
static QString quotedColumnRef (QString name)
 return quoted column reference (in double quotes)
static QString quotedString (QString text)
 return quoted string (in single quotes)
static bool registerFunction (Function *function)
static QString replaceExpressionText (QString action, QgsFeature *feat, QgsVectorLayer *layer, const QMap< QString, QVariant > *substitutionMap=0)
 This function currently replaces each expression between [% and %] in the string with the result of its evaluation on the feature passed as argument.
static QString replaceExpressionText (QString action, QgsFeature &feat, QgsVectorLayer *layer, const QMap< QString, QVariant > *substitutionMap=0)
static void setSpecialColumn (const QString &name, QVariant value)
 Assign a special column.
static QVariant specialColumn (const QString &name)
 Return the value of the given special column or a null QVariant if undefined.
static QList< Function * > specialColumns ()
 Returns a list of special Column definitions.
static bool unregisterFunction (QString name)
static void unsetSpecialColumn (const QString &name)
 Unset a special column.

Static Public Attributes

static const char * BinaryOperatorText []
static QStringList gmBuiltinFunctions
static QList< Function * > gmFunctions
static const char * UnaryOperatorText []

Protected Member Functions

 QgsExpression ()
void initGeomCalculator ()

Static Protected Member Functions

static void initFunctionHelp ()

Protected Attributes

QgsDistanceArea mCalc
QString mEvalErrorString
QString mExpression
QString mParserErrorString
NodemRootNode
int mRowNumber
double mScale

Static Protected Attributes

static QHash< QString, QString > gFunctionHelpTexts
static QHash< QString, QString > gGroups
static QMap< QString, QVariant > gmSpecialColumns

Friends

class QgsOgcUtils

Detailed Description

Class for parsing and evaluation of expressions (formerly called "search strings").

The expressions try to follow both syntax and semantics of SQL expressions.

Usage:

QgsExpression exp("gid*2 > 10 and type not in ('D','F')); if (exp.hasParserError()) { show error message with parserErrorString() and exit } QVariant result = exp.evaluate(feature, fields); if (exp.hasEvalError()) { show error message with evalErrorString() } else { examine the result }

Possible QVariant value types:

  • invalid (null)
  • int
  • double
  • string
  • geometry

Similarly to SQL, this class supports three-value logic: true/false/unknown. Unknown value may be a result of operations with missing data (NULL). Please note that NULL is different value than zero or an empty string. For example 3 > NULL returns unknown.

There is no special (three-value) 'boolean' type: true/false is represented as 1/0 integer, unknown value is represented the same way as NULL values: invalid QVariant.

For better performance with many evaluations you may first call prepare(fields) function to find out indices of columns and then repeatedly call evaluate(feature).

Type conversion: operators and functions that expect arguments to be of particular type automatically convert the arguments to that type, e.g. sin('2.1') will convert the argument to a double, length(123) will first convert the number to a string. Explicit conversion can be achieved with toint, toreal, tostring functions. If implicit or explicit conversion is invalid, the evaluation returns an error. Comparison operators do numeric comparison in case both operators are numeric (int/double) or they can be converted to numeric types.

Arithmetic operators do integer arithmetics if both operands are integer. That is 2+2 yields integer 4, but 2.0+2 returns real number 4.0. There are also two versions of division and modulo operators: 1.0/2 returns 0.5 while 1/2 returns 0.

Note:
added in 2.0

Definition at line 88 of file qgsexpression.h.


Member Typedef Documentation

typedef QVariant( * QgsExpression::FcnEval)(const QVariantList &values, const QgsFeature *f, QgsExpression *parent)

Definition at line 234 of file qgsexpression.h.

Definition at line 555 of file qgsexpression.h.


Member Enumeration Documentation

Enumerator:
boOr 
boAnd 
boEQ 
boNE 
boLE 
boGE 
boLT 
boGT 
boRegexp 
boLike 
boNotLike 
boILike 
boNotILike 
boIs 
boIsNot 
boPlus 
boMinus 
boMul 
boDiv 
boMod 
boPow 
boConcat 

Definition at line 186 of file qgsexpression.h.

Enumerator:
ntUnaryOperator 
ntBinaryOperator 
ntInOperator 
ntFunction 
ntLiteral 
ntColumnRef 
ntCondition 

Definition at line 323 of file qgsexpression.h.

Enumerator:
soBbox 
soIntersects 
soContains 
soCrosses 
soEquals 
soDisjoint 
soOverlaps 
soTouches 
soWithin 

Definition at line 218 of file qgsexpression.h.

Enumerator:
uoNot 
uoMinus 

Definition at line 181 of file qgsexpression.h.


Constructor & Destructor Documentation

QgsExpression::QgsExpression ( const QString &  expr)

Definition at line 1627 of file qgsexpression.cpp.

References mRootNode.

QgsExpression::QgsExpression ( ) [inline, protected]

Definition at line 602 of file qgsexpression.h.


Member Function Documentation

entry function for the visitor pattern

Definition at line 1719 of file qgsexpression.cpp.

References QgsExpression::Node::accept(), and mRootNode.

const QStringList & QgsExpression::BuiltinFunctions ( ) [static]

Definition at line 1398 of file qgsexpression.cpp.

References gmBuiltinFunctions.

Referenced by unregisterFunction().

Return the number used for $rownum special column.

Definition at line 140 of file qgsexpression.h.

Referenced by fcnRowNumber().

QString QgsExpression::dump ( ) const

Return the parsed expression as a string - useful for debugging.

Definition at line 1711 of file qgsexpression.cpp.

References QgsExpression::Node::dump(), mRootNode, and tr.

Referenced by QgsRuleBasedRendererV2::Rule::createFromSld(), QgsSymbolLayerV2Utils::functionFromSldElement(), and QgsEllipseSymbolLayerV2::writeSldMarker().

QVariant QgsExpression::evaluate ( const QgsFeature f = NULL)

Evaluate the feature and return the result.

Note:
prepare() should be called before calling this method

Definition at line 1688 of file qgsexpression.cpp.

References QgsExpression::Node::eval(), mEvalErrorString, mRootNode, and tr.

Referenced by QgsSVGFillSymbolLayer::applyDataDefinedSettings(), QgsLinePatternFillSymbolLayer::applyDataDefinedSettings(), QgsPointPatternFillSymbolLayer::applyDataDefinedSettings(), QgsSimpleFillSymbolLayerV2::applyDataDefinedSymbology(), QgsSimpleLineSymbolLayerV2::applyDataDefinedSymbology(), QgsSearchQueryBuilder::countRecords(), QgsAttributeEditor::createAttributeEditor(), QgsFeatureListModel::data(), QgsPalLayerSettings::dataDefinedValue(), evaluate(), QgsAttributeAction::expandAction(), QgsAttributeTableModel::loadAttributes(), QgsMarkerSymbolLayerV2::markerOffset(), QgsExpressionSelectionDialog::on_mActionAddToSelection_triggered(), QgsExpressionSelectionDialog::on_mActionRemoveFromSelection_triggered(), QgsExpressionSelectionDialog::on_mActionSelect_triggered(), QgsExpressionSelectionDialog::on_mActionSelectInstersect_triggered(), QgsExpressionBuilderWidget::on_txtExpressionString_textChanged(), QgsEllipseSymbolLayerV2::preparePath(), QgsAttributeDialog::QgsAttributeDialog(), QgsPalLayerSettings::registerFeature(), QgsEllipseSymbolLayerV2::renderPoint(), QgsSimpleMarkerSymbolLayerV2::renderPoint(), QgsSvgMarkerSymbolLayerV2::renderPoint(), QgsMarkerLineSymbolLayerV2::renderPolyline(), QgsMarkerLineSymbolLayerV2::renderPolylineInterval(), and replaceExpressionText().

QVariant QgsExpression::evaluate ( const QgsFeature f) [inline]

Evaluate the feature and return the result.

Note:
prepare() should be called before calling this method

Definition at line 120 of file qgsexpression.h.

References evaluate().

Referenced by evaluate().

QVariant QgsExpression::evaluate ( const QgsFeature f,
const QgsFields fields 
)

Evaluate the feature and return the result.

Note:
this method does not expect that prepare() has been called on this instance

Definition at line 1700 of file qgsexpression.cpp.

References evaluate(), and prepare().

QVariant QgsExpression::evaluate ( const QgsFeature f,
const QgsFields fields 
) [inline]

Evaluate the feature and return the result.

Note:
this method does not expect that prepare() has been called on this instance

Definition at line 128 of file qgsexpression.h.

References evaluate().

Referenced by evaluate().

const QString& QgsExpression::expression ( ) const [inline]
int QgsExpression::functionCount ( ) [static]

Returns the number of functions defined in the parser.

Returns:
The number of function defined in the parser.

Definition at line 1605 of file qgsexpression.cpp.

References Functions().

Referenced by functionIndex(), and QgsExpressionBuilderWidget::QgsExpressionBuilderWidget().

const QList< QgsExpression::Function * > & QgsExpression::Functions ( ) [static]

Definition at line 1430 of file qgsexpression.cpp.

References fcnAbs(), fcnAcos(), fcnAge(), fcnAsin(), fcnAtan(), fcnAtan2(), fcnBbox(), fcnBuffer(), fcnCeil(), fcnCentroid(), fcnClamp(), fcnCoalesce(), fcnColorCmyk(), fcnColorHsl(), fcnColorHsv(), fcnColorRgb(), fcnCombine(), fcnConcat(), fcnContains(), fcnConvexHull(), fcnCos(), fcnCrosses(), fcnDay(), fcnDifference(), fcnDisjoint(), fcnDistance(), fcnExp(), fcnExpScale(), fcnFeatureId(), fcnFloor(), fcnFormatDate(), fcnFormatNumber(), fcnFormatString(), fcnGeomArea(), fcnGeometry(), fcnGeomFromGML(), fcnGeomFromWKT(), fcnGeomLength(), fcnGeomPerimeter(), fcnGeomToWKT(), fcnHour(), fcnIntersection(), fcnIntersects(), fcnLeft(), fcnLength(), fcnLinearScale(), fcnLn(), fcnLog(), fcnLog10(), fcnLower(), fcnLPad(), fcnMax(), fcnMin(), fcnMinute(), fcnMonth(), fcnNow(), fcnOverlaps(), fcnPi(), fcnRampColor(), fcnRegexpMatch(), fcnRegexpReplace(), fcnRegexpSubstr(), fcnReplace(), fcnRight(), fcnRnd(), fcnRndF(), fcnRound(), fcnRowNumber(), fcnRPad(), fcnScale(), fcnSeconds(), fcnSin(), fcnSpecialColumn(), fcnSqrt(), fcnStrpos(), fcnSubstr(), fcnSymDifference(), fcnTan(), fcnTitle(), fcnToDate(), fcnToDateTime(), fcnToInt(), fcnToInterval(), fcnToReal(), fcnToString(), fcnToTime(), fcnTouches(), fcnTrim(), fcnUpper(), fcnWeek(), fcnWithin(), fcnX(), fcnXat(), fcnY(), fcnYat(), fcnYear(), fncColorCmyka(), fncColorHsla(), fncColorHsva(), fncColorRgba(), and gmFunctions.

Referenced by QgsExpression::NodeFunction::dump(), QgsExpression::NodeFunction::eval(), QgsOgcUtils::expressionFunctionToOgcFilter(), functionCount(), functionIndex(), isGeometryColumn(), QgsOgcUtils::nodeFunctionFromOgcFilter(), and QgsExpressionBuilderWidget::QgsExpressionBuilderWidget().

Return calculator used for distance and area calculations (used by internal functions)

Definition at line 160 of file qgsexpression.h.

Referenced by fcnGeomArea(), fcnGeomLength(), and fcnGeomPerimeter().

QString QgsExpression::group ( QString  group) [static]

Definition at line 2367 of file qgsexpression.cpp.

References gGroups, and tr.

Referenced by QgsExpressionBuilderWidget::registerItem().

QString QgsExpression::helptext ( QString  name) [static]
static void QgsExpression::initFunctionHelp ( ) [static, protected]

Referenced by helptext().

void QgsExpression::initGeomCalculator ( ) [protected]

Definition at line 1662 of file qgsexpression.cpp.

References mCalc, and QgsDistanceArea::setEllipsoidalMode().

Referenced by QgsExpression().

bool QgsExpression::isFunctionName ( QString  name) [static]

Definition at line 1589 of file qgsexpression.cpp.

References functionIndex().

static QString QgsExpression::quotedColumnRef ( QString  name) [inline, static]

return quoted column reference (in double quotes)

Definition at line 315 of file qgsexpression.h.

Referenced by QgsSearchQueryBuilder::on_lstFields_doubleClicked(), QgsRuleBasedRendererV2::refineRuleCategories(), and QgsRuleBasedRendererV2::refineRuleRanges().

static QString QgsExpression::quotedString ( QString  text) [inline, static]

return quoted string (in single quotes)

Definition at line 317 of file qgsexpression.h.

Referenced by QgsRuleBasedRendererV2::refineRuleCategories().

Definition at line 1367 of file qgsexpression.cpp.

References functionIndex(), and gmFunctions.

QString QgsExpression::replaceExpressionText ( QString  action,
QgsFeature feat,
QgsVectorLayer layer,
const QMap< QString, QVariant > *  substitutionMap = 0 
) [static]

This function currently replaces each expression between [% and %] in the string with the result of its evaluation on the feature passed as argument.

Additional substitutions can be passed through the substitutionMap parameter

Definition at line 1725 of file qgsexpression.cpp.

References evalErrorString(), evaluate(), hasEvalError(), hasParserError(), parserErrorString(), QgsVectorLayer::pendingFields(), QgsDebugMsg, setSpecialColumn(), and specialColumn().

Referenced by QgsComposerLabel::displayText(), QgsAttributeAction::doAction(), QgsMapTip::fetchFeature(), replaceExpressionText(), and QgsHtmlAnnotationItem::setFeatureForMapPosition().

QString QgsExpression::replaceExpressionText ( QString  action,
QgsFeature feat,
QgsVectorLayer layer,
const QMap< QString, QVariant > *  substitutionMap = 0 
) [static]

Definition at line 1800 of file qgsexpression.cpp.

References replaceExpressionText().

const Node* QgsExpression::rootNode ( ) const [inline]

Returns root node of the expression. Root node is null is parsing has failed.

Definition at line 102 of file qgsexpression.h.

Referenced by QgsOgcUtils::expressionToOgcFilter().

int QgsExpression::scale ( ) [inline]

Definition at line 151 of file qgsexpression.h.

Referenced by fcnScale().

void QgsExpression::setCurrentRowNumber ( int  rowNumber) [inline]

Set the number for $rownum special column.

Definition at line 138 of file qgsexpression.h.

void QgsExpression::setScale ( double  scale) [inline]
QVariant QgsExpression::specialColumn ( const QString &  name) [static]

Return the value of the given special column or a null QVariant if undefined.

Definition at line 1563 of file qgsexpression.cpp.

References functionIndex(), and gmSpecialColumns.

Referenced by fcnSpecialColumn(), and replaceExpressionText().

Returns a list of special Column definitions.

Definition at line 1579 of file qgsexpression.cpp.

References gmSpecialColumns.

Referenced by QgsExpressionBuilderWidget::QgsExpressionBuilderWidget().

bool QgsExpression::unregisterFunction ( QString  name) [static]

Definition at line 1378 of file qgsexpression.cpp.

References BuiltinFunctions(), functionIndex(), and gmFunctions.

void QgsExpression::unsetSpecialColumn ( const QString &  name) [static]

Unset a special column.

Definition at line 1554 of file qgsexpression.cpp.

References gmSpecialColumns.


Friends And Related Function Documentation

friend class QgsOgcUtils [friend]

Definition at line 618 of file qgsexpression.h.


Member Data Documentation

const char * QgsExpression::BinaryOperatorText [static]
Initial value:
{
  "OR", "AND",
  "=", "<>", "<=", ">=", "<", ">", "~", "LIKE", "NOT LIKE", "ILIKE", "NOT ILIKE", "IS", "IS NOT",
  "+", "-", "*", "/", "%", "^",
  "||"
}

Definition at line 231 of file qgsexpression.h.

Referenced by QgsExpression::NodeBinaryOperator::dump(), and QgsOgcUtils::expressionBinaryOperatorToOgcFilter().

QHash<QString, QString> QgsExpression::gFunctionHelpTexts [static, protected]

Definition at line 621 of file qgsexpression.h.

Referenced by helptext().

QHash< QString, QString > QgsExpression::gGroups [static, protected]

Definition at line 622 of file qgsexpression.h.

Referenced by group().

QStringList QgsExpression::gmBuiltinFunctions [static]

Definition at line 292 of file qgsexpression.h.

Referenced by BuiltinFunctions().

QMap< QString, QVariant > QgsExpression::gmSpecialColumns [static, protected]

Definition at line 616 of file qgsexpression.h.

Referenced by initGeomCalculator(), and setGeomCalculator().

QString QgsExpression::mEvalErrorString [protected]

Definition at line 610 of file qgsexpression.h.

Referenced by evaluate(), prepare(), and QgsExpression::NodeColumnRef::prepare().

QString QgsExpression::mExpression [protected]

Definition at line 606 of file qgsexpression.h.

Referenced by QgsExpression().

QString QgsExpression::mParserErrorString [protected]

Definition at line 609 of file qgsexpression.h.

Referenced by QgsOgcUtils::expressionFromOgcFilter(), and QgsExpression().

int QgsExpression::mRowNumber [protected]

Definition at line 612 of file qgsexpression.h.

double QgsExpression::mScale [protected]

Definition at line 613 of file qgsexpression.h.

const char * QgsExpression::UnaryOperatorText [static]
Initial value:
{
  "NOT", "-"
}

Definition at line 232 of file qgsexpression.h.

Referenced by QgsExpression::NodeUnaryOperator::dump(), and QgsOgcUtils::expressionUnaryOperatorToOgcFilter().


The documentation for this class was generated from the following files:
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Defines