MCPcopy Create free account
hub / github.com/Datakitpage/Datakit / fixCommonSQLIssues

Function fixCommonSQLIssues

frontend/src/lib/duckdb/sqlSanitizer.ts:51–84  ·  view source on GitHub ↗
(sql: string)

Source from the content-addressed store, hash-verified

49 * Fix common SQL issues in AI-generated queries
50 */
51export function fixCommonSQLIssues(sql: string): string {
52 // Fix UNION ALL queries that might have unquoted columns
53 let fixed = sql;
54
55 // Pattern to find column references in COUNT(DISTINCT ...) that aren't quoted
56 const countDistinctPattern = /COUNT\s*\(\s*DISTINCT\s+([A-Za-z0-9_]+)\s*\)/gi;
57
58 fixed = fixed.replace(countDistinctPattern, (match, columnName) => {
59 // If column name contains numbers or special chars, quote it
60 if (/[^a-zA-Z_]/.test(columnName) || /^\d/.test(columnName)) {
61 return `COUNT(DISTINCT "${columnName}")`;
62 }
63 return match;
64 });
65
66 // Pattern to find column references in SELECT that aren't quoted
67 const selectPattern = /SELECT\s+([^,\s]+)\s+(?:as|AS)/g;
68
69 fixed = fixed.replace(selectPattern, (match, columnRef) => {
70 // Skip if it's already quoted or is a literal string
71 if (columnRef.startsWith('"') || columnRef.startsWith("'")) {
72 return match;
73 }
74
75 // If it looks like a column name with special chars, quote it
76 if (/[^a-zA-Z_]/.test(columnRef) && !columnRef.includes('(')) {
77 return match.replace(columnRef, `"${columnRef}"`);
78 }
79
80 return match;
81 });
82
83 return fixed;
84}
85
86/**
87 * Fix UNION queries with missing FROM clauses

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected