MCPcopy Create free account
hub / github.com/dbcli/mssql-cli / find_prev_keyword

Function find_prev_keyword

mssqlcli/packages/parseutils/utils.py:65–99  ·  view source on GitHub ↗

Find the last sql keyword in an SQL statement Returns the value of the last keyword, and the text of the query with everything after the last keyword stripped

(sql, n_skip=0)

Source from the content-addressed store, hash-verified

63
64
65def find_prev_keyword(sql, n_skip=0):
66 """ Find the last sql keyword in an SQL statement
67
68 Returns the value of the last keyword, and the text of the query with
69 everything after the last keyword stripped
70 """
71 if not sql.strip():
72 return None, ''
73
74 parsed = sqlparse.parse(sql)[0]
75 flattened = list(parsed.flatten())
76 flattened = flattened[:len(flattened) - n_skip]
77
78 logical_operators = ('AND', 'OR', 'NOT', 'BETWEEN')
79
80 for t in reversed(flattened):
81 if t.value == '(' or (t.is_keyword and
82 (t.value.upper() not in logical_operators)
83 ):
84 # Find the location of token t in the original parsed statement
85 # We can't use parsed.token_index(t) because t may be a child token
86 # inside a TokenList, in which case token_index thows an error
87 # Minimal example:
88 # p = sqlparse.parse('select * from foo where bar')
89 # t = list(p.flatten())[-3] # The "Where" token
90 # p.token_index(t) # Throws ValueError: not in list
91 idx = flattened.index(t)
92
93 # Combine the string values of all tokens in the original list
94 # up to and including the target keyword token t, to produce a
95 # query string with everything after the keyword token removed
96 text = ''.join(tok.value for tok in flattened[:idx + 1])
97 return t, text
98
99 return None, ''
100
101
102# Postgresql dollar quote signs look like `$$` or `$tag$`

Calls

no outgoing calls