PageRenderTime 61ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/venv/lib/python2.7/site-packages/sqlalchemy/sql/compiler.py

https://gitlab.com/ismailam/openexport
Python | 1389 lines | 1293 code | 39 blank | 57 comment | 18 complexity | 53b3b278286bae9ea5d4e8e3b4b1108c MD5 | raw file
  1. # sql/compiler.py
  2. # Copyright (C) 2005-2016 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  7. """Base SQL and DDL compiler implementations.
  8. Classes provided include:
  9. :class:`.compiler.SQLCompiler` - renders SQL
  10. strings
  11. :class:`.compiler.DDLCompiler` - renders DDL
  12. (data definition language) strings
  13. :class:`.compiler.GenericTypeCompiler` - renders
  14. type specification strings.
  15. To generate user-defined SQL strings, see
  16. :doc:`/ext/compiler`.
  17. """
  18. import contextlib
  19. import re
  20. from . import schema, sqltypes, operators, functions, visitors, \
  21. elements, selectable, crud
  22. from .. import util, exc
  23. import itertools
  24. RESERVED_WORDS = set([
  25. 'all', 'analyse', 'analyze', 'and', 'any', 'array',
  26. 'as', 'asc', 'asymmetric', 'authorization', 'between',
  27. 'binary', 'both', 'case', 'cast', 'check', 'collate',
  28. 'column', 'constraint', 'create', 'cross', 'current_date',
  29. 'current_role', 'current_time', 'current_timestamp',
  30. 'current_user', 'default', 'deferrable', 'desc',
  31. 'distinct', 'do', 'else', 'end', 'except', 'false',
  32. 'for', 'foreign', 'freeze', 'from', 'full', 'grant',
  33. 'group', 'having', 'ilike', 'in', 'initially', 'inner',
  34. 'intersect', 'into', 'is', 'isnull', 'join', 'leading',
  35. 'left', 'like', 'limit', 'localtime', 'localtimestamp',
  36. 'natural', 'new', 'not', 'notnull', 'null', 'off', 'offset',
  37. 'old', 'on', 'only', 'or', 'order', 'outer', 'overlaps',
  38. 'placing', 'primary', 'references', 'right', 'select',
  39. 'session_user', 'set', 'similar', 'some', 'symmetric', 'table',
  40. 'then', 'to', 'trailing', 'true', 'union', 'unique', 'user',
  41. 'using', 'verbose', 'when', 'where'])
  42. LEGAL_CHARACTERS = re.compile(r'^[A-Z0-9_$]+$', re.I)
  43. ILLEGAL_INITIAL_CHARACTERS = set([str(x) for x in range(0, 10)]).union(['$'])
  44. BIND_PARAMS = re.compile(r'(?<![:\w\$\x5c]):([\w\$]+)(?![:\w\$])', re.UNICODE)
  45. BIND_PARAMS_ESC = re.compile(r'\x5c(:[\w\$]*)(?![:\w\$])', re.UNICODE)
  46. BIND_TEMPLATES = {
  47. 'pyformat': "%%(%(name)s)s",
  48. 'qmark': "?",
  49. 'format': "%%s",
  50. 'numeric': ":[_POSITION]",
  51. 'named': ":%(name)s"
  52. }
  53. OPERATORS = {
  54. # binary
  55. operators.and_: ' AND ',
  56. operators.or_: ' OR ',
  57. operators.add: ' + ',
  58. operators.mul: ' * ',
  59. operators.sub: ' - ',
  60. operators.div: ' / ',
  61. operators.mod: ' % ',
  62. operators.truediv: ' / ',
  63. operators.neg: '-',
  64. operators.lt: ' < ',
  65. operators.le: ' <= ',
  66. operators.ne: ' != ',
  67. operators.gt: ' > ',
  68. operators.ge: ' >= ',
  69. operators.eq: ' = ',
  70. operators.concat_op: ' || ',
  71. operators.match_op: ' MATCH ',
  72. operators.notmatch_op: ' NOT MATCH ',
  73. operators.in_op: ' IN ',
  74. operators.notin_op: ' NOT IN ',
  75. operators.comma_op: ', ',
  76. operators.from_: ' FROM ',
  77. operators.as_: ' AS ',
  78. operators.is_: ' IS ',
  79. operators.isnot: ' IS NOT ',
  80. operators.collate: ' COLLATE ',
  81. # unary
  82. operators.exists: 'EXISTS ',
  83. operators.distinct_op: 'DISTINCT ',
  84. operators.inv: 'NOT ',
  85. # modifiers
  86. operators.desc_op: ' DESC',
  87. operators.asc_op: ' ASC',
  88. operators.nullsfirst_op: ' NULLS FIRST',
  89. operators.nullslast_op: ' NULLS LAST',
  90. }
  91. FUNCTIONS = {
  92. functions.coalesce: 'coalesce%(expr)s',
  93. functions.current_date: 'CURRENT_DATE',
  94. functions.current_time: 'CURRENT_TIME',
  95. functions.current_timestamp: 'CURRENT_TIMESTAMP',
  96. functions.current_user: 'CURRENT_USER',
  97. functions.localtime: 'LOCALTIME',
  98. functions.localtimestamp: 'LOCALTIMESTAMP',
  99. functions.random: 'random%(expr)s',
  100. functions.sysdate: 'sysdate',
  101. functions.session_user: 'SESSION_USER',
  102. functions.user: 'USER'
  103. }
  104. EXTRACT_MAP = {
  105. 'month': 'month',
  106. 'day': 'day',
  107. 'year': 'year',
  108. 'second': 'second',
  109. 'hour': 'hour',
  110. 'doy': 'doy',
  111. 'minute': 'minute',
  112. 'quarter': 'quarter',
  113. 'dow': 'dow',
  114. 'week': 'week',
  115. 'epoch': 'epoch',
  116. 'milliseconds': 'milliseconds',
  117. 'microseconds': 'microseconds',
  118. 'timezone_hour': 'timezone_hour',
  119. 'timezone_minute': 'timezone_minute'
  120. }
  121. COMPOUND_KEYWORDS = {
  122. selectable.CompoundSelect.UNION: 'UNION',
  123. selectable.CompoundSelect.UNION_ALL: 'UNION ALL',
  124. selectable.CompoundSelect.EXCEPT: 'EXCEPT',
  125. selectable.CompoundSelect.EXCEPT_ALL: 'EXCEPT ALL',
  126. selectable.CompoundSelect.INTERSECT: 'INTERSECT',
  127. selectable.CompoundSelect.INTERSECT_ALL: 'INTERSECT ALL'
  128. }
  129. class Compiled(object):
  130. """Represent a compiled SQL or DDL expression.
  131. The ``__str__`` method of the ``Compiled`` object should produce
  132. the actual text of the statement. ``Compiled`` objects are
  133. specific to their underlying database dialect, and also may
  134. or may not be specific to the columns referenced within a
  135. particular set of bind parameters. In no case should the
  136. ``Compiled`` object be dependent on the actual values of those
  137. bind parameters, even though it may reference those values as
  138. defaults.
  139. """
  140. _cached_metadata = None
  141. def __init__(self, dialect, statement, bind=None,
  142. compile_kwargs=util.immutabledict()):
  143. """Construct a new ``Compiled`` object.
  144. :param dialect: ``Dialect`` to compile against.
  145. :param statement: ``ClauseElement`` to be compiled.
  146. :param bind: Optional Engine or Connection to compile this
  147. statement against.
  148. :param compile_kwargs: additional kwargs that will be
  149. passed to the initial call to :meth:`.Compiled.process`.
  150. .. versionadded:: 0.8
  151. """
  152. self.dialect = dialect
  153. self.bind = bind
  154. if statement is not None:
  155. self.statement = statement
  156. self.can_execute = statement.supports_execution
  157. self.string = self.process(self.statement, **compile_kwargs)
  158. @util.deprecated("0.7", ":class:`.Compiled` objects now compile "
  159. "within the constructor.")
  160. def compile(self):
  161. """Produce the internal string representation of this element.
  162. """
  163. pass
  164. def _execute_on_connection(self, connection, multiparams, params):
  165. return connection._execute_compiled(self, multiparams, params)
  166. @property
  167. def sql_compiler(self):
  168. """Return a Compiled that is capable of processing SQL expressions.
  169. If this compiler is one, it would likely just return 'self'.
  170. """
  171. raise NotImplementedError()
  172. def process(self, obj, **kwargs):
  173. return obj._compiler_dispatch(self, **kwargs)
  174. def __str__(self):
  175. """Return the string text of the generated SQL or DDL."""
  176. return self.string or ''
  177. def construct_params(self, params=None):
  178. """Return the bind params for this compiled object.
  179. :param params: a dict of string/object pairs whose values will
  180. override bind values compiled in to the
  181. statement.
  182. """
  183. raise NotImplementedError()
  184. @property
  185. def params(self):
  186. """Return the bind params for this compiled object."""
  187. return self.construct_params()
  188. def execute(self, *multiparams, **params):
  189. """Execute this compiled object."""
  190. e = self.bind
  191. if e is None:
  192. raise exc.UnboundExecutionError(
  193. "This Compiled object is not bound to any Engine "
  194. "or Connection.")
  195. return e._execute_compiled(self, multiparams, params)
  196. def scalar(self, *multiparams, **params):
  197. """Execute this compiled object and return the result's
  198. scalar value."""
  199. return self.execute(*multiparams, **params).scalar()
  200. class TypeCompiler(util.with_metaclass(util.EnsureKWArgType, object)):
  201. """Produces DDL specification for TypeEngine objects."""
  202. ensure_kwarg = 'visit_\w+'
  203. def __init__(self, dialect):
  204. self.dialect = dialect
  205. def process(self, type_, **kw):
  206. return type_._compiler_dispatch(self, **kw)
  207. class _CompileLabel(visitors.Visitable):
  208. """lightweight label object which acts as an expression.Label."""
  209. __visit_name__ = 'label'
  210. __slots__ = 'element', 'name'
  211. def __init__(self, col, name, alt_names=()):
  212. self.element = col
  213. self.name = name
  214. self._alt_names = (col,) + alt_names
  215. @property
  216. def proxy_set(self):
  217. return self.element.proxy_set
  218. @property
  219. def type(self):
  220. return self.element.type
  221. class SQLCompiler(Compiled):
  222. """Default implementation of Compiled.
  223. Compiles ClauseElements into SQL strings. Uses a similar visit
  224. paradigm as visitors.ClauseVisitor but implements its own traversal.
  225. """
  226. extract_map = EXTRACT_MAP
  227. compound_keywords = COMPOUND_KEYWORDS
  228. isdelete = isinsert = isupdate = False
  229. """class-level defaults which can be set at the instance
  230. level to define if this Compiled instance represents
  231. INSERT/UPDATE/DELETE
  232. """
  233. isplaintext = False
  234. returning = None
  235. """holds the "returning" collection of columns if
  236. the statement is CRUD and defines returning columns
  237. either implicitly or explicitly
  238. """
  239. returning_precedes_values = False
  240. """set to True classwide to generate RETURNING
  241. clauses before the VALUES or WHERE clause (i.e. MSSQL)
  242. """
  243. render_table_with_column_in_update_from = False
  244. """set to True classwide to indicate the SET clause
  245. in a multi-table UPDATE statement should qualify
  246. columns with the table name (i.e. MySQL only)
  247. """
  248. ansi_bind_rules = False
  249. """SQL 92 doesn't allow bind parameters to be used
  250. in the columns clause of a SELECT, nor does it allow
  251. ambiguous expressions like "? = ?". A compiler
  252. subclass can set this flag to False if the target
  253. driver/DB enforces this
  254. """
  255. def __init__(self, dialect, statement, column_keys=None,
  256. inline=False, **kwargs):
  257. """Construct a new ``DefaultCompiler`` object.
  258. dialect
  259. Dialect to be used
  260. statement
  261. ClauseElement to be compiled
  262. column_keys
  263. a list of column names to be compiled into an INSERT or UPDATE
  264. statement.
  265. """
  266. self.column_keys = column_keys
  267. # compile INSERT/UPDATE defaults/sequences inlined (no pre-
  268. # execute)
  269. self.inline = inline or getattr(statement, 'inline', False)
  270. # a dictionary of bind parameter keys to BindParameter
  271. # instances.
  272. self.binds = {}
  273. # a dictionary of BindParameter instances to "compiled" names
  274. # that are actually present in the generated SQL
  275. self.bind_names = util.column_dict()
  276. # stack which keeps track of nested SELECT statements
  277. self.stack = []
  278. # relates label names in the final SQL to a tuple of local
  279. # column/label name, ColumnElement object (if any) and
  280. # TypeEngine. ResultProxy uses this for type processing and
  281. # column targeting
  282. self._result_columns = []
  283. # if False, means we can't be sure the list of entries
  284. # in _result_columns is actually the rendered order. This
  285. # gets flipped when we use TextAsFrom, for example.
  286. self._ordered_columns = True
  287. # true if the paramstyle is positional
  288. self.positional = dialect.positional
  289. if self.positional:
  290. self.positiontup = []
  291. self.bindtemplate = BIND_TEMPLATES[dialect.paramstyle]
  292. self.ctes = None
  293. # an IdentifierPreparer that formats the quoting of identifiers
  294. self.preparer = dialect.identifier_preparer
  295. self.label_length = dialect.label_length \
  296. or dialect.max_identifier_length
  297. # a map which tracks "anonymous" identifiers that are created on
  298. # the fly here
  299. self.anon_map = util.PopulateDict(self._process_anon)
  300. # a map which tracks "truncated" names based on
  301. # dialect.label_length or dialect.max_identifier_length
  302. self.truncated_names = {}
  303. Compiled.__init__(self, dialect, statement, **kwargs)
  304. if self.positional and dialect.paramstyle == 'numeric':
  305. self._apply_numbered_params()
  306. @util.memoized_instancemethod
  307. def _init_cte_state(self):
  308. """Initialize collections related to CTEs only if
  309. a CTE is located, to save on the overhead of
  310. these collections otherwise.
  311. """
  312. # collect CTEs to tack on top of a SELECT
  313. self.ctes = util.OrderedDict()
  314. self.ctes_by_name = {}
  315. self.ctes_recursive = False
  316. if self.positional:
  317. self.cte_positional = {}
  318. @contextlib.contextmanager
  319. def _nested_result(self):
  320. """special API to support the use case of 'nested result sets'"""
  321. result_columns, ordered_columns = (
  322. self._result_columns, self._ordered_columns)
  323. self._result_columns, self._ordered_columns = [], False
  324. try:
  325. if self.stack:
  326. entry = self.stack[-1]
  327. entry['need_result_map_for_nested'] = True
  328. else:
  329. entry = None
  330. yield self._result_columns, self._ordered_columns
  331. finally:
  332. if entry:
  333. entry.pop('need_result_map_for_nested')
  334. self._result_columns, self._ordered_columns = (
  335. result_columns, ordered_columns)
  336. def _apply_numbered_params(self):
  337. poscount = itertools.count(1)
  338. self.string = re.sub(
  339. r'\[_POSITION\]',
  340. lambda m: str(util.next(poscount)),
  341. self.string)
  342. @util.memoized_property
  343. def _bind_processors(self):
  344. return dict(
  345. (key, value) for key, value in
  346. ((self.bind_names[bindparam],
  347. bindparam.type._cached_bind_processor(self.dialect))
  348. for bindparam in self.bind_names)
  349. if value is not None
  350. )
  351. def is_subquery(self):
  352. return len(self.stack) > 1
  353. @property
  354. def sql_compiler(self):
  355. return self
  356. def construct_params(self, params=None, _group_number=None, _check=True):
  357. """return a dictionary of bind parameter keys and values"""
  358. if params:
  359. pd = {}
  360. for bindparam in self.bind_names:
  361. name = self.bind_names[bindparam]
  362. if bindparam.key in params:
  363. pd[name] = params[bindparam.key]
  364. elif name in params:
  365. pd[name] = params[name]
  366. elif _check and bindparam.required:
  367. if _group_number:
  368. raise exc.InvalidRequestError(
  369. "A value is required for bind parameter %r, "
  370. "in parameter group %d" %
  371. (bindparam.key, _group_number))
  372. else:
  373. raise exc.InvalidRequestError(
  374. "A value is required for bind parameter %r"
  375. % bindparam.key)
  376. elif bindparam.callable:
  377. pd[name] = bindparam.effective_value
  378. else:
  379. pd[name] = bindparam.value
  380. return pd
  381. else:
  382. pd = {}
  383. for bindparam in self.bind_names:
  384. if _check and bindparam.required:
  385. if _group_number:
  386. raise exc.InvalidRequestError(
  387. "A value is required for bind parameter %r, "
  388. "in parameter group %d" %
  389. (bindparam.key, _group_number))
  390. else:
  391. raise exc.InvalidRequestError(
  392. "A value is required for bind parameter %r"
  393. % bindparam.key)
  394. if bindparam.callable:
  395. pd[self.bind_names[bindparam]] = bindparam.effective_value
  396. else:
  397. pd[self.bind_names[bindparam]] = bindparam.value
  398. return pd
  399. @property
  400. def params(self):
  401. """Return the bind param dictionary embedded into this
  402. compiled object, for those values that are present."""
  403. return self.construct_params(_check=False)
  404. @util.dependencies("sqlalchemy.engine.result")
  405. def _create_result_map(self, result):
  406. """utility method used for unit tests only."""
  407. return result.ResultMetaData._create_result_map(self._result_columns)
  408. def default_from(self):
  409. """Called when a SELECT statement has no froms, and no FROM clause is
  410. to be appended.
  411. Gives Oracle a chance to tack on a ``FROM DUAL`` to the string output.
  412. """
  413. return ""
  414. def visit_grouping(self, grouping, asfrom=False, **kwargs):
  415. return "(" + grouping.element._compiler_dispatch(self, **kwargs) + ")"
  416. def visit_label_reference(
  417. self, element, within_columns_clause=False, **kwargs):
  418. if self.stack and self.dialect.supports_simple_order_by_label:
  419. selectable = self.stack[-1]['selectable']
  420. with_cols, only_froms = selectable._label_resolve_dict
  421. if within_columns_clause:
  422. resolve_dict = only_froms
  423. else:
  424. resolve_dict = with_cols
  425. # this can be None in the case that a _label_reference()
  426. # were subject to a replacement operation, in which case
  427. # the replacement of the Label element may have changed
  428. # to something else like a ColumnClause expression.
  429. order_by_elem = element.element._order_by_label_element
  430. if order_by_elem is not None and order_by_elem.name in \
  431. resolve_dict:
  432. kwargs['render_label_as_label'] = \
  433. element.element._order_by_label_element
  434. return self.process(
  435. element.element, within_columns_clause=within_columns_clause,
  436. **kwargs)
  437. def visit_textual_label_reference(
  438. self, element, within_columns_clause=False, **kwargs):
  439. if not self.stack:
  440. # compiling the element outside of the context of a SELECT
  441. return self.process(
  442. element._text_clause
  443. )
  444. selectable = self.stack[-1]['selectable']
  445. with_cols, only_froms = selectable._label_resolve_dict
  446. try:
  447. if within_columns_clause:
  448. col = only_froms[element.element]
  449. else:
  450. col = with_cols[element.element]
  451. except KeyError:
  452. # treat it like text()
  453. util.warn_limited(
  454. "Can't resolve label reference %r; converting to text()",
  455. util.ellipses_string(element.element))
  456. return self.process(
  457. element._text_clause
  458. )
  459. else:
  460. kwargs['render_label_as_label'] = col
  461. return self.process(
  462. col, within_columns_clause=within_columns_clause, **kwargs)
  463. def visit_label(self, label,
  464. add_to_result_map=None,
  465. within_label_clause=False,
  466. within_columns_clause=False,
  467. render_label_as_label=None,
  468. **kw):
  469. # only render labels within the columns clause
  470. # or ORDER BY clause of a select. dialect-specific compilers
  471. # can modify this behavior.
  472. render_label_with_as = (within_columns_clause and not
  473. within_label_clause)
  474. render_label_only = render_label_as_label is label
  475. if render_label_only or render_label_with_as:
  476. if isinstance(label.name, elements._truncated_label):
  477. labelname = self._truncated_identifier("colident", label.name)
  478. else:
  479. labelname = label.name
  480. if render_label_with_as:
  481. if add_to_result_map is not None:
  482. add_to_result_map(
  483. labelname,
  484. label.name,
  485. (label, labelname, ) + label._alt_names,
  486. label.type
  487. )
  488. return label.element._compiler_dispatch(
  489. self, within_columns_clause=True,
  490. within_label_clause=True, **kw) + \
  491. OPERATORS[operators.as_] + \
  492. self.preparer.format_label(label, labelname)
  493. elif render_label_only:
  494. return self.preparer.format_label(label, labelname)
  495. else:
  496. return label.element._compiler_dispatch(
  497. self, within_columns_clause=False, **kw)
  498. def visit_column(self, column, add_to_result_map=None,
  499. include_table=True, **kwargs):
  500. name = orig_name = column.name
  501. if name is None:
  502. raise exc.CompileError("Cannot compile Column object until "
  503. "its 'name' is assigned.")
  504. is_literal = column.is_literal
  505. if not is_literal and isinstance(name, elements._truncated_label):
  506. name = self._truncated_identifier("colident", name)
  507. if add_to_result_map is not None:
  508. add_to_result_map(
  509. name,
  510. orig_name,
  511. (column, name, column.key),
  512. column.type
  513. )
  514. if is_literal:
  515. name = self.escape_literal_column(name)
  516. else:
  517. name = self.preparer.quote(name)
  518. table = column.table
  519. if table is None or not include_table or not table.named_with_column:
  520. return name
  521. else:
  522. if table.schema:
  523. schema_prefix = self.preparer.quote_schema(table.schema) + '.'
  524. else:
  525. schema_prefix = ''
  526. tablename = table.name
  527. if isinstance(tablename, elements._truncated_label):
  528. tablename = self._truncated_identifier("alias", tablename)
  529. return schema_prefix + \
  530. self.preparer.quote(tablename) + \
  531. "." + name
  532. def escape_literal_column(self, text):
  533. """provide escaping for the literal_column() construct."""
  534. # TODO: some dialects might need different behavior here
  535. return text.replace('%', '%%')
  536. def visit_fromclause(self, fromclause, **kwargs):
  537. return fromclause.name
  538. def visit_index(self, index, **kwargs):
  539. return index.name
  540. def visit_typeclause(self, typeclause, **kw):
  541. kw['type_expression'] = typeclause
  542. return self.dialect.type_compiler.process(typeclause.type, **kw)
  543. def post_process_text(self, text):
  544. return text
  545. def visit_textclause(self, textclause, **kw):
  546. def do_bindparam(m):
  547. name = m.group(1)
  548. if name in textclause._bindparams:
  549. return self.process(textclause._bindparams[name], **kw)
  550. else:
  551. return self.bindparam_string(name, **kw)
  552. if not self.stack:
  553. self.isplaintext = True
  554. # un-escape any \:params
  555. return BIND_PARAMS_ESC.sub(
  556. lambda m: m.group(1),
  557. BIND_PARAMS.sub(
  558. do_bindparam,
  559. self.post_process_text(textclause.text))
  560. )
  561. def visit_text_as_from(self, taf,
  562. compound_index=None,
  563. asfrom=False,
  564. parens=True, **kw):
  565. toplevel = not self.stack
  566. entry = self._default_stack_entry if toplevel else self.stack[-1]
  567. populate_result_map = toplevel or \
  568. (
  569. compound_index == 0 and entry.get(
  570. 'need_result_map_for_compound', False)
  571. ) or entry.get('need_result_map_for_nested', False)
  572. if populate_result_map:
  573. self._ordered_columns = False
  574. for c in taf.column_args:
  575. self.process(c, within_columns_clause=True,
  576. add_to_result_map=self._add_to_result_map)
  577. text = self.process(taf.element, **kw)
  578. if asfrom and parens:
  579. text = "(%s)" % text
  580. return text
  581. def visit_null(self, expr, **kw):
  582. return 'NULL'
  583. def visit_true(self, expr, **kw):
  584. if self.dialect.supports_native_boolean:
  585. return 'true'
  586. else:
  587. return "1"
  588. def visit_false(self, expr, **kw):
  589. if self.dialect.supports_native_boolean:
  590. return 'false'
  591. else:
  592. return "0"
  593. def visit_clauselist(self, clauselist, **kw):
  594. sep = clauselist.operator
  595. if sep is None:
  596. sep = " "
  597. else:
  598. sep = OPERATORS[clauselist.operator]
  599. return sep.join(
  600. s for s in
  601. (
  602. c._compiler_dispatch(self, **kw)
  603. for c in clauselist.clauses)
  604. if s)
  605. def visit_case(self, clause, **kwargs):
  606. x = "CASE "
  607. if clause.value is not None:
  608. x += clause.value._compiler_dispatch(self, **kwargs) + " "
  609. for cond, result in clause.whens:
  610. x += "WHEN " + cond._compiler_dispatch(
  611. self, **kwargs
  612. ) + " THEN " + result._compiler_dispatch(
  613. self, **kwargs) + " "
  614. if clause.else_ is not None:
  615. x += "ELSE " + clause.else_._compiler_dispatch(
  616. self, **kwargs
  617. ) + " "
  618. x += "END"
  619. return x
  620. def visit_cast(self, cast, **kwargs):
  621. return "CAST(%s AS %s)" % \
  622. (cast.clause._compiler_dispatch(self, **kwargs),
  623. cast.typeclause._compiler_dispatch(self, **kwargs))
  624. def visit_over(self, over, **kwargs):
  625. return "%s OVER (%s)" % (
  626. over.func._compiler_dispatch(self, **kwargs),
  627. ' '.join(
  628. '%s BY %s' % (word, clause._compiler_dispatch(self, **kwargs))
  629. for word, clause in (
  630. ('PARTITION', over.partition_by),
  631. ('ORDER', over.order_by)
  632. )
  633. if clause is not None and len(clause)
  634. )
  635. )
  636. def visit_funcfilter(self, funcfilter, **kwargs):
  637. return "%s FILTER (WHERE %s)" % (
  638. funcfilter.func._compiler_dispatch(self, **kwargs),
  639. funcfilter.criterion._compiler_dispatch(self, **kwargs)
  640. )
  641. def visit_extract(self, extract, **kwargs):
  642. field = self.extract_map.get(extract.field, extract.field)
  643. return "EXTRACT(%s FROM %s)" % (
  644. field, extract.expr._compiler_dispatch(self, **kwargs))
  645. def visit_function(self, func, add_to_result_map=None, **kwargs):
  646. if add_to_result_map is not None:
  647. add_to_result_map(
  648. func.name, func.name, (), func.type
  649. )
  650. disp = getattr(self, "visit_%s_func" % func.name.lower(), None)
  651. if disp:
  652. return disp(func, **kwargs)
  653. else:
  654. name = FUNCTIONS.get(func.__class__, func.name + "%(expr)s")
  655. return ".".join(list(func.packagenames) + [name]) % \
  656. {'expr': self.function_argspec(func, **kwargs)}
  657. def visit_next_value_func(self, next_value, **kw):
  658. return self.visit_sequence(next_value.sequence)
  659. def visit_sequence(self, sequence):
  660. raise NotImplementedError(
  661. "Dialect '%s' does not support sequence increments." %
  662. self.dialect.name
  663. )
  664. def function_argspec(self, func, **kwargs):
  665. return func.clause_expr._compiler_dispatch(self, **kwargs)
  666. def visit_compound_select(self, cs, asfrom=False,
  667. parens=True, compound_index=0, **kwargs):
  668. toplevel = not self.stack
  669. entry = self._default_stack_entry if toplevel else self.stack[-1]
  670. need_result_map = toplevel or \
  671. (compound_index == 0
  672. and entry.get('need_result_map_for_compound', False))
  673. self.stack.append(
  674. {
  675. 'correlate_froms': entry['correlate_froms'],
  676. 'asfrom_froms': entry['asfrom_froms'],
  677. 'selectable': cs,
  678. 'need_result_map_for_compound': need_result_map
  679. })
  680. keyword = self.compound_keywords.get(cs.keyword)
  681. text = (" " + keyword + " ").join(
  682. (c._compiler_dispatch(self,
  683. asfrom=asfrom, parens=False,
  684. compound_index=i, **kwargs)
  685. for i, c in enumerate(cs.selects))
  686. )
  687. group_by = cs._group_by_clause._compiler_dispatch(
  688. self, asfrom=asfrom, **kwargs)
  689. if group_by:
  690. text += " GROUP BY " + group_by
  691. text += self.order_by_clause(cs, **kwargs)
  692. text += (cs._limit_clause is not None
  693. or cs._offset_clause is not None) and \
  694. self.limit_clause(cs, **kwargs) or ""
  695. if self.ctes and toplevel:
  696. text = self._render_cte_clause() + text
  697. self.stack.pop(-1)
  698. if asfrom and parens:
  699. return "(" + text + ")"
  700. else:
  701. return text
  702. def visit_unary(self, unary, **kw):
  703. if unary.operator:
  704. if unary.modifier:
  705. raise exc.CompileError(
  706. "Unary expression does not support operator "
  707. "and modifier simultaneously")
  708. disp = getattr(self, "visit_%s_unary_operator" %
  709. unary.operator.__name__, None)
  710. if disp:
  711. return disp(unary, unary.operator, **kw)
  712. else:
  713. return self._generate_generic_unary_operator(
  714. unary, OPERATORS[unary.operator], **kw)
  715. elif unary.modifier:
  716. disp = getattr(self, "visit_%s_unary_modifier" %
  717. unary.modifier.__name__, None)
  718. if disp:
  719. return disp(unary, unary.modifier, **kw)
  720. else:
  721. return self._generate_generic_unary_modifier(
  722. unary, OPERATORS[unary.modifier], **kw)
  723. else:
  724. raise exc.CompileError(
  725. "Unary expression has no operator or modifier")
  726. def visit_istrue_unary_operator(self, element, operator, **kw):
  727. if self.dialect.supports_native_boolean:
  728. return self.process(element.element, **kw)
  729. else:
  730. return "%s = 1" % self.process(element.element, **kw)
  731. def visit_isfalse_unary_operator(self, element, operator, **kw):
  732. if self.dialect.supports_native_boolean:
  733. return "NOT %s" % self.process(element.element, **kw)
  734. else:
  735. return "%s = 0" % self.process(element.element, **kw)
  736. def visit_notmatch_op_binary(self, binary, operator, **kw):
  737. return "NOT %s" % self.visit_binary(
  738. binary, override_operator=operators.match_op)
  739. def visit_binary(self, binary, override_operator=None, **kw):
  740. # don't allow "? = ?" to render
  741. if self.ansi_bind_rules and \
  742. isinstance(binary.left, elements.BindParameter) and \
  743. isinstance(binary.right, elements.BindParameter):
  744. kw['literal_binds'] = True
  745. operator_ = override_operator or binary.operator
  746. disp = getattr(self, "visit_%s_binary" % operator_.__name__, None)
  747. if disp:
  748. return disp(binary, operator_, **kw)
  749. else:
  750. try:
  751. opstring = OPERATORS[operator_]
  752. except KeyError:
  753. raise exc.UnsupportedCompilationError(self, operator_)
  754. else:
  755. return self._generate_generic_binary(binary, opstring, **kw)
  756. def visit_custom_op_binary(self, element, operator, **kw):
  757. return self._generate_generic_binary(
  758. element, " " + operator.opstring + " ", **kw)
  759. def visit_custom_op_unary_operator(self, element, operator, **kw):
  760. return self._generate_generic_unary_operator(
  761. element, operator.opstring + " ", **kw)
  762. def visit_custom_op_unary_modifier(self, element, operator, **kw):
  763. return self._generate_generic_unary_modifier(
  764. element, " " + operator.opstring, **kw)
  765. def _generate_generic_binary(self, binary, opstring, **kw):
  766. return binary.left._compiler_dispatch(self, **kw) + \
  767. opstring + \
  768. binary.right._compiler_dispatch(self, **kw)
  769. def _generate_generic_unary_operator(self, unary, opstring, **kw):
  770. return opstring + unary.element._compiler_dispatch(self, **kw)
  771. def _generate_generic_unary_modifier(self, unary, opstring, **kw):
  772. return unary.element._compiler_dispatch(self, **kw) + opstring
  773. @util.memoized_property
  774. def _like_percent_literal(self):
  775. return elements.literal_column("'%'", type_=sqltypes.STRINGTYPE)
  776. def visit_contains_op_binary(self, binary, operator, **kw):
  777. binary = binary._clone()
  778. percent = self._like_percent_literal
  779. binary.right = percent.__add__(binary.right).__add__(percent)
  780. return self.visit_like_op_binary(binary, operator, **kw)
  781. def visit_notcontains_op_binary(self, binary, operator, **kw):
  782. binary = binary._clone()
  783. percent = self._like_percent_literal
  784. binary.right = percent.__add__(binary.right).__add__(percent)
  785. return self.visit_notlike_op_binary(binary, operator, **kw)
  786. def visit_startswith_op_binary(self, binary, operator, **kw):
  787. binary = binary._clone()
  788. percent = self._like_percent_literal
  789. binary.right = percent.__radd__(
  790. binary.right
  791. )
  792. return self.visit_like_op_binary(binary, operator, **kw)
  793. def visit_notstartswith_op_binary(self, binary, operator, **kw):
  794. binary = binary._clone()
  795. percent = self._like_percent_literal
  796. binary.right = percent.__radd__(
  797. binary.right
  798. )
  799. return self.visit_notlike_op_binary(binary, operator, **kw)
  800. def visit_endswith_op_binary(self, binary, operator, **kw):
  801. binary = binary._clone()
  802. percent = self._like_percent_literal
  803. binary.right = percent.__add__(binary.right)
  804. return self.visit_like_op_binary(binary, operator, **kw)
  805. def visit_notendswith_op_binary(self, binary, operator, **kw):
  806. binary = binary._clone()
  807. percent = self._like_percent_literal
  808. binary.right = percent.__add__(binary.right)
  809. return self.visit_notlike_op_binary(binary, operator, **kw)
  810. def visit_like_op_binary(self, binary, operator, **kw):
  811. escape = binary.modifiers.get("escape", None)
  812. # TODO: use ternary here, not "and"/ "or"
  813. return '%s LIKE %s' % (
  814. binary.left._compiler_dispatch(self, **kw),
  815. binary.right._compiler_dispatch(self, **kw)) \
  816. + (
  817. ' ESCAPE ' +
  818. self.render_literal_value(escape, sqltypes.STRINGTYPE)
  819. if escape else ''
  820. )
  821. def visit_notlike_op_binary(self, binary, operator, **kw):
  822. escape = binary.modifiers.get("escape", None)
  823. return '%s NOT LIKE %s' % (
  824. binary.left._compiler_dispatch(self, **kw),
  825. binary.right._compiler_dispatch(self, **kw)) \
  826. + (
  827. ' ESCAPE ' +
  828. self.render_literal_value(escape, sqltypes.STRINGTYPE)
  829. if escape else ''
  830. )
  831. def visit_ilike_op_binary(self, binary, operator, **kw):
  832. escape = binary.modifiers.get("escape", None)
  833. return 'lower(%s) LIKE lower(%s)' % (
  834. binary.left._compiler_dispatch(self, **kw),
  835. binary.right._compiler_dispatch(self, **kw)) \
  836. + (
  837. ' ESCAPE ' +
  838. self.render_literal_value(escape, sqltypes.STRINGTYPE)
  839. if escape else ''
  840. )
  841. def visit_notilike_op_binary(self, binary, operator, **kw):
  842. escape = binary.modifiers.get("escape", None)
  843. return 'lower(%s) NOT LIKE lower(%s)' % (
  844. binary.left._compiler_dispatch(self, **kw),
  845. binary.right._compiler_dispatch(self, **kw)) \
  846. + (
  847. ' ESCAPE ' +
  848. self.render_literal_value(escape, sqltypes.STRINGTYPE)
  849. if escape else ''
  850. )
  851. def visit_between_op_binary(self, binary, operator, **kw):
  852. symmetric = binary.modifiers.get("symmetric", False)
  853. return self._generate_generic_binary(
  854. binary, " BETWEEN SYMMETRIC "
  855. if symmetric else " BETWEEN ", **kw)
  856. def visit_notbetween_op_binary(self, binary, operator, **kw):
  857. symmetric = binary.modifiers.get("symmetric", False)
  858. return self._generate_generic_binary(
  859. binary, " NOT BETWEEN SYMMETRIC "
  860. if symmetric else " NOT BETWEEN ", **kw)
  861. def visit_bindparam(self, bindparam, within_columns_clause=False,
  862. literal_binds=False,
  863. skip_bind_expression=False,
  864. **kwargs):
  865. if not skip_bind_expression and bindparam.type._has_bind_expression:
  866. bind_expression = bindparam.type.bind_expression(bindparam)
  867. return self.process(bind_expression,
  868. skip_bind_expression=True)
  869. if literal_binds or \
  870. (within_columns_clause and
  871. self.ansi_bind_rules):
  872. if bindparam.value is None and bindparam.callable is None:
  873. raise exc.CompileError("Bind parameter '%s' without a "
  874. "renderable value not allowed here."
  875. % bindparam.key)
  876. return self.render_literal_bindparam(
  877. bindparam, within_columns_clause=True, **kwargs)
  878. name = self._truncate_bindparam(bindparam)
  879. if name in self.binds:
  880. existing = self.binds[name]
  881. if existing is not bindparam:
  882. if (existing.unique or bindparam.unique) and \
  883. not existing.proxy_set.intersection(
  884. bindparam.proxy_set):
  885. raise exc.CompileError(
  886. "Bind parameter '%s' conflicts with "
  887. "unique bind parameter of the same name" %
  888. bindparam.key
  889. )
  890. elif existing._is_crud or bindparam._is_crud:
  891. raise exc.CompileError(
  892. "bindparam() name '%s' is reserved "
  893. "for automatic usage in the VALUES or SET "
  894. "clause of this "
  895. "insert/update statement. Please use a "
  896. "name other than column name when using bindparam() "
  897. "with insert() or update() (for example, 'b_%s')." %
  898. (bindparam.key, bindparam.key)
  899. )
  900. self.binds[bindparam.key] = self.binds[name] = bindparam
  901. return self.bindparam_string(name, **kwargs)
  902. def render_literal_bindparam(self, bindparam, **kw):
  903. value = bindparam.effective_value
  904. return self.render_literal_value(value, bindparam.type)
  905. def render_literal_value(self, value, type_):
  906. """Render the value of a bind parameter as a quoted literal.
  907. This is used for statement sections that do not accept bind parameters
  908. on the target driver/database.
  909. This should be implemented by subclasses using the quoting services
  910. of the DBAPI.
  911. """
  912. processor = type_._cached_literal_processor(self.dialect)
  913. if processor:
  914. return processor(value)
  915. else:
  916. raise NotImplementedError(
  917. "Don't know how to literal-quote value %r" % value)
  918. def _truncate_bindparam(self, bindparam):
  919. if bindparam in self.bind_names:
  920. return self.bind_names[bindparam]
  921. bind_name = bindparam.key
  922. if isinstance(bind_name, elements._truncated_label):
  923. bind_name = self._truncated_identifier("bindparam", bind_name)
  924. # add to bind_names for translation
  925. self.bind_names[bindparam] = bind_name
  926. return bind_name
  927. def _truncated_identifier(self, ident_class, name):
  928. if (ident_class, name) in self.truncated_names:
  929. return self.truncated_names[(ident_class, name)]
  930. anonname = name.apply_map(self.anon_map)
  931. if len(anonname) > self.label_length - 6:
  932. counter = self.truncated_names.get(ident_class, 1)
  933. truncname = anonname[0:max(self.label_length - 6, 0)] + \
  934. "_" + hex(counter)[2:]
  935. self.truncated_names[ident_class] = counter + 1
  936. else:
  937. truncname = anonname
  938. self.truncated_names[(ident_class, name)] = truncname
  939. return truncname
  940. def _anonymize(self, name):
  941. return name % self.anon_map
  942. def _process_anon(self, key):
  943. (ident, derived) = key.split(' ', 1)
  944. anonymous_counter = self.anon_map.get(derived, 1)
  945. self.anon_map[derived] = anonymous_counter + 1
  946. return derived + "_" + str(anonymous_counter)
  947. def bindparam_string(self, name, positional_names=None, **kw):
  948. if self.positional:
  949. if positional_names is not None:
  950. positional_names.append(name)
  951. else:
  952. self.positiontup.append(name)
  953. return self.bindtemplate % {'name': name}
  954. def visit_cte(self, cte, asfrom=False, ashint=False,
  955. fromhints=None,
  956. **kwargs):
  957. self._init_cte_state()
  958. if isinstance(cte.name, elements._truncated_label):
  959. cte_name = self._truncated_identifier("alias", cte.name)
  960. else:
  961. cte_name = cte.name
  962. if cte_name in self.ctes_by_name:
  963. existing_cte = self.ctes_by_name[cte_name]
  964. # we've generated a same-named CTE that we are enclosed in,
  965. # or this is the same CTE. just return the name.
  966. if cte in existing_cte._restates or cte is existing_cte:
  967. return self.preparer.format_alias(cte, cte_name)
  968. elif existing_cte in cte._restates:
  969. # we've generated a same-named CTE that is
  970. # enclosed in us - we take precedence, so
  971. # discard the text for the "inner".
  972. del self.ctes[existing_cte]
  973. else:
  974. raise exc.CompileError(
  975. "Multiple, unrelated CTEs found with "
  976. "the same name: %r" %
  977. cte_name)
  978. self.ctes_by_name[cte_name] = cte
  979. if cte._cte_alias is not None:
  980. orig_cte = cte._cte_alias
  981. if orig_cte not in self.ctes:
  982. self.visit_cte(orig_cte, **kwargs)
  983. cte_alias_name = cte._cte_alias.name
  984. if isinstance(cte_alias_name, elements._truncated_label):
  985. cte_alias_name = self._truncated_identifier(
  986. "alias", cte_alias_name)
  987. else:
  988. orig_cte = cte
  989. cte_alias_name = None
  990. if not cte_alias_name and cte not in self.ctes:
  991. if cte.recursive:
  992. self.ctes_recursive = True
  993. text = self.preparer.format_alias(cte, cte_name)
  994. if cte.recursive:
  995. if isinstance(cte.original, selectable.Select):
  996. col_source = cte.original
  997. elif isinstance(cte.original, selectable.CompoundSelect):
  998. col_source = cte.original.selects[0]
  999. else:
  1000. assert False
  1001. recur_cols = [c for c in
  1002. util.unique_list(col_source.inner_columns)
  1003. if c is not None]
  1004. text += "(%s)" % (", ".join(
  1005. self.preparer.format_column(ident)
  1006. for ident in recur_cols))
  1007. if self.positional:
  1008. kwargs['positional_names'] = self.cte_positional[cte] = []
  1009. text += " AS \n" + \
  1010. cte.original._compiler_dispatch(
  1011. self, asfrom=True, **kwargs
  1012. )
  1013. if cte._suffixes:
  1014. text += " " + self._generate_prefixes(
  1015. cte, cte._suffixes, **kwargs)
  1016. self.ctes[cte] = text
  1017. if asfrom:
  1018. if cte_alias_name:
  1019. text = self.preparer.format_alias(cte, cte_alias_name)
  1020. text += self.get_render_as_alias_suffix(cte_name)
  1021. else:
  1022. return self.preparer.format_alias(cte, cte_name)
  1023. return text
  1024. def visit_alias(self, alias, asfrom=False, ashint=False,
  1025. iscrud=False,
  1026. fromhints=None, **kwargs):
  1027. if asfrom or ashint:
  1028. if isinstance(alias.name, elements._truncated_label):
  1029. alias_name = self._truncated_identifier("alias", alias.name)
  1030. else:
  1031. alias_name = alias.name
  1032. if ashint:
  1033. return self.preparer.format_alias(alias, alias_name)
  1034. elif asfrom:
  1035. ret = alias.original._compiler_dispatch(self,
  1036. asfrom=True, **kwargs) + \
  1037. self.get_render_as_alias_suffix(
  1038. self.preparer.format_alias(alias, alias_name))
  1039. if fromhints and alias in fromhints:
  1040. ret = self.format_from_hint_text(ret, alias,
  1041. fromhints[alias], iscrud)
  1042. return ret
  1043. else:
  1044. return alias.original._compiler_dispatch(self, **kwargs)
  1045. def get_render_as_alias_suffix(self, alias_name_text):
  1046. return " AS " + alias_name_text
  1047. def _add_to_result_map(self, keyname, name, objects, type_):
  1048. self._result_columns.append((keyname, name, objects, type_))
  1049. def _label_select_column(self, select, column,
  1050. populate_result_map,
  1051. asfrom, column_clause_args,
  1052. name=None,
  1053. within_columns_clause=True):
  1054. """produce labeled columns present in a select()."""
  1055. if column.type._has_column_expression and \
  1056. populate_result_map:
  1057. col_expr = column.type.column_expression(column)
  1058. add_to_result_map = lambda keyname, name, objects, type_: \
  1059. self._add_to_result_map(
  1060. keyname, name,
  1061. objects + (column,), type_)
  1062. else:
  1063. col_expr = column
  1064. if populate_result_map:
  1065. add_to_result_map = self._add_to_result_map
  1066. else:
  1067. add_to_result_map = None
  1068. if not within_columns_clause:
  1069. result_expr = col_expr
  1070. elif isinstance(column, elements.Label):
  1071. if col_expr is not column:
  1072. result_expr = _CompileLabel(
  1073. col_expr,
  1074. column.name,
  1075. alt_names=(column.element,)
  1076. )
  1077. else:
  1078. result_expr = col_expr
  1079. elif select is not None and name:
  1080. result_expr = _CompileLabel(
  1081. col_expr,
  1082. name,
  1083. alt_names=(column._key_label,)
  1084. )
  1085. elif \
  1086. asfrom and \
  1087. isinstance(column, elements.ColumnClause) and \
  1088. not column.is_literal and \
  1089. column.table is not None and \
  1090. not isinstance(column.table, selectable.Select):
  1091. result_expr = _CompileLabel(col_expr,
  1092. elements._as_truncated(column.name),
  1093. alt_names=(column.key,))
  1094. elif (
  1095. not isinstance(column, elements.TextClause) and
  1096. (
  1097. not isinstance(column, elements.UnaryExpression) or
  1098. column.wraps_column_expression
  1099. ) and
  1100. (
  1101. not hasattr(column, 'name') or
  1102. isinstance(column, functions.Function)
  1103. )
  1104. ):
  1105. result_expr = _CompileLabel(col_expr, column.anon_label)
  1106. elif col_expr is not column:
  1107. # TODO: are we sure "column" has a .name and .key here ?
  1108. # assert isinstance(column, elements.ColumnClause)
  1109. result_expr = _CompileLabel(col_expr,
  1110. elements._as_truncated(column.name),
  1111. alt_names=(column.key,))
  1112. else:
  1113. result_expr = col_expr
  1114. column_clause_args.update(
  1115. within_columns_clause=within_columns_clause,
  1116. add_to_result_map=add_to_result_map
  1117. )
  1118. return result_expr._compiler_dispatch(
  1119. self,
  1120. **column_clause_args
  1121. )
  1122. def format_from_hint_text(self, sqltext, table, hint, iscrud):
  1123. hinttext = self.get_from_hint_text(table, hint)
  1124. if hinttext:
  1125. sqltext += " " + hinttext
  1126. return sqltext
  1127. def get_select_hint_text(self, byfroms):
  1128. return None
  1129. def get_from_hint_text(self, table, text):
  1130. return None
  1131. def get_crud_hint_text(self, table, text):
  1132. return None
  1133. def get_statement_hint_text(self, hint_texts):
  1134. return " ".join(hint_texts)
  1135. def _transform_select_for_nested_joins(self, select):
  1136. """Rewrite any "a JOIN (b JOIN c)" expression as
  1137. "a JOIN (select * from b JOIN c) AS anon", to support
  1138. databases that can't parse a parenthesized join correctly
  1139. (i.e. sqlite the main one).
  1140. """
  1141. cloned = {}
  1142. column_translate = [{}]
  1143. def visit(element, **kw):
  1144. if element