QGIS API Documentation 4.3.0-Master (0ad0cdb9438)
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 "qgsthreadingutils.h"
26
27#include <QCoreApplication>
28#include <QDomDocument>
29#include <QList>
30#include <QMetaType>
31#include <QReadWriteLock>
32#include <QRecursiveMutex>
33#include <QSet>
34#include <QString>
35#include <QStringList>
36#include <QVariant>
37
38using namespace Qt::StringLiterals;
39
40class QgsFeature;
41class QgsGeometry;
42class QgsOgcUtils;
43class QgsVectorLayer;
45class QgsField;
46class QgsFields;
47class QgsDistanceArea;
48class QDomElement;
50class QgsExpressionPrivate;
52
53#ifndef SIP_RUN
55struct HelpArg
56{
57 HelpArg( const QString &arg, const QString &desc, bool descOnly = false, bool syntaxOnly = false, bool optional = false, const QString &defaultVal = QString() )
58 : mArg( arg )
59 , mDescription( desc )
60 , mDescOnly( descOnly )
61 , mSyntaxOnly( syntaxOnly )
62 , mOptional( optional )
63 , mDefaultVal( defaultVal )
64 {}
65
66 QString mArg;
67 QString mDescription;
68 bool mDescOnly;
69 bool mSyntaxOnly;
70 bool mOptional;
71 QString mDefaultVal;
72};
73
74struct HelpExample
75{
76 HelpExample( const QString &expression, const QString &returns, const QString &note = QString() )
77 : mExpression( expression )
78 , mReturns( returns )
79 , mNote( note )
80 {}
81
82 QString mExpression;
83 QString mReturns;
84 QString mNote;
85};
86
87
88struct HelpVariant
89{
90 HelpVariant(
91 const QString &name,
92 const QString &description,
93 const QList<HelpArg> &arguments = QList<HelpArg>(),
94 bool variableLenArguments = false,
95 const QList<HelpExample> &examples = QList<HelpExample>(),
96 const QString &notes = QString(),
97 const QStringList &tags = QStringList()
98 )
99 : mName( name )
100 , mDescription( description )
101 , mArguments( arguments )
102 , mVariableLenArguments( variableLenArguments )
103 , mExamples( examples )
104 , mNotes( notes )
105 , mTags( tags )
106 {}
107
108 QString mName;
109 QString mDescription;
110 QList<HelpArg> mArguments;
111 bool mVariableLenArguments;
112 QList<HelpExample> mExamples;
113 QString mNotes;
114 QStringList mTags;
115};
116
117
118struct Help
119{
120 Help() = default;
121
122 Help( const QString &name, const QString &type, const QString &description, const QList<HelpVariant> &variants )
123 : mName( name )
124 , mType( type )
125 , mDescription( description )
126 , mVariants( variants )
127 {}
128
129 QString mName;
130 QString mType;
131 QString mDescription;
132 QList<HelpVariant> mVariants;
133};
134
135typedef QHash<QString, Help> HelpTextHash;
136
138#endif
139
196class CORE_EXPORT QgsExpression
197{
198 Q_DECLARE_TR_FUNCTIONS( QgsExpression )
199 public:
200#ifndef SIP_RUN
201 using SharedFunctionPtr = std::shared_ptr<QgsExpressionFunction>;
202
209 class CORE_EXPORT SharedFunctionPtrList : public QList< SharedFunctionPtr >
210 {
211 public:
220 int functionIndex( const QString &name ) const;
221
225 SharedFunctionPtr getFunction( int index ) const;
226
234
235 private:
236 QMap< QString, int> mFunctionIndexMap;
237 };
238
239 using FunctionListSnapshot = std::shared_ptr< const SharedFunctionPtrList >;
240#endif
241
288
295 QgsExpression( const QString &expr );
296
302 QgsExpression( const QgsExpression &other );
303
309 QgsExpression &operator=( const QgsExpression &other );
310
315 operator QString() const SIP_SKIP;
316
322
323 ~QgsExpression();
324
330 bool operator==( const QgsExpression &other ) const;
331
337 bool isValid() const;
338
340 bool hasParserError() const;
342 QString parserErrorString() const;
343
347 QList<QgsExpression::ParserError> parserErrors() const;
348
354 const QgsExpressionNode *rootNode() const;
355
360 bool prepare( const QgsExpressionContext *context );
361
379 QSet<QString> referencedColumns() const;
380
391 QSet<QString> referencedVariables() const;
392
402 QSet<QString> referencedFunctions() const;
403
404#ifndef SIP_RUN
405
412 QList<const QgsExpressionNode *> nodes() const;
413
420 template<class T> QList<const T *> findNodes() const
421 {
422 QList<const T *> lst;
423 const QList<const QgsExpressionNode *> allNodes( nodes() );
424 for ( const auto &node : allNodes )
425 {
426 const T *n = dynamic_cast<const T *>( node );
427 if ( n )
428 lst << n;
429 }
430 return lst;
431 }
432#endif
433
446 QSet<int> referencedAttributeIndexes( const QgsFields &fields ) const;
447
449 bool needsGeometry() const;
450
451 // evaluation
452
457 QVariant evaluate();
458
464 QVariant evaluate( const QgsExpressionContext *context );
465
467 bool hasEvalError() const;
469 QString evalErrorString() const;
471 void setEvalErrorString( const QString &str );
472
478 bool isField() const;
479
492 static int expressionToLayerFieldIndex( const QString &expression, const QgsVectorLayer *layer );
493
506 static QString quoteFieldExpression( const QString &expression, const QgsVectorLayer *layer );
507
515 static bool checkExpression( const QString &text, const QgsExpressionContext *context, QString &errorMessage SIP_OUT );
516
521 void setExpression( const QString &expression );
522
528 QString expression() const;
529
536 QString dump() const;
537
545 QgsDistanceArea *geomCalculator();
546
560 void setGeomCalculator( const QgsDistanceArea *calc );
561
568 Qgis::DistanceUnit distanceUnits() const;
569
578 void setDistanceUnits( Qgis::DistanceUnit unit );
579
586 Qgis::AreaUnit areaUnits() const;
587
596 void setAreaUnits( Qgis::AreaUnit unit );
597
608 static QString replaceExpressionText( const QString &action, const QgsExpressionContext *context, const QgsDistanceArea *distanceArea = nullptr );
609
617 static QSet<QString> referencedVariables( const QString &text );
618
628 static double evaluateToDouble( const QString &text, double fallbackValue );
629
642
648 SIP_SKIP static const FunctionListSnapshot getFunctionsSnapshot();
649
650 // NOTE tagged as deprecated as we don't want this used from c++ code
657 Q_DECL_DEPRECATED static QList<QgsExpressionFunction *> Functions();
658
664 static QStringList BuiltinFunctions();
665
673 static bool registerFunction( QgsExpressionFunction *function, bool transferOwnership = false );
674
680 static bool unregisterFunction( const QString &name );
681
685 static void cleanRegisteredFunctions();
686
688 static bool isFunctionName( const QString &name );
689
690 // NOTE tagged as deprecated as we don't want this used from c++ code
697 Q_DECL_DEPRECATED static int functionIndex( const QString &name );
698
703 static int functionCount();
704
710 static QString quotedColumnRef( QString name );
711
717 static QString quotedString( QString text );
718
726 static QString quotedValue( const QVariant &value );
727
736 static QString quotedValue( const QVariant &value, QMetaType::Type type );
737
747 Q_DECL_DEPRECATED static QString quotedValue( const QVariant &value, QVariant::Type type ) SIP_DEPRECATED;
748
750
751#ifndef SIP_RUN
753 static HelpTextHash &functionHelpTexts();
755#endif
756
763 static QString helpText( QString name );
764
770 static QStringList tags( const QString &name );
771
784 static bool addVariableHelpText( const QString name, const QString &description );
785
792 static QString variableHelpText( const QString &variableName );
793
802 static QString formatVariableHelp( const QString &description, bool showValue = true, const QVariant &value = QVariant() );
803
808 static QString group( const QString &group );
809
818 static QString formatPreviewString( const QVariant &value, bool htmlOutput = true, int maximumPreviewLength = 60 );
819
828 static QString createFieldEqualityExpression( const QString &fieldName, const QVariant &value, QMetaType::Type fieldType = QMetaType::Type::UnknownType );
829
839 Q_DECL_DEPRECATED static QString createFieldEqualityExpression( const QString &fieldName, const QVariant &value, QVariant::Type fieldType ) SIP_DEPRECATED;
840
851 static bool isFieldEqualityExpression( const QString &expression, QString &field SIP_OUT, QVariant &value SIP_OUT );
852
867 static bool attemptReduceToInClause( const QStringList &expressions, QString &result SIP_OUT );
868
878 QgsExpression simplified() const;
879
880 // clang-format off
881#ifdef SIP_RUN
882 SIP_PYOBJECT __repr__();
883 % MethodCode
884 QString str = u"<QgsExpression: '%1'>"_s.arg( sipCpp->expression() );
885 sipRes = PyUnicode_FromString( str.toUtf8().constData() );
886 % End
887#endif
888
889 private:
890 // clang-format on
891
892 void initGeomCalculator( const QgsExpressionContext *context );
893
900 void detach() SIP_SKIP;
901
902 QgsExpressionPrivate *d = nullptr;
903
904 static HelpTextHash sFunctionHelpTexts;
905
907 static void initFunctionHelp() SIP_SKIP;
909 static void buildFunctionHelp() SIP_SKIP;
911 static void initVariableHelp() SIP_SKIP;
913 static void buildVariableHelp() SIP_SKIP;
914
916
917#if defined( __clang__ )
919#else
920 static std::atomic<FunctionListSnapshot> sFunctions;
921#endif
922 static QMutex sFunctionWriteMutex;
923
924 static QStringList sBuiltinFunctionNames;
925
926 friend class QgsOgcUtils;
927};
928
930
931#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.