1212from starlette .responses import PlainTextResponse
1313from src .database import DatabaseManager
1414from src .llm import generate_sql_from_llm
15+ import sqlparse
16+ from sqlparse .sql import Identifier , IdentifierList
17+ from sqlparse .tokens import Keyword
1518
1619logger = logging .getLogger (__name__ )
1720
@@ -27,12 +30,19 @@ def postprocess_llm_pipeline_data(response: object) -> str:
2730
2831def validate_sql_before_execute (sql_query : str ) -> bool :
2932 """Validates the SQL query to ensure it does not contain any potentially dangerous statements."""
30- dangerous_patterns = [r'\bDROP\b' , r'\bDELETE\b' , r'\bTRUNCATE\b' , r'\bALTER\b' ,
31- r'\bUPDATE\b' , r'\bCREATE\b' , r'\bGRANT\b' , r'\bREVOKE\b' ]
32- for pattern in dangerous_patterns :
33- if re .search (pattern , sql_query , re .IGNORECASE ):
34- logger .warning ("Dangerous SQL keyword found! Preventing execution." )
35- raise ValueError ("The SQL query contains a potentially dangerous statement and cannot be executed." )
33+ dangerous_keywords = {"DROP" , "DELETE" , "TRUNCATE" , "ALTER" , "UPDATE" , "CREATE" , "GRANT" , "REVOKE" }
34+
35+ try :
36+ parsed = sqlparse .parse (sql_query )
37+ for statement in parsed :
38+ for token in statement .tokens :
39+ if token .ttype == Keyword and token .value .upper () in dangerous_keywords :
40+ logger .warning (f"Dangerous SQL keyword '{ token .value } ' found! Preventing execution." )
41+ raise ValueError (f"The SQL query contains a potentially dangerous statement: '{ token .value } '" )
42+ except Exception as e :
43+ logger .error (f"Error during SQL validation: { e } " )
44+ raise ValueError ("Invalid SQL query." )
45+
3646 return True
3747
3848def sanitize_query (input_text : str ) -> str :
0 commit comments