QGIS API Documentation 4.3.0-Master (52aa6503bed)
Loading...
Searching...
No Matches
qgsexpression.h
Go to the documentation of this file.
1/***************************************************************************
2 qgsexpression.h
3 -------------------
4 begin : August 2011
5 copyright : (C) 2011 Martin Dobias
6 email : wonder.sk at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
16#ifndef QGSEXPRESSION_H
17#define QGSEXPRESSION_H
18
19#include <functional>
20
21#include "qgis.h"
22#include "qgis_core.h"
23#include "qgsexpressionnode.h"
24#include "qgsinterval.h"
25#include "qgsproject.h"
26#include "qgsthreadingutils.h"
27
28#include <QCoreApplication>
29#include <QDomDocument>
30#include <QList>
31#include <QMetaType>
32#include <QReadWriteLock>
33#include <QRecursiveMutex>
34#include <QSet>
35#include <QString>
36#include <QStringList>
37#include <QVariant>
38
39using namespace Qt::StringLiterals;
40
41class QgsFeature;
42class QgsGeometry;
43class QgsOgcUtils;
44class QgsVectorLayer;
46class QgsField;
47class QgsFields;
48class QgsDistanceArea;
49class QDomElement;
51class QgsExpressionPrivate;
53
54#ifndef SIP_RUN
56struct HelpArg
57{
58 HelpArg( const QString &arg, const QString &desc, bool descOnly = false, bool syntaxOnly = false, bool optional = false, const QString &defaultVal = QString() )
59 : mArg( arg )
60 , mDescription( desc )
61 , mDescOnly( descOnly )
62 , mSyntaxOnly( syntaxOnly )
63 , mOptional( optional )
64 , mDefaultVal( defaultVal )
65 {}
66
67 QString mArg;
68 QString mDescription;
69 bool mDescOnly;
70 bool mSyntaxOnly;
71 bool mOptional;
72 QString mDefaultVal;
73};
74
75struct HelpExample
76{
77 HelpExample( const QString &expression, const QString &returns, const QString &note = QString() )
78 : mExpression( expression )
79 , mReturns( returns )
80 , mNote( note )
81 {}
82
83 QString mExpression;
84 QString mReturns;
85 QString mNote;
86};
87
88
89struct HelpVariant
90{
91 HelpVariant(
92 const QString &name,
93 const QString &description,
94 const QList<HelpArg> &arguments = QList<HelpArg>(),
95 bool variableLenArguments = false,
96 const QList<HelpExample> &examples = QList<HelpExample>(),
97 const QString &notes = QString(),
98 const QStringList &tags = QStringList()
99 )
100 : mName( name )
101 , mDescription( description )
102 , mArguments( arguments )
103 , mVariableLenArguments( variableLenArguments )
104 , mExamples( examples )
105 , mNotes( notes )
106 , mTags( tags )
107 {}
108
109 QString mName;
110 QString mDescription;
111 QList<HelpArg> mArguments;
112 bool mVariableLenArguments;
113 QList<HelpExample> mExamples;
114 QString mNotes;
115 QStringList mTags;
116};
117
118
119struct Help
120{
121 Help() = default;
122
123 Help( const QString &name, const QString &type, const QString &description, const QList<HelpVariant> &variants )
124 : mName( name )
125 , mType( type )
126 , mDescription( description )
127 , mVariants( variants )
128 {}
129
130 QString mName;
131 QString mType;
132 QString mDescription;
133 QList<HelpVariant> mVariants;
134};
135
136typedef QHash<QString, Help> HelpTextHash;
137
139#endif
140
197class CORE_EXPORT QgsExpression
198{
199 Q_DECLARE_TR_FUNCTIONS( QgsExpression )
200 public:
201#ifndef SIP_RUN
202 using SharedFunctionPtr = std::shared_ptr<QgsExpressionFunction>;
203
210 class CORE_EXPORT SharedFunctionPtrList : public QList< SharedFunctionPtr >
211 {
212 public:
221 int functionIndex( const QString &name ) const;
222
226 SharedFunctionPtr getFunction( int index ) const;
227
235
236 private:
237 QMap< QString, int> mFunctionIndexMap;
238 };
239
240 using FunctionListSnapshot = std::shared_ptr< const SharedFunctionPtrList >;
241#endif
242
289
296 QgsExpression( const QString &expr );
297
303 QgsExpression( const QgsExpression &other );
304
310 QgsExpression &operator=( const QgsExpression &other );
311
316 operator QString() const SIP_SKIP;
317
323
324 ~QgsExpression();
325
331 bool operator==( const QgsExpression &other ) const;
332
338 bool isValid() const;
339
341 bool hasParserError() const;
343 QString parserErrorString() const;
344
348 QList<QgsExpression::ParserError> parserErrors() const;
349
355 const QgsExpressionNode *rootNode() const;
356
361 bool prepare( const QgsExpressionContext *context );
362
380 QSet<QString> referencedColumns() const;
381
392 QSet<QString> referencedVariables() const;
393
403 QSet<QString> referencedFunctions() const;
404
405#ifndef SIP_RUN
406
413 QList<const QgsExpressionNode *> nodes() const;
414
421 template<class T> QList<const T *> findNodes() const
422 {
423 QList<const T *> lst;
424 const QList<const QgsExpressionNode *> allNodes( nodes() );
425 for ( const auto &node : allNodes )
426 {
427 const T *n = dynamic_cast<const T *>( node );
428 if ( n )
429 lst << n;
430 }
431 return lst;
432 }
433#endif
434
447 QSet<int> referencedAttributeIndexes( const QgsFields &fields ) const;
448
450 bool needsGeometry() const;
451
452 // evaluation
453
458 QVariant evaluate();
459
465 QVariant evaluate( const QgsExpressionContext *context );
466
468 bool hasEvalError() const;
470 QString evalErrorString() const;
472 void setEvalErrorString( const QString &str );
473
479 bool isField() const;
480
493 static int expressionToLayerFieldIndex( const QString &expression, const QgsVectorLayer *layer );
494
507 static QString quoteFieldExpression( const QString &expression, const QgsVectorLayer *layer );
508
516 static bool checkExpression( const QString &text, const QgsExpressionContext *context, QString &errorMessage SIP_OUT );
517
522 void setExpression( const QString &expression );
523
529 QString expression() const;
530
537 QString dump() const;
538
546 QgsDistanceArea *geomCalculator();
547
561 void setGeomCalculator( const QgsDistanceArea *calc );
562
569 Qgis::DistanceUnit distanceUnits() const;
570
579 void setDistanceUnits( Qgis::DistanceUnit unit );
580
587 Qgis::AreaUnit areaUnits() const;
588
597 void setAreaUnits( Qgis::AreaUnit unit );
598
609 static QString replaceExpressionText( const QString &action, const QgsExpressionContext *context, const QgsDistanceArea *distanceArea = nullptr );
610
618 static QSet<QString> referencedVariables( const QString &text );
619
620 // TODO QGIS 5.0 -- remove this function in favour of version with explicit context
632 Q_DECL_DEPRECATED static double evaluateToDouble( const QString &text, double fallbackValue ) SIP_DEPRECATED;
633
646 static double evaluateToDouble( const QString &text, double fallbackValue, const QgsExpressionContext *context );
647
660
666 SIP_SKIP static const FunctionListSnapshot getFunctionsSnapshot();
667
668 // NOTE tagged as deprecated as we don't want this used from c++ code
675 Q_DECL_DEPRECATED static QList<QgsExpressionFunction *> Functions();
676
682 static QStringList BuiltinFunctions();
683
691 static bool registerFunction( QgsExpressionFunction *function, bool transferOwnership = false );
692
698 static bool unregisterFunction( const QString &name );
699
703 static void cleanRegisteredFunctions();
704
706 static bool isFunctionName( const QString &name );
707
708 // NOTE tagged as deprecated as we don't want this used from c++ code
715 Q_DECL_DEPRECATED static int functionIndex( const QString &name );
716
721 static int functionCount();
722
728 static QString quotedColumnRef( QString name );
729
735 static QString quotedString( QString text );
736
744 static QString quotedValue( const QVariant &value );
745
754 static QString quotedValue( const QVariant &value, QMetaType::Type type );
755
765 Q_DECL_DEPRECATED static QString quotedValue( const QVariant &value, QVariant::Type type ) SIP_DEPRECATED;
766
768
769#ifndef SIP_RUN
771 static HelpTextHash &functionHelpTexts();
773#endif
774
781 static QString helpText( QString name );
782
788 static QStringList tags( const QString &name );
789
802 static bool addVariableHelpText( const QString name, const QString &description );
803
810 static QString variableHelpText( const QString &variableName );
811
820 static QString formatVariableHelp( const QString &description, bool showValue = true, const QVariant &value = QVariant() );
821
826 static QString group( const QString &group );
827
836 static QString formatPreviewString( const QVariant &value, bool htmlOutput = true, int maximumPreviewLength = 60 );
837
846 static QString createFieldEqualityExpression( const QString &fieldName, const QVariant &value, QMetaType::Type fieldType = QMetaType::Type::UnknownType );
847
857 Q_DECL_DEPRECATED static QString createFieldEqualityExpression( const QString &fieldName, const QVariant &value, QVariant::Type fieldType ) SIP_DEPRECATED;
858
869 static bool isFieldEqualityExpression( const QString &expression, QString &field SIP_OUT, QVariant &value SIP_OUT );
870
885 static bool attemptReduceToInClause( const QStringList &expressions, QString &result SIP_OUT );
886
896 QgsExpression simplified() const;
897
898 // clang-format off
899#ifdef SIP_RUN
900 SIP_PYOBJECT __repr__();
901 % MethodCode
902 QString str = u"<QgsExpression: '%1'>"_s.arg( sipCpp->expression() );
903 sipRes = PyUnicode_FromString( str.toUtf8().constData() );
904 % End
905#endif
906
907 private:
908 // clang-format on
909
910 void initGeomCalculator( const QgsExpressionContext *context );
911
918 void detach() SIP_SKIP;
919
920 QgsExpressionPrivate *d = nullptr;
921
922 static HelpTextHash sFunctionHelpTexts;
923
925 static void initFunctionHelp() SIP_SKIP;
927 static void buildFunctionHelp() SIP_SKIP;
929 static void initVariableHelp() SIP_SKIP;
931 static void buildVariableHelp() SIP_SKIP;
932
934
935#if defined( __clang__ )
937#else
938 static std::atomic<FunctionListSnapshot> sFunctions;
939#endif
940 static QMutex sFunctionWriteMutex;
941
942 static QStringList sBuiltinFunctionNames;
943
944 friend class QgsOgcUtils;
945};
946
948
949#endif // QGSEXPRESSION_H
An atomic shared_ptr, for use in LLVM/clang builds (temporarily, until LLVM adds support for c++20 at...
DistanceUnit
Units of distance.
Definition qgis.h:5568
AreaUnit
Units of area.
Definition qgis.h:5645
A general purpose distance and area calculator, capable of performing ellipsoid based calculations.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
An abstract base class for defining QgsExpression functions.
Abstract base class for all nodes that can appear in an expression.
A thread-safe container of shared pointers to registered functions.
int functionIndex(const QString &name) const
Returns the index of the function in the list.
void updateFunctionNameMap()
Updates the map of function names to indices.
SharedFunctionPtr getFunction(int index) const
Returns a shared pointer for the function with the specified index.
Handles parsing and evaluation of expressions (formerly called "search strings").
bool prepare(const QgsExpressionContext *context)
Gets the expression ready for evaluation - find out column indexes.
QgsExpression & operator=(const QgsExpression &other)
Create a copy of this expression.
friend class QgsOgcUtils
QList< const T * > findNodes() const
Returns a list of all nodes of the given class which are used in this expression.
QList< const QgsExpressionNode * > nodes() const
Returns a list of all nodes which are used in this expression.
QSet< QString > referencedVariables() const
Returns a list of all variables which are used in this expression.
bool hasParserError() const
Returns true if an error occurred when parsing the input expression.
std::shared_ptr< const SharedFunctionPtrList > FunctionListSnapshot
QList< QgsExpression::ParserError > parserErrors() const
Returns parser error details including location of error.
QString parserErrorString() const
Returns parser error.
QSet< QString > referencedColumns() const
Gets list of columns referenced by the expression.
QSet< QString > referencedFunctions() const
Returns a list of the names of all functions which are used in this expression.
friend class QgsExpressionNodeFunction
const QgsExpressionNode * rootNode() const
Returns the root node of the expression.
QgsExpression(const QString &expr)
Creates a new expression based on the provided string.
std::shared_ptr< QgsExpressionFunction > SharedFunctionPtr
bool isValid() const
Checks if this expression is valid.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:56
Container of fields for a vector layer.
Definition qgsfields.h:45
A geometry is the spatial representation of a feature.
Provides various utility functions for conversion between OGC (Open Geospatial Consortium) standards ...
Definition qgsogcutils.h:56
Base class for vector data providers.
Represents a vector layer which manages a vector based dataset.
#define SIP_DEPRECATED
Definition qgis_sip.h:113
#define SIP_SKIP
Definition qgis_sip.h:138
#define SIP_OUT
Definition qgis_sip.h:57
Q_DECLARE_METATYPE(QgsDatabaseQueryLogEntry)
QString formatVariableHelp(const QString &variable, const QString &description, bool showValue, const QVariant &value)
Returns a HTML formatted string for use as a variable item help.
Details about any parser errors that were found when parsing the expression.
QgsExpression::ParserError::ParserErrorType errorType
The type of parser error that was found.
int lastColumn
The last column that contained the error in the parser.
int lastLine
The last line that contained the error in the parser.
int firstColumn
The first column that contained the error in the parser.
QString errorMsg
The message for the error at this location.
@ FunctionInvalidParams
Function was called with invalid args.
@ Unknown
Unknown error type.
@ FunctionUnknown
Function was unknown.
@ FunctionNamedArgsError
Non named function arg used after named arg.
@ FunctionWrongArgs
Function was called with the wrong number of args.
int firstLine
The first line that contained the error in the parser.