sql.py 20 KB

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