Escape database names in MSSQL datasource (#99754)

Valid MSSQL database names can contain characters like `-`, which need
to be escaped when used in queries.

This PR wraps database names in `[]`, and fixes Grafana issue #58757.
This commit is contained in:
beejeebus
2025-01-30 15:36:45 -05:00
committed by GitHub
parent ce38eb3398
commit 8ce8c1635f
4 changed files with 30 additions and 2 deletions

View File

@ -0,0 +1,10 @@
import { getSchema } from './MSSqlMetaQuery';
describe('getSchema', () => {
const database = 'foo';
const table = 'bar';
const schema = getSchema(database, table);
it('should escapte database names', () => {
expect(schema).toContain(`USE [${database}]`);
});
});

View File

@ -10,7 +10,7 @@ export function getSchemaAndName(database?: string) {
export function getSchema(database?: string, table?: string) {
return `
USE ${database}
USE [${database}]
SELECT COLUMN_NAME as 'column',DATA_TYPE as 'type'
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='${table}';`;
}

View File

@ -0,0 +1,18 @@
import { SQLQuery, QueryEditorExpressionType } from '@grafana/sql';
import { toRawSql } from './sqlUtil';
describe('toRawSql should escape database names', () => {
const query: SQLQuery = {
dataset: 'foo',
sql: {
columns: [{ name: 'a', alias: 'lol', type: QueryEditorExpressionType.Function }],
},
refId: 'lolsob',
table: 'table',
};
const queryString = toRawSql(query);
it('should escapte database names', () => {
expect(queryString).toContain(`FROM [${query.dataset}].${query.table}`);
});
});

View File

@ -89,7 +89,7 @@ export function toRawSql({ sql, dataset, table }: SQLQuery): string {
rawQuery += createSelectClause(sql.columns, sql.limit);
if (dataset && table) {
rawQuery += `FROM ${dataset}.${table} `;
rawQuery += `FROM [${dataset}].${table} `;
}
if (sql.whereString) {