Files
MAFLO321 ab813cb601 Postgresql: Support tables from non-default schema (#95636)
* Postgresql: Support tables from non-default schema

- Add support for schema-qualified table names.
- Partially resolve an issue where the column type of a table from the
  wrong schema with the same table name was incorrectly used. Now
  limited to tables of schemas within the search_path.

* Support schema in raw query editor

---------

Co-authored-by: Zoltán Bedi <zoltan.bedi@gmail.com>
2024-11-12 09:18:29 +00:00

65 lines
1.8 KiB
TypeScript

import {
ColumnDefinition,
getStandardSQLCompletionProvider,
LanguageCompletionProvider,
LinkedToken,
TableDefinition,
TableIdentifier,
TokenType,
} from '@grafana/experimental';
import { DB, SQLQuery } from '@grafana/sql';
interface CompletionProviderGetterArgs {
getColumns: React.MutableRefObject<(t: SQLQuery) => Promise<ColumnDefinition[]>>;
getTables: React.MutableRefObject<(d?: string) => Promise<TableDefinition[]>>;
}
export const getSqlCompletionProvider: (args: CompletionProviderGetterArgs) => LanguageCompletionProvider =
({ getColumns, getTables }) =>
(monaco, language) => ({
...(language && getStandardSQLCompletionProvider(monaco, language)),
tables: {
resolve: async () => {
return await getTables.current();
},
// Default parser doesn't handle schema.table syntax
parseName: (token: LinkedToken | undefined | null) => {
if (!token) {
return { table: '' };
}
let processedToken = token;
let tablePath = processedToken.value;
// Parse schema.table syntax
while (processedToken.next && processedToken.next.type !== TokenType.Whitespace) {
tablePath += processedToken.next.value;
processedToken = processedToken.next;
}
return { table: tablePath };
},
},
columns: {
resolve: async (t?: TableIdentifier) => {
return await getColumns.current({ table: t?.table, refId: 'A' });
},
},
});
export async function fetchColumns(db: DB, q: SQLQuery) {
const cols = await db.fields(q);
if (cols.length > 0) {
return cols.map((c) => {
return { name: c.value, type: c.value, description: c.value };
});
} else {
return [];
}
}
export async function fetchTables(db: DB) {
const tables = await db.lookup?.();
return tables || [];
}