Skip to content

πŸ”₯ πŸ”₯ πŸ”₯ A Free & Self-hostable Airtable Alternative

WIP on formula return column info

Fendy Heryantoecd699f28981
diff --git a/packages/nocodb-sdk/src/lib/formula/operators.ts b/packages/nocodb-sdk/src/lib/formula/operators.ts
index e3b0bb7166..bc9e2d9f2c 100644
--- a/packages/nocodb-sdk/src/lib/formula/operators.ts
+++ b/packages/nocodb-sdk/src/lib/formula/operators.ts
@@ -1,4 +1,5 @@
import { FormulaDataTypes, JSEPNode } from './enums';
+import { ReferencedInfo } from './types';
export const StringOperators = ['||', '&'] as const;
export const ArithmeticOperators = ['+', '-', '*', '/'] as const;
@@ -19,7 +20,7 @@ export type BaseFormulaNode = {
dataType?: FormulaDataTypes;
cast?: FormulaDataTypes;
errors?: Set<string>;
-};
+} & ReferencedInfo;
export interface BinaryExpressionNode extends BaseFormulaNode {
operator: ArithmeticOperator | ComparisonOperator | StringOperator;
diff --git a/packages/nocodb-sdk/src/lib/formula/referenced-info-extractor.ts b/packages/nocodb-sdk/src/lib/formula/referenced-info-extractor.ts
new file mode 100644
index 0000000000..efc8958d05
--- /dev/null
+++ b/packages/nocodb-sdk/src/lib/formula/referenced-info-extractor.ts
@@ -0,0 +1,264 @@
+import { uniq } from '../arrayHelpers';
+import UITypes from '../UITypes';
+import { FormulaDataTypes } from './enums';
+import {
+ BinaryExpressionNode,
+ CallExpressionNode,
+ ParsedFormulaNode,
+} from './operators';
+import { ReferencedInfo } from './types';
+
+const IMPURE_OPR_UIDT_MAP = new Map<UITypes, UITypes>([
+ [UITypes.SingleSelect, UITypes.SingleLineText],
+ [UITypes.MultiSelect, UITypes.SingleLineText],
+ [UITypes.Attachment, UITypes.SingleLineText],
+ [UITypes.User, UITypes.SingleLineText],
+ [UITypes.Email, UITypes.SingleLineText],
+ [UITypes.URL, UITypes.SingleLineText],
+ [UITypes.Number, UITypes.Decimal],
+ [UITypes.Rating, UITypes.Decimal],
+ [UITypes.Year, UITypes.Number],
+ [UITypes.Year, UITypes.Number],
+]);
+
+export const extractColumnReferencedInfo = ({
+ col,
+}: {
+ col: Record<string, any>;
+}) => {
+ const result: {
+ referencedColumn?: { id: string; uidt: string };
+ uidtCandidates: UITypes[];
+ } = { uidtCandidates: [] };
+ switch (col.uidt) {
+ case UITypes.SingleLineText:
+ case UITypes.SingleSelect:
+ case UITypes.MultiSelect:
+ case UITypes.Email:
+ case UITypes.URL:
+ case UITypes.LongText:
+ case UITypes.PhoneNumber:
+ case UITypes.Number:
+ case UITypes.Decimal:
+ case UITypes.Currency:
+ case UITypes.Percent:
+ case UITypes.Rating:
+ case UITypes.User: {
+ result.referencedColumn = { id: col.id, uidt: col.uidt };
+ result.uidtCandidates.push(col.uidt);
+ break;
+ }
+ }
+ return result;
+};
+
+const filterReferencedInfoByUidt = ({
+ referencedInfo,
+ allowedUidts,
+ defaultUidt,
+ // isPureOperation = operation that don't modify the value
+ // meaningful enough to change it's display value, like TRIM, ARRAYUNIQUE
+ isPureOperation = false,
+}: {
+ referencedInfo: ReferencedInfo;
+ allowedUidts: UITypes[];
+ defaultUidt: UITypes;
+ isPureOperation?: boolean;
+}): ReferencedInfo => {
+ const referencedColumn =
+ referencedInfo.referencedColumn &&
+ allowedUidts.includes(referencedInfo.referencedColumn.uidt as UITypes) &&
+ (isPureOperation ||
+ !IMPURE_OPR_UIDT_MAP.has(referencedInfo.referencedColumn.uidt as UITypes))
+ ? referencedInfo.referencedColumn
+ : undefined;
+ let uidtCandidates = referencedInfo.uidtCandidates.filter((uidt) =>
+ allowedUidts.includes(uidt)
+ );
+ if (isPureOperation) {
+ uidtCandidates = uidtCandidates.map((c) =>
+ IMPURE_OPR_UIDT_MAP.get(c as UITypes)
+ );
+ }
+ return {
+ ...referencedInfo,
+ referencedColumn,
+ uidtCandidates:
+ uidtCandidates.length > 0 ? uniq(uidtCandidates) : [defaultUidt],
+ invalidForReferenceColumn:
+ referencedInfo.invalidForReferenceColumn ||
+ // if the referencedColumn is somehow filtered out, make it invalidForReferenceColumn
+ !!referencedColumn !== !!referencedInfo.referencedColumn,
+ };
+};
+
+export const getReferencedInfoFromArgs = (
+ nodes: ParsedFormulaNode[],
+ dataType: FormulaDataTypes,
+ option: {
+ isPureOperation?: boolean;
+ } = { isPureOperation: false }
+): ReferencedInfo => {
+ let referencedColumn: { id: string; uidt: string };
+ let invalidForReferenceColumn = nodes
+ .map((c) => c.invalidForReferenceColumn)
+ .reduce((acc, cur) => acc || cur, false);
+ const referencedColumns = invalidForReferenceColumn
+ ? []
+ : nodes.map((k) => k.referencedColumn).filter((k) => k);
+ const uniqueLength = uniq(referencedColumns.map((k) => k.id)).length;
+ if (uniqueLength === 1) {
+ referencedColumn = referencedColumns[0];
+ } else if (uniqueLength > 1) {
+ invalidForReferenceColumn = true;
+ }
+ const uidtCandidates = nodes.map((k) => k.uidtCandidates).flat();
+ const referencedInfo = {
+ referencedColumn,
+ uidtCandidates,
+ invalidForReferenceColumn,
+ };
+
+ switch (dataType) {
+ case FormulaDataTypes.BOOLEAN: {
+ return filterReferencedInfoByUidt({
+ referencedInfo,
+ allowedUidts: [UITypes.Checkbox],
+ defaultUidt: UITypes.Checkbox,
+ ...option,
+ });
+ }
+ case FormulaDataTypes.COND_EXP: {
+ return filterReferencedInfoByUidt({
+ referencedInfo,
+ allowedUidts: [UITypes.Checkbox],
+ defaultUidt: UITypes.Checkbox,
+ ...option,
+ });
+ }
+ case FormulaDataTypes.STRING: {
+ return filterReferencedInfoByUidt({
+ referencedInfo,
+ allowedUidts: [
+ UITypes.SingleLineText,
+ UITypes.LongText,
+ UITypes.Email,
+ UITypes.URL,
+ ],
+ defaultUidt: UITypes.SingleLineText,
+ ...option,
+ });
+ }
+ case FormulaDataTypes.NUMERIC: {
+ return filterReferencedInfoByUidt({
+ referencedInfo,
+ allowedUidts: [
+ UITypes.Number,
+ UITypes.Decimal,
+ UITypes.Currency,
+ UITypes.Percent,
+ UITypes.Rating,
+ ],
+ defaultUidt: UITypes.Decimal,
+ ...option,
+ });
+ }
+ case FormulaDataTypes.DATE: {
+ return filterReferencedInfoByUidt({
+ referencedInfo,
+ allowedUidts: [UITypes.Date, UITypes.DateTime],
+ defaultUidt: UITypes.DateTime,
+ ...option,
+ });
+ }
+ case FormulaDataTypes.INTERVAL: {
+ return filterReferencedInfoByUidt({
+ referencedInfo,
+ allowedUidts: [UITypes.Time, UITypes.Duration],
+ defaultUidt: UITypes.Time,
+ ...option,
+ });
+ }
+ default: {
+ return {
+ uidtCandidates: [UITypes.SingleLineText],
+ invalidForReferenceColumn,
+ } as ReferencedInfo;
+ }
+ }
+};
+
+export const extractBinaryExpReferencedInfo = ({
+ parsedTree,
+ left,
+ right,
+}: {
+ parsedTree: BinaryExpressionNode;
+ left: ParsedFormulaNode;
+ right: ParsedFormulaNode;
+}) => {
+ return getReferencedInfoFromArgs([left, right], parsedTree.dataType, {
+ isPureOperation: false,
+ });
+};
+
+export const extractCallExpressionReferencedInfo = ({
+ parsedTree,
+}: {
+ parsedTree: CallExpressionNode;
+}) => {
+ let nodeArgs = parsedTree.arguments ?? [];
+ let isPureOperation = false;
+ switch (parsedTree.callee.name) {
+ case 'TRIM':
+ case 'MAX':
+ case 'MIN':
+ isPureOperation = true;
+ break;
+ case 'ARRAYUNIQUE':
+ case 'ARRAYSORT':
+ case 'ARRAYCOMPACT':
+ case 'ARRAYSLICE':
+ nodeArgs = nodeArgs.slice(0, 1);
+ isPureOperation = true;
+ break;
+ case 'IF': {
+ nodeArgs = nodeArgs.slice(1);
+ // is pure operation if the 2nd and 3rd arguments only has data type NULL or single referenced column
+ const uniqueReferencedColumnIds = uniq(
+ nodeArgs.map((n) => n.referencedColumn?.id).filter((k) => k)
+ );
+ const notNullDataTypes = nodeArgs
+ .filter(
+ (n) => !n.referencedColumn && n.dataType !== FormulaDataTypes.NULL
+ )
+ .map((n) => n.dataType);
+
+ isPureOperation =
+ notNullDataTypes.length === 0 && uniqueReferencedColumnIds.length <= 1;
+ break;
+ }
+ case 'SWITCH': {
+ nodeArgs = nodeArgs.slice(1).filter((_val, index) => index % 2 === 1);
+ // is pure operation if resulting arguments only has data type NULL or single referenced column
+
+ // is pure operation if the 2nd and 3rd arguments only has data type NULL or single referenced column
+ const uniqueReferencedColumnIds = uniq(
+ nodeArgs.map((n) => n.referencedColumn?.id).filter((k) => k)
+ );
+ const notNullDataTypes = nodeArgs
+ .filter(
+ (n) => !n.referencedColumn && n.dataType !== FormulaDataTypes.NULL
+ )
+ .map((n) => n.dataType);
+
+ isPureOperation =
+ notNullDataTypes.length === 0 && uniqueReferencedColumnIds.length <= 1;
+
+ break;
+ }
+ }
+ return getReferencedInfoFromArgs(nodeArgs, parsedTree.dataType, {
+ isPureOperation,
+ });
+};
diff --git a/packages/nocodb-sdk/src/lib/formula/types.ts b/packages/nocodb-sdk/src/lib/formula/types.ts
index fe85bb9726..249f152a01 100644
--- a/packages/nocodb-sdk/src/lib/formula/types.ts
+++ b/packages/nocodb-sdk/src/lib/formula/types.ts
@@ -1,4 +1,11 @@
+import { SqlUiFactory } from '../sqlUi';
+import UITypes from '../UITypes';
import { FormulaDataTypes } from './enums';
+export interface ReferencedInfo {
+ referencedColumn?: { id: string; uidt: string };
+ invalidForReferenceColumn?: boolean;
+ uidtCandidates: UITypes[];
+}
export interface FormulaMeta {
validation?: {
@@ -19,3 +26,14 @@ export interface FormulaMeta {
returnType?: ((args: any[]) => FormulaDataTypes) | FormulaDataTypes;
docsUrl?: string;
}
+export type SqlUI = ReturnType<(typeof SqlUiFactory)['create']>;
+export type ClientTypeOrSqlUI =
+ | 'mysql'
+ | 'pg'
+ | 'sqlite3'
+ | 'mysql2'
+ | 'oracledb'
+ | 'mariadb'
+ | 'sqlite'
+ | 'snowflake'
+ | SqlUI;
diff --git a/packages/nocodb-sdk/src/lib/formula/validate-extract-tree.ts b/packages/nocodb-sdk/src/lib/formula/validate-extract-tree.ts
index 036752a8c6..4ec55f42df 100644
--- a/packages/nocodb-sdk/src/lib/formula/validate-extract-tree.ts
+++ b/packages/nocodb-sdk/src/lib/formula/validate-extract-tree.ts
@@ -17,22 +17,15 @@ import {
IdentifierNode,
ParsedFormulaNode,
} from './operators';
-import { SqlUiFactory } from '../sqlUi';
import { handleFormulaError } from './handle-formula-error';
import { formulas } from './formulas';
import { jsepCurlyHook, jsepIndexHook } from './hooks';
-
-type SqlUI = ReturnType<(typeof SqlUiFactory)['create']>;
-type ClientTypeOrSqlUI =
- | 'mysql'
- | 'pg'
- | 'sqlite3'
- | 'mysql2'
- | 'oracledb'
- | 'mariadb'
- | 'sqlite'
- | 'snowflake'
- | SqlUI;
+import { ClientTypeOrSqlUI } from './types';
+import { SqlUiFactory } from '../sqlUi';
+import {
+ extractBinaryExpReferencedInfo,
+ extractCallExpressionReferencedInfo,
+} from './referenced-info-extractor';
async function extractColumnIdentifierType({
col,
@@ -48,6 +41,7 @@ async function extractColumnIdentifierType({
const res: {
dataType?: FormulaDataTypes;
errors?: Set<string>;
+ referencedColumn?: { id: string; uidt: string };
[p: string]: any;
} = {};
const sqlUI =
@@ -68,6 +62,7 @@ async function extractColumnIdentifierType({
case UITypes.CreatedBy:
case UITypes.LastModifiedBy:
res.dataType = FormulaDataTypes.STRING;
+ res.referencedColumn = { id: col.id, uidt: col.uidt };
break;
// numeric
case UITypes.Year:
@@ -77,6 +72,7 @@ async function extractColumnIdentifierType({
case UITypes.Count:
case UITypes.AutoNumber:
res.dataType = FormulaDataTypes.NUMERIC;
+ res.referencedColumn = { id: col.id, uidt: col.uidt };
break;
// date
case UITypes.Date:
@@ -84,6 +80,7 @@ async function extractColumnIdentifierType({
case UITypes.CreatedTime:
case UITypes.LastModifiedTime:
res.dataType = FormulaDataTypes.DATE;
+ res.referencedColumn = { id: col.id, uidt: col.uidt };
break;
case UITypes.Currency:
@@ -91,6 +88,7 @@ async function extractColumnIdentifierType({
case UITypes.Duration:
case UITypes.Links:
res.dataType = FormulaDataTypes.NUMERIC;
+ res.referencedColumn = { id: col.id, uidt: col.uidt };
break;
case UITypes.Rollup:
@@ -142,6 +140,7 @@ async function extractColumnIdentifierType({
case UITypes.Attachment:
res.dataType = FormulaDataTypes.STRING;
+ res.referencedColumn = { id: col.id, uidt: col.uidt };
break;
case UITypes.Checkbox:
if (col.dt === 'boolean' || col.dt === 'bool') {
@@ -149,9 +148,11 @@ async function extractColumnIdentifierType({
} else {
res.dataType = FormulaDataTypes.NUMERIC;
}
+ res.referencedColumn = { id: col.id, uidt: col.uidt };
break;
case UITypes.Time:
res.dataType = FormulaDataTypes.INTERVAL;
+ res.referencedColumn = { id: col.id, uidt: col.uidt };
break;
case UITypes.ID:
case UITypes.ForeignKey:
@@ -776,6 +777,13 @@ export async function validateFormulaAndExtractTreeWithType({
} else if (formulas[calleeName].returnType) {
res.dataType = formulas[calleeName].returnType as FormulaDataTypes;
}
+
+ Object.assign(
+ res,
+ extractCallExpressionReferencedInfo({
+ parsedTree: res as CallExpressionNode,
+ })
+ );
} else if (parsedTree.type === JSEPNode.IDENTIFIER) {
const identifierName = (parsedTree as IdentifierNode).name;
const col = (colIdToColMap[identifierName] ||
@@ -899,12 +907,10 @@ export async function validateFormulaAndExtractTreeWithType({
);
}
} else if (parsedTree.type === JSEPNode.BINARY_EXP) {
- (res as BinaryExpressionNode).left = await validateAndExtract(
- parsedTree.left
- );
- (res as BinaryExpressionNode).right = await validateAndExtract(
- parsedTree.right
- );
+ const argsLeft = await validateAndExtract(parsedTree.left);
+ const argsRight = await validateAndExtract(parsedTree.right);
+ (res as BinaryExpressionNode).left = argsLeft;
+ (res as BinaryExpressionNode).right = argsRight;
const dateAndTimeParsedNode = handleBinaryExpressionForDateAndTime({
sourceBinaryNode: res as any,
@@ -948,6 +954,15 @@ export async function validateFormulaAndExtractTreeWithType({
} else {
res.dataType = FormulaDataTypes.NUMERIC;
}
+
+ Object.assign(
+ res,
+ extractBinaryExpReferencedInfo({
+ parsedTree: res as BinaryExpressionNode,
+ left: argsLeft,
+ right: argsRight,
+ })
+ );
} else if (parsedTree.type === JSEPNode.MEMBER_EXP) {
throw new FormulaError(
FormulaErrorType.NOT_SUPPORTED,
diff --git a/packages/nocodb-sdk/src/lib/formulaHelpers.spec.ts b/packages/nocodb-sdk/src/lib/formulaHelpers.spec.ts
index bff8190bcf..795e00b4a0 100644
--- a/packages/nocodb-sdk/src/lib/formulaHelpers.spec.ts
+++ b/packages/nocodb-sdk/src/lib/formulaHelpers.spec.ts
@@ -51,7 +51,6 @@ describe('Formula parsing and type validation', () => {
clientOrSqlUi: 'mysql2',
getMeta: async () => ({}),
});
-
expect(result.dataType).toEqual(FormulaDataTypes.STRING);
const result1 = await validateFormulaAndExtractTreeWithType({
@@ -297,4 +296,129 @@ describe('Formula parsing and type validation', () => {
}
});
});
+
+ describe.only('referenced info', () => {
+ it(`will return referenced column when directly referenced`, async () => {
+ const result = await validateFormulaAndExtractTreeWithType({
+ formula: '{column1}',
+ columns: [
+ {
+ id: 'id1',
+ title: 'column1',
+ uidt: UITypes.Number,
+ },
+ ],
+ clientOrSqlUi: 'mysql2',
+ getMeta: async () => ({}),
+ });
+
+ expect(result.referencedColumn.id).toEqual('id1');
+ expect(result.referencedColumn.uidt).toEqual(UITypes.Number);
+ });
+ it(`will return referenced column with binary operation`, async () => {
+ const supportedTypes = [
+ UITypes.Decimal,
+ UITypes.Currency,
+ UITypes.Percent,
+ UITypes.SingleLineText,
+ UITypes.LongText,
+ ];
+ for (const supportedType of supportedTypes) {
+ const result = await validateFormulaAndExtractTreeWithType({
+ formula: '{column1} + 3',
+ columns: [
+ {
+ id: 'id1',
+ title: 'column1',
+ uidt: supportedType,
+ },
+ ],
+ clientOrSqlUi: 'mysql2',
+ getMeta: async () => ({}),
+ });
+ expect(result.referencedColumn.id).toEqual('id1');
+ expect(result.referencedColumn.uidt).toEqual(supportedType);
+ }
+ });
+ it(`will not return referenced column with impure binary operation`, async () => {
+ const result = await validateFormulaAndExtractTreeWithType({
+ formula: '{column1} + 3',
+ columns: [
+ {
+ id: 'id1',
+ title: 'column1',
+ uidt: UITypes.Number,
+ },
+ ],
+ clientOrSqlUi: 'mysql2',
+ getMeta: async () => ({}),
+ });
+ expect(result.referencedColumn).toBeUndefined();
+ expect(result.uidtCandidates).toEqual([UITypes.Decimal]);
+ });
+ it(`will not return referenced column when multiple columns is used`, async () => {
+ const result = await validateFormulaAndExtractTreeWithType({
+ formula: '{column1} + {column2}',
+ columns: [
+ {
+ id: 'id1',
+ title: 'column1',
+ uidt: UITypes.Decimal,
+ },
+ {
+ id: 'id2',
+ title: 'column2',
+ uidt: UITypes.Decimal,
+ },
+ ],
+ clientOrSqlUi: 'mysql2',
+ getMeta: async () => ({}),
+ });
+
+ expect(result.referencedColumn).toBeUndefined();
+ const result2 = await validateFormulaAndExtractTreeWithType({
+ formula: '{column1} + ({column2} + {column3})',
+ columns: [
+ {
+ id: 'id1',
+ title: 'column1',
+ uidt: UITypes.Decimal,
+ },
+ {
+ id: 'id2',
+ title: 'column2',
+ uidt: UITypes.Decimal,
+ },
+ {
+ id: 'id3',
+ title: 'column3',
+ uidt: UITypes.Decimal,
+ },
+ ],
+ clientOrSqlUi: 'mysql2',
+ getMeta: async () => ({}),
+ });
+
+ expect(result2.referencedColumn).toBeUndefined();
+ const result3 = await validateFormulaAndExtractTreeWithType({
+ formula: '{column1} + ({column2} + 1)',
+ columns: [
+ {
+ id: 'id1',
+ title: 'column1',
+ uidt: UITypes.Decimal,
+ },
+ {
+ id: 'id2',
+ title: 'column2',
+ uidt: UITypes.Number,
+ },
+ ],
+ clientOrSqlUi: 'mysql2',
+ getMeta: async () => ({}),
+ });
+
+ expect(result3.referencedColumn).toBeUndefined();
+ });
+ });
});