grouping.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. #
  2. # Copyright (C) 2009-2020 the sqlparse authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of python-sqlparse and is released under
  6. # the BSD License: https://opensource.org/licenses/BSD-3-Clause
  7. from sqlparse import sql
  8. from sqlparse import tokens as T
  9. from sqlparse.utils import recurse, imt
  10. T_NUMERICAL = (T.Number, T.Number.Integer, T.Number.Float)
  11. T_STRING = (T.String, T.String.Single, T.String.Symbol)
  12. T_NAME = (T.Name, T.Name.Placeholder)
  13. def _group_matching(tlist, cls):
  14. """Groups Tokens that have beginning and end."""
  15. opens = []
  16. tidx_offset = 0
  17. for idx, token in enumerate(list(tlist)):
  18. tidx = idx - tidx_offset
  19. if token.is_whitespace:
  20. # ~50% of tokens will be whitespace. Will checking early
  21. # for them avoid 3 comparisons, but then add 1 more comparison
  22. # for the other ~50% of tokens...
  23. continue
  24. if token.is_group and not isinstance(token, cls):
  25. # Check inside previously grouped (i.e. parenthesis) if group
  26. # of different type is inside (i.e., case). though ideally should
  27. # should check for all open/close tokens at once to avoid recursion
  28. _group_matching(token, cls)
  29. continue
  30. if token.match(*cls.M_OPEN):
  31. opens.append(tidx)
  32. elif token.match(*cls.M_CLOSE):
  33. try:
  34. open_idx = opens.pop()
  35. except IndexError:
  36. # this indicates invalid sql and unbalanced tokens.
  37. # instead of break, continue in case other "valid" groups exist
  38. continue
  39. close_idx = tidx
  40. tlist.group_tokens(cls, open_idx, close_idx)
  41. tidx_offset += close_idx - open_idx
  42. def group_brackets(tlist):
  43. _group_matching(tlist, sql.SquareBrackets)
  44. def group_parenthesis(tlist):
  45. _group_matching(tlist, sql.Parenthesis)
  46. def group_case(tlist):
  47. _group_matching(tlist, sql.Case)
  48. def group_if(tlist):
  49. _group_matching(tlist, sql.If)
  50. def group_for(tlist):
  51. _group_matching(tlist, sql.For)
  52. def group_begin(tlist):
  53. _group_matching(tlist, sql.Begin)
  54. def group_typecasts(tlist):
  55. def match(token):
  56. return token.match(T.Punctuation, '::')
  57. def valid(token):
  58. return token is not None
  59. def post(tlist, pidx, tidx, nidx):
  60. return pidx, nidx
  61. valid_prev = valid_next = valid
  62. _group(tlist, sql.Identifier, match, valid_prev, valid_next, post)
  63. def group_tzcasts(tlist):
  64. def match(token):
  65. return token.ttype == T.Keyword.TZCast
  66. def valid_prev(token):
  67. return token is not None
  68. def valid_next(token):
  69. return token is not None and (
  70. token.is_whitespace
  71. or token.match(T.Keyword, 'AS')
  72. or token.match(*sql.TypedLiteral.M_CLOSE)
  73. )
  74. def post(tlist, pidx, tidx, nidx):
  75. return pidx, nidx
  76. _group(tlist, sql.Identifier, match, valid_prev, valid_next, post)
  77. def group_typed_literal(tlist):
  78. # definitely not complete, see e.g.:
  79. # https://docs.microsoft.com/en-us/sql/odbc/reference/appendixes/interval-literal-syntax
  80. # https://docs.microsoft.com/en-us/sql/odbc/reference/appendixes/interval-literals
  81. # https://www.postgresql.org/docs/9.1/datatype-datetime.html
  82. # https://www.postgresql.org/docs/9.1/functions-datetime.html
  83. def match(token):
  84. return imt(token, m=sql.TypedLiteral.M_OPEN)
  85. def match_to_extend(token):
  86. return isinstance(token, sql.TypedLiteral)
  87. def valid_prev(token):
  88. return token is not None
  89. def valid_next(token):
  90. return token is not None and token.match(*sql.TypedLiteral.M_CLOSE)
  91. def valid_final(token):
  92. return token is not None and token.match(*sql.TypedLiteral.M_EXTEND)
  93. def post(tlist, pidx, tidx, nidx):
  94. return tidx, nidx
  95. _group(tlist, sql.TypedLiteral, match, valid_prev, valid_next,
  96. post, extend=False)
  97. _group(tlist, sql.TypedLiteral, match_to_extend, valid_prev, valid_final,
  98. post, extend=True)
  99. def group_period(tlist):
  100. def match(token):
  101. for ttype, value in ((T.Punctuation, '.'),
  102. (T.Operator, '->'),
  103. (T.Operator, '->>')):
  104. if token.match(ttype, value):
  105. return True
  106. return False
  107. def valid_prev(token):
  108. sqlcls = sql.SquareBrackets, sql.Identifier
  109. ttypes = T.Name, T.String.Symbol
  110. return imt(token, i=sqlcls, t=ttypes)
  111. def valid_next(token):
  112. # issue261, allow invalid next token
  113. return True
  114. def post(tlist, pidx, tidx, nidx):
  115. # next_ validation is being performed here. issue261
  116. sqlcls = sql.SquareBrackets, sql.Function
  117. ttypes = T.Name, T.String.Symbol, T.Wildcard, T.String.Single
  118. next_ = tlist[nidx] if nidx is not None else None
  119. valid_next = imt(next_, i=sqlcls, t=ttypes)
  120. return (pidx, nidx) if valid_next else (pidx, tidx)
  121. _group(tlist, sql.Identifier, match, valid_prev, valid_next, post)
  122. def group_as(tlist):
  123. def match(token):
  124. return token.is_keyword and token.normalized == 'AS'
  125. def valid_prev(token):
  126. return token.normalized == 'NULL' or not token.is_keyword
  127. def valid_next(token):
  128. ttypes = T.DML, T.DDL, T.CTE
  129. return not imt(token, t=ttypes) and token is not None
  130. def post(tlist, pidx, tidx, nidx):
  131. return pidx, nidx
  132. _group(tlist, sql.Identifier, match, valid_prev, valid_next, post)
  133. def group_assignment(tlist):
  134. def match(token):
  135. return token.match(T.Assignment, ':=')
  136. def valid(token):
  137. return token is not None and token.ttype not in (T.Keyword,)
  138. def post(tlist, pidx, tidx, nidx):
  139. m_semicolon = T.Punctuation, ';'
  140. snidx, _ = tlist.token_next_by(m=m_semicolon, idx=nidx)
  141. nidx = snidx or nidx
  142. return pidx, nidx
  143. valid_prev = valid_next = valid
  144. _group(tlist, sql.Assignment, match, valid_prev, valid_next, post)
  145. def group_comparison(tlist):
  146. sqlcls = (sql.Parenthesis, sql.Function, sql.Identifier,
  147. sql.Operation, sql.TypedLiteral)
  148. ttypes = T_NUMERICAL + T_STRING + T_NAME
  149. def match(token):
  150. return token.ttype == T.Operator.Comparison
  151. def valid(token):
  152. if imt(token, t=ttypes, i=sqlcls):
  153. return True
  154. elif token and token.is_keyword and token.normalized == 'NULL':
  155. return True
  156. else:
  157. return False
  158. def post(tlist, pidx, tidx, nidx):
  159. return pidx, nidx
  160. valid_prev = valid_next = valid
  161. _group(tlist, sql.Comparison, match,
  162. valid_prev, valid_next, post, extend=False)
  163. @recurse(sql.Identifier)
  164. def group_identifier(tlist):
  165. ttypes = (T.String.Symbol, T.Name)
  166. tidx, token = tlist.token_next_by(t=ttypes)
  167. while token:
  168. tlist.group_tokens(sql.Identifier, tidx, tidx)
  169. tidx, token = tlist.token_next_by(t=ttypes, idx=tidx)
  170. @recurse(sql.Over)
  171. def group_over(tlist):
  172. tidx, token = tlist.token_next_by(m=sql.Over.M_OPEN)
  173. while token:
  174. nidx, next_ = tlist.token_next(tidx)
  175. if imt(next_, i=sql.Parenthesis, t=T.Name):
  176. tlist.group_tokens(sql.Over, tidx, nidx)
  177. tidx, token = tlist.token_next_by(m=sql.Over.M_OPEN, idx=tidx)
  178. def group_arrays(tlist):
  179. sqlcls = sql.SquareBrackets, sql.Identifier, sql.Function
  180. ttypes = T.Name, T.String.Symbol
  181. def match(token):
  182. return isinstance(token, sql.SquareBrackets)
  183. def valid_prev(token):
  184. return imt(token, i=sqlcls, t=ttypes)
  185. def valid_next(token):
  186. return True
  187. def post(tlist, pidx, tidx, nidx):
  188. return pidx, tidx
  189. _group(tlist, sql.Identifier, match,
  190. valid_prev, valid_next, post, extend=True, recurse=False)
  191. def group_operator(tlist):
  192. ttypes = T_NUMERICAL + T_STRING + T_NAME
  193. sqlcls = (sql.SquareBrackets, sql.Parenthesis, sql.Function,
  194. sql.Identifier, sql.Operation, sql.TypedLiteral)
  195. def match(token):
  196. return imt(token, t=(T.Operator, T.Wildcard))
  197. def valid(token):
  198. return imt(token, i=sqlcls, t=ttypes) \
  199. or (token and token.match(
  200. T.Keyword,
  201. ('CURRENT_DATE', 'CURRENT_TIME', 'CURRENT_TIMESTAMP')))
  202. def post(tlist, pidx, tidx, nidx):
  203. tlist[tidx].ttype = T.Operator
  204. return pidx, nidx
  205. valid_prev = valid_next = valid
  206. _group(tlist, sql.Operation, match,
  207. valid_prev, valid_next, post, extend=False)
  208. def group_identifier_list(tlist):
  209. m_role = T.Keyword, ('null', 'role')
  210. sqlcls = (sql.Function, sql.Case, sql.Identifier, sql.Comparison,
  211. sql.IdentifierList, sql.Operation)
  212. ttypes = (T_NUMERICAL + T_STRING + T_NAME
  213. + (T.Keyword, T.Comment, T.Wildcard))
  214. def match(token):
  215. return token.match(T.Punctuation, ',')
  216. def valid(token):
  217. return imt(token, i=sqlcls, m=m_role, t=ttypes)
  218. def post(tlist, pidx, tidx, nidx):
  219. return pidx, nidx
  220. valid_prev = valid_next = valid
  221. _group(tlist, sql.IdentifierList, match,
  222. valid_prev, valid_next, post, extend=True)
  223. @recurse(sql.Comment)
  224. def group_comments(tlist):
  225. tidx, token = tlist.token_next_by(t=T.Comment)
  226. while token:
  227. eidx, end = tlist.token_not_matching(
  228. lambda tk: imt(tk, t=T.Comment) or tk.is_newline, idx=tidx)
  229. if end is not None:
  230. eidx, end = tlist.token_prev(eidx, skip_ws=False)
  231. tlist.group_tokens(sql.Comment, tidx, eidx)
  232. tidx, token = tlist.token_next_by(t=T.Comment, idx=tidx)
  233. @recurse(sql.Where)
  234. def group_where(tlist):
  235. tidx, token = tlist.token_next_by(m=sql.Where.M_OPEN)
  236. while token:
  237. eidx, end = tlist.token_next_by(m=sql.Where.M_CLOSE, idx=tidx)
  238. if end is None:
  239. end = tlist._groupable_tokens[-1]
  240. else:
  241. end = tlist.tokens[eidx - 1]
  242. # TODO: convert this to eidx instead of end token.
  243. # i think above values are len(tlist) and eidx-1
  244. eidx = tlist.token_index(end)
  245. tlist.group_tokens(sql.Where, tidx, eidx)
  246. tidx, token = tlist.token_next_by(m=sql.Where.M_OPEN, idx=tidx)
  247. @recurse()
  248. def group_aliased(tlist):
  249. I_ALIAS = (sql.Parenthesis, sql.Function, sql.Case, sql.Identifier,
  250. sql.Operation, sql.Comparison)
  251. tidx, token = tlist.token_next_by(i=I_ALIAS, t=T.Number)
  252. while token:
  253. nidx, next_ = tlist.token_next(tidx)
  254. if isinstance(next_, sql.Identifier):
  255. tlist.group_tokens(sql.Identifier, tidx, nidx, extend=True)
  256. tidx, token = tlist.token_next_by(i=I_ALIAS, t=T.Number, idx=tidx)
  257. @recurse(sql.Function)
  258. def group_functions(tlist):
  259. has_create = False
  260. has_table = False
  261. has_as = False
  262. for tmp_token in tlist.tokens:
  263. if tmp_token.value.upper() == 'CREATE':
  264. has_create = True
  265. if tmp_token.value.upper() == 'TABLE':
  266. has_table = True
  267. if tmp_token.value == 'AS':
  268. has_as = True
  269. if has_create and has_table and not has_as:
  270. return
  271. tidx, token = tlist.token_next_by(t=T.Name)
  272. while token:
  273. nidx, next_ = tlist.token_next(tidx)
  274. if isinstance(next_, sql.Parenthesis):
  275. over_idx, over = tlist.token_next(nidx)
  276. if over and isinstance(over, sql.Over):
  277. eidx = over_idx
  278. else:
  279. eidx = nidx
  280. tlist.group_tokens(sql.Function, tidx, eidx)
  281. tidx, token = tlist.token_next_by(t=T.Name, idx=tidx)
  282. @recurse(sql.Identifier)
  283. def group_order(tlist):
  284. """Group together Identifier and Asc/Desc token"""
  285. tidx, token = tlist.token_next_by(t=T.Keyword.Order)
  286. while token:
  287. pidx, prev_ = tlist.token_prev(tidx)
  288. if imt(prev_, i=sql.Identifier, t=T.Number):
  289. tlist.group_tokens(sql.Identifier, pidx, tidx)
  290. tidx = pidx
  291. tidx, token = tlist.token_next_by(t=T.Keyword.Order, idx=tidx)
  292. @recurse()
  293. def align_comments(tlist):
  294. tidx, token = tlist.token_next_by(i=sql.Comment)
  295. while token:
  296. pidx, prev_ = tlist.token_prev(tidx)
  297. if isinstance(prev_, sql.TokenList):
  298. tlist.group_tokens(sql.TokenList, pidx, tidx, extend=True)
  299. tidx = pidx
  300. tidx, token = tlist.token_next_by(i=sql.Comment, idx=tidx)
  301. def group_values(tlist):
  302. tidx, token = tlist.token_next_by(m=(T.Keyword, 'VALUES'))
  303. start_idx = tidx
  304. end_idx = -1
  305. while token:
  306. if isinstance(token, sql.Parenthesis):
  307. end_idx = tidx
  308. tidx, token = tlist.token_next(tidx)
  309. if end_idx != -1:
  310. tlist.group_tokens(sql.Values, start_idx, end_idx, extend=True)
  311. def group(stmt):
  312. for func in [
  313. group_comments,
  314. # _group_matching
  315. group_brackets,
  316. group_parenthesis,
  317. group_case,
  318. group_if,
  319. group_for,
  320. group_begin,
  321. group_over,
  322. group_functions,
  323. group_where,
  324. group_period,
  325. group_arrays,
  326. group_identifier,
  327. group_order,
  328. group_typecasts,
  329. group_tzcasts,
  330. group_typed_literal,
  331. group_operator,
  332. group_comparison,
  333. group_as,
  334. group_aliased,
  335. group_assignment,
  336. align_comments,
  337. group_identifier_list,
  338. group_values,
  339. ]:
  340. func(stmt)
  341. return stmt
  342. def _group(tlist, cls, match,
  343. valid_prev=lambda t: True,
  344. valid_next=lambda t: True,
  345. post=None,
  346. extend=True,
  347. recurse=True
  348. ):
  349. """Groups together tokens that are joined by a middle token. i.e. x < y"""
  350. tidx_offset = 0
  351. pidx, prev_ = None, None
  352. for idx, token in enumerate(list(tlist)):
  353. tidx = idx - tidx_offset
  354. if tidx < 0: # tidx shouldn't get negative
  355. continue
  356. if token.is_whitespace:
  357. continue
  358. if recurse and token.is_group and not isinstance(token, cls):
  359. _group(token, cls, match, valid_prev, valid_next, post, extend)
  360. if match(token):
  361. nidx, next_ = tlist.token_next(tidx)
  362. if prev_ and valid_prev(prev_) and valid_next(next_):
  363. from_idx, to_idx = post(tlist, pidx, tidx, nidx)
  364. grp = tlist.group_tokens(cls, from_idx, to_idx, extend=extend)
  365. tidx_offset += to_idx - from_idx
  366. pidx, prev_ = from_idx, grp
  367. continue
  368. pidx, prev_ = tidx, token