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.

5098 lines
168KB

  1. # sql/compiler.py
  2. # Copyright (C) 2005-2021 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 collections
  19. import contextlib
  20. import itertools
  21. import operator
  22. import re
  23. from . import base
  24. from . import coercions
  25. from . import crud
  26. from . import elements
  27. from . import functions
  28. from . import operators
  29. from . import roles
  30. from . import schema
  31. from . import selectable
  32. from . import sqltypes
  33. from .base import NO_ARG
  34. from .base import prefix_anon_map
  35. from .elements import quoted_name
  36. from .. import exc
  37. from .. import util
  38. RESERVED_WORDS = set(
  39. [
  40. "all",
  41. "analyse",
  42. "analyze",
  43. "and",
  44. "any",
  45. "array",
  46. "as",
  47. "asc",
  48. "asymmetric",
  49. "authorization",
  50. "between",
  51. "binary",
  52. "both",
  53. "case",
  54. "cast",
  55. "check",
  56. "collate",
  57. "column",
  58. "constraint",
  59. "create",
  60. "cross",
  61. "current_date",
  62. "current_role",
  63. "current_time",
  64. "current_timestamp",
  65. "current_user",
  66. "default",
  67. "deferrable",
  68. "desc",
  69. "distinct",
  70. "do",
  71. "else",
  72. "end",
  73. "except",
  74. "false",
  75. "for",
  76. "foreign",
  77. "freeze",
  78. "from",
  79. "full",
  80. "grant",
  81. "group",
  82. "having",
  83. "ilike",
  84. "in",
  85. "initially",
  86. "inner",
  87. "intersect",
  88. "into",
  89. "is",
  90. "isnull",
  91. "join",
  92. "leading",
  93. "left",
  94. "like",
  95. "limit",
  96. "localtime",
  97. "localtimestamp",
  98. "natural",
  99. "new",
  100. "not",
  101. "notnull",
  102. "null",
  103. "off",
  104. "offset",
  105. "old",
  106. "on",
  107. "only",
  108. "or",
  109. "order",
  110. "outer",
  111. "overlaps",
  112. "placing",
  113. "primary",
  114. "references",
  115. "right",
  116. "select",
  117. "session_user",
  118. "set",
  119. "similar",
  120. "some",
  121. "symmetric",
  122. "table",
  123. "then",
  124. "to",
  125. "trailing",
  126. "true",
  127. "union",
  128. "unique",
  129. "user",
  130. "using",
  131. "verbose",
  132. "when",
  133. "where",
  134. ]
  135. )
  136. LEGAL_CHARACTERS = re.compile(r"^[A-Z0-9_$]+$", re.I)
  137. LEGAL_CHARACTERS_PLUS_SPACE = re.compile(r"^[A-Z0-9_ $]+$", re.I)
  138. ILLEGAL_INITIAL_CHARACTERS = {str(x) for x in range(0, 10)}.union(["$"])
  139. FK_ON_DELETE = re.compile(
  140. r"^(?:RESTRICT|CASCADE|SET NULL|NO ACTION|SET DEFAULT)$", re.I
  141. )
  142. FK_ON_UPDATE = re.compile(
  143. r"^(?:RESTRICT|CASCADE|SET NULL|NO ACTION|SET DEFAULT)$", re.I
  144. )
  145. FK_INITIALLY = re.compile(r"^(?:DEFERRED|IMMEDIATE)$", re.I)
  146. BIND_PARAMS = re.compile(r"(?<![:\w\$\x5c]):([\w\$]+)(?![:\w\$])", re.UNICODE)
  147. BIND_PARAMS_ESC = re.compile(r"\x5c(:[\w\$]*)(?![:\w\$])", re.UNICODE)
  148. BIND_TEMPLATES = {
  149. "pyformat": "%%(%(name)s)s",
  150. "qmark": "?",
  151. "format": "%%s",
  152. "numeric": ":[_POSITION]",
  153. "named": ":%(name)s",
  154. }
  155. BIND_TRANSLATE = {
  156. "pyformat": re.compile(r"[%\(\)]"),
  157. "named": re.compile(r"[\:]"),
  158. }
  159. _BIND_TRANSLATE_CHARS = {"%": "P", "(": "A", ")": "Z", ":": "C"}
  160. OPERATORS = {
  161. # binary
  162. operators.and_: " AND ",
  163. operators.or_: " OR ",
  164. operators.add: " + ",
  165. operators.mul: " * ",
  166. operators.sub: " - ",
  167. operators.div: " / ",
  168. operators.mod: " % ",
  169. operators.truediv: " / ",
  170. operators.neg: "-",
  171. operators.lt: " < ",
  172. operators.le: " <= ",
  173. operators.ne: " != ",
  174. operators.gt: " > ",
  175. operators.ge: " >= ",
  176. operators.eq: " = ",
  177. operators.is_distinct_from: " IS DISTINCT FROM ",
  178. operators.is_not_distinct_from: " IS NOT DISTINCT FROM ",
  179. operators.concat_op: " || ",
  180. operators.match_op: " MATCH ",
  181. operators.not_match_op: " NOT MATCH ",
  182. operators.in_op: " IN ",
  183. operators.not_in_op: " NOT IN ",
  184. operators.comma_op: ", ",
  185. operators.from_: " FROM ",
  186. operators.as_: " AS ",
  187. operators.is_: " IS ",
  188. operators.is_not: " IS NOT ",
  189. operators.collate: " COLLATE ",
  190. # unary
  191. operators.exists: "EXISTS ",
  192. operators.distinct_op: "DISTINCT ",
  193. operators.inv: "NOT ",
  194. operators.any_op: "ANY ",
  195. operators.all_op: "ALL ",
  196. # modifiers
  197. operators.desc_op: " DESC",
  198. operators.asc_op: " ASC",
  199. operators.nulls_first_op: " NULLS FIRST",
  200. operators.nulls_last_op: " NULLS LAST",
  201. }
  202. FUNCTIONS = {
  203. functions.coalesce: "coalesce",
  204. functions.current_date: "CURRENT_DATE",
  205. functions.current_time: "CURRENT_TIME",
  206. functions.current_timestamp: "CURRENT_TIMESTAMP",
  207. functions.current_user: "CURRENT_USER",
  208. functions.localtime: "LOCALTIME",
  209. functions.localtimestamp: "LOCALTIMESTAMP",
  210. functions.random: "random",
  211. functions.sysdate: "sysdate",
  212. functions.session_user: "SESSION_USER",
  213. functions.user: "USER",
  214. functions.cube: "CUBE",
  215. functions.rollup: "ROLLUP",
  216. functions.grouping_sets: "GROUPING SETS",
  217. }
  218. EXTRACT_MAP = {
  219. "month": "month",
  220. "day": "day",
  221. "year": "year",
  222. "second": "second",
  223. "hour": "hour",
  224. "doy": "doy",
  225. "minute": "minute",
  226. "quarter": "quarter",
  227. "dow": "dow",
  228. "week": "week",
  229. "epoch": "epoch",
  230. "milliseconds": "milliseconds",
  231. "microseconds": "microseconds",
  232. "timezone_hour": "timezone_hour",
  233. "timezone_minute": "timezone_minute",
  234. }
  235. COMPOUND_KEYWORDS = {
  236. selectable.CompoundSelect.UNION: "UNION",
  237. selectable.CompoundSelect.UNION_ALL: "UNION ALL",
  238. selectable.CompoundSelect.EXCEPT: "EXCEPT",
  239. selectable.CompoundSelect.EXCEPT_ALL: "EXCEPT ALL",
  240. selectable.CompoundSelect.INTERSECT: "INTERSECT",
  241. selectable.CompoundSelect.INTERSECT_ALL: "INTERSECT ALL",
  242. }
  243. RM_RENDERED_NAME = 0
  244. RM_NAME = 1
  245. RM_OBJECTS = 2
  246. RM_TYPE = 3
  247. ExpandedState = collections.namedtuple(
  248. "ExpandedState",
  249. [
  250. "statement",
  251. "additional_parameters",
  252. "processors",
  253. "positiontup",
  254. "parameter_expansion",
  255. ],
  256. )
  257. NO_LINTING = util.symbol("NO_LINTING", "Disable all linting.", canonical=0)
  258. COLLECT_CARTESIAN_PRODUCTS = util.symbol(
  259. "COLLECT_CARTESIAN_PRODUCTS",
  260. "Collect data on FROMs and cartesian products and gather "
  261. "into 'self.from_linter'",
  262. canonical=1,
  263. )
  264. WARN_LINTING = util.symbol(
  265. "WARN_LINTING", "Emit warnings for linters that find problems", canonical=2
  266. )
  267. FROM_LINTING = util.symbol(
  268. "FROM_LINTING",
  269. "Warn for cartesian products; "
  270. "combines COLLECT_CARTESIAN_PRODUCTS and WARN_LINTING",
  271. canonical=COLLECT_CARTESIAN_PRODUCTS | WARN_LINTING,
  272. )
  273. class FromLinter(collections.namedtuple("FromLinter", ["froms", "edges"])):
  274. def lint(self, start=None):
  275. froms = self.froms
  276. if not froms:
  277. return None, None
  278. edges = set(self.edges)
  279. the_rest = set(froms)
  280. if start is not None:
  281. start_with = start
  282. the_rest.remove(start_with)
  283. else:
  284. start_with = the_rest.pop()
  285. stack = collections.deque([start_with])
  286. while stack and the_rest:
  287. node = stack.popleft()
  288. the_rest.discard(node)
  289. # comparison of nodes in edges here is based on hash equality, as
  290. # there are "annotated" elements that match the non-annotated ones.
  291. # to remove the need for in-python hash() calls, use native
  292. # containment routines (e.g. "node in edge", "edge.index(node)")
  293. to_remove = {edge for edge in edges if node in edge}
  294. # appendleft the node in each edge that is not
  295. # the one that matched.
  296. stack.extendleft(edge[not edge.index(node)] for edge in to_remove)
  297. edges.difference_update(to_remove)
  298. # FROMS left over? boom
  299. if the_rest:
  300. return the_rest, start_with
  301. else:
  302. return None, None
  303. def warn(self):
  304. the_rest, start_with = self.lint()
  305. # FROMS left over? boom
  306. if the_rest:
  307. froms = the_rest
  308. if froms:
  309. template = (
  310. "SELECT statement has a cartesian product between "
  311. "FROM element(s) {froms} and "
  312. 'FROM element "{start}". Apply join condition(s) '
  313. "between each element to resolve."
  314. )
  315. froms_str = ", ".join(
  316. '"{elem}"'.format(elem=self.froms[from_])
  317. for from_ in froms
  318. )
  319. message = template.format(
  320. froms=froms_str, start=self.froms[start_with]
  321. )
  322. util.warn(message)
  323. class Compiled(object):
  324. """Represent a compiled SQL or DDL expression.
  325. The ``__str__`` method of the ``Compiled`` object should produce
  326. the actual text of the statement. ``Compiled`` objects are
  327. specific to their underlying database dialect, and also may
  328. or may not be specific to the columns referenced within a
  329. particular set of bind parameters. In no case should the
  330. ``Compiled`` object be dependent on the actual values of those
  331. bind parameters, even though it may reference those values as
  332. defaults.
  333. """
  334. _cached_metadata = None
  335. _result_columns = None
  336. schema_translate_map = None
  337. execution_options = util.EMPTY_DICT
  338. """
  339. Execution options propagated from the statement. In some cases,
  340. sub-elements of the statement can modify these.
  341. """
  342. _annotations = util.EMPTY_DICT
  343. compile_state = None
  344. """Optional :class:`.CompileState` object that maintains additional
  345. state used by the compiler.
  346. Major executable objects such as :class:`_expression.Insert`,
  347. :class:`_expression.Update`, :class:`_expression.Delete`,
  348. :class:`_expression.Select` will generate this
  349. state when compiled in order to calculate additional information about the
  350. object. For the top level object that is to be executed, the state can be
  351. stored here where it can also have applicability towards result set
  352. processing.
  353. .. versionadded:: 1.4
  354. """
  355. cache_key = None
  356. _gen_time = None
  357. def __init__(
  358. self,
  359. dialect,
  360. statement,
  361. schema_translate_map=None,
  362. render_schema_translate=False,
  363. compile_kwargs=util.immutabledict(),
  364. ):
  365. """Construct a new :class:`.Compiled` object.
  366. :param dialect: :class:`.Dialect` to compile against.
  367. :param statement: :class:`_expression.ClauseElement` to be compiled.
  368. :param schema_translate_map: dictionary of schema names to be
  369. translated when forming the resultant SQL
  370. .. versionadded:: 1.1
  371. .. seealso::
  372. :ref:`schema_translating`
  373. :param compile_kwargs: additional kwargs that will be
  374. passed to the initial call to :meth:`.Compiled.process`.
  375. """
  376. self.dialect = dialect
  377. self.preparer = self.dialect.identifier_preparer
  378. if schema_translate_map:
  379. self.schema_translate_map = schema_translate_map
  380. self.preparer = self.preparer._with_schema_translate(
  381. schema_translate_map
  382. )
  383. if statement is not None:
  384. self.statement = statement
  385. self.can_execute = statement.supports_execution
  386. self._annotations = statement._annotations
  387. if self.can_execute:
  388. self.execution_options = statement._execution_options
  389. self.string = self.process(self.statement, **compile_kwargs)
  390. if render_schema_translate:
  391. self.string = self.preparer._render_schema_translates(
  392. self.string, schema_translate_map
  393. )
  394. self._gen_time = util.perf_counter()
  395. def _execute_on_connection(
  396. self, connection, multiparams, params, execution_options
  397. ):
  398. if self.can_execute:
  399. return connection._execute_compiled(
  400. self, multiparams, params, execution_options
  401. )
  402. else:
  403. raise exc.ObjectNotExecutableError(self.statement)
  404. def visit_unsupported_compilation(self, element, err):
  405. util.raise_(
  406. exc.UnsupportedCompilationError(self, type(element)),
  407. replace_context=err,
  408. )
  409. @property
  410. def sql_compiler(self):
  411. """Return a Compiled that is capable of processing SQL expressions.
  412. If this compiler is one, it would likely just return 'self'.
  413. """
  414. raise NotImplementedError()
  415. def process(self, obj, **kwargs):
  416. return obj._compiler_dispatch(self, **kwargs)
  417. def __str__(self):
  418. """Return the string text of the generated SQL or DDL."""
  419. return self.string or ""
  420. def construct_params(self, params=None, extracted_parameters=None):
  421. """Return the bind params for this compiled object.
  422. :param params: a dict of string/object pairs whose values will
  423. override bind values compiled in to the
  424. statement.
  425. """
  426. raise NotImplementedError()
  427. @property
  428. def params(self):
  429. """Return the bind params for this compiled object."""
  430. return self.construct_params()
  431. class TypeCompiler(util.with_metaclass(util.EnsureKWArgType, object)):
  432. """Produces DDL specification for TypeEngine objects."""
  433. ensure_kwarg = r"visit_\w+"
  434. def __init__(self, dialect):
  435. self.dialect = dialect
  436. def process(self, type_, **kw):
  437. return type_._compiler_dispatch(self, **kw)
  438. def visit_unsupported_compilation(self, element, err, **kw):
  439. util.raise_(
  440. exc.UnsupportedCompilationError(self, element),
  441. replace_context=err,
  442. )
  443. # this was a Visitable, but to allow accurate detection of
  444. # column elements this is actually a column element
  445. class _CompileLabel(elements.ColumnElement):
  446. """lightweight label object which acts as an expression.Label."""
  447. __visit_name__ = "label"
  448. __slots__ = "element", "name"
  449. def __init__(self, col, name, alt_names=()):
  450. self.element = col
  451. self.name = name
  452. self._alt_names = (col,) + alt_names
  453. @property
  454. def proxy_set(self):
  455. return self.element.proxy_set
  456. @property
  457. def type(self):
  458. return self.element.type
  459. def self_group(self, **kw):
  460. return self
  461. class SQLCompiler(Compiled):
  462. """Default implementation of :class:`.Compiled`.
  463. Compiles :class:`_expression.ClauseElement` objects into SQL strings.
  464. """
  465. extract_map = EXTRACT_MAP
  466. compound_keywords = COMPOUND_KEYWORDS
  467. isdelete = isinsert = isupdate = False
  468. """class-level defaults which can be set at the instance
  469. level to define if this Compiled instance represents
  470. INSERT/UPDATE/DELETE
  471. """
  472. isplaintext = False
  473. returning = None
  474. """holds the "returning" collection of columns if
  475. the statement is CRUD and defines returning columns
  476. either implicitly or explicitly
  477. """
  478. returning_precedes_values = False
  479. """set to True classwide to generate RETURNING
  480. clauses before the VALUES or WHERE clause (i.e. MSSQL)
  481. """
  482. render_table_with_column_in_update_from = False
  483. """set to True classwide to indicate the SET clause
  484. in a multi-table UPDATE statement should qualify
  485. columns with the table name (i.e. MySQL only)
  486. """
  487. ansi_bind_rules = False
  488. """SQL 92 doesn't allow bind parameters to be used
  489. in the columns clause of a SELECT, nor does it allow
  490. ambiguous expressions like "? = ?". A compiler
  491. subclass can set this flag to False if the target
  492. driver/DB enforces this
  493. """
  494. _textual_ordered_columns = False
  495. """tell the result object that the column names as rendered are important,
  496. but they are also "ordered" vs. what is in the compiled object here.
  497. """
  498. _ordered_columns = True
  499. """
  500. if False, means we can't be sure the list of entries
  501. in _result_columns is actually the rendered order. Usually
  502. True unless using an unordered TextualSelect.
  503. """
  504. _loose_column_name_matching = False
  505. """tell the result object that the SQL staement is textual, wants to match
  506. up to Column objects, and may be using the ._label in the SELECT rather
  507. than the base name.
  508. """
  509. _numeric_binds = False
  510. """
  511. True if paramstyle is "numeric". This paramstyle is trickier than
  512. all the others.
  513. """
  514. _render_postcompile = False
  515. """
  516. whether to render out POSTCOMPILE params during the compile phase.
  517. """
  518. insert_single_values_expr = None
  519. """When an INSERT is compiled with a single set of parameters inside
  520. a VALUES expression, the string is assigned here, where it can be
  521. used for insert batching schemes to rewrite the VALUES expression.
  522. .. versionadded:: 1.3.8
  523. """
  524. literal_execute_params = frozenset()
  525. """bindparameter objects that are rendered as literal values at statement
  526. execution time.
  527. """
  528. post_compile_params = frozenset()
  529. """bindparameter objects that are rendered as bound parameter placeholders
  530. at statement execution time.
  531. """
  532. escaped_bind_names = util.EMPTY_DICT
  533. """Late escaping of bound parameter names that has to be converted
  534. to the original name when looking in the parameter dictionary.
  535. """
  536. has_out_parameters = False
  537. """if True, there are bindparam() objects that have the isoutparam
  538. flag set."""
  539. insert_prefetch = update_prefetch = ()
  540. postfetch_lastrowid = False
  541. """if True, and this in insert, use cursor.lastrowid to populate
  542. result.inserted_primary_key. """
  543. _cache_key_bind_match = None
  544. """a mapping that will relate the BindParameter object we compile
  545. to those that are part of the extracted collection of parameters
  546. in the cache key, if we were given a cache key.
  547. """
  548. inline = False
  549. def __init__(
  550. self,
  551. dialect,
  552. statement,
  553. cache_key=None,
  554. column_keys=None,
  555. for_executemany=False,
  556. linting=NO_LINTING,
  557. **kwargs
  558. ):
  559. """Construct a new :class:`.SQLCompiler` object.
  560. :param dialect: :class:`.Dialect` to be used
  561. :param statement: :class:`_expression.ClauseElement` to be compiled
  562. :param column_keys: a list of column names to be compiled into an
  563. INSERT or UPDATE statement.
  564. :param for_executemany: whether INSERT / UPDATE statements should
  565. expect that they are to be invoked in an "executemany" style,
  566. which may impact how the statement will be expected to return the
  567. values of defaults and autoincrement / sequences and similar.
  568. Depending on the backend and driver in use, support for retrieving
  569. these values may be disabled which means SQL expressions may
  570. be rendered inline, RETURNING may not be rendered, etc.
  571. :param kwargs: additional keyword arguments to be consumed by the
  572. superclass.
  573. """
  574. self.column_keys = column_keys
  575. self.cache_key = cache_key
  576. if cache_key:
  577. self._cache_key_bind_match = ckbm = {
  578. b.key: b for b in cache_key[1]
  579. }
  580. ckbm.update({b: [b] for b in cache_key[1]})
  581. # compile INSERT/UPDATE defaults/sequences to expect executemany
  582. # style execution, which may mean no pre-execute of defaults,
  583. # or no RETURNING
  584. self.for_executemany = for_executemany
  585. self.linting = linting
  586. # a dictionary of bind parameter keys to BindParameter
  587. # instances.
  588. self.binds = {}
  589. # a dictionary of BindParameter instances to "compiled" names
  590. # that are actually present in the generated SQL
  591. self.bind_names = util.column_dict()
  592. # stack which keeps track of nested SELECT statements
  593. self.stack = []
  594. # relates label names in the final SQL to a tuple of local
  595. # column/label name, ColumnElement object (if any) and
  596. # TypeEngine. CursorResult uses this for type processing and
  597. # column targeting
  598. self._result_columns = []
  599. # true if the paramstyle is positional
  600. self.positional = dialect.positional
  601. if self.positional:
  602. self.positiontup = []
  603. self._numeric_binds = dialect.paramstyle == "numeric"
  604. self.bindtemplate = BIND_TEMPLATES[dialect.paramstyle]
  605. self._bind_translate = BIND_TRANSLATE.get(dialect.paramstyle, None)
  606. self.ctes = None
  607. self.label_length = (
  608. dialect.label_length or dialect.max_identifier_length
  609. )
  610. # a map which tracks "anonymous" identifiers that are created on
  611. # the fly here
  612. self.anon_map = prefix_anon_map()
  613. # a map which tracks "truncated" names based on
  614. # dialect.label_length or dialect.max_identifier_length
  615. self.truncated_names = {}
  616. Compiled.__init__(self, dialect, statement, **kwargs)
  617. if self.isinsert or self.isupdate or self.isdelete:
  618. if statement._returning:
  619. self.returning = statement._returning
  620. if self.isinsert or self.isupdate:
  621. if statement._inline:
  622. self.inline = True
  623. elif self.for_executemany and (
  624. not self.isinsert
  625. or (
  626. self.dialect.insert_executemany_returning
  627. and statement._return_defaults
  628. )
  629. ):
  630. self.inline = True
  631. if self.positional and self._numeric_binds:
  632. self._apply_numbered_params()
  633. if self._render_postcompile:
  634. self._process_parameters_for_postcompile(_populate_self=True)
  635. @property
  636. def current_executable(self):
  637. """Return the current 'executable' that is being compiled.
  638. This is currently the :class:`_sql.Select`, :class:`_sql.Insert`,
  639. :class:`_sql.Update`, :class:`_sql.Delete`,
  640. :class:`_sql.CompoundSelect` object that is being compiled.
  641. Specifically it's assigned to the ``self.stack`` list of elements.
  642. When a statement like the above is being compiled, it normally
  643. is also assigned to the ``.statement`` attribute of the
  644. :class:`_sql.Compiler` object. However, all SQL constructs are
  645. ultimately nestable, and this attribute should never be consulted
  646. by a ``visit_`` method, as it is not guaranteed to be assigned
  647. nor guaranteed to correspond to the current statement being compiled.
  648. .. versionadded:: 1.3.21
  649. For compatibility with previous versions, use the following
  650. recipe::
  651. statement = getattr(self, "current_executable", False)
  652. if statement is False:
  653. statement = self.stack[-1]["selectable"]
  654. For versions 1.4 and above, ensure only .current_executable
  655. is used; the format of "self.stack" may change.
  656. """
  657. try:
  658. return self.stack[-1]["selectable"]
  659. except IndexError as ie:
  660. util.raise_(
  661. IndexError("Compiler does not have a stack entry"),
  662. replace_context=ie,
  663. )
  664. @property
  665. def prefetch(self):
  666. return list(self.insert_prefetch + self.update_prefetch)
  667. @util.memoized_property
  668. def _global_attributes(self):
  669. return {}
  670. @util.memoized_instancemethod
  671. def _init_cte_state(self):
  672. """Initialize collections related to CTEs only if
  673. a CTE is located, to save on the overhead of
  674. these collections otherwise.
  675. """
  676. # collect CTEs to tack on top of a SELECT
  677. self.ctes = util.OrderedDict()
  678. self.ctes_by_name = {}
  679. self.ctes_recursive = False
  680. if self.positional:
  681. self.cte_positional = {}
  682. @contextlib.contextmanager
  683. def _nested_result(self):
  684. """special API to support the use case of 'nested result sets'"""
  685. result_columns, ordered_columns = (
  686. self._result_columns,
  687. self._ordered_columns,
  688. )
  689. self._result_columns, self._ordered_columns = [], False
  690. try:
  691. if self.stack:
  692. entry = self.stack[-1]
  693. entry["need_result_map_for_nested"] = True
  694. else:
  695. entry = None
  696. yield self._result_columns, self._ordered_columns
  697. finally:
  698. if entry:
  699. entry.pop("need_result_map_for_nested")
  700. self._result_columns, self._ordered_columns = (
  701. result_columns,
  702. ordered_columns,
  703. )
  704. def _apply_numbered_params(self):
  705. poscount = itertools.count(1)
  706. self.string = re.sub(
  707. r"\[_POSITION\]", lambda m: str(util.next(poscount)), self.string
  708. )
  709. @util.memoized_property
  710. def _bind_processors(self):
  711. return dict(
  712. (key, value)
  713. for key, value in (
  714. (
  715. self.bind_names[bindparam],
  716. bindparam.type._cached_bind_processor(self.dialect)
  717. if not bindparam.type._is_tuple_type
  718. else tuple(
  719. elem_type._cached_bind_processor(self.dialect)
  720. for elem_type in bindparam.type.types
  721. ),
  722. )
  723. for bindparam in self.bind_names
  724. )
  725. if value is not None
  726. )
  727. def is_subquery(self):
  728. return len(self.stack) > 1
  729. @property
  730. def sql_compiler(self):
  731. return self
  732. def construct_params(
  733. self,
  734. params=None,
  735. _group_number=None,
  736. _check=True,
  737. extracted_parameters=None,
  738. ):
  739. """return a dictionary of bind parameter keys and values"""
  740. has_escaped_names = bool(self.escaped_bind_names)
  741. if extracted_parameters:
  742. # related the bound parameters collected in the original cache key
  743. # to those collected in the incoming cache key. They will not have
  744. # matching names but they will line up positionally in the same
  745. # way. The parameters present in self.bind_names may be clones of
  746. # these original cache key params in the case of DML but the .key
  747. # will be guaranteed to match.
  748. try:
  749. orig_extracted = self.cache_key[1]
  750. except TypeError as err:
  751. util.raise_(
  752. exc.CompileError(
  753. "This compiled object has no original cache key; "
  754. "can't pass extracted_parameters to construct_params"
  755. ),
  756. replace_context=err,
  757. )
  758. ckbm = self._cache_key_bind_match
  759. resolved_extracted = {
  760. bind: extracted
  761. for b, extracted in zip(orig_extracted, extracted_parameters)
  762. for bind in ckbm[b]
  763. }
  764. else:
  765. resolved_extracted = None
  766. if params:
  767. pd = {}
  768. for bindparam, name in self.bind_names.items():
  769. escaped_name = (
  770. self.escaped_bind_names.get(name, name)
  771. if has_escaped_names
  772. else name
  773. )
  774. if bindparam.key in params:
  775. pd[escaped_name] = params[bindparam.key]
  776. elif name in params:
  777. pd[escaped_name] = params[name]
  778. elif _check and bindparam.required:
  779. if _group_number:
  780. raise exc.InvalidRequestError(
  781. "A value is required for bind parameter %r, "
  782. "in parameter group %d"
  783. % (bindparam.key, _group_number),
  784. code="cd3x",
  785. )
  786. else:
  787. raise exc.InvalidRequestError(
  788. "A value is required for bind parameter %r"
  789. % bindparam.key,
  790. code="cd3x",
  791. )
  792. else:
  793. if resolved_extracted:
  794. value_param = resolved_extracted.get(
  795. bindparam, bindparam
  796. )
  797. else:
  798. value_param = bindparam
  799. if bindparam.callable:
  800. pd[escaped_name] = value_param.effective_value
  801. else:
  802. pd[escaped_name] = value_param.value
  803. return pd
  804. else:
  805. pd = {}
  806. for bindparam, name in self.bind_names.items():
  807. escaped_name = (
  808. self.escaped_bind_names.get(name, name)
  809. if has_escaped_names
  810. else name
  811. )
  812. if _check and bindparam.required:
  813. if _group_number:
  814. raise exc.InvalidRequestError(
  815. "A value is required for bind parameter %r, "
  816. "in parameter group %d"
  817. % (bindparam.key, _group_number),
  818. code="cd3x",
  819. )
  820. else:
  821. raise exc.InvalidRequestError(
  822. "A value is required for bind parameter %r"
  823. % bindparam.key,
  824. code="cd3x",
  825. )
  826. if resolved_extracted:
  827. value_param = resolved_extracted.get(bindparam, bindparam)
  828. else:
  829. value_param = bindparam
  830. if bindparam.callable:
  831. pd[escaped_name] = value_param.effective_value
  832. else:
  833. pd[escaped_name] = value_param.value
  834. return pd
  835. @util.memoized_instancemethod
  836. def _get_set_input_sizes_lookup(
  837. self, include_types=None, exclude_types=None
  838. ):
  839. if not hasattr(self, "bind_names"):
  840. return None
  841. dialect = self.dialect
  842. dbapi = self.dialect.dbapi
  843. # _unwrapped_dialect_impl() is necessary so that we get the
  844. # correct dialect type for a custom TypeDecorator, or a Variant,
  845. # which is also a TypeDecorator. Special types like Interval,
  846. # that use TypeDecorator but also might be mapped directly
  847. # for a dialect impl, also subclass Emulated first which overrides
  848. # this behavior in those cases to behave like the default.
  849. if include_types is None and exclude_types is None:
  850. def _lookup_type(typ):
  851. dbtype = typ.dialect_impl(dialect).get_dbapi_type(dbapi)
  852. return dbtype
  853. else:
  854. def _lookup_type(typ):
  855. # note we get dbtype from the possibly TypeDecorator-wrapped
  856. # dialect_impl, but the dialect_impl itself that we use for
  857. # include/exclude is the unwrapped version.
  858. dialect_impl = typ._unwrapped_dialect_impl(dialect)
  859. dbtype = typ.dialect_impl(dialect).get_dbapi_type(dbapi)
  860. if (
  861. dbtype is not None
  862. and (
  863. exclude_types is None
  864. or dbtype not in exclude_types
  865. and type(dialect_impl) not in exclude_types
  866. )
  867. and (
  868. include_types is None
  869. or dbtype in include_types
  870. or type(dialect_impl) in include_types
  871. )
  872. ):
  873. return dbtype
  874. else:
  875. return None
  876. inputsizes = {}
  877. literal_execute_params = self.literal_execute_params
  878. for bindparam in self.bind_names:
  879. if bindparam in literal_execute_params:
  880. continue
  881. if bindparam.type._is_tuple_type:
  882. inputsizes[bindparam] = [
  883. _lookup_type(typ) for typ in bindparam.type.types
  884. ]
  885. else:
  886. inputsizes[bindparam] = _lookup_type(bindparam.type)
  887. return inputsizes
  888. @property
  889. def params(self):
  890. """Return the bind param dictionary embedded into this
  891. compiled object, for those values that are present."""
  892. return self.construct_params(_check=False)
  893. def _process_parameters_for_postcompile(
  894. self, parameters=None, _populate_self=False
  895. ):
  896. """handle special post compile parameters.
  897. These include:
  898. * "expanding" parameters -typically IN tuples that are rendered
  899. on a per-parameter basis for an otherwise fixed SQL statement string.
  900. * literal_binds compiled with the literal_execute flag. Used for
  901. things like SQL Server "TOP N" where the driver does not accommodate
  902. N as a bound parameter.
  903. """
  904. if parameters is None:
  905. parameters = self.construct_params()
  906. expanded_parameters = {}
  907. if self.positional:
  908. positiontup = []
  909. else:
  910. positiontup = None
  911. processors = self._bind_processors
  912. new_processors = {}
  913. if self.positional and self._numeric_binds:
  914. # I'm not familiar with any DBAPI that uses 'numeric'.
  915. # strategy would likely be to make use of numbers greater than
  916. # the highest number present; then for expanding parameters,
  917. # append them to the end of the parameter list. that way
  918. # we avoid having to renumber all the existing parameters.
  919. raise NotImplementedError(
  920. "'post-compile' bind parameters are not supported with "
  921. "the 'numeric' paramstyle at this time."
  922. )
  923. replacement_expressions = {}
  924. to_update_sets = {}
  925. for name in (
  926. self.positiontup if self.positional else self.bind_names.values()
  927. ):
  928. parameter = self.binds[name]
  929. if parameter in self.literal_execute_params:
  930. if name not in replacement_expressions:
  931. value = parameters.pop(name)
  932. replacement_expressions[name] = self.render_literal_bindparam(
  933. parameter, render_literal_value=value
  934. )
  935. continue
  936. if parameter in self.post_compile_params:
  937. if name in replacement_expressions:
  938. to_update = to_update_sets[name]
  939. else:
  940. # we are removing the parameter from parameters
  941. # because it is a list value, which is not expected by
  942. # TypeEngine objects that would otherwise be asked to
  943. # process it. the single name is being replaced with
  944. # individual numbered parameters for each value in the
  945. # param.
  946. values = parameters.pop(name)
  947. leep = self._literal_execute_expanding_parameter
  948. to_update, replacement_expr = leep(name, parameter, values)
  949. to_update_sets[name] = to_update
  950. replacement_expressions[name] = replacement_expr
  951. if not parameter.literal_execute:
  952. parameters.update(to_update)
  953. if parameter.type._is_tuple_type:
  954. new_processors.update(
  955. (
  956. "%s_%s_%s" % (name, i, j),
  957. processors[name][j - 1],
  958. )
  959. for i, tuple_element in enumerate(values, 1)
  960. for j, value in enumerate(tuple_element, 1)
  961. if name in processors
  962. and processors[name][j - 1] is not None
  963. )
  964. else:
  965. new_processors.update(
  966. (key, processors[name])
  967. for key, value in to_update
  968. if name in processors
  969. )
  970. if self.positional:
  971. positiontup.extend(name for name, value in to_update)
  972. expanded_parameters[name] = [
  973. expand_key for expand_key, value in to_update
  974. ]
  975. elif self.positional:
  976. positiontup.append(name)
  977. def process_expanding(m):
  978. return replacement_expressions[m.group(1)]
  979. statement = re.sub(
  980. r"\[POSTCOMPILE_(\S+)\]", process_expanding, self.string
  981. )
  982. expanded_state = ExpandedState(
  983. statement,
  984. parameters,
  985. new_processors,
  986. positiontup,
  987. expanded_parameters,
  988. )
  989. if _populate_self:
  990. # this is for the "render_postcompile" flag, which is not
  991. # otherwise used internally and is for end-user debugging and
  992. # special use cases.
  993. self.string = expanded_state.statement
  994. self._bind_processors.update(expanded_state.processors)
  995. self.positiontup = expanded_state.positiontup
  996. self.post_compile_params = frozenset()
  997. for key in expanded_state.parameter_expansion:
  998. bind = self.binds.pop(key)
  999. self.bind_names.pop(bind)
  1000. for value, expanded_key in zip(
  1001. bind.value, expanded_state.parameter_expansion[key]
  1002. ):
  1003. self.binds[expanded_key] = new_param = bind._with_value(
  1004. value
  1005. )
  1006. self.bind_names[new_param] = expanded_key
  1007. return expanded_state
  1008. @util.preload_module("sqlalchemy.engine.cursor")
  1009. def _create_result_map(self):
  1010. """utility method used for unit tests only."""
  1011. cursor = util.preloaded.engine_cursor
  1012. return cursor.CursorResultMetaData._create_description_match_map(
  1013. self._result_columns
  1014. )
  1015. @util.memoized_property
  1016. @util.preload_module("sqlalchemy.engine.result")
  1017. def _inserted_primary_key_from_lastrowid_getter(self):
  1018. result = util.preloaded.engine_result
  1019. key_getter = self._key_getters_for_crud_column[2]
  1020. table = self.statement.table
  1021. getters = [
  1022. (operator.methodcaller("get", key_getter(col), None), col)
  1023. for col in table.primary_key
  1024. ]
  1025. autoinc_col = table._autoincrement_column
  1026. if autoinc_col is not None:
  1027. # apply type post processors to the lastrowid
  1028. proc = autoinc_col.type._cached_result_processor(
  1029. self.dialect, None
  1030. )
  1031. else:
  1032. proc = None
  1033. row_fn = result.result_tuple([col.key for col in table.primary_key])
  1034. def get(lastrowid, parameters):
  1035. if proc is not None:
  1036. lastrowid = proc(lastrowid)
  1037. if lastrowid is None:
  1038. return row_fn(getter(parameters) for getter, col in getters)
  1039. else:
  1040. return row_fn(
  1041. lastrowid if col is autoinc_col else getter(parameters)
  1042. for getter, col in getters
  1043. )
  1044. return get
  1045. @util.memoized_property
  1046. @util.preload_module("sqlalchemy.engine.result")
  1047. def _inserted_primary_key_from_returning_getter(self):
  1048. result = util.preloaded.engine_result
  1049. key_getter = self._key_getters_for_crud_column[2]
  1050. table = self.statement.table
  1051. ret = {col: idx for idx, col in enumerate(self.returning)}
  1052. getters = [
  1053. (operator.itemgetter(ret[col]), True)
  1054. if col in ret
  1055. else (operator.methodcaller("get", key_getter(col), None), False)
  1056. for col in table.primary_key
  1057. ]
  1058. row_fn = result.result_tuple([col.key for col in table.primary_key])
  1059. def get(row, parameters):
  1060. return row_fn(
  1061. getter(row) if use_row else getter(parameters)
  1062. for getter, use_row in getters
  1063. )
  1064. return get
  1065. def default_from(self):
  1066. """Called when a SELECT statement has no froms, and no FROM clause is
  1067. to be appended.
  1068. Gives Oracle a chance to tack on a ``FROM DUAL`` to the string output.
  1069. """
  1070. return ""
  1071. def visit_grouping(self, grouping, asfrom=False, **kwargs):
  1072. return "(" + grouping.element._compiler_dispatch(self, **kwargs) + ")"
  1073. def visit_label_reference(
  1074. self, element, within_columns_clause=False, **kwargs
  1075. ):
  1076. if self.stack and self.dialect.supports_simple_order_by_label:
  1077. compile_state = self.stack[-1]["compile_state"]
  1078. (
  1079. with_cols,
  1080. only_froms,
  1081. only_cols,
  1082. ) = compile_state._label_resolve_dict
  1083. if within_columns_clause:
  1084. resolve_dict = only_froms
  1085. else:
  1086. resolve_dict = only_cols
  1087. # this can be None in the case that a _label_reference()
  1088. # were subject to a replacement operation, in which case
  1089. # the replacement of the Label element may have changed
  1090. # to something else like a ColumnClause expression.
  1091. order_by_elem = element.element._order_by_label_element
  1092. if (
  1093. order_by_elem is not None
  1094. and order_by_elem.name in resolve_dict
  1095. and order_by_elem.shares_lineage(
  1096. resolve_dict[order_by_elem.name]
  1097. )
  1098. ):
  1099. kwargs[
  1100. "render_label_as_label"
  1101. ] = element.element._order_by_label_element
  1102. return self.process(
  1103. element.element,
  1104. within_columns_clause=within_columns_clause,
  1105. **kwargs
  1106. )
  1107. def visit_textual_label_reference(
  1108. self, element, within_columns_clause=False, **kwargs
  1109. ):
  1110. if not self.stack:
  1111. # compiling the element outside of the context of a SELECT
  1112. return self.process(element._text_clause)
  1113. compile_state = self.stack[-1]["compile_state"]
  1114. with_cols, only_froms, only_cols = compile_state._label_resolve_dict
  1115. try:
  1116. if within_columns_clause:
  1117. col = only_froms[element.element]
  1118. else:
  1119. col = with_cols[element.element]
  1120. except KeyError as err:
  1121. coercions._no_text_coercion(
  1122. element.element,
  1123. extra=(
  1124. "Can't resolve label reference for ORDER BY / "
  1125. "GROUP BY / DISTINCT etc."
  1126. ),
  1127. exc_cls=exc.CompileError,
  1128. err=err,
  1129. )
  1130. else:
  1131. kwargs["render_label_as_label"] = col
  1132. return self.process(
  1133. col, within_columns_clause=within_columns_clause, **kwargs
  1134. )
  1135. def visit_label(
  1136. self,
  1137. label,
  1138. add_to_result_map=None,
  1139. within_label_clause=False,
  1140. within_columns_clause=False,
  1141. render_label_as_label=None,
  1142. result_map_targets=(),
  1143. **kw
  1144. ):
  1145. # only render labels within the columns clause
  1146. # or ORDER BY clause of a select. dialect-specific compilers
  1147. # can modify this behavior.
  1148. render_label_with_as = (
  1149. within_columns_clause and not within_label_clause
  1150. )
  1151. render_label_only = render_label_as_label is label
  1152. if render_label_only or render_label_with_as:
  1153. if isinstance(label.name, elements._truncated_label):
  1154. labelname = self._truncated_identifier("colident", label.name)
  1155. else:
  1156. labelname = label.name
  1157. if render_label_with_as:
  1158. if add_to_result_map is not None:
  1159. add_to_result_map(
  1160. labelname,
  1161. label.name,
  1162. (label, labelname) + label._alt_names + result_map_targets,
  1163. label.type,
  1164. )
  1165. return (
  1166. label.element._compiler_dispatch(
  1167. self,
  1168. within_columns_clause=True,
  1169. within_label_clause=True,
  1170. **kw
  1171. )
  1172. + OPERATORS[operators.as_]
  1173. + self.preparer.format_label(label, labelname)
  1174. )
  1175. elif render_label_only:
  1176. return self.preparer.format_label(label, labelname)
  1177. else:
  1178. return label.element._compiler_dispatch(
  1179. self, within_columns_clause=False, **kw
  1180. )
  1181. def _fallback_column_name(self, column):
  1182. raise exc.CompileError(
  1183. "Cannot compile Column object until " "its 'name' is assigned."
  1184. )
  1185. def visit_lambda_element(self, element, **kw):
  1186. sql_element = element._resolved
  1187. return self.process(sql_element, **kw)
  1188. def visit_column(
  1189. self,
  1190. column,
  1191. add_to_result_map=None,
  1192. include_table=True,
  1193. result_map_targets=(),
  1194. **kwargs
  1195. ):
  1196. name = orig_name = column.name
  1197. if name is None:
  1198. name = self._fallback_column_name(column)
  1199. is_literal = column.is_literal
  1200. if not is_literal and isinstance(name, elements._truncated_label):
  1201. name = self._truncated_identifier("colident", name)
  1202. if add_to_result_map is not None:
  1203. targets = (column, name, column.key) + result_map_targets
  1204. if column._label:
  1205. targets += (column._label,)
  1206. add_to_result_map(name, orig_name, targets, column.type)
  1207. if is_literal:
  1208. # note we are not currently accommodating for
  1209. # literal_column(quoted_name('ident', True)) here
  1210. name = self.escape_literal_column(name)
  1211. else:
  1212. name = self.preparer.quote(name)
  1213. table = column.table
  1214. if table is None or not include_table or not table.named_with_column:
  1215. return name
  1216. else:
  1217. effective_schema = self.preparer.schema_for_object(table)
  1218. if effective_schema:
  1219. schema_prefix = (
  1220. self.preparer.quote_schema(effective_schema) + "."
  1221. )
  1222. else:
  1223. schema_prefix = ""
  1224. tablename = table.name
  1225. if isinstance(tablename, elements._truncated_label):
  1226. tablename = self._truncated_identifier("alias", tablename)
  1227. return schema_prefix + self.preparer.quote(tablename) + "." + name
  1228. def visit_collation(self, element, **kw):
  1229. return self.preparer.format_collation(element.collation)
  1230. def visit_fromclause(self, fromclause, **kwargs):
  1231. return fromclause.name
  1232. def visit_index(self, index, **kwargs):
  1233. return index.name
  1234. def visit_typeclause(self, typeclause, **kw):
  1235. kw["type_expression"] = typeclause
  1236. return self.dialect.type_compiler.process(typeclause.type, **kw)
  1237. def post_process_text(self, text):
  1238. if self.preparer._double_percents:
  1239. text = text.replace("%", "%%")
  1240. return text
  1241. def escape_literal_column(self, text):
  1242. if self.preparer._double_percents:
  1243. text = text.replace("%", "%%")
  1244. return text
  1245. def visit_textclause(self, textclause, add_to_result_map=None, **kw):
  1246. def do_bindparam(m):
  1247. name = m.group(1)
  1248. if name in textclause._bindparams:
  1249. return self.process(textclause._bindparams[name], **kw)
  1250. else:
  1251. return self.bindparam_string(name, **kw)
  1252. if not self.stack:
  1253. self.isplaintext = True
  1254. if add_to_result_map:
  1255. # text() object is present in the columns clause of a
  1256. # select(). Add a no-name entry to the result map so that
  1257. # row[text()] produces a result
  1258. add_to_result_map(None, None, (textclause,), sqltypes.NULLTYPE)
  1259. # un-escape any \:params
  1260. return BIND_PARAMS_ESC.sub(
  1261. lambda m: m.group(1),
  1262. BIND_PARAMS.sub(
  1263. do_bindparam, self.post_process_text(textclause.text)
  1264. ),
  1265. )
  1266. def visit_textual_select(
  1267. self, taf, compound_index=None, asfrom=False, **kw
  1268. ):
  1269. toplevel = not self.stack
  1270. entry = self._default_stack_entry if toplevel else self.stack[-1]
  1271. populate_result_map = (
  1272. toplevel
  1273. or (
  1274. compound_index == 0
  1275. and entry.get("need_result_map_for_compound", False)
  1276. )
  1277. or entry.get("need_result_map_for_nested", False)
  1278. )
  1279. if populate_result_map:
  1280. self._ordered_columns = (
  1281. self._textual_ordered_columns
  1282. ) = taf.positional
  1283. # enable looser result column matching when the SQL text links to
  1284. # Column objects by name only
  1285. self._loose_column_name_matching = not taf.positional and bool(
  1286. taf.column_args
  1287. )
  1288. for c in taf.column_args:
  1289. self.process(
  1290. c,
  1291. within_columns_clause=True,
  1292. add_to_result_map=self._add_to_result_map,
  1293. )
  1294. return self.process(taf.element, **kw)
  1295. def visit_null(self, expr, **kw):
  1296. return "NULL"
  1297. def visit_true(self, expr, **kw):
  1298. if self.dialect.supports_native_boolean:
  1299. return "true"
  1300. else:
  1301. return "1"
  1302. def visit_false(self, expr, **kw):
  1303. if self.dialect.supports_native_boolean:
  1304. return "false"
  1305. else:
  1306. return "0"
  1307. def _generate_delimited_list(self, elements, separator, **kw):
  1308. return separator.join(
  1309. s
  1310. for s in (c._compiler_dispatch(self, **kw) for c in elements)
  1311. if s
  1312. )
  1313. def _generate_delimited_and_list(self, clauses, **kw):
  1314. lcc, clauses = elements.BooleanClauseList._process_clauses_for_boolean(
  1315. operators.and_,
  1316. elements.True_._singleton,
  1317. elements.False_._singleton,
  1318. clauses,
  1319. )
  1320. if lcc == 1:
  1321. return clauses[0]._compiler_dispatch(self, **kw)
  1322. else:
  1323. separator = OPERATORS[operators.and_]
  1324. return separator.join(
  1325. s
  1326. for s in (c._compiler_dispatch(self, **kw) for c in clauses)
  1327. if s
  1328. )
  1329. def visit_tuple(self, clauselist, **kw):
  1330. return "(%s)" % self.visit_clauselist(clauselist, **kw)
  1331. def visit_clauselist(self, clauselist, **kw):
  1332. sep = clauselist.operator
  1333. if sep is None:
  1334. sep = " "
  1335. else:
  1336. sep = OPERATORS[clauselist.operator]
  1337. return self._generate_delimited_list(clauselist.clauses, sep, **kw)
  1338. def visit_case(self, clause, **kwargs):
  1339. x = "CASE "
  1340. if clause.value is not None:
  1341. x += clause.value._compiler_dispatch(self, **kwargs) + " "
  1342. for cond, result in clause.whens:
  1343. x += (
  1344. "WHEN "
  1345. + cond._compiler_dispatch(self, **kwargs)
  1346. + " THEN "
  1347. + result._compiler_dispatch(self, **kwargs)
  1348. + " "
  1349. )
  1350. if clause.else_ is not None:
  1351. x += (
  1352. "ELSE " + clause.else_._compiler_dispatch(self, **kwargs) + " "
  1353. )
  1354. x += "END"
  1355. return x
  1356. def visit_type_coerce(self, type_coerce, **kw):
  1357. return type_coerce.typed_expression._compiler_dispatch(self, **kw)
  1358. def visit_cast(self, cast, **kwargs):
  1359. return "CAST(%s AS %s)" % (
  1360. cast.clause._compiler_dispatch(self, **kwargs),
  1361. cast.typeclause._compiler_dispatch(self, **kwargs),
  1362. )
  1363. def _format_frame_clause(self, range_, **kw):
  1364. return "%s AND %s" % (
  1365. "UNBOUNDED PRECEDING"
  1366. if range_[0] is elements.RANGE_UNBOUNDED
  1367. else "CURRENT ROW"
  1368. if range_[0] is elements.RANGE_CURRENT
  1369. else "%s PRECEDING"
  1370. % (self.process(elements.literal(abs(range_[0])), **kw),)
  1371. if range_[0] < 0
  1372. else "%s FOLLOWING"
  1373. % (self.process(elements.literal(range_[0]), **kw),),
  1374. "UNBOUNDED FOLLOWING"
  1375. if range_[1] is elements.RANGE_UNBOUNDED
  1376. else "CURRENT ROW"
  1377. if range_[1] is elements.RANGE_CURRENT
  1378. else "%s PRECEDING"
  1379. % (self.process(elements.literal(abs(range_[1])), **kw),)
  1380. if range_[1] < 0
  1381. else "%s FOLLOWING"
  1382. % (self.process(elements.literal(range_[1]), **kw),),
  1383. )
  1384. def visit_over(self, over, **kwargs):
  1385. if over.range_:
  1386. range_ = "RANGE BETWEEN %s" % self._format_frame_clause(
  1387. over.range_, **kwargs
  1388. )
  1389. elif over.rows:
  1390. range_ = "ROWS BETWEEN %s" % self._format_frame_clause(
  1391. over.rows, **kwargs
  1392. )
  1393. else:
  1394. range_ = None
  1395. return "%s OVER (%s)" % (
  1396. over.element._compiler_dispatch(self, **kwargs),
  1397. " ".join(
  1398. [
  1399. "%s BY %s"
  1400. % (word, clause._compiler_dispatch(self, **kwargs))
  1401. for word, clause in (
  1402. ("PARTITION", over.partition_by),
  1403. ("ORDER", over.order_by),
  1404. )
  1405. if clause is not None and len(clause)
  1406. ]
  1407. + ([range_] if range_ else [])
  1408. ),
  1409. )
  1410. def visit_withingroup(self, withingroup, **kwargs):
  1411. return "%s WITHIN GROUP (ORDER BY %s)" % (
  1412. withingroup.element._compiler_dispatch(self, **kwargs),
  1413. withingroup.order_by._compiler_dispatch(self, **kwargs),
  1414. )
  1415. def visit_funcfilter(self, funcfilter, **kwargs):
  1416. return "%s FILTER (WHERE %s)" % (
  1417. funcfilter.func._compiler_dispatch(self, **kwargs),
  1418. funcfilter.criterion._compiler_dispatch(self, **kwargs),
  1419. )
  1420. def visit_extract(self, extract, **kwargs):
  1421. field = self.extract_map.get(extract.field, extract.field)
  1422. return "EXTRACT(%s FROM %s)" % (
  1423. field,
  1424. extract.expr._compiler_dispatch(self, **kwargs),
  1425. )
  1426. def visit_scalar_function_column(self, element, **kw):
  1427. compiled_fn = self.visit_function(element.fn, **kw)
  1428. compiled_col = self.visit_column(element, **kw)
  1429. return "(%s).%s" % (compiled_fn, compiled_col)
  1430. def visit_function(self, func, add_to_result_map=None, **kwargs):
  1431. if add_to_result_map is not None:
  1432. add_to_result_map(func.name, func.name, (), func.type)
  1433. disp = getattr(self, "visit_%s_func" % func.name.lower(), None)
  1434. if disp:
  1435. text = disp(func, **kwargs)
  1436. else:
  1437. name = FUNCTIONS.get(func._deannotate().__class__, None)
  1438. if name:
  1439. if func._has_args:
  1440. name += "%(expr)s"
  1441. else:
  1442. name = func.name
  1443. name = (
  1444. self.preparer.quote(name)
  1445. if self.preparer._requires_quotes_illegal_chars(name)
  1446. or isinstance(name, elements.quoted_name)
  1447. else name
  1448. )
  1449. name = name + "%(expr)s"
  1450. text = ".".join(
  1451. [
  1452. (
  1453. self.preparer.quote(tok)
  1454. if self.preparer._requires_quotes_illegal_chars(tok)
  1455. or isinstance(name, elements.quoted_name)
  1456. else tok
  1457. )
  1458. for tok in func.packagenames
  1459. ]
  1460. + [name]
  1461. ) % {"expr": self.function_argspec(func, **kwargs)}
  1462. if func._with_ordinality:
  1463. text += " WITH ORDINALITY"
  1464. return text
  1465. def visit_next_value_func(self, next_value, **kw):
  1466. return self.visit_sequence(next_value.sequence)
  1467. def visit_sequence(self, sequence, **kw):
  1468. raise NotImplementedError(
  1469. "Dialect '%s' does not support sequence increments."
  1470. % self.dialect.name
  1471. )
  1472. def function_argspec(self, func, **kwargs):
  1473. return func.clause_expr._compiler_dispatch(self, **kwargs)
  1474. def visit_compound_select(
  1475. self, cs, asfrom=False, compound_index=None, **kwargs
  1476. ):
  1477. toplevel = not self.stack
  1478. compile_state = cs._compile_state_factory(cs, self, **kwargs)
  1479. if toplevel and not self.compile_state:
  1480. self.compile_state = compile_state
  1481. entry = self._default_stack_entry if toplevel else self.stack[-1]
  1482. need_result_map = toplevel or (
  1483. not compound_index
  1484. and entry.get("need_result_map_for_compound", False)
  1485. )
  1486. # indicates there is already a CompoundSelect in play
  1487. if compound_index == 0:
  1488. entry["select_0"] = cs
  1489. self.stack.append(
  1490. {
  1491. "correlate_froms": entry["correlate_froms"],
  1492. "asfrom_froms": entry["asfrom_froms"],
  1493. "selectable": cs,
  1494. "compile_state": compile_state,
  1495. "need_result_map_for_compound": need_result_map,
  1496. }
  1497. )
  1498. keyword = self.compound_keywords.get(cs.keyword)
  1499. text = (" " + keyword + " ").join(
  1500. (
  1501. c._compiler_dispatch(
  1502. self, asfrom=asfrom, compound_index=i, **kwargs
  1503. )
  1504. for i, c in enumerate(cs.selects)
  1505. )
  1506. )
  1507. kwargs["include_table"] = False
  1508. text += self.group_by_clause(cs, **dict(asfrom=asfrom, **kwargs))
  1509. text += self.order_by_clause(cs, **kwargs)
  1510. if cs._has_row_limiting_clause:
  1511. text += self._row_limit_clause(cs, **kwargs)
  1512. if self.ctes and toplevel:
  1513. text = self._render_cte_clause() + text
  1514. self.stack.pop(-1)
  1515. return text
  1516. def _row_limit_clause(self, cs, **kwargs):
  1517. if cs._fetch_clause is not None:
  1518. return self.fetch_clause(cs, **kwargs)
  1519. else:
  1520. return self.limit_clause(cs, **kwargs)
  1521. def _get_operator_dispatch(self, operator_, qualifier1, qualifier2):
  1522. attrname = "visit_%s_%s%s" % (
  1523. operator_.__name__,
  1524. qualifier1,
  1525. "_" + qualifier2 if qualifier2 else "",
  1526. )
  1527. return getattr(self, attrname, None)
  1528. def visit_unary(
  1529. self, unary, add_to_result_map=None, result_map_targets=(), **kw
  1530. ):
  1531. if add_to_result_map is not None:
  1532. result_map_targets += (unary,)
  1533. kw["add_to_result_map"] = add_to_result_map
  1534. kw["result_map_targets"] = result_map_targets
  1535. if unary.operator:
  1536. if unary.modifier:
  1537. raise exc.CompileError(
  1538. "Unary expression does not support operator "
  1539. "and modifier simultaneously"
  1540. )
  1541. disp = self._get_operator_dispatch(
  1542. unary.operator, "unary", "operator"
  1543. )
  1544. if disp:
  1545. return disp(unary, unary.operator, **kw)
  1546. else:
  1547. return self._generate_generic_unary_operator(
  1548. unary, OPERATORS[unary.operator], **kw
  1549. )
  1550. elif unary.modifier:
  1551. disp = self._get_operator_dispatch(
  1552. unary.modifier, "unary", "modifier"
  1553. )
  1554. if disp:
  1555. return disp(unary, unary.modifier, **kw)
  1556. else:
  1557. return self._generate_generic_unary_modifier(
  1558. unary, OPERATORS[unary.modifier], **kw
  1559. )
  1560. else:
  1561. raise exc.CompileError(
  1562. "Unary expression has no operator or modifier"
  1563. )
  1564. def visit_is_true_unary_operator(self, element, operator, **kw):
  1565. if (
  1566. element._is_implicitly_boolean
  1567. or self.dialect.supports_native_boolean
  1568. ):
  1569. return self.process(element.element, **kw)
  1570. else:
  1571. return "%s = 1" % self.process(element.element, **kw)
  1572. def visit_is_false_unary_operator(self, element, operator, **kw):
  1573. if (
  1574. element._is_implicitly_boolean
  1575. or self.dialect.supports_native_boolean
  1576. ):
  1577. return "NOT %s" % self.process(element.element, **kw)
  1578. else:
  1579. return "%s = 0" % self.process(element.element, **kw)
  1580. def visit_not_match_op_binary(self, binary, operator, **kw):
  1581. return "NOT %s" % self.visit_binary(
  1582. binary, override_operator=operators.match_op
  1583. )
  1584. def visit_not_in_op_binary(self, binary, operator, **kw):
  1585. # The brackets are required in the NOT IN operation because the empty
  1586. # case is handled using the form "(col NOT IN (null) OR 1 = 1)".
  1587. # The presence of the OR makes the brackets required.
  1588. return "(%s)" % self._generate_generic_binary(
  1589. binary, OPERATORS[operator], **kw
  1590. )
  1591. def visit_empty_set_op_expr(self, type_, expand_op):
  1592. if expand_op is operators.not_in_op:
  1593. if len(type_) > 1:
  1594. return "(%s)) OR (1 = 1" % (
  1595. ", ".join("NULL" for element in type_)
  1596. )
  1597. else:
  1598. return "NULL) OR (1 = 1"
  1599. elif expand_op is operators.in_op:
  1600. if len(type_) > 1:
  1601. return "(%s)) AND (1 != 1" % (
  1602. ", ".join("NULL" for element in type_)
  1603. )
  1604. else:
  1605. return "NULL) AND (1 != 1"
  1606. else:
  1607. return self.visit_empty_set_expr(type_)
  1608. def visit_empty_set_expr(self, element_types):
  1609. raise NotImplementedError(
  1610. "Dialect '%s' does not support empty set expression."
  1611. % self.dialect.name
  1612. )
  1613. def _literal_execute_expanding_parameter_literal_binds(
  1614. self, parameter, values
  1615. ):
  1616. if not values:
  1617. if parameter.type._is_tuple_type:
  1618. replacement_expression = (
  1619. "VALUES " if self.dialect.tuple_in_values else ""
  1620. ) + self.visit_empty_set_op_expr(
  1621. parameter.type.types, parameter.expand_op
  1622. )
  1623. else:
  1624. replacement_expression = self.visit_empty_set_op_expr(
  1625. [parameter.type], parameter.expand_op
  1626. )
  1627. elif isinstance(values[0], (tuple, list)):
  1628. assert parameter.type._is_tuple_type
  1629. replacement_expression = (
  1630. "VALUES " if self.dialect.tuple_in_values else ""
  1631. ) + ", ".join(
  1632. "(%s)"
  1633. % (
  1634. ", ".join(
  1635. self.render_literal_value(value, param_type)
  1636. for value, param_type in zip(
  1637. tuple_element, parameter.type.types
  1638. )
  1639. )
  1640. )
  1641. for i, tuple_element in enumerate(values)
  1642. )
  1643. else:
  1644. assert not parameter.type._is_tuple_type
  1645. replacement_expression = ", ".join(
  1646. self.render_literal_value(value, parameter.type)
  1647. for value in values
  1648. )
  1649. return (), replacement_expression
  1650. def _literal_execute_expanding_parameter(self, name, parameter, values):
  1651. if parameter.literal_execute:
  1652. return self._literal_execute_expanding_parameter_literal_binds(
  1653. parameter, values
  1654. )
  1655. if not values:
  1656. to_update = []
  1657. if parameter.type._is_tuple_type:
  1658. replacement_expression = self.visit_empty_set_op_expr(
  1659. parameter.type.types, parameter.expand_op
  1660. )
  1661. else:
  1662. replacement_expression = self.visit_empty_set_op_expr(
  1663. [parameter.type], parameter.expand_op
  1664. )
  1665. elif isinstance(values[0], (tuple, list)):
  1666. to_update = [
  1667. ("%s_%s_%s" % (name, i, j), value)
  1668. for i, tuple_element in enumerate(values, 1)
  1669. for j, value in enumerate(tuple_element, 1)
  1670. ]
  1671. replacement_expression = (
  1672. "VALUES " if self.dialect.tuple_in_values else ""
  1673. ) + ", ".join(
  1674. "(%s)"
  1675. % (
  1676. ", ".join(
  1677. self.bindtemplate
  1678. % {"name": to_update[i * len(tuple_element) + j][0]}
  1679. for j, value in enumerate(tuple_element)
  1680. )
  1681. )
  1682. for i, tuple_element in enumerate(values)
  1683. )
  1684. else:
  1685. to_update = [
  1686. ("%s_%s" % (name, i), value)
  1687. for i, value in enumerate(values, 1)
  1688. ]
  1689. replacement_expression = ", ".join(
  1690. self.bindtemplate % {"name": key} for key, value in to_update
  1691. )
  1692. return to_update, replacement_expression
  1693. def visit_binary(
  1694. self,
  1695. binary,
  1696. override_operator=None,
  1697. eager_grouping=False,
  1698. from_linter=None,
  1699. lateral_from_linter=None,
  1700. **kw
  1701. ):
  1702. if from_linter and operators.is_comparison(binary.operator):
  1703. if lateral_from_linter is not None:
  1704. enclosing_lateral = kw["enclosing_lateral"]
  1705. lateral_from_linter.edges.update(
  1706. itertools.product(
  1707. binary.left._from_objects + [enclosing_lateral],
  1708. binary.right._from_objects + [enclosing_lateral],
  1709. )
  1710. )
  1711. else:
  1712. from_linter.edges.update(
  1713. itertools.product(
  1714. binary.left._from_objects, binary.right._from_objects
  1715. )
  1716. )
  1717. # don't allow "? = ?" to render
  1718. if (
  1719. self.ansi_bind_rules
  1720. and isinstance(binary.left, elements.BindParameter)
  1721. and isinstance(binary.right, elements.BindParameter)
  1722. ):
  1723. kw["literal_execute"] = True
  1724. operator_ = override_operator or binary.operator
  1725. disp = self._get_operator_dispatch(operator_, "binary", None)
  1726. if disp:
  1727. return disp(binary, operator_, **kw)
  1728. else:
  1729. try:
  1730. opstring = OPERATORS[operator_]
  1731. except KeyError as err:
  1732. util.raise_(
  1733. exc.UnsupportedCompilationError(self, operator_),
  1734. replace_context=err,
  1735. )
  1736. else:
  1737. return self._generate_generic_binary(
  1738. binary,
  1739. opstring,
  1740. from_linter=from_linter,
  1741. lateral_from_linter=lateral_from_linter,
  1742. **kw
  1743. )
  1744. def visit_function_as_comparison_op_binary(self, element, operator, **kw):
  1745. return self.process(element.sql_function, **kw)
  1746. def visit_mod_binary(self, binary, operator, **kw):
  1747. if self.preparer._double_percents:
  1748. return (
  1749. self.process(binary.left, **kw)
  1750. + " %% "
  1751. + self.process(binary.right, **kw)
  1752. )
  1753. else:
  1754. return (
  1755. self.process(binary.left, **kw)
  1756. + " % "
  1757. + self.process(binary.right, **kw)
  1758. )
  1759. def visit_custom_op_binary(self, element, operator, **kw):
  1760. kw["eager_grouping"] = operator.eager_grouping
  1761. return self._generate_generic_binary(
  1762. element,
  1763. " " + self.escape_literal_column(operator.opstring) + " ",
  1764. **kw
  1765. )
  1766. def visit_custom_op_unary_operator(self, element, operator, **kw):
  1767. return self._generate_generic_unary_operator(
  1768. element, self.escape_literal_column(operator.opstring) + " ", **kw
  1769. )
  1770. def visit_custom_op_unary_modifier(self, element, operator, **kw):
  1771. return self._generate_generic_unary_modifier(
  1772. element, " " + self.escape_literal_column(operator.opstring), **kw
  1773. )
  1774. def _generate_generic_binary(
  1775. self, binary, opstring, eager_grouping=False, **kw
  1776. ):
  1777. _in_binary = kw.get("_in_binary", False)
  1778. kw["_in_binary"] = True
  1779. kw["_binary_op"] = binary.operator
  1780. text = (
  1781. binary.left._compiler_dispatch(
  1782. self, eager_grouping=eager_grouping, **kw
  1783. )
  1784. + opstring
  1785. + binary.right._compiler_dispatch(
  1786. self, eager_grouping=eager_grouping, **kw
  1787. )
  1788. )
  1789. if _in_binary and eager_grouping:
  1790. text = "(%s)" % text
  1791. return text
  1792. def _generate_generic_unary_operator(self, unary, opstring, **kw):
  1793. return opstring + unary.element._compiler_dispatch(self, **kw)
  1794. def _generate_generic_unary_modifier(self, unary, opstring, **kw):
  1795. return unary.element._compiler_dispatch(self, **kw) + opstring
  1796. @util.memoized_property
  1797. def _like_percent_literal(self):
  1798. return elements.literal_column("'%'", type_=sqltypes.STRINGTYPE)
  1799. def visit_contains_op_binary(self, binary, operator, **kw):
  1800. binary = binary._clone()
  1801. percent = self._like_percent_literal
  1802. binary.right = percent.__add__(binary.right).__add__(percent)
  1803. return self.visit_like_op_binary(binary, operator, **kw)
  1804. def visit_not_contains_op_binary(self, binary, operator, **kw):
  1805. binary = binary._clone()
  1806. percent = self._like_percent_literal
  1807. binary.right = percent.__add__(binary.right).__add__(percent)
  1808. return self.visit_not_like_op_binary(binary, operator, **kw)
  1809. def visit_startswith_op_binary(self, binary, operator, **kw):
  1810. binary = binary._clone()
  1811. percent = self._like_percent_literal
  1812. binary.right = percent.__radd__(binary.right)
  1813. return self.visit_like_op_binary(binary, operator, **kw)
  1814. def visit_not_startswith_op_binary(self, binary, operator, **kw):
  1815. binary = binary._clone()
  1816. percent = self._like_percent_literal
  1817. binary.right = percent.__radd__(binary.right)
  1818. return self.visit_not_like_op_binary(binary, operator, **kw)
  1819. def visit_endswith_op_binary(self, binary, operator, **kw):
  1820. binary = binary._clone()
  1821. percent = self._like_percent_literal
  1822. binary.right = percent.__add__(binary.right)
  1823. return self.visit_like_op_binary(binary, operator, **kw)
  1824. def visit_not_endswith_op_binary(self, binary, operator, **kw):
  1825. binary = binary._clone()
  1826. percent = self._like_percent_literal
  1827. binary.right = percent.__add__(binary.right)
  1828. return self.visit_not_like_op_binary(binary, operator, **kw)
  1829. def visit_like_op_binary(self, binary, operator, **kw):
  1830. escape = binary.modifiers.get("escape", None)
  1831. # TODO: use ternary here, not "and"/ "or"
  1832. return "%s LIKE %s" % (
  1833. binary.left._compiler_dispatch(self, **kw),
  1834. binary.right._compiler_dispatch(self, **kw),
  1835. ) + (
  1836. " ESCAPE " + self.render_literal_value(escape, sqltypes.STRINGTYPE)
  1837. if escape
  1838. else ""
  1839. )
  1840. def visit_not_like_op_binary(self, binary, operator, **kw):
  1841. escape = binary.modifiers.get("escape", None)
  1842. return "%s NOT LIKE %s" % (
  1843. binary.left._compiler_dispatch(self, **kw),
  1844. binary.right._compiler_dispatch(self, **kw),
  1845. ) + (
  1846. " ESCAPE " + self.render_literal_value(escape, sqltypes.STRINGTYPE)
  1847. if escape
  1848. else ""
  1849. )
  1850. def visit_ilike_op_binary(self, binary, operator, **kw):
  1851. escape = binary.modifiers.get("escape", None)
  1852. return "lower(%s) LIKE lower(%s)" % (
  1853. binary.left._compiler_dispatch(self, **kw),
  1854. binary.right._compiler_dispatch(self, **kw),
  1855. ) + (
  1856. " ESCAPE " + self.render_literal_value(escape, sqltypes.STRINGTYPE)
  1857. if escape
  1858. else ""
  1859. )
  1860. def visit_not_ilike_op_binary(self, binary, operator, **kw):
  1861. escape = binary.modifiers.get("escape", None)
  1862. return "lower(%s) NOT LIKE lower(%s)" % (
  1863. binary.left._compiler_dispatch(self, **kw),
  1864. binary.right._compiler_dispatch(self, **kw),
  1865. ) + (
  1866. " ESCAPE " + self.render_literal_value(escape, sqltypes.STRINGTYPE)
  1867. if escape
  1868. else ""
  1869. )
  1870. def visit_between_op_binary(self, binary, operator, **kw):
  1871. symmetric = binary.modifiers.get("symmetric", False)
  1872. return self._generate_generic_binary(
  1873. binary, " BETWEEN SYMMETRIC " if symmetric else " BETWEEN ", **kw
  1874. )
  1875. def visit_not_between_op_binary(self, binary, operator, **kw):
  1876. symmetric = binary.modifiers.get("symmetric", False)
  1877. return self._generate_generic_binary(
  1878. binary,
  1879. " NOT BETWEEN SYMMETRIC " if symmetric else " NOT BETWEEN ",
  1880. **kw
  1881. )
  1882. def visit_regexp_match_op_binary(self, binary, operator, **kw):
  1883. raise exc.CompileError(
  1884. "%s dialect does not support regular expressions"
  1885. % self.dialect.name
  1886. )
  1887. def visit_not_regexp_match_op_binary(self, binary, operator, **kw):
  1888. raise exc.CompileError(
  1889. "%s dialect does not support regular expressions"
  1890. % self.dialect.name
  1891. )
  1892. def visit_regexp_replace_op_binary(self, binary, operator, **kw):
  1893. raise exc.CompileError(
  1894. "%s dialect does not support regular expression replacements"
  1895. % self.dialect.name
  1896. )
  1897. def visit_bindparam(
  1898. self,
  1899. bindparam,
  1900. within_columns_clause=False,
  1901. literal_binds=False,
  1902. skip_bind_expression=False,
  1903. literal_execute=False,
  1904. render_postcompile=False,
  1905. **kwargs
  1906. ):
  1907. if not skip_bind_expression:
  1908. impl = bindparam.type.dialect_impl(self.dialect)
  1909. if impl._has_bind_expression:
  1910. bind_expression = impl.bind_expression(bindparam)
  1911. return self.process(
  1912. bind_expression,
  1913. skip_bind_expression=True,
  1914. within_columns_clause=within_columns_clause,
  1915. literal_binds=literal_binds,
  1916. literal_execute=literal_execute,
  1917. **kwargs
  1918. )
  1919. if not literal_binds:
  1920. literal_execute = (
  1921. literal_execute
  1922. or bindparam.literal_execute
  1923. or (within_columns_clause and self.ansi_bind_rules)
  1924. )
  1925. post_compile = literal_execute or bindparam.expanding
  1926. else:
  1927. post_compile = False
  1928. if not literal_execute and (literal_binds):
  1929. ret = self.render_literal_bindparam(
  1930. bindparam, within_columns_clause=True, **kwargs
  1931. )
  1932. if bindparam.expanding:
  1933. ret = "(%s)" % ret
  1934. return ret
  1935. name = self._truncate_bindparam(bindparam)
  1936. if name in self.binds:
  1937. existing = self.binds[name]
  1938. if existing is not bindparam:
  1939. if (
  1940. existing.unique or bindparam.unique
  1941. ) and not existing.proxy_set.intersection(bindparam.proxy_set):
  1942. raise exc.CompileError(
  1943. "Bind parameter '%s' conflicts with "
  1944. "unique bind parameter of the same name"
  1945. % bindparam.key
  1946. )
  1947. elif existing._is_crud or bindparam._is_crud:
  1948. raise exc.CompileError(
  1949. "bindparam() name '%s' is reserved "
  1950. "for automatic usage in the VALUES or SET "
  1951. "clause of this "
  1952. "insert/update statement. Please use a "
  1953. "name other than column name when using bindparam() "
  1954. "with insert() or update() (for example, 'b_%s')."
  1955. % (bindparam.key, bindparam.key)
  1956. )
  1957. self.binds[bindparam.key] = self.binds[name] = bindparam
  1958. # if we are given a cache key that we're going to match against,
  1959. # relate the bindparam here to one that is most likely present
  1960. # in the "extracted params" portion of the cache key. this is used
  1961. # to set up a positional mapping that is used to determine the
  1962. # correct parameters for a subsequent use of this compiled with
  1963. # a different set of parameter values. here, we accommodate for
  1964. # parameters that may have been cloned both before and after the cache
  1965. # key was been generated.
  1966. ckbm = self._cache_key_bind_match
  1967. if ckbm:
  1968. for bp in bindparam._cloned_set:
  1969. if bp.key in ckbm:
  1970. cb = ckbm[bp.key]
  1971. ckbm[cb].append(bindparam)
  1972. if bindparam.isoutparam:
  1973. self.has_out_parameters = True
  1974. if post_compile:
  1975. if render_postcompile:
  1976. self._render_postcompile = True
  1977. if literal_execute:
  1978. self.literal_execute_params |= {bindparam}
  1979. else:
  1980. self.post_compile_params |= {bindparam}
  1981. ret = self.bindparam_string(
  1982. name,
  1983. post_compile=post_compile,
  1984. expanding=bindparam.expanding,
  1985. **kwargs
  1986. )
  1987. if bindparam.expanding:
  1988. ret = "(%s)" % ret
  1989. return ret
  1990. def render_literal_bindparam(
  1991. self, bindparam, render_literal_value=NO_ARG, **kw
  1992. ):
  1993. if render_literal_value is not NO_ARG:
  1994. value = render_literal_value
  1995. else:
  1996. if bindparam.value is None and bindparam.callable is None:
  1997. op = kw.get("_binary_op", None)
  1998. if op and op not in (operators.is_, operators.is_not):
  1999. util.warn_limited(
  2000. "Bound parameter '%s' rendering literal NULL in a SQL "
  2001. "expression; comparisons to NULL should not use "
  2002. "operators outside of 'is' or 'is not'",
  2003. (bindparam.key,),
  2004. )
  2005. return self.process(sqltypes.NULLTYPE, **kw)
  2006. value = bindparam.effective_value
  2007. if bindparam.expanding:
  2008. leep = self._literal_execute_expanding_parameter_literal_binds
  2009. to_update, replacement_expr = leep(bindparam, value)
  2010. return replacement_expr
  2011. else:
  2012. return self.render_literal_value(value, bindparam.type)
  2013. def render_literal_value(self, value, type_):
  2014. """Render the value of a bind parameter as a quoted literal.
  2015. This is used for statement sections that do not accept bind parameters
  2016. on the target driver/database.
  2017. This should be implemented by subclasses using the quoting services
  2018. of the DBAPI.
  2019. """
  2020. processor = type_._cached_literal_processor(self.dialect)
  2021. if processor:
  2022. return processor(value)
  2023. else:
  2024. raise NotImplementedError(
  2025. "Don't know how to literal-quote value %r" % value
  2026. )
  2027. def _truncate_bindparam(self, bindparam):
  2028. if bindparam in self.bind_names:
  2029. return self.bind_names[bindparam]
  2030. bind_name = bindparam.key
  2031. if isinstance(bind_name, elements._truncated_label):
  2032. bind_name = self._truncated_identifier("bindparam", bind_name)
  2033. # add to bind_names for translation
  2034. self.bind_names[bindparam] = bind_name
  2035. return bind_name
  2036. def _truncated_identifier(self, ident_class, name):
  2037. if (ident_class, name) in self.truncated_names:
  2038. return self.truncated_names[(ident_class, name)]
  2039. anonname = name.apply_map(self.anon_map)
  2040. if len(anonname) > self.label_length - 6:
  2041. counter = self.truncated_names.get(ident_class, 1)
  2042. truncname = (
  2043. anonname[0 : max(self.label_length - 6, 0)]
  2044. + "_"
  2045. + hex(counter)[2:]
  2046. )
  2047. self.truncated_names[ident_class] = counter + 1
  2048. else:
  2049. truncname = anonname
  2050. self.truncated_names[(ident_class, name)] = truncname
  2051. return truncname
  2052. def _anonymize(self, name):
  2053. return name % self.anon_map
  2054. def bindparam_string(
  2055. self,
  2056. name,
  2057. positional_names=None,
  2058. post_compile=False,
  2059. expanding=False,
  2060. escaped_from=None,
  2061. **kw
  2062. ):
  2063. if self.positional:
  2064. if positional_names is not None:
  2065. positional_names.append(name)
  2066. else:
  2067. self.positiontup.append(name)
  2068. elif not post_compile and not escaped_from:
  2069. tr_reg = self._bind_translate
  2070. if tr_reg.search(name):
  2071. # i'd rather use translate() here but I can't get it to work
  2072. # in all cases under Python 2, not worth it right now
  2073. new_name = tr_reg.sub(
  2074. lambda m: _BIND_TRANSLATE_CHARS[m.group(0)],
  2075. name,
  2076. )
  2077. escaped_from = name
  2078. name = new_name
  2079. if escaped_from:
  2080. if not self.escaped_bind_names:
  2081. self.escaped_bind_names = {}
  2082. self.escaped_bind_names[escaped_from] = name
  2083. if post_compile:
  2084. return "[POSTCOMPILE_%s]" % name
  2085. else:
  2086. return self.bindtemplate % {"name": name}
  2087. def visit_cte(
  2088. self,
  2089. cte,
  2090. asfrom=False,
  2091. ashint=False,
  2092. fromhints=None,
  2093. visiting_cte=None,
  2094. from_linter=None,
  2095. **kwargs
  2096. ):
  2097. self._init_cte_state()
  2098. kwargs["visiting_cte"] = cte
  2099. if isinstance(cte.name, elements._truncated_label):
  2100. cte_name = self._truncated_identifier("alias", cte.name)
  2101. else:
  2102. cte_name = cte.name
  2103. is_new_cte = True
  2104. embedded_in_current_named_cte = False
  2105. if cte_name in self.ctes_by_name:
  2106. existing_cte = self.ctes_by_name[cte_name]
  2107. embedded_in_current_named_cte = visiting_cte is existing_cte
  2108. # we've generated a same-named CTE that we are enclosed in,
  2109. # or this is the same CTE. just return the name.
  2110. if cte in existing_cte._restates or cte is existing_cte:
  2111. is_new_cte = False
  2112. elif existing_cte in cte._restates:
  2113. # we've generated a same-named CTE that is
  2114. # enclosed in us - we take precedence, so
  2115. # discard the text for the "inner".
  2116. del self.ctes[existing_cte]
  2117. else:
  2118. raise exc.CompileError(
  2119. "Multiple, unrelated CTEs found with "
  2120. "the same name: %r" % cte_name
  2121. )
  2122. if asfrom or is_new_cte:
  2123. if cte._cte_alias is not None:
  2124. pre_alias_cte = cte._cte_alias
  2125. cte_pre_alias_name = cte._cte_alias.name
  2126. if isinstance(cte_pre_alias_name, elements._truncated_label):
  2127. cte_pre_alias_name = self._truncated_identifier(
  2128. "alias", cte_pre_alias_name
  2129. )
  2130. else:
  2131. pre_alias_cte = cte
  2132. cte_pre_alias_name = None
  2133. if is_new_cte:
  2134. self.ctes_by_name[cte_name] = cte
  2135. if (
  2136. "autocommit" in cte.element._execution_options
  2137. and "autocommit" not in self.execution_options
  2138. ):
  2139. self.execution_options = self.execution_options.union(
  2140. {
  2141. "autocommit": cte.element._execution_options[
  2142. "autocommit"
  2143. ]
  2144. }
  2145. )
  2146. if pre_alias_cte not in self.ctes:
  2147. self.visit_cte(pre_alias_cte, **kwargs)
  2148. if not cte_pre_alias_name and cte not in self.ctes:
  2149. if cte.recursive:
  2150. self.ctes_recursive = True
  2151. text = self.preparer.format_alias(cte, cte_name)
  2152. if cte.recursive:
  2153. if isinstance(cte.element, selectable.Select):
  2154. col_source = cte.element
  2155. elif isinstance(cte.element, selectable.CompoundSelect):
  2156. col_source = cte.element.selects[0]
  2157. else:
  2158. assert False, "cte should only be against SelectBase"
  2159. recur_cols = [
  2160. c
  2161. for c in util.unique_list(
  2162. col_source._all_selected_columns
  2163. )
  2164. if c is not None
  2165. ]
  2166. text += "(%s)" % (
  2167. ", ".join(
  2168. self.preparer.format_column(
  2169. ident, anon_map=self.anon_map
  2170. )
  2171. for ident in recur_cols
  2172. )
  2173. )
  2174. if self.positional:
  2175. kwargs["positional_names"] = self.cte_positional[cte] = []
  2176. assert kwargs.get("subquery", False) is False
  2177. if not self.stack:
  2178. # toplevel, this is a stringify of the
  2179. # cte directly. just compile the inner
  2180. # the way alias() does.
  2181. return cte.element._compiler_dispatch(
  2182. self, asfrom=asfrom, **kwargs
  2183. )
  2184. else:
  2185. prefixes = self._generate_prefixes(
  2186. cte, cte._prefixes, **kwargs
  2187. )
  2188. inner = cte.element._compiler_dispatch(
  2189. self, asfrom=True, **kwargs
  2190. )
  2191. text += " AS %s\n(%s)" % (prefixes, inner)
  2192. if cte._suffixes:
  2193. text += " " + self._generate_prefixes(
  2194. cte, cte._suffixes, **kwargs
  2195. )
  2196. self.ctes[cte] = text
  2197. if asfrom:
  2198. if from_linter:
  2199. from_linter.froms[cte] = cte_name
  2200. if not is_new_cte and embedded_in_current_named_cte:
  2201. return self.preparer.format_alias(cte, cte_name)
  2202. if cte_pre_alias_name:
  2203. text = self.preparer.format_alias(cte, cte_pre_alias_name)
  2204. if self.preparer._requires_quotes(cte_name):
  2205. cte_name = self.preparer.quote(cte_name)
  2206. text += self.get_render_as_alias_suffix(cte_name)
  2207. return text
  2208. else:
  2209. return self.preparer.format_alias(cte, cte_name)
  2210. def visit_table_valued_alias(self, element, **kw):
  2211. if element._is_lateral:
  2212. return self.visit_lateral(element, **kw)
  2213. else:
  2214. return self.visit_alias(element, **kw)
  2215. def visit_table_valued_column(self, element, **kw):
  2216. return self.visit_column(element, **kw)
  2217. def visit_alias(
  2218. self,
  2219. alias,
  2220. asfrom=False,
  2221. ashint=False,
  2222. iscrud=False,
  2223. fromhints=None,
  2224. subquery=False,
  2225. lateral=False,
  2226. enclosing_alias=None,
  2227. from_linter=None,
  2228. **kwargs
  2229. ):
  2230. if lateral:
  2231. if "enclosing_lateral" not in kwargs:
  2232. # if lateral is set and enclosing_lateral is not
  2233. # present, we assume we are being called directly
  2234. # from visit_lateral() and we need to set enclosing_lateral.
  2235. assert alias._is_lateral
  2236. kwargs["enclosing_lateral"] = alias
  2237. # for lateral objects, we track a second from_linter that is...
  2238. # lateral! to the level above us.
  2239. if (
  2240. from_linter
  2241. and "lateral_from_linter" not in kwargs
  2242. and "enclosing_lateral" in kwargs
  2243. ):
  2244. kwargs["lateral_from_linter"] = from_linter
  2245. if enclosing_alias is not None and enclosing_alias.element is alias:
  2246. inner = alias.element._compiler_dispatch(
  2247. self,
  2248. asfrom=asfrom,
  2249. ashint=ashint,
  2250. iscrud=iscrud,
  2251. fromhints=fromhints,
  2252. lateral=lateral,
  2253. enclosing_alias=alias,
  2254. **kwargs
  2255. )
  2256. if subquery and (asfrom or lateral):
  2257. inner = "(%s)" % (inner,)
  2258. return inner
  2259. else:
  2260. enclosing_alias = kwargs["enclosing_alias"] = alias
  2261. if asfrom or ashint:
  2262. if isinstance(alias.name, elements._truncated_label):
  2263. alias_name = self._truncated_identifier("alias", alias.name)
  2264. else:
  2265. alias_name = alias.name
  2266. if ashint:
  2267. return self.preparer.format_alias(alias, alias_name)
  2268. elif asfrom:
  2269. if from_linter:
  2270. from_linter.froms[alias] = alias_name
  2271. inner = alias.element._compiler_dispatch(
  2272. self, asfrom=True, lateral=lateral, **kwargs
  2273. )
  2274. if subquery:
  2275. inner = "(%s)" % (inner,)
  2276. ret = inner + self.get_render_as_alias_suffix(
  2277. self.preparer.format_alias(alias, alias_name)
  2278. )
  2279. if alias._supports_derived_columns and alias._render_derived:
  2280. ret += "(%s)" % (
  2281. ", ".join(
  2282. "%s%s"
  2283. % (
  2284. self.preparer.quote(col.name),
  2285. " %s"
  2286. % self.dialect.type_compiler.process(
  2287. col.type, **kwargs
  2288. )
  2289. if alias._render_derived_w_types
  2290. else "",
  2291. )
  2292. for col in alias.c
  2293. )
  2294. )
  2295. if fromhints and alias in fromhints:
  2296. ret = self.format_from_hint_text(
  2297. ret, alias, fromhints[alias], iscrud
  2298. )
  2299. return ret
  2300. else:
  2301. # note we cancel the "subquery" flag here as well
  2302. return alias.element._compiler_dispatch(
  2303. self, lateral=lateral, **kwargs
  2304. )
  2305. def visit_subquery(self, subquery, **kw):
  2306. kw["subquery"] = True
  2307. return self.visit_alias(subquery, **kw)
  2308. def visit_lateral(self, lateral_, **kw):
  2309. kw["lateral"] = True
  2310. return "LATERAL %s" % self.visit_alias(lateral_, **kw)
  2311. def visit_tablesample(self, tablesample, asfrom=False, **kw):
  2312. text = "%s TABLESAMPLE %s" % (
  2313. self.visit_alias(tablesample, asfrom=True, **kw),
  2314. tablesample._get_method()._compiler_dispatch(self, **kw),
  2315. )
  2316. if tablesample.seed is not None:
  2317. text += " REPEATABLE (%s)" % (
  2318. tablesample.seed._compiler_dispatch(self, **kw)
  2319. )
  2320. return text
  2321. def visit_values(self, element, asfrom=False, from_linter=None, **kw):
  2322. kw.setdefault("literal_binds", element.literal_binds)
  2323. v = "VALUES %s" % ", ".join(
  2324. self.process(
  2325. elements.Tuple(
  2326. types=element._column_types, *elem
  2327. ).self_group(),
  2328. **kw
  2329. )
  2330. for chunk in element._data
  2331. for elem in chunk
  2332. )
  2333. if isinstance(element.name, elements._truncated_label):
  2334. name = self._truncated_identifier("values", element.name)
  2335. else:
  2336. name = element.name
  2337. if element._is_lateral:
  2338. lateral = "LATERAL "
  2339. else:
  2340. lateral = ""
  2341. if asfrom:
  2342. if from_linter:
  2343. from_linter.froms[element] = (
  2344. name if name is not None else "(unnamed VALUES element)"
  2345. )
  2346. if name:
  2347. v = "%s(%s)%s (%s)" % (
  2348. lateral,
  2349. v,
  2350. self.get_render_as_alias_suffix(self.preparer.quote(name)),
  2351. (
  2352. ", ".join(
  2353. c._compiler_dispatch(
  2354. self, include_table=False, **kw
  2355. )
  2356. for c in element.columns
  2357. )
  2358. ),
  2359. )
  2360. else:
  2361. v = "%s(%s)" % (lateral, v)
  2362. return v
  2363. def get_render_as_alias_suffix(self, alias_name_text):
  2364. return " AS " + alias_name_text
  2365. def _add_to_result_map(self, keyname, name, objects, type_):
  2366. if keyname is None or keyname == "*":
  2367. self._ordered_columns = False
  2368. self._textual_ordered_columns = True
  2369. if type_._is_tuple_type:
  2370. raise exc.CompileError(
  2371. "Most backends don't support SELECTing "
  2372. "from a tuple() object. If this is an ORM query, "
  2373. "consider using the Bundle object."
  2374. )
  2375. self._result_columns.append((keyname, name, objects, type_))
  2376. def _label_select_column(
  2377. self,
  2378. select,
  2379. column,
  2380. populate_result_map,
  2381. asfrom,
  2382. column_clause_args,
  2383. name=None,
  2384. within_columns_clause=True,
  2385. column_is_repeated=False,
  2386. need_column_expressions=False,
  2387. ):
  2388. """produce labeled columns present in a select()."""
  2389. impl = column.type.dialect_impl(self.dialect)
  2390. if impl._has_column_expression and (
  2391. need_column_expressions or populate_result_map
  2392. ):
  2393. col_expr = impl.column_expression(column)
  2394. else:
  2395. col_expr = column
  2396. if populate_result_map:
  2397. # pass an "add_to_result_map" callable into the compilation
  2398. # of embedded columns. this collects information about the
  2399. # column as it will be fetched in the result and is coordinated
  2400. # with cursor.description when the query is executed.
  2401. add_to_result_map = self._add_to_result_map
  2402. # if the SELECT statement told us this column is a repeat,
  2403. # wrap the callable with one that prevents the addition of the
  2404. # targets
  2405. if column_is_repeated:
  2406. _add_to_result_map = add_to_result_map
  2407. def add_to_result_map(keyname, name, objects, type_):
  2408. _add_to_result_map(keyname, name, (), type_)
  2409. # if we redefined col_expr for type expressions, wrap the
  2410. # callable with one that adds the original column to the targets
  2411. elif col_expr is not column:
  2412. _add_to_result_map = add_to_result_map
  2413. def add_to_result_map(keyname, name, objects, type_):
  2414. _add_to_result_map(
  2415. keyname, name, (column,) + objects, type_
  2416. )
  2417. else:
  2418. add_to_result_map = None
  2419. if not within_columns_clause:
  2420. result_expr = col_expr
  2421. elif isinstance(column, elements.Label):
  2422. if col_expr is not column:
  2423. result_expr = _CompileLabel(
  2424. col_expr, column.name, alt_names=(column.element,)
  2425. )
  2426. else:
  2427. result_expr = col_expr
  2428. elif select is not None and name:
  2429. result_expr = _CompileLabel(
  2430. col_expr, name, alt_names=(column._key_label,)
  2431. )
  2432. elif (
  2433. asfrom
  2434. and isinstance(column, elements.ColumnClause)
  2435. and not column.is_literal
  2436. and column.table is not None
  2437. and not isinstance(column.table, selectable.Select)
  2438. ):
  2439. result_expr = _CompileLabel(
  2440. col_expr,
  2441. coercions.expect(roles.TruncatedLabelRole, column.name),
  2442. alt_names=(column.key,),
  2443. )
  2444. elif (
  2445. not isinstance(column, elements.TextClause)
  2446. and (
  2447. not isinstance(column, elements.UnaryExpression)
  2448. or column.wraps_column_expression
  2449. or asfrom
  2450. )
  2451. and (
  2452. not hasattr(column, "name")
  2453. or isinstance(column, functions.FunctionElement)
  2454. )
  2455. ):
  2456. result_expr = _CompileLabel(
  2457. col_expr,
  2458. column._anon_name_label
  2459. if not column_is_repeated
  2460. else column._dedupe_label_anon_label,
  2461. )
  2462. elif col_expr is not column:
  2463. # TODO: are we sure "column" has a .name and .key here ?
  2464. # assert isinstance(column, elements.ColumnClause)
  2465. result_expr = _CompileLabel(
  2466. col_expr,
  2467. coercions.expect(roles.TruncatedLabelRole, column.name),
  2468. alt_names=(column.key,),
  2469. )
  2470. else:
  2471. result_expr = col_expr
  2472. column_clause_args.update(
  2473. within_columns_clause=within_columns_clause,
  2474. add_to_result_map=add_to_result_map,
  2475. )
  2476. return result_expr._compiler_dispatch(self, **column_clause_args)
  2477. def format_from_hint_text(self, sqltext, table, hint, iscrud):
  2478. hinttext = self.get_from_hint_text(table, hint)
  2479. if hinttext:
  2480. sqltext += " " + hinttext
  2481. return sqltext
  2482. def get_select_hint_text(self, byfroms):
  2483. return None
  2484. def get_from_hint_text(self, table, text):
  2485. return None
  2486. def get_crud_hint_text(self, table, text):
  2487. return None
  2488. def get_statement_hint_text(self, hint_texts):
  2489. return " ".join(hint_texts)
  2490. _default_stack_entry = util.immutabledict(
  2491. [("correlate_froms", frozenset()), ("asfrom_froms", frozenset())]
  2492. )
  2493. def _display_froms_for_select(
  2494. self, select_stmt, asfrom, lateral=False, **kw
  2495. ):
  2496. # utility method to help external dialects
  2497. # get the correct from list for a select.
  2498. # specifically the oracle dialect needs this feature
  2499. # right now.
  2500. toplevel = not self.stack
  2501. entry = self._default_stack_entry if toplevel else self.stack[-1]
  2502. compile_state = select_stmt._compile_state_factory(select_stmt, self)
  2503. correlate_froms = entry["correlate_froms"]
  2504. asfrom_froms = entry["asfrom_froms"]
  2505. if asfrom and not lateral:
  2506. froms = compile_state._get_display_froms(
  2507. explicit_correlate_froms=correlate_froms.difference(
  2508. asfrom_froms
  2509. ),
  2510. implicit_correlate_froms=(),
  2511. )
  2512. else:
  2513. froms = compile_state._get_display_froms(
  2514. explicit_correlate_froms=correlate_froms,
  2515. implicit_correlate_froms=asfrom_froms,
  2516. )
  2517. return froms
  2518. translate_select_structure = None
  2519. """if not ``None``, should be a callable which accepts ``(select_stmt,
  2520. **kw)`` and returns a select object. this is used for structural changes
  2521. mostly to accommodate for LIMIT/OFFSET schemes
  2522. """
  2523. def visit_select(
  2524. self,
  2525. select_stmt,
  2526. asfrom=False,
  2527. fromhints=None,
  2528. compound_index=None,
  2529. select_wraps_for=None,
  2530. lateral=False,
  2531. from_linter=None,
  2532. **kwargs
  2533. ):
  2534. assert select_wraps_for is None, (
  2535. "SQLAlchemy 1.4 requires use of "
  2536. "the translate_select_structure hook for structural "
  2537. "translations of SELECT objects"
  2538. )
  2539. # initial setup of SELECT. the compile_state_factory may now
  2540. # be creating a totally different SELECT from the one that was
  2541. # passed in. for ORM use this will convert from an ORM-state
  2542. # SELECT to a regular "Core" SELECT. other composed operations
  2543. # such as computation of joins will be performed.
  2544. compile_state = select_stmt._compile_state_factory(
  2545. select_stmt, self, **kwargs
  2546. )
  2547. select_stmt = compile_state.statement
  2548. toplevel = not self.stack
  2549. if toplevel and not self.compile_state:
  2550. self.compile_state = compile_state
  2551. # translate step for Oracle, SQL Server which often need to
  2552. # restructure the SELECT to allow for LIMIT/OFFSET and possibly
  2553. # other conditions
  2554. if self.translate_select_structure:
  2555. new_select_stmt = self.translate_select_structure(
  2556. select_stmt, asfrom=asfrom, **kwargs
  2557. )
  2558. # if SELECT was restructured, maintain a link to the originals
  2559. # and assemble a new compile state
  2560. if new_select_stmt is not select_stmt:
  2561. compile_state_wraps_for = compile_state
  2562. select_wraps_for = select_stmt
  2563. select_stmt = new_select_stmt
  2564. compile_state = select_stmt._compile_state_factory(
  2565. select_stmt, self, **kwargs
  2566. )
  2567. select_stmt = compile_state.statement
  2568. entry = self._default_stack_entry if toplevel else self.stack[-1]
  2569. populate_result_map = need_column_expressions = (
  2570. toplevel
  2571. or entry.get("need_result_map_for_compound", False)
  2572. or entry.get("need_result_map_for_nested", False)
  2573. )
  2574. # indicates there is a CompoundSelect in play and we are not the
  2575. # first select
  2576. if compound_index:
  2577. populate_result_map = False
  2578. # this was first proposed as part of #3372; however, it is not
  2579. # reached in current tests and could possibly be an assertion
  2580. # instead.
  2581. if not populate_result_map and "add_to_result_map" in kwargs:
  2582. del kwargs["add_to_result_map"]
  2583. froms = self._setup_select_stack(
  2584. select_stmt, compile_state, entry, asfrom, lateral, compound_index
  2585. )
  2586. column_clause_args = kwargs.copy()
  2587. column_clause_args.update(
  2588. {"within_label_clause": False, "within_columns_clause": False}
  2589. )
  2590. text = "SELECT " # we're off to a good start !
  2591. if select_stmt._hints:
  2592. hint_text, byfrom = self._setup_select_hints(select_stmt)
  2593. if hint_text:
  2594. text += hint_text + " "
  2595. else:
  2596. byfrom = None
  2597. if select_stmt._prefixes:
  2598. text += self._generate_prefixes(
  2599. select_stmt, select_stmt._prefixes, **kwargs
  2600. )
  2601. text += self.get_select_precolumns(select_stmt, **kwargs)
  2602. # the actual list of columns to print in the SELECT column list.
  2603. inner_columns = [
  2604. c
  2605. for c in [
  2606. self._label_select_column(
  2607. select_stmt,
  2608. column,
  2609. populate_result_map,
  2610. asfrom,
  2611. column_clause_args,
  2612. name=name,
  2613. column_is_repeated=repeated,
  2614. need_column_expressions=need_column_expressions,
  2615. )
  2616. for name, column, repeated in compile_state.columns_plus_names
  2617. ]
  2618. if c is not None
  2619. ]
  2620. if populate_result_map and select_wraps_for is not None:
  2621. # if this select was generated from translate_select,
  2622. # rewrite the targeted columns in the result map
  2623. translate = dict(
  2624. zip(
  2625. [
  2626. name
  2627. for (
  2628. key,
  2629. name,
  2630. repeated,
  2631. ) in compile_state.columns_plus_names
  2632. ],
  2633. [
  2634. name
  2635. for (
  2636. key,
  2637. name,
  2638. repeated,
  2639. ) in compile_state_wraps_for.columns_plus_names
  2640. ],
  2641. )
  2642. )
  2643. self._result_columns = [
  2644. (key, name, tuple(translate.get(o, o) for o in obj), type_)
  2645. for key, name, obj, type_ in self._result_columns
  2646. ]
  2647. text = self._compose_select_body(
  2648. text,
  2649. select_stmt,
  2650. compile_state,
  2651. inner_columns,
  2652. froms,
  2653. byfrom,
  2654. toplevel,
  2655. kwargs,
  2656. )
  2657. if select_stmt._statement_hints:
  2658. per_dialect = [
  2659. ht
  2660. for (dialect_name, ht) in select_stmt._statement_hints
  2661. if dialect_name in ("*", self.dialect.name)
  2662. ]
  2663. if per_dialect:
  2664. text += " " + self.get_statement_hint_text(per_dialect)
  2665. if self.ctes and toplevel:
  2666. text = self._render_cte_clause() + text
  2667. if select_stmt._suffixes:
  2668. text += " " + self._generate_prefixes(
  2669. select_stmt, select_stmt._suffixes, **kwargs
  2670. )
  2671. self.stack.pop(-1)
  2672. return text
  2673. def _setup_select_hints(self, select):
  2674. byfrom = dict(
  2675. [
  2676. (
  2677. from_,
  2678. hinttext
  2679. % {"name": from_._compiler_dispatch(self, ashint=True)},
  2680. )
  2681. for (from_, dialect), hinttext in select._hints.items()
  2682. if dialect in ("*", self.dialect.name)
  2683. ]
  2684. )
  2685. hint_text = self.get_select_hint_text(byfrom)
  2686. return hint_text, byfrom
  2687. def _setup_select_stack(
  2688. self, select, compile_state, entry, asfrom, lateral, compound_index
  2689. ):
  2690. correlate_froms = entry["correlate_froms"]
  2691. asfrom_froms = entry["asfrom_froms"]
  2692. if compound_index == 0:
  2693. entry["select_0"] = select
  2694. elif compound_index:
  2695. select_0 = entry["select_0"]
  2696. numcols = len(select_0._all_selected_columns)
  2697. if len(compile_state.columns_plus_names) != numcols:
  2698. raise exc.CompileError(
  2699. "All selectables passed to "
  2700. "CompoundSelect must have identical numbers of "
  2701. "columns; select #%d has %d columns, select "
  2702. "#%d has %d"
  2703. % (
  2704. 1,
  2705. numcols,
  2706. compound_index + 1,
  2707. len(select._all_selected_columns),
  2708. )
  2709. )
  2710. if asfrom and not lateral:
  2711. froms = compile_state._get_display_froms(
  2712. explicit_correlate_froms=correlate_froms.difference(
  2713. asfrom_froms
  2714. ),
  2715. implicit_correlate_froms=(),
  2716. )
  2717. else:
  2718. froms = compile_state._get_display_froms(
  2719. explicit_correlate_froms=correlate_froms,
  2720. implicit_correlate_froms=asfrom_froms,
  2721. )
  2722. new_correlate_froms = set(selectable._from_objects(*froms))
  2723. all_correlate_froms = new_correlate_froms.union(correlate_froms)
  2724. new_entry = {
  2725. "asfrom_froms": new_correlate_froms,
  2726. "correlate_froms": all_correlate_froms,
  2727. "selectable": select,
  2728. "compile_state": compile_state,
  2729. }
  2730. self.stack.append(new_entry)
  2731. return froms
  2732. def _compose_select_body(
  2733. self,
  2734. text,
  2735. select,
  2736. compile_state,
  2737. inner_columns,
  2738. froms,
  2739. byfrom,
  2740. toplevel,
  2741. kwargs,
  2742. ):
  2743. text += ", ".join(inner_columns)
  2744. if self.linting & COLLECT_CARTESIAN_PRODUCTS:
  2745. from_linter = FromLinter({}, set())
  2746. warn_linting = self.linting & WARN_LINTING
  2747. if toplevel:
  2748. self.from_linter = from_linter
  2749. else:
  2750. from_linter = None
  2751. warn_linting = False
  2752. if froms:
  2753. text += " \nFROM "
  2754. if select._hints:
  2755. text += ", ".join(
  2756. [
  2757. f._compiler_dispatch(
  2758. self,
  2759. asfrom=True,
  2760. fromhints=byfrom,
  2761. from_linter=from_linter,
  2762. **kwargs
  2763. )
  2764. for f in froms
  2765. ]
  2766. )
  2767. else:
  2768. text += ", ".join(
  2769. [
  2770. f._compiler_dispatch(
  2771. self,
  2772. asfrom=True,
  2773. from_linter=from_linter,
  2774. **kwargs
  2775. )
  2776. for f in froms
  2777. ]
  2778. )
  2779. else:
  2780. text += self.default_from()
  2781. if select._where_criteria:
  2782. t = self._generate_delimited_and_list(
  2783. select._where_criteria, from_linter=from_linter, **kwargs
  2784. )
  2785. if t:
  2786. text += " \nWHERE " + t
  2787. if warn_linting:
  2788. from_linter.warn()
  2789. if select._group_by_clauses:
  2790. text += self.group_by_clause(select, **kwargs)
  2791. if select._having_criteria:
  2792. t = self._generate_delimited_and_list(
  2793. select._having_criteria, **kwargs
  2794. )
  2795. if t:
  2796. text += " \nHAVING " + t
  2797. if select._order_by_clauses:
  2798. text += self.order_by_clause(select, **kwargs)
  2799. if select._has_row_limiting_clause:
  2800. text += self._row_limit_clause(select, **kwargs)
  2801. if select._for_update_arg is not None:
  2802. text += self.for_update_clause(select, **kwargs)
  2803. return text
  2804. def _generate_prefixes(self, stmt, prefixes, **kw):
  2805. clause = " ".join(
  2806. prefix._compiler_dispatch(self, **kw)
  2807. for prefix, dialect_name in prefixes
  2808. if dialect_name is None or dialect_name == self.dialect.name
  2809. )
  2810. if clause:
  2811. clause += " "
  2812. return clause
  2813. def _render_cte_clause(self):
  2814. if self.positional:
  2815. self.positiontup = (
  2816. sum([self.cte_positional[cte] for cte in self.ctes], [])
  2817. + self.positiontup
  2818. )
  2819. cte_text = self.get_cte_preamble(self.ctes_recursive) + " "
  2820. cte_text += ", \n".join([txt for txt in self.ctes.values()])
  2821. cte_text += "\n "
  2822. return cte_text
  2823. def get_cte_preamble(self, recursive):
  2824. if recursive:
  2825. return "WITH RECURSIVE"
  2826. else:
  2827. return "WITH"
  2828. def get_select_precolumns(self, select, **kw):
  2829. """Called when building a ``SELECT`` statement, position is just
  2830. before column list.
  2831. """
  2832. if select._distinct_on:
  2833. util.warn_deprecated(
  2834. "DISTINCT ON is currently supported only by the PostgreSQL "
  2835. "dialect. Use of DISTINCT ON for other backends is currently "
  2836. "silently ignored, however this usage is deprecated, and will "
  2837. "raise CompileError in a future release for all backends "
  2838. "that do not support this syntax.",
  2839. version="1.4",
  2840. )
  2841. return "DISTINCT " if select._distinct else ""
  2842. def group_by_clause(self, select, **kw):
  2843. """allow dialects to customize how GROUP BY is rendered."""
  2844. group_by = self._generate_delimited_list(
  2845. select._group_by_clauses, OPERATORS[operators.comma_op], **kw
  2846. )
  2847. if group_by:
  2848. return " GROUP BY " + group_by
  2849. else:
  2850. return ""
  2851. def order_by_clause(self, select, **kw):
  2852. """allow dialects to customize how ORDER BY is rendered."""
  2853. order_by = self._generate_delimited_list(
  2854. select._order_by_clauses, OPERATORS[operators.comma_op], **kw
  2855. )
  2856. if order_by:
  2857. return " ORDER BY " + order_by
  2858. else:
  2859. return ""
  2860. def for_update_clause(self, select, **kw):
  2861. return " FOR UPDATE"
  2862. def returning_clause(self, stmt, returning_cols):
  2863. raise exc.CompileError(
  2864. "RETURNING is not supported by this "
  2865. "dialect's statement compiler."
  2866. )
  2867. def limit_clause(self, select, **kw):
  2868. text = ""
  2869. if select._limit_clause is not None:
  2870. text += "\n LIMIT " + self.process(select._limit_clause, **kw)
  2871. if select._offset_clause is not None:
  2872. if select._limit_clause is None:
  2873. text += "\n LIMIT -1"
  2874. text += " OFFSET " + self.process(select._offset_clause, **kw)
  2875. return text
  2876. def fetch_clause(self, select, **kw):
  2877. text = ""
  2878. if select._offset_clause is not None:
  2879. text += "\n OFFSET %s ROWS" % self.process(
  2880. select._offset_clause, **kw
  2881. )
  2882. if select._fetch_clause is not None:
  2883. text += "\n FETCH FIRST %s%s ROWS %s" % (
  2884. self.process(select._fetch_clause, **kw),
  2885. " PERCENT" if select._fetch_clause_options["percent"] else "",
  2886. "WITH TIES"
  2887. if select._fetch_clause_options["with_ties"]
  2888. else "ONLY",
  2889. )
  2890. return text
  2891. def visit_table(
  2892. self,
  2893. table,
  2894. asfrom=False,
  2895. iscrud=False,
  2896. ashint=False,
  2897. fromhints=None,
  2898. use_schema=True,
  2899. from_linter=None,
  2900. **kwargs
  2901. ):
  2902. if from_linter:
  2903. from_linter.froms[table] = table.fullname
  2904. if asfrom or ashint:
  2905. effective_schema = self.preparer.schema_for_object(table)
  2906. if use_schema and effective_schema:
  2907. ret = (
  2908. self.preparer.quote_schema(effective_schema)
  2909. + "."
  2910. + self.preparer.quote(table.name)
  2911. )
  2912. else:
  2913. ret = self.preparer.quote(table.name)
  2914. if fromhints and table in fromhints:
  2915. ret = self.format_from_hint_text(
  2916. ret, table, fromhints[table], iscrud
  2917. )
  2918. return ret
  2919. else:
  2920. return ""
  2921. def visit_join(self, join, asfrom=False, from_linter=None, **kwargs):
  2922. if from_linter:
  2923. from_linter.edges.add((join.left, join.right))
  2924. if join.full:
  2925. join_type = " FULL OUTER JOIN "
  2926. elif join.isouter:
  2927. join_type = " LEFT OUTER JOIN "
  2928. else:
  2929. join_type = " JOIN "
  2930. return (
  2931. join.left._compiler_dispatch(
  2932. self, asfrom=True, from_linter=from_linter, **kwargs
  2933. )
  2934. + join_type
  2935. + join.right._compiler_dispatch(
  2936. self, asfrom=True, from_linter=from_linter, **kwargs
  2937. )
  2938. + " ON "
  2939. # TODO: likely need asfrom=True here?
  2940. + join.onclause._compiler_dispatch(
  2941. self, from_linter=from_linter, **kwargs
  2942. )
  2943. )
  2944. def _setup_crud_hints(self, stmt, table_text):
  2945. dialect_hints = dict(
  2946. [
  2947. (table, hint_text)
  2948. for (table, dialect), hint_text in stmt._hints.items()
  2949. if dialect in ("*", self.dialect.name)
  2950. ]
  2951. )
  2952. if stmt.table in dialect_hints:
  2953. table_text = self.format_from_hint_text(
  2954. table_text, stmt.table, dialect_hints[stmt.table], True
  2955. )
  2956. return dialect_hints, table_text
  2957. def visit_insert(self, insert_stmt, **kw):
  2958. compile_state = insert_stmt._compile_state_factory(
  2959. insert_stmt, self, **kw
  2960. )
  2961. insert_stmt = compile_state.statement
  2962. toplevel = not self.stack
  2963. if toplevel:
  2964. self.isinsert = True
  2965. if not self.compile_state:
  2966. self.compile_state = compile_state
  2967. self.stack.append(
  2968. {
  2969. "correlate_froms": set(),
  2970. "asfrom_froms": set(),
  2971. "selectable": insert_stmt,
  2972. }
  2973. )
  2974. crud_params = crud._get_crud_params(
  2975. self, insert_stmt, compile_state, **kw
  2976. )
  2977. if (
  2978. not crud_params
  2979. and not self.dialect.supports_default_values
  2980. and not self.dialect.supports_default_metavalue
  2981. and not self.dialect.supports_empty_insert
  2982. ):
  2983. raise exc.CompileError(
  2984. "The '%s' dialect with current database "
  2985. "version settings does not support empty "
  2986. "inserts." % self.dialect.name
  2987. )
  2988. if compile_state._has_multi_parameters:
  2989. if not self.dialect.supports_multivalues_insert:
  2990. raise exc.CompileError(
  2991. "The '%s' dialect with current database "
  2992. "version settings does not support "
  2993. "in-place multirow inserts." % self.dialect.name
  2994. )
  2995. crud_params_single = crud_params[0]
  2996. else:
  2997. crud_params_single = crud_params
  2998. preparer = self.preparer
  2999. supports_default_values = self.dialect.supports_default_values
  3000. text = "INSERT "
  3001. if insert_stmt._prefixes:
  3002. text += self._generate_prefixes(
  3003. insert_stmt, insert_stmt._prefixes, **kw
  3004. )
  3005. text += "INTO "
  3006. table_text = preparer.format_table(insert_stmt.table)
  3007. if insert_stmt._hints:
  3008. _, table_text = self._setup_crud_hints(insert_stmt, table_text)
  3009. text += table_text
  3010. if crud_params_single or not supports_default_values:
  3011. text += " (%s)" % ", ".join(
  3012. [expr for c, expr, value in crud_params_single]
  3013. )
  3014. if self.returning or insert_stmt._returning:
  3015. returning_clause = self.returning_clause(
  3016. insert_stmt, self.returning or insert_stmt._returning
  3017. )
  3018. if self.returning_precedes_values:
  3019. text += " " + returning_clause
  3020. else:
  3021. returning_clause = None
  3022. if insert_stmt.select is not None:
  3023. select_text = self.process(self._insert_from_select, **kw)
  3024. if self.ctes and toplevel and self.dialect.cte_follows_insert:
  3025. text += " %s%s" % (self._render_cte_clause(), select_text)
  3026. else:
  3027. text += " %s" % select_text
  3028. elif not crud_params and supports_default_values:
  3029. text += " DEFAULT VALUES"
  3030. elif compile_state._has_multi_parameters:
  3031. text += " VALUES %s" % (
  3032. ", ".join(
  3033. "(%s)"
  3034. % (", ".join(value for c, expr, value in crud_param_set))
  3035. for crud_param_set in crud_params
  3036. )
  3037. )
  3038. else:
  3039. insert_single_values_expr = ", ".join(
  3040. [value for c, expr, value in crud_params]
  3041. )
  3042. text += " VALUES (%s)" % insert_single_values_expr
  3043. if toplevel and insert_stmt._post_values_clause is None:
  3044. # don't assign insert_single_values_expr if _post_values_clause
  3045. # is present. what this means concretely is that the
  3046. # "fast insert executemany helper" won't be used, in other
  3047. # words we won't convert "executemany()" of many parameter
  3048. # sets into a single INSERT with many elements in VALUES.
  3049. # We can't apply that optimization safely if for example the
  3050. # statement includes a clause like "ON CONFLICT DO UPDATE"
  3051. self.insert_single_values_expr = insert_single_values_expr
  3052. if insert_stmt._post_values_clause is not None:
  3053. post_values_clause = self.process(
  3054. insert_stmt._post_values_clause, **kw
  3055. )
  3056. if post_values_clause:
  3057. text += " " + post_values_clause
  3058. if returning_clause and not self.returning_precedes_values:
  3059. text += " " + returning_clause
  3060. if self.ctes and toplevel and not self.dialect.cte_follows_insert:
  3061. text = self._render_cte_clause() + text
  3062. self.stack.pop(-1)
  3063. return text
  3064. def update_limit_clause(self, update_stmt):
  3065. """Provide a hook for MySQL to add LIMIT to the UPDATE"""
  3066. return None
  3067. def update_tables_clause(self, update_stmt, from_table, extra_froms, **kw):
  3068. """Provide a hook to override the initial table clause
  3069. in an UPDATE statement.
  3070. MySQL overrides this.
  3071. """
  3072. kw["asfrom"] = True
  3073. return from_table._compiler_dispatch(self, iscrud=True, **kw)
  3074. def update_from_clause(
  3075. self, update_stmt, from_table, extra_froms, from_hints, **kw
  3076. ):
  3077. """Provide a hook to override the generation of an
  3078. UPDATE..FROM clause.
  3079. MySQL and MSSQL override this.
  3080. """
  3081. raise NotImplementedError(
  3082. "This backend does not support multiple-table "
  3083. "criteria within UPDATE"
  3084. )
  3085. def visit_update(self, update_stmt, **kw):
  3086. compile_state = update_stmt._compile_state_factory(
  3087. update_stmt, self, **kw
  3088. )
  3089. update_stmt = compile_state.statement
  3090. toplevel = not self.stack
  3091. if toplevel:
  3092. self.isupdate = True
  3093. if not self.compile_state:
  3094. self.compile_state = compile_state
  3095. extra_froms = compile_state._extra_froms
  3096. is_multitable = bool(extra_froms)
  3097. if is_multitable:
  3098. # main table might be a JOIN
  3099. main_froms = set(selectable._from_objects(update_stmt.table))
  3100. render_extra_froms = [
  3101. f for f in extra_froms if f not in main_froms
  3102. ]
  3103. correlate_froms = main_froms.union(extra_froms)
  3104. else:
  3105. render_extra_froms = []
  3106. correlate_froms = {update_stmt.table}
  3107. self.stack.append(
  3108. {
  3109. "correlate_froms": correlate_froms,
  3110. "asfrom_froms": correlate_froms,
  3111. "selectable": update_stmt,
  3112. }
  3113. )
  3114. text = "UPDATE "
  3115. if update_stmt._prefixes:
  3116. text += self._generate_prefixes(
  3117. update_stmt, update_stmt._prefixes, **kw
  3118. )
  3119. table_text = self.update_tables_clause(
  3120. update_stmt, update_stmt.table, render_extra_froms, **kw
  3121. )
  3122. crud_params = crud._get_crud_params(
  3123. self, update_stmt, compile_state, **kw
  3124. )
  3125. if update_stmt._hints:
  3126. dialect_hints, table_text = self._setup_crud_hints(
  3127. update_stmt, table_text
  3128. )
  3129. else:
  3130. dialect_hints = None
  3131. text += table_text
  3132. text += " SET "
  3133. text += ", ".join(expr + "=" + value for c, expr, value in crud_params)
  3134. if self.returning or update_stmt._returning:
  3135. if self.returning_precedes_values:
  3136. text += " " + self.returning_clause(
  3137. update_stmt, self.returning or update_stmt._returning
  3138. )
  3139. if extra_froms:
  3140. extra_from_text = self.update_from_clause(
  3141. update_stmt,
  3142. update_stmt.table,
  3143. render_extra_froms,
  3144. dialect_hints,
  3145. **kw
  3146. )
  3147. if extra_from_text:
  3148. text += " " + extra_from_text
  3149. if update_stmt._where_criteria:
  3150. t = self._generate_delimited_and_list(
  3151. update_stmt._where_criteria, **kw
  3152. )
  3153. if t:
  3154. text += " WHERE " + t
  3155. limit_clause = self.update_limit_clause(update_stmt)
  3156. if limit_clause:
  3157. text += " " + limit_clause
  3158. if (
  3159. self.returning or update_stmt._returning
  3160. ) and not self.returning_precedes_values:
  3161. text += " " + self.returning_clause(
  3162. update_stmt, self.returning or update_stmt._returning
  3163. )
  3164. if self.ctes and toplevel:
  3165. text = self._render_cte_clause() + text
  3166. self.stack.pop(-1)
  3167. return text
  3168. def delete_extra_from_clause(
  3169. self, update_stmt, from_table, extra_froms, from_hints, **kw
  3170. ):
  3171. """Provide a hook to override the generation of an
  3172. DELETE..FROM clause.
  3173. This can be used to implement DELETE..USING for example.
  3174. MySQL and MSSQL override this.
  3175. """
  3176. raise NotImplementedError(
  3177. "This backend does not support multiple-table "
  3178. "criteria within DELETE"
  3179. )
  3180. def delete_table_clause(self, delete_stmt, from_table, extra_froms):
  3181. return from_table._compiler_dispatch(self, asfrom=True, iscrud=True)
  3182. def visit_delete(self, delete_stmt, **kw):
  3183. compile_state = delete_stmt._compile_state_factory(
  3184. delete_stmt, self, **kw
  3185. )
  3186. delete_stmt = compile_state.statement
  3187. toplevel = not self.stack
  3188. if toplevel:
  3189. self.isdelete = True
  3190. if not self.compile_state:
  3191. self.compile_state = compile_state
  3192. extra_froms = compile_state._extra_froms
  3193. correlate_froms = {delete_stmt.table}.union(extra_froms)
  3194. self.stack.append(
  3195. {
  3196. "correlate_froms": correlate_froms,
  3197. "asfrom_froms": correlate_froms,
  3198. "selectable": delete_stmt,
  3199. }
  3200. )
  3201. text = "DELETE "
  3202. if delete_stmt._prefixes:
  3203. text += self._generate_prefixes(
  3204. delete_stmt, delete_stmt._prefixes, **kw
  3205. )
  3206. text += "FROM "
  3207. table_text = self.delete_table_clause(
  3208. delete_stmt, delete_stmt.table, extra_froms
  3209. )
  3210. if delete_stmt._hints:
  3211. dialect_hints, table_text = self._setup_crud_hints(
  3212. delete_stmt, table_text
  3213. )
  3214. else:
  3215. dialect_hints = None
  3216. text += table_text
  3217. if delete_stmt._returning:
  3218. if self.returning_precedes_values:
  3219. text += " " + self.returning_clause(
  3220. delete_stmt, delete_stmt._returning
  3221. )
  3222. if extra_froms:
  3223. extra_from_text = self.delete_extra_from_clause(
  3224. delete_stmt,
  3225. delete_stmt.table,
  3226. extra_froms,
  3227. dialect_hints,
  3228. **kw
  3229. )
  3230. if extra_from_text:
  3231. text += " " + extra_from_text
  3232. if delete_stmt._where_criteria:
  3233. t = self._generate_delimited_and_list(
  3234. delete_stmt._where_criteria, **kw
  3235. )
  3236. if t:
  3237. text += " WHERE " + t
  3238. if delete_stmt._returning and not self.returning_precedes_values:
  3239. text += " " + self.returning_clause(
  3240. delete_stmt, delete_stmt._returning
  3241. )
  3242. if self.ctes and toplevel:
  3243. text = self._render_cte_clause() + text
  3244. self.stack.pop(-1)
  3245. return text
  3246. def visit_savepoint(self, savepoint_stmt):
  3247. return "SAVEPOINT %s" % self.preparer.format_savepoint(savepoint_stmt)
  3248. def visit_rollback_to_savepoint(self, savepoint_stmt):
  3249. return "ROLLBACK TO SAVEPOINT %s" % self.preparer.format_savepoint(
  3250. savepoint_stmt
  3251. )
  3252. def visit_release_savepoint(self, savepoint_stmt):
  3253. return "RELEASE SAVEPOINT %s" % self.preparer.format_savepoint(
  3254. savepoint_stmt
  3255. )
  3256. class StrSQLCompiler(SQLCompiler):
  3257. """A :class:`.SQLCompiler` subclass which allows a small selection
  3258. of non-standard SQL features to render into a string value.
  3259. The :class:`.StrSQLCompiler` is invoked whenever a Core expression
  3260. element is directly stringified without calling upon the
  3261. :meth:`_expression.ClauseElement.compile` method.
  3262. It can render a limited set
  3263. of non-standard SQL constructs to assist in basic stringification,
  3264. however for more substantial custom or dialect-specific SQL constructs,
  3265. it will be necessary to make use of
  3266. :meth:`_expression.ClauseElement.compile`
  3267. directly.
  3268. .. seealso::
  3269. :ref:`faq_sql_expression_string`
  3270. """
  3271. def _fallback_column_name(self, column):
  3272. return "<name unknown>"
  3273. @util.preload_module("sqlalchemy.engine.url")
  3274. def visit_unsupported_compilation(self, element, err, **kw):
  3275. if element.stringify_dialect != "default":
  3276. url = util.preloaded.engine_url
  3277. dialect = url.URL.create(element.stringify_dialect).get_dialect()()
  3278. compiler = dialect.statement_compiler(dialect, None)
  3279. if not isinstance(compiler, StrSQLCompiler):
  3280. return compiler.process(element)
  3281. return super(StrSQLCompiler, self).visit_unsupported_compilation(
  3282. element, err
  3283. )
  3284. def visit_getitem_binary(self, binary, operator, **kw):
  3285. return "%s[%s]" % (
  3286. self.process(binary.left, **kw),
  3287. self.process(binary.right, **kw),
  3288. )
  3289. def visit_json_getitem_op_binary(self, binary, operator, **kw):
  3290. return self.visit_getitem_binary(binary, operator, **kw)
  3291. def visit_json_path_getitem_op_binary(self, binary, operator, **kw):
  3292. return self.visit_getitem_binary(binary, operator, **kw)
  3293. def visit_sequence(self, seq, **kw):
  3294. return "<next sequence value: %s>" % self.preparer.format_sequence(seq)
  3295. def returning_clause(self, stmt, returning_cols):
  3296. columns = [
  3297. self._label_select_column(None, c, True, False, {})
  3298. for c in base._select_iterables(returning_cols)
  3299. ]
  3300. return "RETURNING " + ", ".join(columns)
  3301. def update_from_clause(
  3302. self, update_stmt, from_table, extra_froms, from_hints, **kw
  3303. ):
  3304. kw["asfrom"] = True
  3305. return "FROM " + ", ".join(
  3306. t._compiler_dispatch(self, fromhints=from_hints, **kw)
  3307. for t in extra_froms
  3308. )
  3309. def delete_extra_from_clause(
  3310. self, update_stmt, from_table, extra_froms, from_hints, **kw
  3311. ):
  3312. kw["asfrom"] = True
  3313. return ", " + ", ".join(
  3314. t._compiler_dispatch(self, fromhints=from_hints, **kw)
  3315. for t in extra_froms
  3316. )
  3317. def visit_empty_set_expr(self, type_):
  3318. return "SELECT 1 WHERE 1!=1"
  3319. def get_from_hint_text(self, table, text):
  3320. return "[%s]" % text
  3321. def visit_regexp_match_op_binary(self, binary, operator, **kw):
  3322. return self._generate_generic_binary(binary, " <regexp> ", **kw)
  3323. def visit_not_regexp_match_op_binary(self, binary, operator, **kw):
  3324. return self._generate_generic_binary(binary, " <not regexp> ", **kw)
  3325. def visit_regexp_replace_op_binary(self, binary, operator, **kw):
  3326. replacement = binary.modifiers["replacement"]
  3327. return "<regexp replace>(%s, %s, %s)" % (
  3328. binary.left._compiler_dispatch(self, **kw),
  3329. binary.right._compiler_dispatch(self, **kw),
  3330. replacement._compiler_dispatch(self, **kw),
  3331. )
  3332. class DDLCompiler(Compiled):
  3333. @util.memoized_property
  3334. def sql_compiler(self):
  3335. return self.dialect.statement_compiler(
  3336. self.dialect, None, schema_translate_map=self.schema_translate_map
  3337. )
  3338. @util.memoized_property
  3339. def type_compiler(self):
  3340. return self.dialect.type_compiler
  3341. def construct_params(self, params=None, extracted_parameters=None):
  3342. return None
  3343. def visit_ddl(self, ddl, **kwargs):
  3344. # table events can substitute table and schema name
  3345. context = ddl.context
  3346. if isinstance(ddl.target, schema.Table):
  3347. context = context.copy()
  3348. preparer = self.preparer
  3349. path = preparer.format_table_seq(ddl.target)
  3350. if len(path) == 1:
  3351. table, sch = path[0], ""
  3352. else:
  3353. table, sch = path[-1], path[0]
  3354. context.setdefault("table", table)
  3355. context.setdefault("schema", sch)
  3356. context.setdefault("fullname", preparer.format_table(ddl.target))
  3357. return self.sql_compiler.post_process_text(ddl.statement % context)
  3358. def visit_create_schema(self, create, **kw):
  3359. schema = self.preparer.format_schema(create.element)
  3360. return "CREATE SCHEMA " + schema
  3361. def visit_drop_schema(self, drop, **kw):
  3362. schema = self.preparer.format_schema(drop.element)
  3363. text = "DROP SCHEMA " + schema
  3364. if drop.cascade:
  3365. text += " CASCADE"
  3366. return text
  3367. def visit_create_table(self, create, **kw):
  3368. table = create.element
  3369. preparer = self.preparer
  3370. text = "\nCREATE "
  3371. if table._prefixes:
  3372. text += " ".join(table._prefixes) + " "
  3373. text += "TABLE "
  3374. if create.if_not_exists:
  3375. text += "IF NOT EXISTS "
  3376. text += preparer.format_table(table) + " "
  3377. create_table_suffix = self.create_table_suffix(table)
  3378. if create_table_suffix:
  3379. text += create_table_suffix + " "
  3380. text += "("
  3381. separator = "\n"
  3382. # if only one primary key, specify it along with the column
  3383. first_pk = False
  3384. for create_column in create.columns:
  3385. column = create_column.element
  3386. try:
  3387. processed = self.process(
  3388. create_column, first_pk=column.primary_key and not first_pk
  3389. )
  3390. if processed is not None:
  3391. text += separator
  3392. separator = ", \n"
  3393. text += "\t" + processed
  3394. if column.primary_key:
  3395. first_pk = True
  3396. except exc.CompileError as ce:
  3397. util.raise_(
  3398. exc.CompileError(
  3399. util.u("(in table '%s', column '%s'): %s")
  3400. % (table.description, column.name, ce.args[0])
  3401. ),
  3402. from_=ce,
  3403. )
  3404. const = self.create_table_constraints(
  3405. table,
  3406. _include_foreign_key_constraints=create.include_foreign_key_constraints, # noqa
  3407. )
  3408. if const:
  3409. text += separator + "\t" + const
  3410. text += "\n)%s\n\n" % self.post_create_table(table)
  3411. return text
  3412. def visit_create_column(self, create, first_pk=False, **kw):
  3413. column = create.element
  3414. if column.system:
  3415. return None
  3416. text = self.get_column_specification(column, first_pk=first_pk)
  3417. const = " ".join(
  3418. self.process(constraint) for constraint in column.constraints
  3419. )
  3420. if const:
  3421. text += " " + const
  3422. return text
  3423. def create_table_constraints(
  3424. self, table, _include_foreign_key_constraints=None, **kw
  3425. ):
  3426. # On some DB order is significant: visit PK first, then the
  3427. # other constraints (engine.ReflectionTest.testbasic failed on FB2)
  3428. constraints = []
  3429. if table.primary_key:
  3430. constraints.append(table.primary_key)
  3431. all_fkcs = table.foreign_key_constraints
  3432. if _include_foreign_key_constraints is not None:
  3433. omit_fkcs = all_fkcs.difference(_include_foreign_key_constraints)
  3434. else:
  3435. omit_fkcs = set()
  3436. constraints.extend(
  3437. [
  3438. c
  3439. for c in table._sorted_constraints
  3440. if c is not table.primary_key and c not in omit_fkcs
  3441. ]
  3442. )
  3443. return ", \n\t".join(
  3444. p
  3445. for p in (
  3446. self.process(constraint)
  3447. for constraint in constraints
  3448. if (
  3449. constraint._create_rule is None
  3450. or constraint._create_rule(self)
  3451. )
  3452. and (
  3453. not self.dialect.supports_alter
  3454. or not getattr(constraint, "use_alter", False)
  3455. )
  3456. )
  3457. if p is not None
  3458. )
  3459. def visit_drop_table(self, drop, **kw):
  3460. text = "\nDROP TABLE "
  3461. if drop.if_exists:
  3462. text += "IF EXISTS "
  3463. return text + self.preparer.format_table(drop.element)
  3464. def visit_drop_view(self, drop, **kw):
  3465. return "\nDROP VIEW " + self.preparer.format_table(drop.element)
  3466. def _verify_index_table(self, index):
  3467. if index.table is None:
  3468. raise exc.CompileError(
  3469. "Index '%s' is not associated " "with any table." % index.name
  3470. )
  3471. def visit_create_index(
  3472. self, create, include_schema=False, include_table_schema=True, **kw
  3473. ):
  3474. index = create.element
  3475. self._verify_index_table(index)
  3476. preparer = self.preparer
  3477. text = "CREATE "
  3478. if index.unique:
  3479. text += "UNIQUE "
  3480. if index.name is None:
  3481. raise exc.CompileError(
  3482. "CREATE INDEX requires that the index have a name"
  3483. )
  3484. text += "INDEX "
  3485. if create.if_not_exists:
  3486. text += "IF NOT EXISTS "
  3487. text += "%s ON %s (%s)" % (
  3488. self._prepared_index_name(index, include_schema=include_schema),
  3489. preparer.format_table(
  3490. index.table, use_schema=include_table_schema
  3491. ),
  3492. ", ".join(
  3493. self.sql_compiler.process(
  3494. expr, include_table=False, literal_binds=True
  3495. )
  3496. for expr in index.expressions
  3497. ),
  3498. )
  3499. return text
  3500. def visit_drop_index(self, drop, **kw):
  3501. index = drop.element
  3502. if index.name is None:
  3503. raise exc.CompileError(
  3504. "DROP INDEX requires that the index have a name"
  3505. )
  3506. text = "\nDROP INDEX "
  3507. if drop.if_exists:
  3508. text += "IF EXISTS "
  3509. return text + self._prepared_index_name(index, include_schema=True)
  3510. def _prepared_index_name(self, index, include_schema=False):
  3511. if index.table is not None:
  3512. effective_schema = self.preparer.schema_for_object(index.table)
  3513. else:
  3514. effective_schema = None
  3515. if include_schema and effective_schema:
  3516. schema_name = self.preparer.quote_schema(effective_schema)
  3517. else:
  3518. schema_name = None
  3519. index_name = self.preparer.format_index(index)
  3520. if schema_name:
  3521. index_name = schema_name + "." + index_name
  3522. return index_name
  3523. def visit_add_constraint(self, create, **kw):
  3524. return "ALTER TABLE %s ADD %s" % (
  3525. self.preparer.format_table(create.element.table),
  3526. self.process(create.element),
  3527. )
  3528. def visit_set_table_comment(self, create, **kw):
  3529. return "COMMENT ON TABLE %s IS %s" % (
  3530. self.preparer.format_table(create.element),
  3531. self.sql_compiler.render_literal_value(
  3532. create.element.comment, sqltypes.String()
  3533. ),
  3534. )
  3535. def visit_drop_table_comment(self, drop, **kw):
  3536. return "COMMENT ON TABLE %s IS NULL" % self.preparer.format_table(
  3537. drop.element
  3538. )
  3539. def visit_set_column_comment(self, create, **kw):
  3540. return "COMMENT ON COLUMN %s IS %s" % (
  3541. self.preparer.format_column(
  3542. create.element, use_table=True, use_schema=True
  3543. ),
  3544. self.sql_compiler.render_literal_value(
  3545. create.element.comment, sqltypes.String()
  3546. ),
  3547. )
  3548. def visit_drop_column_comment(self, drop, **kw):
  3549. return "COMMENT ON COLUMN %s IS NULL" % self.preparer.format_column(
  3550. drop.element, use_table=True
  3551. )
  3552. def get_identity_options(self, identity_options):
  3553. text = []
  3554. if identity_options.increment is not None:
  3555. text.append("INCREMENT BY %d" % identity_options.increment)
  3556. if identity_options.start is not None:
  3557. text.append("START WITH %d" % identity_options.start)
  3558. if identity_options.minvalue is not None:
  3559. text.append("MINVALUE %d" % identity_options.minvalue)
  3560. if identity_options.maxvalue is not None:
  3561. text.append("MAXVALUE %d" % identity_options.maxvalue)
  3562. if identity_options.nominvalue is not None:
  3563. text.append("NO MINVALUE")
  3564. if identity_options.nomaxvalue is not None:
  3565. text.append("NO MAXVALUE")
  3566. if identity_options.cache is not None:
  3567. text.append("CACHE %d" % identity_options.cache)
  3568. if identity_options.order is not None:
  3569. text.append("ORDER" if identity_options.order else "NO ORDER")
  3570. if identity_options.cycle is not None:
  3571. text.append("CYCLE" if identity_options.cycle else "NO CYCLE")
  3572. return " ".join(text)
  3573. def visit_create_sequence(self, create, prefix=None, **kw):
  3574. text = "CREATE SEQUENCE %s" % self.preparer.format_sequence(
  3575. create.element
  3576. )
  3577. if prefix:
  3578. text += prefix
  3579. if create.element.start is None:
  3580. create.element.start = self.dialect.default_sequence_base
  3581. options = self.get_identity_options(create.element)
  3582. if options:
  3583. text += " " + options
  3584. return text
  3585. def visit_drop_sequence(self, drop, **kw):
  3586. return "DROP SEQUENCE %s" % self.preparer.format_sequence(drop.element)
  3587. def visit_drop_constraint(self, drop, **kw):
  3588. constraint = drop.element
  3589. if constraint.name is not None:
  3590. formatted_name = self.preparer.format_constraint(constraint)
  3591. else:
  3592. formatted_name = None
  3593. if formatted_name is None:
  3594. raise exc.CompileError(
  3595. "Can't emit DROP CONSTRAINT for constraint %r; "
  3596. "it has no name" % drop.element
  3597. )
  3598. return "ALTER TABLE %s DROP CONSTRAINT %s%s" % (
  3599. self.preparer.format_table(drop.element.table),
  3600. formatted_name,
  3601. drop.cascade and " CASCADE" or "",
  3602. )
  3603. def get_column_specification(self, column, **kwargs):
  3604. colspec = (
  3605. self.preparer.format_column(column)
  3606. + " "
  3607. + self.dialect.type_compiler.process(
  3608. column.type, type_expression=column
  3609. )
  3610. )
  3611. default = self.get_column_default_string(column)
  3612. if default is not None:
  3613. colspec += " DEFAULT " + default
  3614. if column.computed is not None:
  3615. colspec += " " + self.process(column.computed)
  3616. if (
  3617. column.identity is not None
  3618. and self.dialect.supports_identity_columns
  3619. ):
  3620. colspec += " " + self.process(column.identity)
  3621. if not column.nullable and (
  3622. not column.identity or not self.dialect.supports_identity_columns
  3623. ):
  3624. colspec += " NOT NULL"
  3625. return colspec
  3626. def create_table_suffix(self, table):
  3627. return ""
  3628. def post_create_table(self, table):
  3629. return ""
  3630. def get_column_default_string(self, column):
  3631. if isinstance(column.server_default, schema.DefaultClause):
  3632. if isinstance(column.server_default.arg, util.string_types):
  3633. return self.sql_compiler.render_literal_value(
  3634. column.server_default.arg, sqltypes.STRINGTYPE
  3635. )
  3636. else:
  3637. return self.sql_compiler.process(
  3638. column.server_default.arg, literal_binds=True
  3639. )
  3640. else:
  3641. return None
  3642. def visit_table_or_column_check_constraint(self, constraint, **kw):
  3643. if constraint.is_column_level:
  3644. return self.visit_column_check_constraint(constraint)
  3645. else:
  3646. return self.visit_check_constraint(constraint)
  3647. def visit_check_constraint(self, constraint, **kw):
  3648. text = ""
  3649. if constraint.name is not None:
  3650. formatted_name = self.preparer.format_constraint(constraint)
  3651. if formatted_name is not None:
  3652. text += "CONSTRAINT %s " % formatted_name
  3653. text += "CHECK (%s)" % self.sql_compiler.process(
  3654. constraint.sqltext, include_table=False, literal_binds=True
  3655. )
  3656. text += self.define_constraint_deferrability(constraint)
  3657. return text
  3658. def visit_column_check_constraint(self, constraint, **kw):
  3659. text = ""
  3660. if constraint.name is not None:
  3661. formatted_name = self.preparer.format_constraint(constraint)
  3662. if formatted_name is not None:
  3663. text += "CONSTRAINT %s " % formatted_name
  3664. text += "CHECK (%s)" % self.sql_compiler.process(
  3665. constraint.sqltext, include_table=False, literal_binds=True
  3666. )
  3667. text += self.define_constraint_deferrability(constraint)
  3668. return text
  3669. def visit_primary_key_constraint(self, constraint, **kw):
  3670. if len(constraint) == 0:
  3671. return ""
  3672. text = ""
  3673. if constraint.name is not None:
  3674. formatted_name = self.preparer.format_constraint(constraint)
  3675. if formatted_name is not None:
  3676. text += "CONSTRAINT %s " % formatted_name
  3677. text += "PRIMARY KEY "
  3678. text += "(%s)" % ", ".join(
  3679. self.preparer.quote(c.name)
  3680. for c in (
  3681. constraint.columns_autoinc_first
  3682. if constraint._implicit_generated
  3683. else constraint.columns
  3684. )
  3685. )
  3686. text += self.define_constraint_deferrability(constraint)
  3687. return text
  3688. def visit_foreign_key_constraint(self, constraint, **kw):
  3689. preparer = self.preparer
  3690. text = ""
  3691. if constraint.name is not None:
  3692. formatted_name = self.preparer.format_constraint(constraint)
  3693. if formatted_name is not None:
  3694. text += "CONSTRAINT %s " % formatted_name
  3695. remote_table = list(constraint.elements)[0].column.table
  3696. text += "FOREIGN KEY(%s) REFERENCES %s (%s)" % (
  3697. ", ".join(
  3698. preparer.quote(f.parent.name) for f in constraint.elements
  3699. ),
  3700. self.define_constraint_remote_table(
  3701. constraint, remote_table, preparer
  3702. ),
  3703. ", ".join(
  3704. preparer.quote(f.column.name) for f in constraint.elements
  3705. ),
  3706. )
  3707. text += self.define_constraint_match(constraint)
  3708. text += self.define_constraint_cascades(constraint)
  3709. text += self.define_constraint_deferrability(constraint)
  3710. return text
  3711. def define_constraint_remote_table(self, constraint, table, preparer):
  3712. """Format the remote table clause of a CREATE CONSTRAINT clause."""
  3713. return preparer.format_table(table)
  3714. def visit_unique_constraint(self, constraint, **kw):
  3715. if len(constraint) == 0:
  3716. return ""
  3717. text = ""
  3718. if constraint.name is not None:
  3719. formatted_name = self.preparer.format_constraint(constraint)
  3720. if formatted_name is not None:
  3721. text += "CONSTRAINT %s " % formatted_name
  3722. text += "UNIQUE (%s)" % (
  3723. ", ".join(self.preparer.quote(c.name) for c in constraint)
  3724. )
  3725. text += self.define_constraint_deferrability(constraint)
  3726. return text
  3727. def define_constraint_cascades(self, constraint):
  3728. text = ""
  3729. if constraint.ondelete is not None:
  3730. text += " ON DELETE %s" % self.preparer.validate_sql_phrase(
  3731. constraint.ondelete, FK_ON_DELETE
  3732. )
  3733. if constraint.onupdate is not None:
  3734. text += " ON UPDATE %s" % self.preparer.validate_sql_phrase(
  3735. constraint.onupdate, FK_ON_UPDATE
  3736. )
  3737. return text
  3738. def define_constraint_deferrability(self, constraint):
  3739. text = ""
  3740. if constraint.deferrable is not None:
  3741. if constraint.deferrable:
  3742. text += " DEFERRABLE"
  3743. else:
  3744. text += " NOT DEFERRABLE"
  3745. if constraint.initially is not None:
  3746. text += " INITIALLY %s" % self.preparer.validate_sql_phrase(
  3747. constraint.initially, FK_INITIALLY
  3748. )
  3749. return text
  3750. def define_constraint_match(self, constraint):
  3751. text = ""
  3752. if constraint.match is not None:
  3753. text += " MATCH %s" % constraint.match
  3754. return text
  3755. def visit_computed_column(self, generated, **kw):
  3756. text = "GENERATED ALWAYS AS (%s)" % self.sql_compiler.process(
  3757. generated.sqltext, include_table=False, literal_binds=True
  3758. )
  3759. if generated.persisted is True:
  3760. text += " STORED"
  3761. elif generated.persisted is False:
  3762. text += " VIRTUAL"
  3763. return text
  3764. def visit_identity_column(self, identity, **kw):
  3765. text = "GENERATED %s AS IDENTITY" % (
  3766. "ALWAYS" if identity.always else "BY DEFAULT",
  3767. )
  3768. options = self.get_identity_options(identity)
  3769. if options:
  3770. text += " (%s)" % options
  3771. return text
  3772. class GenericTypeCompiler(TypeCompiler):
  3773. def visit_FLOAT(self, type_, **kw):
  3774. return "FLOAT"
  3775. def visit_REAL(self, type_, **kw):
  3776. return "REAL"
  3777. def visit_NUMERIC(self, type_, **kw):
  3778. if type_.precision is None:
  3779. return "NUMERIC"
  3780. elif type_.scale is None:
  3781. return "NUMERIC(%(precision)s)" % {"precision": type_.precision}
  3782. else:
  3783. return "NUMERIC(%(precision)s, %(scale)s)" % {
  3784. "precision": type_.precision,
  3785. "scale": type_.scale,
  3786. }
  3787. def visit_DECIMAL(self, type_, **kw):
  3788. if type_.precision is None:
  3789. return "DECIMAL"
  3790. elif type_.scale is None:
  3791. return "DECIMAL(%(precision)s)" % {"precision": type_.precision}
  3792. else:
  3793. return "DECIMAL(%(precision)s, %(scale)s)" % {
  3794. "precision": type_.precision,
  3795. "scale": type_.scale,
  3796. }
  3797. def visit_INTEGER(self, type_, **kw):
  3798. return "INTEGER"
  3799. def visit_SMALLINT(self, type_, **kw):
  3800. return "SMALLINT"
  3801. def visit_BIGINT(self, type_, **kw):
  3802. return "BIGINT"
  3803. def visit_TIMESTAMP(self, type_, **kw):
  3804. return "TIMESTAMP"
  3805. def visit_DATETIME(self, type_, **kw):
  3806. return "DATETIME"
  3807. def visit_DATE(self, type_, **kw):
  3808. return "DATE"
  3809. def visit_TIME(self, type_, **kw):
  3810. return "TIME"
  3811. def visit_CLOB(self, type_, **kw):
  3812. return "CLOB"
  3813. def visit_NCLOB(self, type_, **kw):
  3814. return "NCLOB"
  3815. def _render_string_type(self, type_, name):
  3816. text = name
  3817. if type_.length:
  3818. text += "(%d)" % type_.length
  3819. if type_.collation:
  3820. text += ' COLLATE "%s"' % type_.collation
  3821. return text
  3822. def visit_CHAR(self, type_, **kw):
  3823. return self._render_string_type(type_, "CHAR")
  3824. def visit_NCHAR(self, type_, **kw):
  3825. return self._render_string_type(type_, "NCHAR")
  3826. def visit_VARCHAR(self, type_, **kw):
  3827. return self._render_string_type(type_, "VARCHAR")
  3828. def visit_NVARCHAR(self, type_, **kw):
  3829. return self._render_string_type(type_, "NVARCHAR")
  3830. def visit_TEXT(self, type_, **kw):
  3831. return self._render_string_type(type_, "TEXT")
  3832. def visit_BLOB(self, type_, **kw):
  3833. return "BLOB"
  3834. def visit_BINARY(self, type_, **kw):
  3835. return "BINARY" + (type_.length and "(%d)" % type_.length or "")
  3836. def visit_VARBINARY(self, type_, **kw):
  3837. return "VARBINARY" + (type_.length and "(%d)" % type_.length or "")
  3838. def visit_BOOLEAN(self, type_, **kw):
  3839. return "BOOLEAN"
  3840. def visit_large_binary(self, type_, **kw):
  3841. return self.visit_BLOB(type_, **kw)
  3842. def visit_boolean(self, type_, **kw):
  3843. return self.visit_BOOLEAN(type_, **kw)
  3844. def visit_time(self, type_, **kw):
  3845. return self.visit_TIME(type_, **kw)
  3846. def visit_datetime(self, type_, **kw):
  3847. return self.visit_DATETIME(type_, **kw)
  3848. def visit_date(self, type_, **kw):
  3849. return self.visit_DATE(type_, **kw)
  3850. def visit_big_integer(self, type_, **kw):
  3851. return self.visit_BIGINT(type_, **kw)
  3852. def visit_small_integer(self, type_, **kw):
  3853. return self.visit_SMALLINT(type_, **kw)
  3854. def visit_integer(self, type_, **kw):
  3855. return self.visit_INTEGER(type_, **kw)
  3856. def visit_real(self, type_, **kw):
  3857. return self.visit_REAL(type_, **kw)
  3858. def visit_float(self, type_, **kw):
  3859. return self.visit_FLOAT(type_, **kw)
  3860. def visit_numeric(self, type_, **kw):
  3861. return self.visit_NUMERIC(type_, **kw)
  3862. def visit_string(self, type_, **kw):
  3863. return self.visit_VARCHAR(type_, **kw)
  3864. def visit_unicode(self, type_, **kw):
  3865. return self.visit_VARCHAR(type_, **kw)
  3866. def visit_text(self, type_, **kw):
  3867. return self.visit_TEXT(type_, **kw)
  3868. def visit_unicode_text(self, type_, **kw):
  3869. return self.visit_TEXT(type_, **kw)
  3870. def visit_enum(self, type_, **kw):
  3871. return self.visit_VARCHAR(type_, **kw)
  3872. def visit_null(self, type_, **kw):
  3873. raise exc.CompileError(
  3874. "Can't generate DDL for %r; "
  3875. "did you forget to specify a "
  3876. "type on this Column?" % type_
  3877. )
  3878. def visit_type_decorator(self, type_, **kw):
  3879. return self.process(type_.type_engine(self.dialect), **kw)
  3880. def visit_user_defined(self, type_, **kw):
  3881. return type_.get_col_spec(**kw)
  3882. class StrSQLTypeCompiler(GenericTypeCompiler):
  3883. def process(self, type_, **kw):
  3884. try:
  3885. _compiler_dispatch = type_._compiler_dispatch
  3886. except AttributeError:
  3887. return self._visit_unknown(type_, **kw)
  3888. else:
  3889. return _compiler_dispatch(self, **kw)
  3890. def __getattr__(self, key):
  3891. if key.startswith("visit_"):
  3892. return self._visit_unknown
  3893. else:
  3894. raise AttributeError(key)
  3895. def _visit_unknown(self, type_, **kw):
  3896. if type_.__class__.__name__ == type_.__class__.__name__.upper():
  3897. return type_.__class__.__name__
  3898. else:
  3899. return repr(type_)
  3900. def visit_null(self, type_, **kw):
  3901. return "NULL"
  3902. def visit_user_defined(self, type_, **kw):
  3903. try:
  3904. get_col_spec = type_.get_col_spec
  3905. except AttributeError:
  3906. return repr(type_)
  3907. else:
  3908. return get_col_spec(**kw)
  3909. class IdentifierPreparer(object):
  3910. """Handle quoting and case-folding of identifiers based on options."""
  3911. reserved_words = RESERVED_WORDS
  3912. legal_characters = LEGAL_CHARACTERS
  3913. illegal_initial_characters = ILLEGAL_INITIAL_CHARACTERS
  3914. schema_for_object = operator.attrgetter("schema")
  3915. """Return the .schema attribute for an object.
  3916. For the default IdentifierPreparer, the schema for an object is always
  3917. the value of the ".schema" attribute. if the preparer is replaced
  3918. with one that has a non-empty schema_translate_map, the value of the
  3919. ".schema" attribute is rendered a symbol that will be converted to a
  3920. real schema name from the mapping post-compile.
  3921. """
  3922. def __init__(
  3923. self,
  3924. dialect,
  3925. initial_quote='"',
  3926. final_quote=None,
  3927. escape_quote='"',
  3928. quote_case_sensitive_collations=True,
  3929. omit_schema=False,
  3930. ):
  3931. """Construct a new ``IdentifierPreparer`` object.
  3932. initial_quote
  3933. Character that begins a delimited identifier.
  3934. final_quote
  3935. Character that ends a delimited identifier. Defaults to
  3936. `initial_quote`.
  3937. omit_schema
  3938. Prevent prepending schema name. Useful for databases that do
  3939. not support schemae.
  3940. """
  3941. self.dialect = dialect
  3942. self.initial_quote = initial_quote
  3943. self.final_quote = final_quote or self.initial_quote
  3944. self.escape_quote = escape_quote
  3945. self.escape_to_quote = self.escape_quote * 2
  3946. self.omit_schema = omit_schema
  3947. self.quote_case_sensitive_collations = quote_case_sensitive_collations
  3948. self._strings = {}
  3949. self._double_percents = self.dialect.paramstyle in (
  3950. "format",
  3951. "pyformat",
  3952. )
  3953. def _with_schema_translate(self, schema_translate_map):
  3954. prep = self.__class__.__new__(self.__class__)
  3955. prep.__dict__.update(self.__dict__)
  3956. def symbol_getter(obj):
  3957. name = obj.schema
  3958. if name in schema_translate_map and obj._use_schema_map:
  3959. if name is not None and ("[" in name or "]" in name):
  3960. raise exc.CompileError(
  3961. "Square bracket characters ([]) not supported "
  3962. "in schema translate name '%s'" % name
  3963. )
  3964. return quoted_name(
  3965. "[SCHEMA_%s]" % (name or "_none"), quote=False
  3966. )
  3967. else:
  3968. return obj.schema
  3969. prep.schema_for_object = symbol_getter
  3970. return prep
  3971. def _render_schema_translates(self, statement, schema_translate_map):
  3972. d = schema_translate_map
  3973. if None in d:
  3974. d["_none"] = d[None]
  3975. def replace(m):
  3976. name = m.group(2)
  3977. effective_schema = d[name]
  3978. if not effective_schema:
  3979. effective_schema = self.dialect.default_schema_name
  3980. if not effective_schema:
  3981. # TODO: no coverage here
  3982. raise exc.CompileError(
  3983. "Dialect has no default schema name; can't "
  3984. "use None as dynamic schema target."
  3985. )
  3986. return self.quote(effective_schema)
  3987. return re.sub(r"(\[SCHEMA_([^\]]+)\])", replace, statement)
  3988. def _escape_identifier(self, value):
  3989. """Escape an identifier.
  3990. Subclasses should override this to provide database-dependent
  3991. escaping behavior.
  3992. """
  3993. value = value.replace(self.escape_quote, self.escape_to_quote)
  3994. if self._double_percents:
  3995. value = value.replace("%", "%%")
  3996. return value
  3997. def _unescape_identifier(self, value):
  3998. """Canonicalize an escaped identifier.
  3999. Subclasses should override this to provide database-dependent
  4000. unescaping behavior that reverses _escape_identifier.
  4001. """
  4002. return value.replace(self.escape_to_quote, self.escape_quote)
  4003. def validate_sql_phrase(self, element, reg):
  4004. """keyword sequence filter.
  4005. a filter for elements that are intended to represent keyword sequences,
  4006. such as "INITIALLY", "INITIALLY DEFERRED", etc. no special characters
  4007. should be present.
  4008. .. versionadded:: 1.3
  4009. """
  4010. if element is not None and not reg.match(element):
  4011. raise exc.CompileError(
  4012. "Unexpected SQL phrase: %r (matching against %r)"
  4013. % (element, reg.pattern)
  4014. )
  4015. return element
  4016. def quote_identifier(self, value):
  4017. """Quote an identifier.
  4018. Subclasses should override this to provide database-dependent
  4019. quoting behavior.
  4020. """
  4021. return (
  4022. self.initial_quote
  4023. + self._escape_identifier(value)
  4024. + self.final_quote
  4025. )
  4026. def _requires_quotes(self, value):
  4027. """Return True if the given identifier requires quoting."""
  4028. lc_value = value.lower()
  4029. return (
  4030. lc_value in self.reserved_words
  4031. or value[0] in self.illegal_initial_characters
  4032. or not self.legal_characters.match(util.text_type(value))
  4033. or (lc_value != value)
  4034. )
  4035. def _requires_quotes_illegal_chars(self, value):
  4036. """Return True if the given identifier requires quoting, but
  4037. not taking case convention into account."""
  4038. return not self.legal_characters.match(util.text_type(value))
  4039. def quote_schema(self, schema, force=None):
  4040. """Conditionally quote a schema name.
  4041. The name is quoted if it is a reserved word, contains quote-necessary
  4042. characters, or is an instance of :class:`.quoted_name` which includes
  4043. ``quote`` set to ``True``.
  4044. Subclasses can override this to provide database-dependent
  4045. quoting behavior for schema names.
  4046. :param schema: string schema name
  4047. :param force: unused
  4048. .. deprecated:: 0.9
  4049. The :paramref:`.IdentifierPreparer.quote_schema.force`
  4050. parameter is deprecated and will be removed in a future
  4051. release. This flag has no effect on the behavior of the
  4052. :meth:`.IdentifierPreparer.quote` method; please refer to
  4053. :class:`.quoted_name`.
  4054. """
  4055. if force is not None:
  4056. # not using the util.deprecated_params() decorator in this
  4057. # case because of the additional function call overhead on this
  4058. # very performance-critical spot.
  4059. util.warn_deprecated(
  4060. "The IdentifierPreparer.quote_schema.force parameter is "
  4061. "deprecated and will be removed in a future release. This "
  4062. "flag has no effect on the behavior of the "
  4063. "IdentifierPreparer.quote method; please refer to "
  4064. "quoted_name().",
  4065. # deprecated 0.9. warning from 1.3
  4066. version="0.9",
  4067. )
  4068. return self.quote(schema)
  4069. def quote(self, ident, force=None):
  4070. """Conditionally quote an identifier.
  4071. The identifier is quoted if it is a reserved word, contains
  4072. quote-necessary characters, or is an instance of
  4073. :class:`.quoted_name` which includes ``quote`` set to ``True``.
  4074. Subclasses can override this to provide database-dependent
  4075. quoting behavior for identifier names.
  4076. :param ident: string identifier
  4077. :param force: unused
  4078. .. deprecated:: 0.9
  4079. The :paramref:`.IdentifierPreparer.quote.force`
  4080. parameter is deprecated and will be removed in a future
  4081. release. This flag has no effect on the behavior of the
  4082. :meth:`.IdentifierPreparer.quote` method; please refer to
  4083. :class:`.quoted_name`.
  4084. """
  4085. if force is not None:
  4086. # not using the util.deprecated_params() decorator in this
  4087. # case because of the additional function call overhead on this
  4088. # very performance-critical spot.
  4089. util.warn_deprecated(
  4090. "The IdentifierPreparer.quote.force parameter is "
  4091. "deprecated and will be removed in a future release. This "
  4092. "flag has no effect on the behavior of the "
  4093. "IdentifierPreparer.quote method; please refer to "
  4094. "quoted_name().",
  4095. # deprecated 0.9. warning from 1.3
  4096. version="0.9",
  4097. )
  4098. force = getattr(ident, "quote", None)
  4099. if force is None:
  4100. if ident in self._strings:
  4101. return self._strings[ident]
  4102. else:
  4103. if self._requires_quotes(ident):
  4104. self._strings[ident] = self.quote_identifier(ident)
  4105. else:
  4106. self._strings[ident] = ident
  4107. return self._strings[ident]
  4108. elif force:
  4109. return self.quote_identifier(ident)
  4110. else:
  4111. return ident
  4112. def format_collation(self, collation_name):
  4113. if self.quote_case_sensitive_collations:
  4114. return self.quote(collation_name)
  4115. else:
  4116. return collation_name
  4117. def format_sequence(self, sequence, use_schema=True):
  4118. name = self.quote(sequence.name)
  4119. effective_schema = self.schema_for_object(sequence)
  4120. if (
  4121. not self.omit_schema
  4122. and use_schema
  4123. and effective_schema is not None
  4124. ):
  4125. name = self.quote_schema(effective_schema) + "." + name
  4126. return name
  4127. def format_label(self, label, name=None):
  4128. return self.quote(name or label.name)
  4129. def format_alias(self, alias, name=None):
  4130. return self.quote(name or alias.name)
  4131. def format_savepoint(self, savepoint, name=None):
  4132. # Running the savepoint name through quoting is unnecessary
  4133. # for all known dialects. This is here to support potential
  4134. # third party use cases
  4135. ident = name or savepoint.ident
  4136. if self._requires_quotes(ident):
  4137. ident = self.quote_identifier(ident)
  4138. return ident
  4139. @util.preload_module("sqlalchemy.sql.naming")
  4140. def format_constraint(self, constraint, _alembic_quote=True):
  4141. naming = util.preloaded.sql_naming
  4142. if constraint.name is elements._NONE_NAME:
  4143. name = naming._constraint_name_for_table(
  4144. constraint, constraint.table
  4145. )
  4146. if name is None:
  4147. return None
  4148. else:
  4149. name = constraint.name
  4150. if isinstance(name, elements._truncated_label):
  4151. # calculate these at format time so that ad-hoc changes
  4152. # to dialect.max_identifier_length etc. can be reflected
  4153. # as IdentifierPreparer is long lived
  4154. if constraint.__visit_name__ == "index":
  4155. max_ = (
  4156. self.dialect.max_index_name_length
  4157. or self.dialect.max_identifier_length
  4158. )
  4159. else:
  4160. max_ = (
  4161. self.dialect.max_constraint_name_length
  4162. or self.dialect.max_identifier_length
  4163. )
  4164. if len(name) > max_:
  4165. name = name[0 : max_ - 8] + "_" + util.md5_hex(name)[-4:]
  4166. else:
  4167. self.dialect.validate_identifier(name)
  4168. if not _alembic_quote:
  4169. return name
  4170. else:
  4171. return self.quote(name)
  4172. def format_index(self, index):
  4173. return self.format_constraint(index)
  4174. def format_table(self, table, use_schema=True, name=None):
  4175. """Prepare a quoted table and schema name."""
  4176. if name is None:
  4177. name = table.name
  4178. result = self.quote(name)
  4179. effective_schema = self.schema_for_object(table)
  4180. if not self.omit_schema and use_schema and effective_schema:
  4181. result = self.quote_schema(effective_schema) + "." + result
  4182. return result
  4183. def format_schema(self, name):
  4184. """Prepare a quoted schema name."""
  4185. return self.quote(name)
  4186. def format_column(
  4187. self,
  4188. column,
  4189. use_table=False,
  4190. name=None,
  4191. table_name=None,
  4192. use_schema=False,
  4193. anon_map=None,
  4194. ):
  4195. """Prepare a quoted column name."""
  4196. if name is None:
  4197. name = column.name
  4198. if anon_map is not None and isinstance(
  4199. name, elements._truncated_label
  4200. ):
  4201. name = name.apply_map(anon_map)
  4202. if not getattr(column, "is_literal", False):
  4203. if use_table:
  4204. return (
  4205. self.format_table(
  4206. column.table, use_schema=use_schema, name=table_name
  4207. )
  4208. + "."
  4209. + self.quote(name)
  4210. )
  4211. else:
  4212. return self.quote(name)
  4213. else:
  4214. # literal textual elements get stuck into ColumnClause a lot,
  4215. # which shouldn't get quoted
  4216. if use_table:
  4217. return (
  4218. self.format_table(
  4219. column.table, use_schema=use_schema, name=table_name
  4220. )
  4221. + "."
  4222. + name
  4223. )
  4224. else:
  4225. return name
  4226. def format_table_seq(self, table, use_schema=True):
  4227. """Format table name and schema as a tuple."""
  4228. # Dialects with more levels in their fully qualified references
  4229. # ('database', 'owner', etc.) could override this and return
  4230. # a longer sequence.
  4231. effective_schema = self.schema_for_object(table)
  4232. if not self.omit_schema and use_schema and effective_schema:
  4233. return (
  4234. self.quote_schema(effective_schema),
  4235. self.format_table(table, use_schema=False),
  4236. )
  4237. else:
  4238. return (self.format_table(table, use_schema=False),)
  4239. @util.memoized_property
  4240. def _r_identifiers(self):
  4241. initial, final, escaped_final = [
  4242. re.escape(s)
  4243. for s in (
  4244. self.initial_quote,
  4245. self.final_quote,
  4246. self._escape_identifier(self.final_quote),
  4247. )
  4248. ]
  4249. r = re.compile(
  4250. r"(?:"
  4251. r"(?:%(initial)s((?:%(escaped)s|[^%(final)s])+)%(final)s"
  4252. r"|([^\.]+))(?=\.|$))+"
  4253. % {"initial": initial, "final": final, "escaped": escaped_final}
  4254. )
  4255. return r
  4256. def unformat_identifiers(self, identifiers):
  4257. """Unpack 'schema.table.column'-like strings into components."""
  4258. r = self._r_identifiers
  4259. return [
  4260. self._unescape_identifier(i)
  4261. for i in [a or b for a, b in r.findall(identifiers)]
  4262. ]