PDGGK commented on code in PR #134: URL: https://github.com/apache/iotdb-extras/pull/134#discussion_r4231720170
########## connectors/grafana-plugin/src/componments/TablePicker.tsx: ########## @@ -0,0 +1,176 @@ +/* + * 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 React, { useEffect, useState } from 'react'; +import { SelectableValue } from '@grafana/data'; +import { Button, Select } from '@grafana/ui'; +import { DataSource } from '../datasource'; +import { starterTableQuery } from '../tableQuery'; +import { TableColumn } from '../types'; +import { QueryInlineField } from './Form'; + +interface Props { + datasource: DataSource; + database: string; + table: string; + onDatabaseChange: (database: string) => void; + onTableChange: (table: string) => void; + onSqlChange: (sql: string) => void; +} + +interface Loaded<T> { + value?: T; + loading: boolean; + error?: string; +} + +const categories = ['TAG', 'FIELD', 'ATTRIBUTE']; + +function toOptions(names: string[] | undefined): Array<SelectableValue<string>> { + return (names ?? []).map((name) => ({ label: name, value: name })); +} + +function toValue(name: string): SelectableValue<string> | null { + return name ? { label: name, value: name } : null; +} + +function errorMessage(err: unknown): string { + const e = err as { data?: { message?: string }; message?: string }; + return e?.data?.message ?? e?.message ?? String(err); +} + +// useLoaded runs one metadata lookup whenever its key changes. State is only +// written when a lookup settles, and a result is only used while its key is +// current. A failed lookup keeps its message; the pickers still accept a typed +// name, so the editor stays usable when metadata cannot be read. +function useLoaded<T>(key: string, load: (() => Promise<T>) | undefined): Loaded<T> { + const [result, setResult] = useState<{ key: string; value?: T; error?: string }>(); + useEffect(() => { + if (!load) { + return; + } + let cancelled = false; + load().then( + (value) => { + if (!cancelled) { + setResult({ key, value }); + } + }, + (err) => { + if (!cancelled) { + setResult({ key, error: errorMessage(err) }); + } + } + ); + return () => { + cancelled = true; + }; + // The key identifies the lookup; `load` is a fresh closure on every render. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [key]); + if (!load) { + return { loading: false }; + } + if (result?.key !== key) { + return { loading: true }; + } + return { value: result.value, error: result.error, loading: false }; +} + +// TablePicker lists the databases, tables and columns of the connected server +// for the table-model editor, and can fill in a starter query for the chosen +// table. +export function TablePicker({ datasource, database, table, onDatabaseChange, onTableChange, onSqlChange }: Props) { + const databases = useLoaded('databases', () => datasource.getTableDatabases()); + const tables = useLoaded(`tables|${database}`, database ? () => datasource.getTableTables(database) : undefined); + const columns = useLoaded<TableColumn[]>( + `columns|${database}|${table}`, + database && table ? () => datasource.getTableColumns(database, table) : undefined + ); + const error = databases.error ?? tables.error ?? columns.error; + + return ( + <> + <div className="gf-form"> + <QueryInlineField label={'DATABASE'}> + {/* Select rather than Combobox: with Combobox, picking information_schema + crashed Explore on Grafana 12.3 with React error 185 raised from the + popover's floating-ui reference; Select does not. */} + <Select + inputId="iotdb-table-database" + width={30} + options={toOptions(databases.value)} + value={toValue(database)} Review Comment: Fixed in 3694fe8. Both pickers now memoize their options, add the current value when the server does not list it (a typed or variable name), and pass the matching option as `value`. The e2e test opens the TABLE picker on `tables`, which is 19th of the 21 tables in information_schema, and presses Tab. With the old `value` object it switches to `columns`; with this change it stays on `tables`. ########## connectors/grafana-plugin/src/componments/TablePicker.tsx: ########## @@ -0,0 +1,176 @@ +/* + * 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 React, { useEffect, useState } from 'react'; +import { SelectableValue } from '@grafana/data'; +import { Button, Select } from '@grafana/ui'; +import { DataSource } from '../datasource'; +import { starterTableQuery } from '../tableQuery'; +import { TableColumn } from '../types'; +import { QueryInlineField } from './Form'; + +interface Props { + datasource: DataSource; + database: string; + table: string; + onDatabaseChange: (database: string) => void; + onTableChange: (table: string) => void; + onSqlChange: (sql: string) => void; +} + +interface Loaded<T> { + value?: T; + loading: boolean; + error?: string; +} + +const categories = ['TAG', 'FIELD', 'ATTRIBUTE']; + +function toOptions(names: string[] | undefined): Array<SelectableValue<string>> { + return (names ?? []).map((name) => ({ label: name, value: name })); +} + +function toValue(name: string): SelectableValue<string> | null { + return name ? { label: name, value: name } : null; +} + +function errorMessage(err: unknown): string { + const e = err as { data?: { message?: string }; message?: string }; + return e?.data?.message ?? e?.message ?? String(err); +} + +// useLoaded runs one metadata lookup whenever its key changes. State is only +// written when a lookup settles, and a result is only used while its key is +// current. A failed lookup keeps its message; the pickers still accept a typed +// name, so the editor stays usable when metadata cannot be read. +function useLoaded<T>(key: string, load: (() => Promise<T>) | undefined): Loaded<T> { + const [result, setResult] = useState<{ key: string; value?: T; error?: string }>(); + useEffect(() => { + if (!load) { + return; + } + let cancelled = false; + load().then( + (value) => { + if (!cancelled) { + setResult({ key, value }); + } + }, + (err) => { + if (!cancelled) { + setResult({ key, error: errorMessage(err) }); + } + } + ); + return () => { + cancelled = true; + }; + // The key identifies the lookup; `load` is a fresh closure on every render. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [key]); + if (!load) { + return { loading: false }; + } + if (result?.key !== key) { + return { loading: true }; + } + return { value: result.value, error: result.error, loading: false }; +} + +// TablePicker lists the databases, tables and columns of the connected server +// for the table-model editor, and can fill in a starter query for the chosen +// table. +export function TablePicker({ datasource, database, table, onDatabaseChange, onTableChange, onSqlChange }: Props) { + const databases = useLoaded('databases', () => datasource.getTableDatabases()); + const tables = useLoaded(`tables|${database}`, database ? () => datasource.getTableTables(database) : undefined); + const columns = useLoaded<TableColumn[]>( + `columns|${database}|${table}`, + database && table ? () => datasource.getTableColumns(database, table) : undefined + ); + const error = databases.error ?? tables.error ?? columns.error; + + return ( + <> + <div className="gf-form"> + <QueryInlineField label={'DATABASE'}> + {/* Select rather than Combobox: with Combobox, picking information_schema + crashed Explore on Grafana 12.3 with React error 185 raised from the + popover's floating-ui reference; Select does not. */} + <Select + inputId="iotdb-table-database" + width={30} + options={toOptions(databases.value)} + value={toValue(database)} + isLoading={databases.loading} + allowCustomValue Review Comment: Both pickers now pass `allowCreateWhileLoading`, keep the typed text from `onInputChange`, and commit it (trimmed) in `onBlur`. A component test types ` $database ` and blurs, and expects `$database` to be committed. It fails without the `onBlur`. The e2e test also types `columns` into TABLE and leaves the picker. ########## connectors/grafana-plugin/src/componments/TablePicker.tsx: ########## @@ -0,0 +1,176 @@ +/* + * 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 React, { useEffect, useState } from 'react'; +import { SelectableValue } from '@grafana/data'; +import { Button, Select } from '@grafana/ui'; +import { DataSource } from '../datasource'; +import { starterTableQuery } from '../tableQuery'; +import { TableColumn } from '../types'; +import { QueryInlineField } from './Form'; + +interface Props { + datasource: DataSource; + database: string; + table: string; + onDatabaseChange: (database: string) => void; + onTableChange: (table: string) => void; + onSqlChange: (sql: string) => void; +} + +interface Loaded<T> { + value?: T; + loading: boolean; + error?: string; +} + +const categories = ['TAG', 'FIELD', 'ATTRIBUTE']; + +function toOptions(names: string[] | undefined): Array<SelectableValue<string>> { + return (names ?? []).map((name) => ({ label: name, value: name })); +} + +function toValue(name: string): SelectableValue<string> | null { + return name ? { label: name, value: name } : null; +} + +function errorMessage(err: unknown): string { + const e = err as { data?: { message?: string }; message?: string }; + return e?.data?.message ?? e?.message ?? String(err); +} + +// useLoaded runs one metadata lookup whenever its key changes. State is only +// written when a lookup settles, and a result is only used while its key is +// current. A failed lookup keeps its message; the pickers still accept a typed +// name, so the editor stays usable when metadata cannot be read. +function useLoaded<T>(key: string, load: (() => Promise<T>) | undefined): Loaded<T> { + const [result, setResult] = useState<{ key: string; value?: T; error?: string }>(); + useEffect(() => { + if (!load) { + return; + } + let cancelled = false; + load().then( + (value) => { + if (!cancelled) { + setResult({ key, value }); + } + }, + (err) => { + if (!cancelled) { + setResult({ key, error: errorMessage(err) }); + } + } + ); + return () => { + cancelled = true; + }; + // The key identifies the lookup; `load` is a fresh closure on every render. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [key]); + if (!load) { + return { loading: false }; + } + if (result?.key !== key) { + return { loading: true }; + } + return { value: result.value, error: result.error, loading: false }; +} + +// TablePicker lists the databases, tables and columns of the connected server +// for the table-model editor, and can fill in a starter query for the chosen +// table. +export function TablePicker({ datasource, database, table, onDatabaseChange, onTableChange, onSqlChange }: Props) { + const databases = useLoaded('databases', () => datasource.getTableDatabases()); + const tables = useLoaded(`tables|${database}`, database ? () => datasource.getTableTables(database) : undefined); + const columns = useLoaded<TableColumn[]>( + `columns|${database}|${table}`, + database && table ? () => datasource.getTableColumns(database, table) : undefined + ); Review Comment: The lookups are now keyed on the resolved names. They are expanded with the panel's `scopedVars` (`data.request.scopedVars`) through the same `getTemplateSrv().replace` call that `applyTemplateVariables` makes, so `$db` resolves the same way in the editor and in the query. A component test changes what `$db` resolves to and checks that the tables are fetched again. It fails when the key is built from the raw string. ########## connectors/grafana-plugin/src/datasource.ts: ########## @@ -181,6 +181,24 @@ export class DataSource extends DataSourceWithBackend<IoTDBQuery, IoTDBOptions> .then((data) => data.map(toMetricFindValue)); } + // Metadata behind the table-model editor's pickers. Template variables are + // expanded first, so a dashboard whose database is `$database` still lists + // its tables. + getTableDatabases(): Promise<string[]> { + return this.getResource('tableDatabases'); Review Comment: All three lookups now pass `{ showErrorAlert: false }`. The e2e test enters a table that does not exist, then checks for the inline message and that there is no alert about it. When I removed the option from `getTableColumns`, the same test found the alert. That run, like the others, was against Grafana 12.3.0. ########## connectors/grafana-plugin/src/tableQuery.ts: ########## @@ -0,0 +1,45 @@ +/* + * 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 { TableColumn } from './types'; + +// quoteIdentifier wraps a name in double quotes, doubling any embedded quote. +// The names come from DESC, so quoting them never changes what they refer to, +// and it keeps the query valid when a name is a reserved word such as "order" +// or "group", or contains a space. +export function quoteIdentifier(name: string): string { + return `"${name.replace(/"/g, '""')}"`; +} + +// starterTableQuery builds a first query for a table: the time column, every +// TAG column and every FIELD column, limited to the dashboard's time range. +// ATTRIBUTE columns are left out because they do not change over time. The +// TAG columns are what the Time series format uses to split the result into +// one series per device. A table without a time column, such as the views in +// information_schema, gets no time filter. +export function starterTableQuery(table: string, columns: TableColumn[]): string { + const time = columns.find((c) => c.category === 'TIME')?.name; + const selected = [ + ...(time ? [time] : []), + ...columns.filter((c) => c.category === 'TAG').map((c) => c.name), + ...columns.filter((c) => c.category === 'FIELD').map((c) => c.name), Review Comment: The starter query now selects only INT32/INT64/FLOAT/DOUBLE fields. When a table has none, as with the information_schema views, it falls back to every field, so the query still returns rows in Table format. I left the `date_bin` aggregation out of this PR. I have a query builder prototype that generates `date_bin($__interval, time)` aggregations, and I would rather propose it on its own once this is in. ########## connectors/grafana-plugin/src/QueryEditor.tsx: ########## @@ -144,20 +145,28 @@ export class QueryEditor extends PureComponent<Props, State> { onChange({ ...query, groupBy: g }); }; - onDatabaseChange = (event: ChangeEvent<HTMLInputElement>) => { + onDatabaseChange = (database: string) => { const { onChange, query } = this.props; - const database = event.target.value; this.setState({ database }); - onChange({ ...query, database }); + // A table belongs to one database, so switching database clears it. + onChange({ ...query, database, table: undefined }); Review Comment: Fixed. The table is now cleared only when the picked database differs from the current one. -- 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]
