Postgres: Handle single quotes in table names in the query editor (#80951)

postgres: handle single quotes in table names
This commit is contained in:
Gábor Farkas 2024-01-22 15:36:45 +01:00 committed by GitHub
parent 2be8211555
commit 279aa4863b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 27 additions and 3 deletions

View File

@ -67,7 +67,12 @@ export class PostgresDatasource extends SqlDatasource {
}
async fetchFields(query: SQLQuery): Promise<SQLSelectableValue[]> {
const schema = await this.runSql<{ column: string; type: string }>(getSchema(query.table), { refId: 'columns' });
const { table } = query;
if (table === undefined) {
// if no table-name, we are not able to query for fields
return [];
}
const schema = await this.runSql<{ column: string; type: string }>(getSchema(table), { refId: 'columns' });
const result: SQLSelectableValue[] = [];
for (let i = 0; i < schema.length; i++) {
const column = schema.fields.column.values[i];

View File

@ -0,0 +1,14 @@
import { getSchema } from './postgresMetaQuery';
describe('postgredsMetaQuery.getSchema', () => {
it('should handle table-names with single quote', () => {
// testing multi-line with single-quote, double-quote, backtick
const tableName = `'a''bcd'efg'h' "a""b" ` + '`x``y`z' + `\n a'b''c`;
const escapedName = `''a''''bcd''efg''h'' "a""b" ` + '`x``y`z' + `\n a''b''''c`;
const schemaQuery = getSchema(tableName);
expect(schemaQuery.includes(escapedName)).toBeTruthy();
expect(schemaQuery.includes(tableName)).toBeFalsy();
});
});

View File

@ -19,10 +19,15 @@ export function showTables() {
and ${buildSchemaConstraint()}`;
}
export function getSchema(table?: string) {
export function getSchema(table: string) {
// we will put table-name between single-quotes, so we need to escape single-quotes
// in the table-name
const tableNamePart = "'" + table.replace(/'/g, "''") + "'";
return `select quote_ident(column_name) as "column", data_type as "type"
from information_schema.columns
where quote_ident(table_name) = '${table}'`;
where quote_ident(table_name) = ${tableNamePart};
`;
}
function buildSchemaConstraint() {