grouping.py 13 KB

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