Skip to main content

Formulas

The JitAI Formula Engine supports a wide range of functions, including inline formulas (numeric calculation, date processing, text manipulation, logical operations) and database column aggregation functions. All function names use UPPERCASE.

This document is organized by function category, providing parameter descriptions, functionality details, and usage examples for each function.

Core Concepts

Inline Formulas

  • Configuration Location: The formula attribute of a data type field (string type).
  • Syntax Example: "MAX(F('f1'), F('f2')) + 100"
  • Transformation Logic: Automatically converted to SQL expressions during ORM parsing.
  • Features: Supports nested function calls and arithmetic operations.

Column Aggregation Functions

  • Configuration Location: The Formula object in a Select expression.
  • Syntax Example: Select([F(Formula('COLSUM(F("f1"))'))], From(...))
  • Transformation Logic: Generates aggregate query SQL (e.g., SUM(f1)).

General Rules

  • Function names must be ALL UPPERCASE.
  • Field reference format: F('FieldID').
  • Supports constant values and basic operators (+, -, *, /).

Configuration Examples

Inline Formula Configuration

# Data Type Definition
NumberField(
name="Total Score",
# Auto-calculation: (Business Ability + Communication Ability) / 2, rounded to 1 decimal place
formula="ROUND(AVG(F('business_ability'), F('communication_ability')), 1)"
)

Generated SQL Example:

SELECT ROUND(AVG(business_ability + communication_ability)/2, 1) AS Total Score

Column Aggregation Configuration

# Statistical query directly via queryset
model.queryset.select(F(Formula("COLSUM(F(\"score\"))"), "total")).all()

# Select Expression (for charts or aggregate tables)
select = Select([
F(Formula('COLAVG(F("score"))')),
F(Formula('COLMAX(F("age"))'))
],
From(['user_table', "u"])
)

Generated SQL Example:

SELECT AVG(score), MAX(age) FROM user_table as u

Function Reference

Inline Formula Functions

Numeric Calculation

FunctionParametersDescriptionExample
MAX1-10 paramsReturns the maximum value among all parameters.MAX(2,4,3) = 4
MIN1-10 paramsReturns the minimum value among all parameters.MIN(2,4,3) = 2
AVG1-10 paramsReturns the average of all parameters.AVG(2,4,3) = 3
SUM1-10 paramsReturns the sum of all parameters.SUM(2,4,3) = 9
ROUNDvalue, decimalsRounds the value to the specified number of decimal places.ROUND(2.456, 2) = 2.46
TRUNCATEvalue, decimalsTruncates the value to the specified number of decimal places (without rounding).TRUNCATE(2.456, 2) = 2.45
POWERvalue, exponentReturns the value raised to the power of the exponent.POWER(3, 2) = 9
ABSvalueReturns the absolute value of a number.ABS(-4) = 4
MODdividend, divisorReturns the remainder of a division.MOD(10,4) = 2
RANDOMmin, max, decimalsGenerates a random real number between min and max with specified decimal places.RANDOM(1, 10, 1) = 2.5

Date Processing

FunctionParametersDescriptionExample
NOWNoneReturns the current date and time.NOW() = 2022-01-28 12:12:12
TODAYNoneReturns the current date.TODAY() = 2022-01-28
DATESTRdateConverts a date to a string.DATESTR(2022-01-28) = "20220128"
EXTRACTdate, unitExtracts part of a date. Units: 'Y' (Year), 'M' (Month), 'D' (Day).EXTRACT(2022-01-28, 'Y') = 2022
DATEDELTAdate1, date2, unitReturns the difference between two dates.DATEDELTA(2022-01-28, 2022-01-22, 'D') = 6
DATEADDdate, value, unitAdds a specified time interval to a date.DATEADD(2022-01-28, 2, 'D') = 2022-01-30
MONTHDAYSdateReturns the number of days in the month of the given date.MONTHDAYS(2022-01-28) = 31
DAYOFYEARdateReturns the day of the year (1-366).DAYOFYEAR(2022-01-28) = 28
WEEKOFYEARdateReturns the week number of the year.WEEKOFYEAR(2022-01-28) = 5
DATEyear, month, dayConstructs a date from year, month, and day.DATE(2022, 1, 28) = 2022-01-28
WEEKDAYNUMdateReturns the day of the week as a number.WEEKDAYNUM(2022-01-28) = 6
WEEKDAYSTRdateReturns the day of the week as text.WEEKDAYSTR(2022-01-28) = 'Saturday'
MONTHSTARTdateReturns the first day of the month.MONTHSTART(2022-01-28) = 2022-01-01
MONTHENDdateReturns the last day of the month.MONTHEND(2022-01-28) = 2022-01-31
YEARfieldTruncates to the start of the year.YEAR(2023-12-31) = 2023-01-01
YEARQUARTERfieldTruncates to the start of the quarter.YEARQUARTER(2023-12-31) = 2023-10-01
YEARMONTHfieldTruncates to the start of the month.YEARMONTH(2023-12-31) = 2023-12-01
YEARWEEKfieldTruncates to the Monday of the week.YEARWEEK(2023-2-2) = 2023-1-30
YEARMONTHDAYfieldTruncates to the day (removes time).YEARWEEK(2023-1-1 12:12:12) = 2023-1-1

Text Manipulation

FunctionParametersDescriptionExample
CONCAT2+ paramsConcatenates multiple strings.CONCAT('a', 'b', 'c') = "abc"
REPLACEtext, match, replaceReplaces all occurrences of a substring.REPLACE('abc', 'b', 'x') = "axc"
INSERTtext, pos, len, newReplaces a specified length of characters starting at a position.INSERT('abc', 2, 2, 'xx') = "axx"
LEFTtext, lengthreturns the leftmost characters.LEFT('abc', 2) = "ab"
RIGHTtext, lengthReturns the rightmost characters.RIGHT('abc', 2) = "bc"
MIDtext, pos, lengthExtracts a substring starting at a position.MID('abcd', 2, 3) = "bcd"
LENtextReturns the length of the string.LEN('abcd') = 4
TRIMtextRemoves leading and trailing whitespace.TRIM(' abcd ') = "abcd"
LOCATEsub, textChecks if text contains the substring (Boolean).LOCATE('a', 'abc') = True
IDCARDBIRTHDAYid_cardExtracts birth date from a Chinese ID card.IDCARDBIRTHDAY('...') = 1999-03-02
IDCARDSEXid_cardExtracts gender from a Chinese ID card.IDCARDSEX('...') = "Male"

Logical Operations

FunctionParametersDescriptionExample
IFcond, true_val, false_valReturns true_val if condition is met, else false_val.IF(2>1, 3, 2) = 3
IFS(cond, val)..., defaultChecks multiple conditions; returns value of first TRUE condition.IFS(3>2, 0, 2>2, 1, 2) = 0
AND1-10 conditionsReturns True if all conditions are met.AND(2>1, 3>1) = True
OR1-10 conditionsReturns True if any condition is met.OR(2>1, 0>1) = True
EMPTYNoneReturns a null value (None).EMPTY() = None
ISEMPTYexprReturns True if expression is empty.ISEMPTY(1) = False
ISNOTEMPTYexprReturns True if expression is not empty.ISNOTEMPTY(1) = True
EMPTYSTRNoneReturns an empty string.EMPTYSTR() = ""
DEFAULTVALUEvalue, defaultReturns default if value is empty.DEFAULTVALUE(None, 2) = 2

Database Column Functions

Configured in Select expressions for aggregation statistics.

FunctionParametersDescription
COLSUMFieldSum of the column values meeting the condition.
COLAVGFieldAverage of the column values meeting the condition.
COLMAXFieldMaximum value in the column meeting the condition.
COLMINFieldMinimum value in the column meeting the condition.
COUNTFieldCount of non-null values in the column meeting the condition.
DISTINCTFieldCount of distinct values in the column meeting the condition.
STDDEVFieldStandard deviation of the column values.
VARIANCEFieldVariance of the column values.
MEDIANFieldMedian of the column values.
FILLFieldCount of non-null values (Alias for COUNT).
NOTFILLFieldCount of Null values in the column.
COUNTFIELDFieldCount of non-null values (Alias for COUNT).
SELECTEDFieldCount of selected items (typically for multi-select fields).
NOTSELECTEDFieldCount of unselected items.

Advanced Usage

Nested Functions

# Check if sales target is met and concatenate department name
"""
IF(COLSUM(F('sales')) > 100000,
CONCAT('Target Met:', F('dept')),
CONCAT('Target Missed:', F('dept')))
"""

Mixed Operations

# Calculate total price after discount
"(F('price') * F('quantity')) - DISCOUNT(F('vip_level'))"

Notes

Syntax Specifications
  1. Field Reference: Must use the F('FieldID') format.
  2. String Parameters: Must be enclosed in single quotes, e.g., CONCAT(F('last_name'), '·', F('first_name')).
  3. Date Format: Date literals must follow ISO format, e.g., DATE('2023-12-31').
  4. Aggregation Limits: Aggregation functions cannot be nested.
  5. Null Handling: It is recommended to use DEFAULTVALUE to handle potential null values, e.g., DEFAULTVALUE(F('score'), 0).
JitAI AssistantBeta
Powered by JitAI