sql.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  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. """This module contains classes representing syntactical elements of SQL."""
  8. import re
  9. from sqlparse import tokens as T
  10. from sqlparse.utils import imt, remove_quotes
  11. class NameAliasMixin:
  12. """Implements get_real_name and get_alias."""
  13. def get_real_name(self):
  14. """Returns the real name (object name) of this identifier."""
  15. # a.b.c -> real name is the component after the *last* dot
  16. dot_idx = None
  17. for idx, tok in enumerate(self.tokens):
  18. if tok.match(T.Punctuation, '.'):
  19. dot_idx = idx
  20. return self._get_first_name(dot_idx, real_name=True)
  21. def get_alias(self):
  22. """Returns the alias for this identifier or ``None``."""
  23. # "name AS alias"
  24. kw_idx, kw = self.token_next_by(m=(T.Keyword, 'AS'))
  25. if kw is not None:
  26. return self._get_first_name(kw_idx + 1, keywords=True)
  27. # "name alias" or "complicated column expression alias"
  28. _, ws = self.token_next_by(t=T.Whitespace)
  29. if len(self.tokens) > 2 and ws is not None:
  30. return self._get_first_name(reverse=True)
  31. class Token:
  32. """Base class for all other classes in this module.
  33. It represents a single token and has two instance attributes:
  34. ``value`` is the unchanged value of the token and ``ttype`` is
  35. the type of the token.
  36. """
  37. __slots__ = (
  38. 'is_group',
  39. 'is_keyword',
  40. 'is_newline',
  41. 'is_whitespace',
  42. 'normalized',
  43. 'parent',
  44. 'ttype',
  45. 'value',
  46. )
  47. def __init__(self, ttype, value):
  48. value = str(value)
  49. self.value = value
  50. self.ttype = ttype
  51. self.parent = None
  52. self.is_group = False
  53. self.is_keyword = ttype in T.Keyword
  54. self.is_whitespace = self.ttype in T.Whitespace
  55. self.is_newline = self.ttype in T.Newline
  56. self.normalized = value.upper() if self.is_keyword else value
  57. def __str__(self):
  58. return self.value
  59. # Pending tokenlist __len__ bug fix
  60. # def __len__(self):
  61. # return len(self.value)
  62. def __repr__(self):
  63. cls = self._get_repr_name()
  64. value = self._get_repr_value()
  65. q = '"' if value.startswith("'") and value.endswith("'") else "'"
  66. return "<{cls} {q}{value}{q} at 0x{id:2X}>".format(
  67. id=id(self), **locals())
  68. def _get_repr_name(self):
  69. return str(self.ttype).split('.')[-1]
  70. def _get_repr_value(self):
  71. raw = str(self)
  72. if len(raw) > 7:
  73. raw = raw[:6] + '...'
  74. return re.sub(r'\s+', ' ', raw)
  75. def flatten(self):
  76. """Resolve subgroups."""
  77. yield self
  78. def match(self, ttype, values, regex=False):
  79. """Checks whether the token matches the given arguments.
  80. *ttype* is a token type as defined in `sqlparse.tokens`. If it does
  81. not match, ``False`` is returned.
  82. *values* is a list of possible values for this token. For match to be
  83. considered valid, the token value needs to be in this list. For tokens
  84. of type ``Keyword`` the comparison is case-insensitive. For
  85. convenience, a single value can be given passed as a string.
  86. If *regex* is ``True``, the given values are treated as regular
  87. expressions. Partial matches are allowed. Defaults to ``False``.
  88. """
  89. type_matched = self.ttype is ttype
  90. if not type_matched or values is None:
  91. return type_matched
  92. if isinstance(values, str):
  93. values = (values,)
  94. if regex:
  95. # TODO: Add test for regex with is_keyword = false
  96. flag = re.IGNORECASE if self.is_keyword else 0
  97. values = (re.compile(v, flag) for v in values)
  98. return any(pattern.search(self.normalized) for pattern in values)
  99. if self.is_keyword:
  100. values = (v.upper() for v in values)
  101. return self.normalized in values
  102. def within(self, group_cls):
  103. """Returns ``True`` if this token is within *group_cls*.
  104. Use this method for example to check if an identifier is within
  105. a function: ``t.within(sql.Function)``.
  106. """
  107. parent = self.parent
  108. while parent:
  109. if isinstance(parent, group_cls):
  110. return True
  111. parent = parent.parent
  112. return False
  113. def is_child_of(self, other):
  114. """Returns ``True`` if this token is a direct child of *other*."""
  115. return self.parent == other
  116. def has_ancestor(self, other):
  117. """Returns ``True`` if *other* is in this tokens ancestry."""
  118. parent = self.parent
  119. while parent:
  120. if parent == other:
  121. return True
  122. parent = parent.parent
  123. return False
  124. class TokenList(Token):
  125. """A group of tokens.
  126. It has an additional instance attribute ``tokens`` which holds a
  127. list of child-tokens.
  128. """
  129. __slots__ = 'tokens'
  130. def __init__(self, tokens=None):
  131. self.tokens = tokens or []
  132. [setattr(token, 'parent', self) for token in self.tokens]
  133. super().__init__(None, ''.join(token.value for token in self.tokens))
  134. self.is_group = True
  135. def __str__(self):
  136. return ''.join(token.value for token in self.flatten())
  137. # weird bug
  138. # def __len__(self):
  139. # return len(self.tokens)
  140. def __iter__(self):
  141. return iter(self.tokens)
  142. def __getitem__(self, item):
  143. return self.tokens[item]
  144. def _get_repr_name(self):
  145. return type(self).__name__
  146. def _pprint_tree(self, max_depth=None, depth=0, f=None, _pre=''):
  147. """Pretty-print the object tree."""
  148. token_count = len(self.tokens)
  149. for idx, token in enumerate(self.tokens):
  150. cls = token._get_repr_name()
  151. value = token._get_repr_value()
  152. last = idx == (token_count - 1)
  153. pre = '`- ' if last else '|- '
  154. q = '"' if value.startswith("'") and value.endswith("'") else "'"
  155. print(f"{_pre}{pre}{idx} {cls} {q}{value}{q}", file=f)
  156. if token.is_group and (max_depth is None or depth < max_depth):
  157. parent_pre = ' ' if last else '| '
  158. token._pprint_tree(max_depth, depth + 1, f, _pre + parent_pre)
  159. def get_token_at_offset(self, offset):
  160. """Returns the token that is on position offset."""
  161. idx = 0
  162. for token in self.flatten():
  163. end = idx + len(token.value)
  164. if idx <= offset < end:
  165. return token
  166. idx = end
  167. def flatten(self):
  168. """Generator yielding ungrouped tokens.
  169. This method is recursively called for all child tokens.
  170. """
  171. for token in self.tokens:
  172. if token.is_group:
  173. yield from token.flatten()
  174. else:
  175. yield token
  176. def get_sublists(self):
  177. for token in self.tokens:
  178. if token.is_group:
  179. yield token
  180. @property
  181. def _groupable_tokens(self):
  182. return self.tokens
  183. def _token_matching(self, funcs, start=0, end=None, reverse=False):
  184. """next token that match functions"""
  185. if start is None:
  186. return None
  187. if not isinstance(funcs, (list, tuple)):
  188. funcs = (funcs,)
  189. if reverse:
  190. assert end is None
  191. indexes = range(start - 2, -1, -1)
  192. else:
  193. if end is None:
  194. end = len(self.tokens)
  195. indexes = range(start, end)
  196. for idx in indexes:
  197. token = self.tokens[idx]
  198. for func in funcs:
  199. if func(token):
  200. return idx, token
  201. return None, None
  202. def token_first(self, skip_ws=True, skip_cm=False):
  203. """Returns the first child token.
  204. If *skip_ws* is ``True`` (the default), whitespace
  205. tokens are ignored.
  206. if *skip_cm* is ``True`` (default: ``False``), comments are
  207. ignored too.
  208. """
  209. # this on is inconsistent, using Comment instead of T.Comment...
  210. def matcher(tk):
  211. return not ((skip_ws and tk.is_whitespace)
  212. or (skip_cm and imt(tk, t=T.Comment, i=Comment)))
  213. return self._token_matching(matcher)[1]
  214. def token_next_by(self, i=None, m=None, t=None, idx=-1, end=None):
  215. idx += 1
  216. return self._token_matching(lambda tk: imt(tk, i, m, t), idx, end)
  217. def token_not_matching(self, funcs, idx):
  218. funcs = (funcs,) if not isinstance(funcs, (list, tuple)) else funcs
  219. funcs = [lambda tk, func=func: not func(tk) for func in funcs]
  220. return self._token_matching(funcs, idx)
  221. def token_matching(self, funcs, idx):
  222. return self._token_matching(funcs, idx)[1]
  223. def token_prev(self, idx, skip_ws=True, skip_cm=False):
  224. """Returns the previous token relative to *idx*.
  225. If *skip_ws* is ``True`` (the default) whitespace tokens are ignored.
  226. If *skip_cm* is ``True`` comments are ignored.
  227. ``None`` is returned if there's no previous token.
  228. """
  229. return self.token_next(idx, skip_ws, skip_cm, _reverse=True)
  230. # TODO: May need to re-add default value to idx
  231. def token_next(self, idx, skip_ws=True, skip_cm=False, _reverse=False):
  232. """Returns the next token relative to *idx*.
  233. If *skip_ws* is ``True`` (the default) whitespace tokens are ignored.
  234. If *skip_cm* is ``True`` comments are ignored.
  235. ``None`` is returned if there's no next token.
  236. """
  237. if idx is None:
  238. return None, None
  239. idx += 1 # alot of code usage current pre-compensates for this
  240. def matcher(tk):
  241. return not ((skip_ws and tk.is_whitespace)
  242. or (skip_cm and imt(tk, t=T.Comment, i=Comment)))
  243. return self._token_matching(matcher, idx, reverse=_reverse)
  244. def token_index(self, token, start=0):
  245. """Return list index of token."""
  246. start = start if isinstance(start, int) else self.token_index(start)
  247. return start + self.tokens[start:].index(token)
  248. def group_tokens(self, grp_cls, start, end, include_end=True,
  249. extend=False):
  250. """Replace tokens by an instance of *grp_cls*."""
  251. start_idx = start
  252. start = self.tokens[start_idx]
  253. end_idx = end + include_end
  254. # will be needed later for new group_clauses
  255. # while skip_ws and tokens and tokens[-1].is_whitespace:
  256. # tokens = tokens[:-1]
  257. if extend and isinstance(start, grp_cls):
  258. subtokens = self.tokens[start_idx + 1:end_idx]
  259. grp = start
  260. grp.tokens.extend(subtokens)
  261. del self.tokens[start_idx + 1:end_idx]
  262. grp.value += ''.join(token.value for token in subtokens)
  263. else:
  264. subtokens = self.tokens[start_idx:end_idx]
  265. grp = grp_cls(subtokens)
  266. self.tokens[start_idx:end_idx] = [grp]
  267. grp.parent = self
  268. for token in subtokens:
  269. token.parent = grp
  270. return grp
  271. def insert_before(self, where, token):
  272. """Inserts *token* before *where*."""
  273. if not isinstance(where, int):
  274. where = self.token_index(where)
  275. token.parent = self
  276. self.tokens.insert(where, token)
  277. def insert_after(self, where, token, skip_ws=True):
  278. """Inserts *token* after *where*."""
  279. if not isinstance(where, int):
  280. where = self.token_index(where)
  281. nidx, next_ = self.token_next(where, skip_ws=skip_ws)
  282. token.parent = self
  283. if next_ is None:
  284. self.tokens.append(token)
  285. else:
  286. self.tokens.insert(nidx, token)
  287. def has_alias(self):
  288. """Returns ``True`` if an alias is present."""
  289. return self.get_alias() is not None
  290. def get_alias(self):
  291. """Returns the alias for this identifier or ``None``."""
  292. return None
  293. def get_name(self):
  294. """Returns the name of this identifier.
  295. This is either it's alias or it's real name. The returned valued can
  296. be considered as the name under which the object corresponding to
  297. this identifier is known within the current statement.
  298. """
  299. return self.get_alias() or self.get_real_name()
  300. def get_real_name(self):
  301. """Returns the real name (object name) of this identifier."""
  302. return None
  303. def get_parent_name(self):
  304. """Return name of the parent object if any.
  305. A parent object is identified by the first occurring dot.
  306. """
  307. dot_idx, _ = self.token_next_by(m=(T.Punctuation, '.'))
  308. _, prev_ = self.token_prev(dot_idx)
  309. return remove_quotes(prev_.value) if prev_ is not None else None
  310. def _get_first_name(self, idx=None, reverse=False, keywords=False,
  311. real_name=False):
  312. """Returns the name of the first token with a name"""
  313. tokens = self.tokens[idx:] if idx else self.tokens
  314. tokens = reversed(tokens) if reverse else tokens
  315. types = [T.Name, T.Wildcard, T.String.Symbol]
  316. if keywords:
  317. types.append(T.Keyword)
  318. for token in tokens:
  319. if token.ttype in types:
  320. return remove_quotes(token.value)
  321. elif isinstance(token, (Identifier, Function)):
  322. return token.get_real_name() if real_name else token.get_name()
  323. class Statement(TokenList):
  324. """Represents a SQL statement."""
  325. def get_type(self):
  326. """Returns the type of a statement.
  327. The returned value is a string holding an upper-cased reprint of
  328. the first DML or DDL keyword. If the first token in this group
  329. isn't a DML or DDL keyword "UNKNOWN" is returned.
  330. Whitespaces and comments at the beginning of the statement
  331. are ignored.
  332. """
  333. token = self.token_first(skip_cm=True)
  334. if token is None:
  335. # An "empty" statement that either has not tokens at all
  336. # or only whitespace tokens.
  337. return 'UNKNOWN'
  338. elif token.ttype in (T.Keyword.DML, T.Keyword.DDL):
  339. return token.normalized
  340. elif token.ttype == T.Keyword.CTE:
  341. # The WITH keyword should be followed by either an Identifier or
  342. # an IdentifierList containing the CTE definitions; the actual
  343. # DML keyword (e.g. SELECT, INSERT) will follow next.
  344. tidx = self.token_index(token)
  345. while tidx is not None:
  346. tidx, token = self.token_next(tidx, skip_ws=True)
  347. if isinstance(token, (Identifier, IdentifierList)):
  348. tidx, token = self.token_next(tidx, skip_ws=True)
  349. if token is not None \
  350. and token.ttype == T.Keyword.DML:
  351. return token.normalized
  352. # Hmm, probably invalid syntax, so return unknown.
  353. return 'UNKNOWN'
  354. class Identifier(NameAliasMixin, TokenList):
  355. """Represents an identifier.
  356. Identifiers may have aliases or typecasts.
  357. """
  358. def is_wildcard(self):
  359. """Return ``True`` if this identifier contains a wildcard."""
  360. _, token = self.token_next_by(t=T.Wildcard)
  361. return token is not None
  362. def get_typecast(self):
  363. """Returns the typecast or ``None`` of this object as a string."""
  364. midx, marker = self.token_next_by(m=(T.Punctuation, '::'))
  365. nidx, next_ = self.token_next(midx, skip_ws=False)
  366. return next_.value if next_ else None
  367. def get_ordering(self):
  368. """Returns the ordering or ``None`` as uppercase string."""
  369. _, ordering = self.token_next_by(t=T.Keyword.Order)
  370. return ordering.normalized if ordering else None
  371. def get_array_indices(self):
  372. """Returns an iterator of index token lists"""
  373. for token in self.tokens:
  374. if isinstance(token, SquareBrackets):
  375. # Use [1:-1] index to discard the square brackets
  376. yield token.tokens[1:-1]
  377. class IdentifierList(TokenList):
  378. """A list of :class:`~sqlparse.sql.Identifier`\'s."""
  379. def get_identifiers(self):
  380. """Returns the identifiers.
  381. Whitespaces and punctuations are not included in this generator.
  382. """
  383. for token in self.tokens:
  384. if not (token.is_whitespace or token.match(T.Punctuation, ',')):
  385. yield token
  386. class TypedLiteral(TokenList):
  387. """A typed literal, such as "date '2001-09-28'" or "interval '2 hours'"."""
  388. M_OPEN = [(T.Name.Builtin, None), (T.Keyword, "TIMESTAMP")]
  389. M_CLOSE = T.String.Single, None
  390. M_EXTEND = T.Keyword, ("DAY", "HOUR", "MINUTE", "MONTH", "SECOND", "YEAR")
  391. class Parenthesis(TokenList):
  392. """Tokens between parenthesis."""
  393. M_OPEN = T.Punctuation, '('
  394. M_CLOSE = T.Punctuation, ')'
  395. @property
  396. def _groupable_tokens(self):
  397. return self.tokens[1:-1]
  398. class SquareBrackets(TokenList):
  399. """Tokens between square brackets"""
  400. M_OPEN = T.Punctuation, '['
  401. M_CLOSE = T.Punctuation, ']'
  402. @property
  403. def _groupable_tokens(self):
  404. return self.tokens[1:-1]
  405. class Assignment(TokenList):
  406. """An assignment like 'var := val;'"""
  407. class If(TokenList):
  408. """An 'if' clause with possible 'else if' or 'else' parts."""
  409. M_OPEN = T.Keyword, 'IF'
  410. M_CLOSE = T.Keyword, 'END IF'
  411. class For(TokenList):
  412. """A 'FOR' loop."""
  413. M_OPEN = T.Keyword, ('FOR', 'FOREACH')
  414. M_CLOSE = T.Keyword, 'END LOOP'
  415. class Comparison(TokenList):
  416. """A comparison used for example in WHERE clauses."""
  417. @property
  418. def left(self):
  419. return self.tokens[0]
  420. @property
  421. def right(self):
  422. return self.tokens[-1]
  423. class Comment(TokenList):
  424. """A comment."""
  425. def is_multiline(self):
  426. return self.tokens and self.tokens[0].ttype == T.Comment.Multiline
  427. class Where(TokenList):
  428. """A WHERE clause."""
  429. M_OPEN = T.Keyword, 'WHERE'
  430. M_CLOSE = T.Keyword, (
  431. 'ORDER BY', 'GROUP BY', 'LIMIT', 'UNION', 'UNION ALL', 'EXCEPT',
  432. 'INTERSECT', 'HAVING', 'RETURNING', 'INTO')
  433. class Over(TokenList):
  434. """An OVER clause."""
  435. M_OPEN = T.Keyword, 'OVER'
  436. class Having(TokenList):
  437. """A HAVING clause."""
  438. M_OPEN = T.Keyword, 'HAVING'
  439. M_CLOSE = T.Keyword, ('ORDER BY', 'LIMIT')
  440. class Case(TokenList):
  441. """A CASE statement with one or more WHEN and possibly an ELSE part."""
  442. M_OPEN = T.Keyword, 'CASE'
  443. M_CLOSE = T.Keyword, 'END'
  444. def get_cases(self, skip_ws=False):
  445. """Returns a list of 2-tuples (condition, value).
  446. If an ELSE exists condition is None.
  447. """
  448. CONDITION = 1
  449. VALUE = 2
  450. ret = []
  451. mode = CONDITION
  452. for token in self.tokens:
  453. # Set mode from the current statement
  454. if token.match(T.Keyword, 'CASE') or (skip_ws and token.ttype in T.Whitespace):
  455. continue
  456. elif token.match(T.Keyword, 'WHEN'):
  457. ret.append(([], []))
  458. mode = CONDITION
  459. elif token.match(T.Keyword, 'THEN'):
  460. mode = VALUE
  461. elif token.match(T.Keyword, 'ELSE'):
  462. ret.append((None, []))
  463. mode = VALUE
  464. elif token.match(T.Keyword, 'END'):
  465. mode = None
  466. # First condition without preceding WHEN
  467. if mode and not ret:
  468. ret.append(([], []))
  469. # Append token depending of the current mode
  470. if mode == CONDITION:
  471. ret[-1][0].append(token)
  472. elif mode == VALUE:
  473. ret[-1][1].append(token)
  474. # Return cases list
  475. return ret
  476. class Function(NameAliasMixin, TokenList):
  477. """A function or procedure call."""
  478. def get_parameters(self):
  479. """Return a list of parameters."""
  480. parenthesis = self.token_next_by(i=Parenthesis)[1]
  481. result = []
  482. for token in parenthesis.tokens:
  483. if isinstance(token, IdentifierList):
  484. return token.get_identifiers()
  485. elif imt(token, i=(Function, Identifier, TypedLiteral),
  486. t=T.Literal):
  487. result.append(token)
  488. return result
  489. def get_window(self):
  490. """Return the window if it exists."""
  491. over_clause = self.token_next_by(i=Over)
  492. if not over_clause:
  493. return None
  494. return over_clause[1].tokens[-1]
  495. class Begin(TokenList):
  496. """A BEGIN/END block."""
  497. M_OPEN = T.Keyword, 'BEGIN'
  498. M_CLOSE = T.Keyword, 'END'
  499. class Operation(TokenList):
  500. """Grouping of operations"""
  501. class Values(TokenList):
  502. """Grouping of values"""
  503. class Command(TokenList):
  504. """Grouping of CLI commands."""