Skip to content

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

improve error handling and track position

Fendy Heryanto6613f3d431da
diff --git a/packages/nc-gui/components/smartsheet/column/ButtonOptions/index.vue b/packages/nc-gui/components/smartsheet/column/ButtonOptions/index.vue
index db0d682b1f..8d71e3391d 100644
--- a/packages/nc-gui/components/smartsheet/column/ButtonOptions/index.vue
+++ b/packages/nc-gui/components/smartsheet/column/ButtonOptions/index.vue
@@ -132,6 +132,7 @@ const validators = {
columns: supportedColumns.value,
clientOrSqlUi: sqlUi.value,
getMeta,
+ trackPosition: true,
})
} catch (e: any) {
if (e instanceof FormulaError && e.extra?.key) {
diff --git a/packages/nc-gui/components/smartsheet/column/FormulaOptions.vue b/packages/nc-gui/components/smartsheet/column/FormulaOptions.vue
index fe0ccb93ce..bbee951f8c 100644
--- a/packages/nc-gui/components/smartsheet/column/FormulaOptions.vue
+++ b/packages/nc-gui/components/smartsheet/column/FormulaOptions.vue
@@ -76,6 +76,7 @@ const validators = {
columns: supportedColumns.value,
clientOrSqlUi: sqlUi.value,
getMeta,
+ trackPosition: true,
})
editorError.value = { ...defaultEditorError }
} catch (e: any) {
@@ -136,6 +137,7 @@ const debouncedValidate = useDebounceFn(async () => {
column: column.value ?? undefined,
clientOrSqlUi: source.value?.type as any,
getMeta: async (modelId) => await getMeta(modelId),
+ trackPosition: true,
})
// Update parsedTree only if this is the latest invocation
diff --git a/packages/nc-gui/lang/en.json b/packages/nc-gui/lang/en.json
index a4347b7fee..608daf1ac9 100644
--- a/packages/nc-gui/lang/en.json
+++ b/packages/nc-gui/lang/en.json
@@ -1984,7 +1984,8 @@
"columnNotAvailable": "Field {columnName} is not available",
"cantSaveCircularReference": "Can’t save field because it causes a circular reference",
"columnWithTypeFoundButExpected": "Field {columnName} with {columnType} type is found but {expectedType} type is expected",
- "columnNotMatchedWithType": "{columnName} is not matched with {columnType}"
+ "columnNotMatchedWithType": "{columnName} is not matched with {columnType}",
+ "formulaMissingParentheses": "Missing parentheses after function name \"{calleeName}\""
},
"selectOption": {
"cantBeNull": "Select options can't be null",
diff --git a/packages/nocodb-sdk/src/lib/formulaHelpers.spec.ts b/packages/nocodb-sdk/src/lib/formulaHelpers.spec.ts
index ed43b9e8fe..0ce26521c0 100644
--- a/packages/nocodb-sdk/src/lib/formulaHelpers.spec.ts
+++ b/packages/nocodb-sdk/src/lib/formulaHelpers.spec.ts
@@ -158,6 +158,7 @@ describe('Formula parsing and type validation', () => {
columns: [],
clientOrSqlUi: 'mysql2',
getMeta: async () => ({}),
+ trackPosition: true,
});
} catch (ex) {
expect(ex.extra.position).toEqual({
@@ -172,6 +173,7 @@ describe('Formula parsing and type validation', () => {
columns: [],
clientOrSqlUi: 'mysql2',
getMeta: async () => ({}),
+ trackPosition: true,
});
} catch (ex) {
expect(ex.extra.position).toEqual({
@@ -188,6 +190,7 @@ describe('Formula parsing and type validation', () => {
columns: [],
clientOrSqlUi: 'mysql2',
getMeta: async () => ({}),
+ trackPosition: true,
});
} catch (ex) {
expect(ex.extra.position).toEqual({
@@ -202,6 +205,7 @@ describe('Formula parsing and type validation', () => {
columns: [],
clientOrSqlUi: 'mysql2',
getMeta: async () => ({}),
+ trackPosition: true,
});
} catch (ex) {
expect(ex.extra.position).toEqual({
@@ -210,6 +214,39 @@ describe('Formula parsing and type validation', () => {
length: 4,
});
}
+ try {
+ await validateFormulaAndExtractTreeWithType({
+ formula: 'CONCAT(__a_ , "A")',
+ columns: [],
+ clientOrSqlUi: 'mysql2',
+ getMeta: async () => ({}),
+ trackPosition: true,
+ });
+ } catch (ex) {
+ expect(ex.extra.position).toEqual({
+ column: 7,
+ row: 0,
+ length: 6,
+ });
+ }
+ });
+ it(`will handle formula missing parentheses`, async () => {
+ try {
+ await validateFormulaAndExtractTreeWithType({
+ formula: 'CONCAT',
+ columns: [],
+ clientOrSqlUi: 'mysql2',
+ getMeta: async () => ({}),
+ trackPosition: true,
+ });
+ } catch (ex) {
+ expect(ex.message).toContain('Missing parentheses after function name');
+ expect(ex.extra.position).toEqual({
+ column: 6,
+ row: 0,
+ length: 1,
+ });
+ }
});
});
});
diff --git a/packages/nocodb-sdk/src/lib/formulaHelpers.ts b/packages/nocodb-sdk/src/lib/formulaHelpers.ts
index a841552b53..a188835d7c 100644
--- a/packages/nocodb-sdk/src/lib/formulaHelpers.ts
+++ b/packages/nocodb-sdk/src/lib/formulaHelpers.ts
@@ -107,6 +107,32 @@ export type ParsedFormulaNode =
const OCURLY_CODE = 123; // '{'
const CCURLY_CODE = 125; // '}'
+export const jsepIndexHook = {
+ name: 'indexing',
+ init(jsep) {
+ // Match identifier in following pattern: {abc-cde}
+ jsep.hooks.add('after-expression', function escapedIdentifier(env) {
+ const needle: string = env.node.name ?? env.node.raw;
+ if (needle) {
+ for (const match of env.context.expr.matchAll(
+ new RegExp(`${needle}\\s*`, 'g')
+ )) {
+ if (match.index + match[0].length === this.index) {
+ env.node.indexStart = this.index - match[0].length;
+ env.node.nodeLength = match[0].length;
+ }
+ }
+ } else {
+ const needle = env.context.expr;
+ env.node.indexStart = this.index - needle.length;
+ env.node.nodeLength = needle.length;
+ }
+ env.node.indexEnd = this.index;
+ return env.node;
+ });
+ },
+} as jsep.IPlugin;
+
export const jsepCurlyHook = {
name: 'curly',
init(jsep) {
@@ -1809,13 +1835,15 @@ export function handleFormulaError({
}) {
let position: number;
let identifierLength: number;
- if (error.extra?.columnName) {
- const identifierMatch = formula.match(
- new RegExp(`\\b${error.extra?.columnName}\\b`)
- );
+ if (error.extra?.position) {
+ position = error.extra.position.index;
+ identifierLength = error.extra.position.length;
+ } else if (error.extra?.columnName ?? error.extra?.calleeName) {
+ const needle = error.extra?.columnName ?? error.extra?.calleeName;
+ const identifierMatch = formula.match(new RegExp(`\\b${needle}\\b`));
if (typeof identifierMatch?.index === 'number') {
position = identifierMatch.index;
- identifierLength = error.extra.columnName.length;
+ identifierLength = needle.length;
}
} else {
const message: string = error.message;
@@ -1852,12 +1880,14 @@ export async function validateFormulaAndExtractTreeWithType({
columns,
clientOrSqlUi,
getMeta,
+ trackPosition,
}: {
formula: string;
columns: ColumnType[];
clientOrSqlUi: ClientTypeOrSqlUI;
column?: ColumnType;
getMeta: (tableId: string) => Promise<any>;
+ trackPosition?: boolean;
}): Promise<ParsedFormulaNode> {
const sqlUI =
typeof clientOrSqlUi === 'string'
@@ -1885,13 +1915,31 @@ export async function validateFormulaAndExtractTreeWithType({
if (!formulas[calleeName]) {
throw new FormulaError(
FormulaErrorType.INVALID_FUNCTION_NAME,
- {},
+ {
+ calleeName,
+ position:
+ (parsedTree as any).indexStart >= 0
+ ? {
+ index: (parsedTree as any).indexStart,
+ length: (parsedTree as any).nodeLength,
+ }
+ : undefined,
+ },
`Function ${calleeName} is not available`
);
} else if (sqlUI?.getUnsupportedFnList().includes(calleeName)) {
throw new FormulaError(
FormulaErrorType.INVALID_FUNCTION_NAME,
- {},
+ {
+ calleeName,
+ position:
+ (parsedTree as any).indexStart >= 0
+ ? {
+ index: (parsedTree as any).indexStart,
+ length: (parsedTree as any).nodeLength,
+ }
+ : undefined,
+ },
`Function ${calleeName} is unavailable for your database`
);
}
@@ -1910,6 +1958,13 @@ export async function validateFormulaAndExtractTreeWithType({
key: 'msg.formula.requiredArgumentsFormula',
requiredArguments: validation.args.rqd,
calleeName,
+ position:
+ (parsedTree as any).indexStart >= 0
+ ? {
+ index: (parsedTree as any).indexStart,
+ length: (parsedTree as any).nodeLength,
+ }
+ : undefined,
},
'Required arguments missing'
);
@@ -1923,6 +1978,13 @@ export async function validateFormulaAndExtractTreeWithType({
key: 'msg.formula.minRequiredArgumentsFormula',
minRequiredArguments: validation.args.min,
calleeName,
+ position:
+ (parsedTree as any).indexStart >= 0
+ ? {
+ index: (parsedTree as any).indexStart,
+ length: (parsedTree as any).nodeLength,
+ }
+ : undefined,
},
'Minimum arguments required'
);
@@ -1936,6 +1998,13 @@ export async function validateFormulaAndExtractTreeWithType({
key: 'msg.formula.maxRequiredArgumentsFormula',
maxRequiredArguments: validation.args.max,
calleeName,
+ position:
+ (parsedTree as any).indexStart >= 0
+ ? {
+ index: (parsedTree as any).indexStart,
+ length: (parsedTree as any).nodeLength,
+ }
+ : undefined,
},
'Maximum arguments missing'
);
@@ -2038,22 +2107,44 @@ export async function validateFormulaAndExtractTreeWithType({
res.dataType = formulas[calleeName].returnType as FormulaDataTypes;
}
} else if (parsedTree.type === JSEPNode.IDENTIFIER) {
- const col = (colIdToColMap[(parsedTree as IdentifierNode).name] ||
- colAliasToColMap[(parsedTree as IdentifierNode).name]) as Record<
- string,
- any
- >;
+ const identifierName = (parsedTree as IdentifierNode).name;
+ const col = (colIdToColMap[identifierName] ||
+ colAliasToColMap[identifierName]) as Record<string, any>;
if (!col) {
+ if (formulas[identifierName]) {
+ throw new FormulaError(
+ FormulaErrorType.INVALID_SYNTAX,
+ {
+ key: 'msg.formula.formulaMissingParentheses',
+ calleeName: identifierName,
+ position:
+ (parsedTree as any).indexStart >= 0
+ ? {
+ index: (parsedTree as any).indexEnd,
+ length: 1,
+ }
+ : undefined,
+ },
+ `Missing parentheses after function name "${JSON.stringify(
+ identifierName
+ )}"`
+ );
+ }
throw new FormulaError(
FormulaErrorType.INVALID_COLUMN,
{
key: 'msg.formula.columnNotAvailable',
- columnName: (parsedTree as IdentifierNode).name,
+ columnName: identifierName,
+ position:
+ (parsedTree as any).indexStart >= 0
+ ? {
+ index: (parsedTree as any).indexStart,
+ length: (parsedTree as any).nodeLength,
+ }
+ : undefined,
},
- `Invalid column name/id ${JSON.stringify(
- (parsedTree as IdentifierNode).name
- )} in formula`
+ `Invalid column name/id ${JSON.stringify(identifierName)} in formula`
);
}
@@ -2212,6 +2303,9 @@ export async function validateFormulaAndExtractTreeWithType({
try {
// register jsep curly hook
jsep.plugins.register(jsepCurlyHook);
+ if (trackPosition) {
+ jsep.plugins.register(jsepIndexHook);
+ }
const parsedFormula = jsep(formula);
// TODO: better jsep expression handling
const result = await validateAndExtract(
@@ -2219,7 +2313,9 @@ export async function validateFormulaAndExtractTreeWithType({
);
return result;
} catch (ex) {
- handleFormulaError({ formula, error: ex });
+ if (trackPosition) {
+ handleFormulaError({ formula, error: ex });
+ }
throw ex;
}
}