Development of an internal social media platform with personalised dashboards for students
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 19KB

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