AISqlQueryFastApi / backend /app /services /utility_sql.py
Vivek0912's picture
initial commit for huggingface
69e9d44
Raw
History Blame Contribute Delete
886 Bytes
import sqlparse
class UtilityClass:
@staticmethod
def is_valid_sql_query(sql: str) -> bool:
"""
Returns True if the string is a valid SQL statement (not just a keyword in text).
Uses sqlparse to check for a valid statement structure.
"""
if not sql or not isinstance(sql, str):
return False
parsed = sqlparse.parse(sql)
if not parsed or not parsed[0].tokens:
return False
# Check if the first token is a DML/DDL keyword and the statement is not just a keyword
stmt = parsed[0]
first_token = stmt.token_first(skip_cm=True, skip_ws=True)
if first_token is None:
return False
# Accept only if the first token is a SQL keyword and there is more than one token
return first_token.ttype in sqlparse.tokens.Keyword.DML and len(stmt.tokens) > 1