Expression Handling

Chapter Updated 07/06/26


Overview

The main objective of this chapter is to provide information regarding the basic concepts of using the Xbase64 Expression module.

The Xbase64 library includes an expression parsing routine which assists application programmers by providing a high level data manipulation tool and also allows for building complex index keys. The functions included were derived from dBASE version 3 through 12 and Clipper 5.

Expressions are primarily used for index key definitions and filter criteria, but can also be used for other tasks as well.

Internal fuctioning

The expression module works in two phases. Firstly, method ParseExpression is called and builds an expression tree from all the components of the expression. The tree is made up of individual nodes. The expression is checked for valid field names, literals, operands and functions. Any field references are resolved. If fields are used in an expression and the database name for the field is not included in the name with the -> operand, the routines assume the associated database has been successfully opened.

Secondly, method ProcessExpression is called to process the expression tree created by ParseExpression(). The routine parses each node in the expression tree, executing functions, processing operands and manipulating data to produce the desired result.

If an expression will be processed repeatedly, it is best to pre-parse the tree using ParseExpression, then for each new call to the expression, execute method ProcessExpression which processes the tree.

Expression Return Types

Expressions will return a base type of CHAR, NUMERIC, DATE, LOGICAL or TIMESTAMP.

An expression return type can be determined with method xbExp::GetReturnType after parsing it.

Beginning with release 4.2.8 there is also a subtype which can be accessed with method xbExp::GetSubType(). For NUMERIC base types, the sub type will be one of XB_EXP_FLOAT, XB_EXP_LONG, XB_EXP_AUTOINCREMENT or XB_EXP_TIME.

Expressions returning a return type of CHAR are limited to a 200 byte internal buffer. There is also a 100 byte limit for NDX and MDX index key support. If the 200 byte limit is not large enough for your application, adjust field enum { WorkBufMaxLen = 200 }; in file exp.h.

Return TypeXBase Type
CHARxbString
NUMERICxbDouble
DATExbDate
LOGICALxbBool
TIMESTAMPxbTimeStamp


Date routines return an xbDate result. In addition, the date value can be extracted using GetStringResult() which returns YYYYMMDD or GetDoubleResult() which returns a julian value.

Expression Functions

Each expression function also has a corresponding C++ function. It is slightly more efficient to call the C++ functions directly, rather than execute the expression parsing routines.

Function NameReturn TypeParametersDescription
ABS( num )NField name, numeric value or numeric expressionCalculate absolute value of a numeric expression.
ACOS( num )NField name, numeric value or numeric expressionCalculate the inverse cosine (arccosine) of a number in radians.
ALLTRIM( string )CField name, string or string expressionTrim leading and trailing whitespace from a string.
ASC( string )NField name, string or string expressionReturn ASCII code for first character in a string.
ASIN( num )NField name, numeric value or numeric expressionCalculate the inverse sine (arcsine) of a number in radians.
AT( needle, haystack )NField names or stringReturn starting position of a string within a string. Returns 0 if not found.
ATAN( num )NField name, numeric value or numeric expressionReturn inverse tangent (arctangent) of a number in radians.
ATN2( numSine, numCosine )NField names, numerivc values or numeric expressionsReturn inverse tangent (arctanget) of a given point.
CDOW( date )CDate field or date expression ie; STOD( "YYYYMMDD" )Retun character weekday name for a date.
CEILING( num )NField name, numeric value or numeric expressionRound up to nearest integer value.
CENTER( string, num, char)CString Expression, new size of centered string, pad characterReturn a centered string.
CHR( int )CInteger value or field.Convert numeric expression to a character.
CMONTH( date )CDate field or date expressionReturn month name for a date.
COS( num )NField name, numeric value or numeric expressionCalculate the cosine of an angle in radians.
CTOD( mm/dd/yy )DString date in mm/dd/yy formatConvert mm/dd/yy date to a yyyymmdd date.
CTODT( time stamp )N,TSOne of:
MM/DD/YY HH:MM:SS
YYYY-MM-DD HH:MM:SS
MM/DD/YY HH:MM
YYYY-MM-DD HH:MM.
MM/DD/YY
YYYY-MM-DD
HH:MM:SS
HH:MM
Convert string to time stamp.
CTOT( time )NOne of:
HH:MM:SS
HH:MM
Convert string to time.
DATE()DNoneReturn system date.
DATETIME()N,TSNoneReturn current system date and time as time stamp.
DAY( date )NDate field or date expressionReturn the day of the month from a date.
DBF()CNoneReturns the current database file name.
DEL()CNoneReturn record deletion status for a record.
DELETED()LNoneReturn record deletion status for a record.
DESCEND( expression )1Valid expressionClipper DESCEND function. Creates a compliment of the input expression.
Originally used for index tags that don't support descending keys.
DOW( date )NDate field or date expressionReturn number of day of week.
DTOC( date )CDate field or date expressionReturn character date from input date.
DTODT( date )N,TSDate field or date expressionReturn a time stamp field from a date input field.
DTOR( num )NDegreesReturn radian value of an angle from degrees input.
DTOS( date )CDate field or date expressionReturn character CCYYMMDD date from input date.
DTTOD( TimeStamp )NTimeStampTimeStamp to Date.
DTTOT( TimeStamp )NTimeStampTimestamp to Time.
ELAPSED( time, time )
ELAPSED( string, string )
Ntime valuesReturn difference between two times in seconds.
EMPTY( string )LString expressionReturns true if string expression is empty, else returns false.
EXP( num )NField name, numeric value or numeric expressionReturn exponent value.
FCOUNT()NNoneReturns number of fields in current DBF file.
FIELD( num )NField number, first field is 1Return field name for given field number.
FLDCOUNT()NNoneReturns number of fields in current DBF file.
FLOOR( num )NField name, numeric value or numeric expressionRound down to nearest integer value.
HTOI( string )NNoneHex to integer conversion.
IIF( Evaluation Expression, True Result Response, False Result Response )CValid expression input, equal length true and false valuesImmediate If.
INT( num )NNumberConvert number to integer, truncate any decimals.
ISALPHA( string )LString expressionCheck if string begins with alpha character.
ISBLANK( string )LString expressionCheck if empty or null.
ISLOWER( string )LString expressionCheck if string begins with lower case alpha character.
ISNULL( field name )LField nameCheck if a database field is null.
ISUPPER( string )LString expressionCheck if string begins with upper case character.
ITOH( num )CNumeric expressionInteger to hex conversion.
LEFT(string, count )CField name, string or string expression, number chars to extract from the leftReturn left characters from a string.
LEN( string )NField name, string or string expressionReturn length of string.
LOG( num )NField name, numeric value or numeric expressionCalculate logarithm.
LOG10( num )NField name, numeric value or numeric expressionCalculate base 10 logarithm.
LOWER( string )CField name, string or string expressionConvert upper case to lower case.
LTRIM( string )CField name, string or string expressionTrim white space from left side of a string.
MAX( num, num )NField names, numbers or numeric expressionsReturn higher of two values.
MIN( num, num )NField names, numbers or numeric expressionsReturn lesser of two values.
MOD( num, num )NField names, numbers or numeric expressionsReturn modulus of two values.
MONTH( date )NDate field or date expressionReturn number of month for a given date.
RECNO()NNoneReturn current rec number for a given table.
RECCOUNT()NNoneReturn number of records in a given table.
REPLICATE( string, num )CString expression, numeric expressionRepeat character expression N times.
RIGHT( string, num )CString expression, numeric expressionReturn right characters from as string.
RTRIM( string )CString expressionTrim white space from right side of string.
SECONDS()NNoneSeconds since midnight (local time).
SPACE( num )CNumeric expressionGenerate a string of N spaces.
SQRT( num )NNumeric expressionCalculate square root.
STOD( string )DString expression in yyyymmdd formatConvert 8 byte CCYYMMDD date to date.
STR( num )
STR( num, len )
STR( num, len, dec )
CNumeric expression, optional length, optional decimalConvert number to character string.
STRZERO( num )
STRZERO( num, len )
STRZERO( num, len, dec )
CNumeric expression, optional length, optional decimal. Convert number to character string with leading zeroes.
SUBSTR( string, startpos, len )CString expression, starting position, optional lengthExtract portion of one string from another string.
TRIM( string )CStrng expressionTrim white space from left and right sides of a string.
UPPER( string )CString expressionConvert lower case to upper case.
VAL( string )NString expressionConvert numeric characters to number.
YEAR( date )NDate field or date expressionReturn year for a given date.


Expression Components

Expressions are made up of one or more tokens. A token is one of literal, database field, operand or function. Literals are either numeric or character. Character literals are enclosed in 'single' or "double" quotes. numeric literals are a series of one or more contiguous numerals, ".", "+" or "-'".

A field is simply a field name in the default database, or is in the form of database->fieldname.

Expression Literals

TypeExample
CHAR"literal" or 'literal'
NUMERIC+99999.99
DATE{10/07/60} or {02/09/1989}
TIMESTAMP"CCYY-MM-DD HH:MM:SS
TIME"HH:MM:SS"


Expression Operators

TypeOperatorPrecedenceResultDescription
Parens()12Sets precedence
Numeric Operator+ (unary)11NNumeric unary
Numeric Operator- (unary)11NNumeric unary
Numeric Operator--X10NNumeric pre-decrement
Numeric Operator++X10NNumeric pre-increment
Numeric Operator**9NNumeric exponentiation
Numeric Operator^9NSame as **, exponentiation
Numeric Operator%8NModulus (Remainder)
Numeric Operator*8NNumeric multiplication
Numeric Operator/8NNumeric division
Numeric Operator+ Addition7NNumeric addition
Numeric Operator- Subtraction7NNumeric subtraction
Numeric OperatorX--6NNumeric post-decrement
Numeric OperatorX++6NNumeric post-increment
String Operator+5CConcatonate 1
String Operator-5CConcatonate 2
Relational Operator=, ==4LEquals operator
Relational Operator#, <>, !=4LNot equals operators
Relational Operator<4LLess than operator
Relational Operator>4LGreater than operator
Relational Operator<=4LLess than or equal oerator
Relational Operator>=4LGreater than or equal operator
Relational Operator$4LContains operator
Relational Operator==Clipper operator, not implemented yet
Logical OperatorNOT3LLogical NOT
Logical Operator.NOT.3LLogicial NOT
Logical OperatorAND2LLogical AND
Logical Operator.AND.2LLogical AND
Logical OperatorOR1LLogical OR
Logical Operator.OR.1LLogical OR


Adding New Functions

To add a new function, find a function that is similar to what you need to use as an example and take the following steps.

Example Expressions

  • FieldName
  • "SomeText"
  • 'SomeText'
  • 27.4
  • {01/03/1988}
  • CUSTOMERS->LNAME + ", " + CUSTOMERS->FNAME
  • LNAME + ", " + FNAME
  • STARTDT + 90
  • DATE() - 7
  • YEAR( DATE() )
  • IIF( "A" = "N", "true result ", "false result" )
  • IIF( "A" = "N" .OR. 2 > 1 , "true result ", "false result" )
  • IIF( .NOT. "A" = "N", "true result ", "false result" )
  • .NOT. DELETED()

    Example program

    For an example on how to use the expression logic, see program src/examples/xb_ex_expression.cpp.