Files
beekeeper-studio/apps/ui-kit/lib/utils/sql.ts
2025-04-20 16:16:14 +07:00

23 lines
1.0 KiB
TypeScript

import { identify } from 'sql-query-identifier'
import { Dialect } from 'sql-query-identifier/lib/defines';
// a function that takes in a string and a dialect,
// if the string is determined to be most likely a query and it is quoted, we remove the quotes,
// else we just return the trimmed query
export function removeQueryQuotes(possibleQuery: string, dialect: Dialect): string {
// ensure there's no leading/trailing whitespace before we make our checks
possibleQuery = possibleQuery.trim();
const quotes = ["'", '"', '`'];
const first = possibleQuery[0], last = possibleQuery[possibleQuery.length - 1];
const isQuoted = quotes.includes(first) && quotes.includes(last) && first === last;
const unquotedQuery = possibleQuery.slice(1, possibleQuery.length - 1);
// if the query is quoted and we can identify at least one valid sql statement, we'll unquote it.
if (isQuoted && identify(unquotedQuery, { strict: false, dialect })?.some((res) => res.type != 'UNKNOWN')) {
return unquotedQuery;
}
return possibleQuery;
}