sql.py 20 KB

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