File size: 886 Bytes
69e9d44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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