import { format } from 'sql-formatter'; const GRAFANA_TEMPLATE_VARIABLE_REGEX = String.raw`\$[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*`; const GRAFANA_MACRO_REGEX = String.raw`\$__[a-zA-Z_][a-zA-Z0-9_]*`; export function formatSql(sql: string): string { try { const formatted = format(sql, { tabWidth: 2, keywordCase: 'upper', // Treat Grafana-style variables/macros as placeholders so the formatter can // parse expressions like $database.cpu and $__timeFilter(ts). paramTypes: { custom: [{ regex: GRAFANA_TEMPLATE_VARIABLE_REGEX }], }, }); // sql-formatter treats $__xxx as a placeholder and inserts a space before '('. // Remove that extra space so $__timeFilter( stays intact as a function call. return formatted.replace(new RegExp(`(${GRAFANA_MACRO_REGEX})\\s+\\(`, 'g'), '$1('); } catch { // If formatting fails, return the original SQL return sql; } }