sql.py 20 KB

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