Copilot commented on code in PR #109:
URL: https://github.com/apache/iotdb-extras/pull/109#discussion_r3292457169


##########
connectors/grafana-plugin/src/datasource.ts:
##########
@@ -30,16 +30,81 @@ export class DataSource extends 
DataSourceWithBackend<IoTDBQuery, IoTDBOptions>
     this.username = instanceSettings.jsonData.username;
   }
   applyTemplateVariables(query: IoTDBQuery, scopedVars: ScopedVars) {
-    if (query.sqlType === 'SQL: Full Customized') {
+    if (!query.sqlType || query.sqlType === 'SQL: Full Customized') {
       if (query.expression) {
         query.expression.map(
           (_, index) => (query.expression[index] = 
getTemplateSrv().replace(query.expression[index], scopedVars))
         );
       }
       if (query.prefixPath) {
-        query.prefixPath.map(
-          (_, index) => (query.prefixPath[index] = 
getTemplateSrv().replace(query.prefixPath[index], scopedVars))
-        );
+        const expanded: string[] = [];
+        const templateSrv = getTemplateSrv();
+        const varPattern = /\$\{(\w+)(?::[^}]*)?\}|\$(\w+)\b/;
+        for (const path of query.prefixPath) {
+          if (varPattern.test(path)) {
+            const varMatch = path.match(/\$\{(\w+)(?::[^}]*)?\}|\$(\w+)\b/);
+            if (varMatch) {
+              const varName = varMatch[1] || varMatch[2];
+              const idx = varMatch.index!;
+              const prefix = path.substring(0, idx);
+              const suffix = path.substring(idx + varMatch[0].length);
+              let values: string[] = [];
+              if (scopedVars && scopedVars[varName]) {
+                const val = scopedVars[varName].value;
+                if (val === '$__all') {
+                  const allVars = templateSrv.getVariables() as any[];
+                  const found = allVars.find((v: any) => v.name === varName);
+                  if (found && found.options) {
+                    values = found.options
+                      .filter((o: any) => o.value !== '$__all')
+                      .map((o: any) => o.value);
+                  }
+                } else {
+                  values = Array.isArray(val) ? val : [String(val)];
+                }
+              } else {

Review Comment:
   When `scopedVars[varName].value === '$__all'` but the variable cannot be 
found in `templateSrv.getVariables()` or it has no `options`, `values` remains 
empty. In that case the code falls through to the `for (const val of values)` 
loop, which pushes **no** entries and effectively drops this `prefixPath` item 
(silent data loss). Add a fallback to replace the whole path (same behavior as 
the unresolved-variable fallback in the non-scopedVars branch).
   



##########
connectors/grafana-plugin/src/datasource.ts:
##########
@@ -30,16 +30,81 @@ export class DataSource extends 
DataSourceWithBackend<IoTDBQuery, IoTDBOptions>
     this.username = instanceSettings.jsonData.username;
   }
   applyTemplateVariables(query: IoTDBQuery, scopedVars: ScopedVars) {
-    if (query.sqlType === 'SQL: Full Customized') {
+    if (!query.sqlType || query.sqlType === 'SQL: Full Customized') {
       if (query.expression) {
         query.expression.map(
           (_, index) => (query.expression[index] = 
getTemplateSrv().replace(query.expression[index], scopedVars))
         );
       }
       if (query.prefixPath) {
-        query.prefixPath.map(
-          (_, index) => (query.prefixPath[index] = 
getTemplateSrv().replace(query.prefixPath[index], scopedVars))
-        );
+        const expanded: string[] = [];
+        const templateSrv = getTemplateSrv();
+        const varPattern = /\$\{(\w+)(?::[^}]*)?\}|\$(\w+)\b/;
+        for (const path of query.prefixPath) {
+          if (varPattern.test(path)) {
+            const varMatch = path.match(/\$\{(\w+)(?::[^}]*)?\}|\$(\w+)\b/);
+            if (varMatch) {
+              const varName = varMatch[1] || varMatch[2];
+              const idx = varMatch.index!;

Review Comment:
   `prefixPath` expansion only considers the *first* template token in a path 
(`path.match(...)`). If a multi-value variable is not the first variable in the 
string (e.g. `root.${app}.${device}` where `${device}` is multi-value), the 
code will expand `${app}` and then `templateSrv.replace()` the suffix, leaving 
`${device}` as a comma-joined value and producing an invalid IoTDB path. 
Consider scanning all template tokens and expanding the one(s) with multiple 
selected values (ideally generating a Cartesian product when multiple 
multi-value vars are present), or clearly documenting a restriction that only 
one (and first) variable can be multi-value per `prefixPath` entry.



##########
connectors/grafana-plugin/src/datasource.test.ts:
##########
@@ -0,0 +1,240 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+import { DataSource } from './datasource';
+import { IoTDBQuery } from './types';
+import { ScopedVars } from '@grafana/data';
+
+const mockReplace = jest.fn();
+const mockContainsTemplate = jest.fn();
+const mockGetVariables = jest.fn();
+
+jest.mock('@grafana/runtime', () => ({
+  DataSourceWithBackend: class {},
+  getTemplateSrv: () => ({
+    replace: mockReplace,
+    containsTemplate: mockContainsTemplate,
+    getVariables: mockGetVariables,
+  }),
+}));
+
+describe('DataSource', () => {
+  let ds: DataSource;
+
+  beforeEach(() => {
+    ds = new DataSource({ jsonData: { url: 'http://localhost:6667', username: 
'root' } } as any);
+    mockReplace.mockReset();
+    mockContainsTemplate.mockReset();
+    mockGetVariables.mockReset();
+    mockGetVariables.mockReturnValue([]);
+  });
+
+  describe('applyTemplateVariables - prefixPath expansion', () => {
+    const baseQuery: Partial<IoTDBQuery> = {
+      sqlType: 'SQL: Full Customized',
+      expression: [],
+      prefixPath: [],
+      condition: '',
+      control: '',
+    };
+    const scopedVars: ScopedVars = {};
+
+    it('should pass through literal paths without variables', () => {
+      mockContainsTemplate.mockReturnValue(false);
+      const query = { ...baseQuery, prefixPath: ['root.app.device1', 
'root.app.device2'] } as IoTDBQuery;
+
+      const result = ds.applyTemplateVariables(query, scopedVars);
+
+      expect(result.prefixPath).toEqual(['root.app.device1', 
'root.app.device2']);
+      expect(mockReplace).not.toHaveBeenCalled();
+    });
+
+    it('should handle single-value variable without expansion', () => {
+      mockContainsTemplate.mockReturnValue(true);
+      mockGetVariables.mockReturnValue([
+        { name: 'device', current: { value: 'device1' }, options: [{ value: 
'$__all' }, { value: 'device1' }] },
+      ]);
+      mockReplace.mockReturnValue('device1');
+      const query = { ...baseQuery, prefixPath: ['root.app.${device}'] } as 
IoTDBQuery;
+
+      const result = ds.applyTemplateVariables(query, scopedVars);
+
+      expect(result.prefixPath).toEqual(['root.app.device1']);
+    });
+
+    it('should expand multi-value variable into multiple paths', () => {
+      mockContainsTemplate.mockReturnValue(true);
+      mockGetVariables.mockReturnValue([
+        {
+          name: 'device',
+          current: { value: ['device1', 'device2', 'device3'] },
+          options: [{ value: '$__all' }, { value: 'device1' }, { value: 
'device2' }, { value: 'device3' }],
+        },
+      ]);
+      const query = { ...baseQuery, prefixPath: ['root.app.${device}'] } as 
IoTDBQuery;
+
+      const result = ds.applyTemplateVariables(query, scopedVars);
+
+      expect(result.prefixPath).toEqual(['root.app.device1', 
'root.app.device2', 'root.app.device3']);
+    });
+
+    it('should handle mixed literal and template paths', () => {
+      mockContainsTemplate.mockImplementation((path: string) => 
path.includes('${'));
+      mockGetVariables.mockReturnValue([
+        { name: 'device', current: { value: ['device1', 'device2'] }, options: 
[{ value: '$__all' }, { value: 'device1' }, { value: 'device2' }] },
+      ]);
+      const query = {
+        ...baseQuery,
+        prefixPath: ['root.static.path', 'root.app.${device}'],
+      } as IoTDBQuery;
+
+      const result = ds.applyTemplateVariables(query, scopedVars);
+
+      expect(result.prefixPath).toEqual(['root.static.path', 
'root.app.device1', 'root.app.device2']);
+    });
+

Review Comment:
   There is no unit test covering the case where the multi-value variable is 
*not* the first template variable in a `prefixPath` entry (e.g. 
`root.${app}.${device}` with `${device}` multi-select). Given the current 
implementation only expands the first match, this regression scenario would not 
be caught. Add a test for this expected behavior (and update implementation 
accordingly).
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to