You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sql.py 20KB

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