Improve handling of template vars in regex

This commit is contained in:
Andreas Christou 2025-02-14 19:30:23 +00:00
parent 77fd572973
commit 78d708264b
No known key found for this signature in database
GPG Key ID: F35DD1D12B626FB6
2 changed files with 32 additions and 9 deletions

View File

@ -363,6 +363,18 @@ describe('interpolateQueryExpr', () => {
expect(result).toBe(expectation);
});
it('should **not** return the escaped value if the value **is not** wrapped in regex and the query is more complex (e.g. text is contained between two / but not a regex', () => {
const value = 'testmatch';
const variableMock = queryBuilder().withId('tempVar').withName('tempVar').withMulti(false).build();
const result = ds.interpolateQueryExpr(
value,
variableMock,
`select value where ("tag"::tag =~ /value/) AND where other = $tempVar $timeFilter GROUP BY time($__interval) tz('Europe/London')`
);
const expectation = `testmatch`;
expect(result).toBe(expectation);
});
it('should return floating point number as it is', () => {
const variableMock = queryBuilder()
.withId('tempVar')

View File

@ -351,19 +351,30 @@ export default class InfluxDatasource extends DataSourceWithBackend<InfluxQuery,
// If the variable is not a multi-value variable
// we want to see how it's been used. If it is used in a regex expression
// we escape it. Otherwise, we return it directly.
// regex below checks if the variable inside /^...$/ (^ and $ is optional)
// The regex below searches for regexes within the query string
const regexMatcher = new RegExp(
/\/((?![*+?])(?:[^\r\n\[/\\]|\\.|\[(?:[^\r\n\]\\]|\\.)*\])+)\/((?:g(?:im?|mi?)?|i(?:gm?|mg?)?|m(?:gi?|ig?)?)?)/,
'gm'
);
// If matches are found this regex is evaluated to check if the variable is contained in the regex /^...$/ (^ and $ is optional)
// i.e. /^$myVar$/ or /$myVar/ or /^($myVar)$/
const regex = new RegExp(`\\/(?:\\^)?(.*)(\\$${variable.name})(.*)(?:\\$)?\\/`, 'gm');
if (query && regex.test(query)) {
if (typeof value === 'string') {
return escapeRegex(value);
if (query) {
const queryMatches = query.match(regexMatcher);
if (queryMatches) {
for (const match of queryMatches) {
if (match.match(regex)) {
if (typeof value === 'string') {
return escapeRegex(value);
}
// If the value is a string array first escape them then join them with pipe
// then put inside parenthesis.
return `(${value.map((v) => escapeRegex(v)).join('|')})`;
}
}
}
// If the value is a string array first escape them then join them with pipe
// then put inside parenthesis.
return `(${value.map((v) => escapeRegex(v)).join('|')})`;
}
return value;
}