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.

5119 lines
167KB

  1. # sql/elements.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. """Core SQL expression elements, including :class:`_expression.ClauseElement`,
  8. :class:`_expression.ColumnElement`, and derived classes.
  9. """
  10. from __future__ import unicode_literals
  11. import itertools
  12. import operator
  13. import re
  14. from . import coercions
  15. from . import operators
  16. from . import roles
  17. from . import traversals
  18. from . import type_api
  19. from .annotation import Annotated
  20. from .annotation import SupportsWrappingAnnotations
  21. from .base import _clone
  22. from .base import _generative
  23. from .base import Executable
  24. from .base import HasMemoized
  25. from .base import Immutable
  26. from .base import NO_ARG
  27. from .base import PARSE_AUTOCOMMIT
  28. from .base import SingletonConstant
  29. from .coercions import _document_text_coercion
  30. from .traversals import HasCopyInternals
  31. from .traversals import MemoizedHasCacheKey
  32. from .traversals import NO_CACHE
  33. from .visitors import cloned_traverse
  34. from .visitors import InternalTraversal
  35. from .visitors import traverse
  36. from .visitors import Traversible
  37. from .. import exc
  38. from .. import inspection
  39. from .. import util
  40. def collate(expression, collation):
  41. """Return the clause ``expression COLLATE collation``.
  42. e.g.::
  43. collate(mycolumn, 'utf8_bin')
  44. produces::
  45. mycolumn COLLATE utf8_bin
  46. The collation expression is also quoted if it is a case sensitive
  47. identifier, e.g. contains uppercase characters.
  48. .. versionchanged:: 1.2 quoting is automatically applied to COLLATE
  49. expressions if they are case sensitive.
  50. """
  51. expr = coercions.expect(roles.ExpressionElementRole, expression)
  52. return BinaryExpression(
  53. expr, CollationClause(collation), operators.collate, type_=expr.type
  54. )
  55. def between(expr, lower_bound, upper_bound, symmetric=False):
  56. """Produce a ``BETWEEN`` predicate clause.
  57. E.g.::
  58. from sqlalchemy import between
  59. stmt = select(users_table).where(between(users_table.c.id, 5, 7))
  60. Would produce SQL resembling::
  61. SELECT id, name FROM user WHERE id BETWEEN :id_1 AND :id_2
  62. The :func:`.between` function is a standalone version of the
  63. :meth:`_expression.ColumnElement.between` method available on all
  64. SQL expressions, as in::
  65. stmt = select(users_table).where(users_table.c.id.between(5, 7))
  66. All arguments passed to :func:`.between`, including the left side
  67. column expression, are coerced from Python scalar values if a
  68. the value is not a :class:`_expression.ColumnElement` subclass.
  69. For example,
  70. three fixed values can be compared as in::
  71. print(between(5, 3, 7))
  72. Which would produce::
  73. :param_1 BETWEEN :param_2 AND :param_3
  74. :param expr: a column expression, typically a
  75. :class:`_expression.ColumnElement`
  76. instance or alternatively a Python scalar expression to be coerced
  77. into a column expression, serving as the left side of the ``BETWEEN``
  78. expression.
  79. :param lower_bound: a column or Python scalar expression serving as the
  80. lower bound of the right side of the ``BETWEEN`` expression.
  81. :param upper_bound: a column or Python scalar expression serving as the
  82. upper bound of the right side of the ``BETWEEN`` expression.
  83. :param symmetric: if True, will render " BETWEEN SYMMETRIC ". Note
  84. that not all databases support this syntax.
  85. .. versionadded:: 0.9.5
  86. .. seealso::
  87. :meth:`_expression.ColumnElement.between`
  88. """
  89. expr = coercions.expect(roles.ExpressionElementRole, expr)
  90. return expr.between(lower_bound, upper_bound, symmetric=symmetric)
  91. def literal(value, type_=None):
  92. r"""Return a literal clause, bound to a bind parameter.
  93. Literal clauses are created automatically when non-
  94. :class:`_expression.ClauseElement` objects (such as strings, ints, dates,
  95. etc.) are
  96. used in a comparison operation with a :class:`_expression.ColumnElement`
  97. subclass,
  98. such as a :class:`~sqlalchemy.schema.Column` object. Use this function
  99. to force the generation of a literal clause, which will be created as a
  100. :class:`BindParameter` with a bound value.
  101. :param value: the value to be bound. Can be any Python object supported by
  102. the underlying DB-API, or is translatable via the given type argument.
  103. :param type\_: an optional :class:`~sqlalchemy.types.TypeEngine` which
  104. will provide bind-parameter translation for this literal.
  105. """
  106. return coercions.expect(roles.LiteralValueRole, value, type_=type_)
  107. def outparam(key, type_=None):
  108. """Create an 'OUT' parameter for usage in functions (stored procedures),
  109. for databases which support them.
  110. The ``outparam`` can be used like a regular function parameter.
  111. The "output" value will be available from the
  112. :class:`~sqlalchemy.engine.CursorResult` object via its ``out_parameters``
  113. attribute, which returns a dictionary containing the values.
  114. """
  115. return BindParameter(key, None, type_=type_, unique=False, isoutparam=True)
  116. def not_(clause):
  117. """Return a negation of the given clause, i.e. ``NOT(clause)``.
  118. The ``~`` operator is also overloaded on all
  119. :class:`_expression.ColumnElement` subclasses to produce the
  120. same result.
  121. """
  122. return operators.inv(coercions.expect(roles.ExpressionElementRole, clause))
  123. @inspection._self_inspects
  124. class ClauseElement(
  125. roles.SQLRole,
  126. SupportsWrappingAnnotations,
  127. MemoizedHasCacheKey,
  128. HasCopyInternals,
  129. Traversible,
  130. ):
  131. """Base class for elements of a programmatically constructed SQL
  132. expression.
  133. """
  134. __visit_name__ = "clause"
  135. _propagate_attrs = util.immutabledict()
  136. """like annotations, however these propagate outwards liberally
  137. as SQL constructs are built, and are set up at construction time.
  138. """
  139. supports_execution = False
  140. stringify_dialect = "default"
  141. _from_objects = []
  142. bind = None
  143. description = None
  144. _is_clone_of = None
  145. is_clause_element = True
  146. is_selectable = False
  147. _is_textual = False
  148. _is_from_clause = False
  149. _is_returns_rows = False
  150. _is_text_clause = False
  151. _is_from_container = False
  152. _is_select_container = False
  153. _is_select_statement = False
  154. _is_bind_parameter = False
  155. _is_clause_list = False
  156. _is_lambda_element = False
  157. _order_by_label_element = None
  158. _cache_key_traversal = None
  159. def _set_propagate_attrs(self, values):
  160. # usually, self._propagate_attrs is empty here. one case where it's
  161. # not is a subquery against ORM select, that is then pulled as a
  162. # property of an aliased class. should all be good
  163. # assert not self._propagate_attrs
  164. self._propagate_attrs = util.immutabledict(values)
  165. return self
  166. def _clone(self, **kw):
  167. """Create a shallow copy of this ClauseElement.
  168. This method may be used by a generative API. Its also used as
  169. part of the "deep" copy afforded by a traversal that combines
  170. the _copy_internals() method.
  171. """
  172. skip = self._memoized_keys
  173. c = self.__class__.__new__(self.__class__)
  174. c.__dict__ = {k: v for k, v in self.__dict__.items() if k not in skip}
  175. # this is a marker that helps to "equate" clauses to each other
  176. # when a Select returns its list of FROM clauses. the cloning
  177. # process leaves around a lot of remnants of the previous clause
  178. # typically in the form of column expressions still attached to the
  179. # old table.
  180. c._is_clone_of = self
  181. return c
  182. def _negate_in_binary(self, negated_op, original_op):
  183. """a hook to allow the right side of a binary expression to respond
  184. to a negation of the binary expression.
  185. Used for the special case of expanding bind parameter with IN.
  186. """
  187. return self
  188. def _with_binary_element_type(self, type_):
  189. """in the context of binary expression, convert the type of this
  190. object to the one given.
  191. applies only to :class:`_expression.ColumnElement` classes.
  192. """
  193. return self
  194. @property
  195. def _constructor(self):
  196. """return the 'constructor' for this ClauseElement.
  197. This is for the purposes for creating a new object of
  198. this type. Usually, its just the element's __class__.
  199. However, the "Annotated" version of the object overrides
  200. to return the class of its proxied element.
  201. """
  202. return self.__class__
  203. @HasMemoized.memoized_attribute
  204. def _cloned_set(self):
  205. """Return the set consisting all cloned ancestors of this
  206. ClauseElement.
  207. Includes this ClauseElement. This accessor tends to be used for
  208. FromClause objects to identify 'equivalent' FROM clauses, regardless
  209. of transformative operations.
  210. """
  211. s = util.column_set()
  212. f = self
  213. # note this creates a cycle, asserted in test_memusage. however,
  214. # turning this into a plain @property adds tends of thousands of method
  215. # calls to Core / ORM performance tests, so the small overhead
  216. # introduced by the relatively small amount of short term cycles
  217. # produced here is preferable
  218. while f is not None:
  219. s.add(f)
  220. f = f._is_clone_of
  221. return s
  222. @property
  223. def entity_namespace(self):
  224. raise AttributeError(
  225. "This SQL expression has no entity namespace "
  226. "with which to filter from."
  227. )
  228. def __getstate__(self):
  229. d = self.__dict__.copy()
  230. d.pop("_is_clone_of", None)
  231. d.pop("_generate_cache_key", None)
  232. return d
  233. def _execute_on_connection(
  234. self, connection, multiparams, params, execution_options, _force=False
  235. ):
  236. if _force or self.supports_execution:
  237. return connection._execute_clauseelement(
  238. self, multiparams, params, execution_options
  239. )
  240. else:
  241. raise exc.ObjectNotExecutableError(self)
  242. def unique_params(self, *optionaldict, **kwargs):
  243. """Return a copy with :func:`_expression.bindparam` elements
  244. replaced.
  245. Same functionality as :meth:`_expression.ClauseElement.params`,
  246. except adds `unique=True`
  247. to affected bind parameters so that multiple statements can be
  248. used.
  249. """
  250. return self._replace_params(True, optionaldict, kwargs)
  251. def params(self, *optionaldict, **kwargs):
  252. """Return a copy with :func:`_expression.bindparam` elements
  253. replaced.
  254. Returns a copy of this ClauseElement with
  255. :func:`_expression.bindparam`
  256. elements replaced with values taken from the given dictionary::
  257. >>> clause = column('x') + bindparam('foo')
  258. >>> print(clause.compile().params)
  259. {'foo':None}
  260. >>> print(clause.params({'foo':7}).compile().params)
  261. {'foo':7}
  262. """
  263. return self._replace_params(False, optionaldict, kwargs)
  264. def _replace_params(self, unique, optionaldict, kwargs):
  265. if len(optionaldict) == 1:
  266. kwargs.update(optionaldict[0])
  267. elif len(optionaldict) > 1:
  268. raise exc.ArgumentError(
  269. "params() takes zero or one positional dictionary argument"
  270. )
  271. def visit_bindparam(bind):
  272. if bind.key in kwargs:
  273. bind.value = kwargs[bind.key]
  274. bind.required = False
  275. if unique:
  276. bind._convert_to_unique()
  277. return cloned_traverse(
  278. self, {"maintain_key": True}, {"bindparam": visit_bindparam}
  279. )
  280. def compare(self, other, **kw):
  281. r"""Compare this :class:`_expression.ClauseElement` to
  282. the given :class:`_expression.ClauseElement`.
  283. Subclasses should override the default behavior, which is a
  284. straight identity comparison.
  285. \**kw are arguments consumed by subclass ``compare()`` methods and
  286. may be used to modify the criteria for comparison
  287. (see :class:`_expression.ColumnElement`).
  288. """
  289. return traversals.compare(self, other, **kw)
  290. def self_group(self, against=None):
  291. """Apply a 'grouping' to this :class:`_expression.ClauseElement`.
  292. This method is overridden by subclasses to return a "grouping"
  293. construct, i.e. parenthesis. In particular it's used by "binary"
  294. expressions to provide a grouping around themselves when placed into a
  295. larger expression, as well as by :func:`_expression.select`
  296. constructs when placed into the FROM clause of another
  297. :func:`_expression.select`. (Note that subqueries should be
  298. normally created using the :meth:`_expression.Select.alias` method,
  299. as many
  300. platforms require nested SELECT statements to be named).
  301. As expressions are composed together, the application of
  302. :meth:`self_group` is automatic - end-user code should never
  303. need to use this method directly. Note that SQLAlchemy's
  304. clause constructs take operator precedence into account -
  305. so parenthesis might not be needed, for example, in
  306. an expression like ``x OR (y AND z)`` - AND takes precedence
  307. over OR.
  308. The base :meth:`self_group` method of
  309. :class:`_expression.ClauseElement`
  310. just returns self.
  311. """
  312. return self
  313. def _ungroup(self):
  314. """Return this :class:`_expression.ClauseElement`
  315. without any groupings.
  316. """
  317. return self
  318. @util.preload_module("sqlalchemy.engine.default")
  319. @util.preload_module("sqlalchemy.engine.url")
  320. def compile(self, bind=None, dialect=None, **kw):
  321. """Compile this SQL expression.
  322. The return value is a :class:`~.Compiled` object.
  323. Calling ``str()`` or ``unicode()`` on the returned value will yield a
  324. string representation of the result. The
  325. :class:`~.Compiled` object also can return a
  326. dictionary of bind parameter names and values
  327. using the ``params`` accessor.
  328. :param bind: An ``Engine`` or ``Connection`` from which a
  329. ``Compiled`` will be acquired. This argument takes precedence over
  330. this :class:`_expression.ClauseElement`'s bound engine, if any.
  331. :param column_keys: Used for INSERT and UPDATE statements, a list of
  332. column names which should be present in the VALUES clause of the
  333. compiled statement. If ``None``, all columns from the target table
  334. object are rendered.
  335. :param dialect: A ``Dialect`` instance from which a ``Compiled``
  336. will be acquired. This argument takes precedence over the `bind`
  337. argument as well as this :class:`_expression.ClauseElement`
  338. 's bound engine,
  339. if any.
  340. :param compile_kwargs: optional dictionary of additional parameters
  341. that will be passed through to the compiler within all "visit"
  342. methods. This allows any custom flag to be passed through to
  343. a custom compilation construct, for example. It is also used
  344. for the case of passing the ``literal_binds`` flag through::
  345. from sqlalchemy.sql import table, column, select
  346. t = table('t', column('x'))
  347. s = select(t).where(t.c.x == 5)
  348. print(s.compile(compile_kwargs={"literal_binds": True}))
  349. .. versionadded:: 0.9.0
  350. .. seealso::
  351. :ref:`faq_sql_expression_string`
  352. """
  353. if not dialect:
  354. if bind:
  355. dialect = bind.dialect
  356. elif self.bind:
  357. dialect = self.bind.dialect
  358. else:
  359. if self.stringify_dialect == "default":
  360. default = util.preloaded.engine_default
  361. dialect = default.StrCompileDialect()
  362. else:
  363. url = util.preloaded.engine_url
  364. dialect = url.URL.create(
  365. self.stringify_dialect
  366. ).get_dialect()()
  367. return self._compiler(dialect, **kw)
  368. def _compile_w_cache(
  369. self,
  370. dialect,
  371. compiled_cache=None,
  372. column_keys=None,
  373. for_executemany=False,
  374. schema_translate_map=None,
  375. **kw
  376. ):
  377. if compiled_cache is not None and dialect._supports_statement_cache:
  378. elem_cache_key = self._generate_cache_key()
  379. else:
  380. elem_cache_key = None
  381. if elem_cache_key:
  382. cache_key, extracted_params = elem_cache_key
  383. key = (
  384. dialect,
  385. cache_key,
  386. tuple(column_keys),
  387. bool(schema_translate_map),
  388. for_executemany,
  389. )
  390. compiled_sql = compiled_cache.get(key)
  391. if compiled_sql is None:
  392. cache_hit = dialect.CACHE_MISS
  393. compiled_sql = self._compiler(
  394. dialect,
  395. cache_key=elem_cache_key,
  396. column_keys=column_keys,
  397. for_executemany=for_executemany,
  398. schema_translate_map=schema_translate_map,
  399. **kw
  400. )
  401. compiled_cache[key] = compiled_sql
  402. else:
  403. cache_hit = dialect.CACHE_HIT
  404. else:
  405. extracted_params = None
  406. compiled_sql = self._compiler(
  407. dialect,
  408. cache_key=elem_cache_key,
  409. column_keys=column_keys,
  410. for_executemany=for_executemany,
  411. schema_translate_map=schema_translate_map,
  412. **kw
  413. )
  414. if not dialect._supports_statement_cache:
  415. cache_hit = dialect.NO_DIALECT_SUPPORT
  416. elif compiled_cache is None:
  417. cache_hit = dialect.CACHING_DISABLED
  418. else:
  419. cache_hit = dialect.NO_CACHE_KEY
  420. return compiled_sql, extracted_params, cache_hit
  421. def _compiler(self, dialect, **kw):
  422. """Return a compiler appropriate for this ClauseElement, given a
  423. Dialect."""
  424. return dialect.statement_compiler(dialect, self, **kw)
  425. def __str__(self):
  426. if util.py3k:
  427. return str(self.compile())
  428. else:
  429. return unicode(self.compile()).encode( # noqa
  430. "ascii", "backslashreplace"
  431. ) # noqa
  432. def __invert__(self):
  433. # undocumented element currently used by the ORM for
  434. # relationship.contains()
  435. if hasattr(self, "negation_clause"):
  436. return self.negation_clause
  437. else:
  438. return self._negate()
  439. def _negate(self):
  440. return UnaryExpression(
  441. self.self_group(against=operators.inv), operator=operators.inv
  442. )
  443. def __bool__(self):
  444. raise TypeError("Boolean value of this clause is not defined")
  445. __nonzero__ = __bool__
  446. def __repr__(self):
  447. friendly = self.description
  448. if friendly is None:
  449. return object.__repr__(self)
  450. else:
  451. return "<%s.%s at 0x%x; %s>" % (
  452. self.__module__,
  453. self.__class__.__name__,
  454. id(self),
  455. friendly,
  456. )
  457. class ColumnElement(
  458. roles.ColumnArgumentOrKeyRole,
  459. roles.StatementOptionRole,
  460. roles.WhereHavingRole,
  461. roles.BinaryElementRole,
  462. roles.OrderByRole,
  463. roles.ColumnsClauseRole,
  464. roles.LimitOffsetRole,
  465. roles.DMLColumnRole,
  466. roles.DDLConstraintColumnRole,
  467. roles.DDLExpressionRole,
  468. operators.ColumnOperators,
  469. ClauseElement,
  470. ):
  471. """Represent a column-oriented SQL expression suitable for usage in the
  472. "columns" clause, WHERE clause etc. of a statement.
  473. While the most familiar kind of :class:`_expression.ColumnElement` is the
  474. :class:`_schema.Column` object, :class:`_expression.ColumnElement`
  475. serves as the basis
  476. for any unit that may be present in a SQL expression, including
  477. the expressions themselves, SQL functions, bound parameters,
  478. literal expressions, keywords such as ``NULL``, etc.
  479. :class:`_expression.ColumnElement`
  480. is the ultimate base class for all such elements.
  481. A wide variety of SQLAlchemy Core functions work at the SQL expression
  482. level, and are intended to accept instances of
  483. :class:`_expression.ColumnElement` as
  484. arguments. These functions will typically document that they accept a
  485. "SQL expression" as an argument. What this means in terms of SQLAlchemy
  486. usually refers to an input which is either already in the form of a
  487. :class:`_expression.ColumnElement` object,
  488. or a value which can be **coerced** into
  489. one. The coercion rules followed by most, but not all, SQLAlchemy Core
  490. functions with regards to SQL expressions are as follows:
  491. * a literal Python value, such as a string, integer or floating
  492. point value, boolean, datetime, ``Decimal`` object, or virtually
  493. any other Python object, will be coerced into a "literal bound
  494. value". This generally means that a :func:`.bindparam` will be
  495. produced featuring the given value embedded into the construct; the
  496. resulting :class:`.BindParameter` object is an instance of
  497. :class:`_expression.ColumnElement`.
  498. The Python value will ultimately be sent
  499. to the DBAPI at execution time as a parameterized argument to the
  500. ``execute()`` or ``executemany()`` methods, after SQLAlchemy
  501. type-specific converters (e.g. those provided by any associated
  502. :class:`.TypeEngine` objects) are applied to the value.
  503. * any special object value, typically ORM-level constructs, which
  504. feature an accessor called ``__clause_element__()``. The Core
  505. expression system looks for this method when an object of otherwise
  506. unknown type is passed to a function that is looking to coerce the
  507. argument into a :class:`_expression.ColumnElement` and sometimes a
  508. :class:`_expression.SelectBase` expression.
  509. It is used within the ORM to
  510. convert from ORM-specific objects like mapped classes and
  511. mapped attributes into Core expression objects.
  512. * The Python ``None`` value is typically interpreted as ``NULL``,
  513. which in SQLAlchemy Core produces an instance of :func:`.null`.
  514. A :class:`_expression.ColumnElement` provides the ability to generate new
  515. :class:`_expression.ColumnElement`
  516. objects using Python expressions. This means that Python operators
  517. such as ``==``, ``!=`` and ``<`` are overloaded to mimic SQL operations,
  518. and allow the instantiation of further :class:`_expression.ColumnElement`
  519. instances
  520. which are composed from other, more fundamental
  521. :class:`_expression.ColumnElement`
  522. objects. For example, two :class:`.ColumnClause` objects can be added
  523. together with the addition operator ``+`` to produce
  524. a :class:`.BinaryExpression`.
  525. Both :class:`.ColumnClause` and :class:`.BinaryExpression` are subclasses
  526. of :class:`_expression.ColumnElement`::
  527. >>> from sqlalchemy.sql import column
  528. >>> column('a') + column('b')
  529. <sqlalchemy.sql.expression.BinaryExpression object at 0x101029dd0>
  530. >>> print(column('a') + column('b'))
  531. a + b
  532. .. seealso::
  533. :class:`_schema.Column`
  534. :func:`_expression.column`
  535. """
  536. __visit_name__ = "column_element"
  537. primary_key = False
  538. foreign_keys = []
  539. _proxies = ()
  540. _label = None
  541. """The named label that can be used to target
  542. this column in a result set.
  543. This label is almost always the label used when
  544. rendering <expr> AS <label> in a SELECT statement. It also
  545. refers to a name that this column expression can be located from
  546. in a result set.
  547. For a regular Column bound to a Table, this is typically the label
  548. <tablename>_<columnname>. For other constructs, different rules
  549. may apply, such as anonymized labels and others.
  550. """
  551. key = None
  552. """The 'key' that in some circumstances refers to this object in a
  553. Python namespace.
  554. This typically refers to the "key" of the column as present in the
  555. ``.c`` collection of a selectable, e.g. ``sometable.c["somekey"]`` would
  556. return a :class:`_schema.Column` with a ``.key`` of "somekey".
  557. """
  558. _key_label = None
  559. """A label-based version of 'key' that in some circumstances refers
  560. to this object in a Python namespace.
  561. _key_label comes into play when a select() statement is constructed with
  562. apply_labels(); in this case, all Column objects in the ``.c`` collection
  563. are rendered as <tablename>_<columnname> in SQL; this is essentially the
  564. value of ._label. But to locate those columns in the ``.c`` collection,
  565. the name is along the lines of <tablename>_<key>; that's the typical
  566. value of .key_label.
  567. """
  568. _render_label_in_columns_clause = True
  569. """A flag used by select._columns_plus_names that helps to determine
  570. we are actually going to render in terms of "SELECT <col> AS <label>".
  571. This flag can be returned as False for some Column objects that want
  572. to be rendered as simple "SELECT <col>"; typically columns that don't have
  573. any parent table and are named the same as what the label would be
  574. in any case.
  575. """
  576. _resolve_label = None
  577. """The name that should be used to identify this ColumnElement in a
  578. select() object when "label resolution" logic is used; this refers
  579. to using a string name in an expression like order_by() or group_by()
  580. that wishes to target a labeled expression in the columns clause.
  581. The name is distinct from that of .name or ._label to account for the case
  582. where anonymizing logic may be used to change the name that's actually
  583. rendered at compile time; this attribute should hold onto the original
  584. name that was user-assigned when producing a .label() construct.
  585. """
  586. _allow_label_resolve = True
  587. """A flag that can be flipped to prevent a column from being resolvable
  588. by string label name."""
  589. _is_implicitly_boolean = False
  590. _alt_names = ()
  591. def self_group(self, against=None):
  592. if (
  593. against in (operators.and_, operators.or_, operators._asbool)
  594. and self.type._type_affinity is type_api.BOOLEANTYPE._type_affinity
  595. ):
  596. return AsBoolean(self, operators.is_true, operators.is_false)
  597. elif against in (operators.any_op, operators.all_op):
  598. return Grouping(self)
  599. else:
  600. return self
  601. def _negate(self):
  602. if self.type._type_affinity is type_api.BOOLEANTYPE._type_affinity:
  603. return AsBoolean(self, operators.is_false, operators.is_true)
  604. else:
  605. return super(ColumnElement, self)._negate()
  606. @util.memoized_property
  607. def type(self):
  608. return type_api.NULLTYPE
  609. @HasMemoized.memoized_attribute
  610. def comparator(self):
  611. try:
  612. comparator_factory = self.type.comparator_factory
  613. except AttributeError as err:
  614. util.raise_(
  615. TypeError(
  616. "Object %r associated with '.type' attribute "
  617. "is not a TypeEngine class or object" % self.type
  618. ),
  619. replace_context=err,
  620. )
  621. else:
  622. return comparator_factory(self)
  623. def __getattr__(self, key):
  624. try:
  625. return getattr(self.comparator, key)
  626. except AttributeError as err:
  627. util.raise_(
  628. AttributeError(
  629. "Neither %r object nor %r object has an attribute %r"
  630. % (
  631. type(self).__name__,
  632. type(self.comparator).__name__,
  633. key,
  634. )
  635. ),
  636. replace_context=err,
  637. )
  638. def operate(self, op, *other, **kwargs):
  639. return op(self.comparator, *other, **kwargs)
  640. def reverse_operate(self, op, other, **kwargs):
  641. return op(other, self.comparator, **kwargs)
  642. def _bind_param(self, operator, obj, type_=None, expanding=False):
  643. return BindParameter(
  644. None,
  645. obj,
  646. _compared_to_operator=operator,
  647. type_=type_,
  648. _compared_to_type=self.type,
  649. unique=True,
  650. expanding=expanding,
  651. )
  652. @property
  653. def expression(self):
  654. """Return a column expression.
  655. Part of the inspection interface; returns self.
  656. """
  657. return self
  658. @property
  659. def _select_iterable(self):
  660. return (self,)
  661. @util.memoized_property
  662. def base_columns(self):
  663. return util.column_set(c for c in self.proxy_set if not c._proxies)
  664. @util.memoized_property
  665. def proxy_set(self):
  666. s = util.column_set([self])
  667. for c in self._proxies:
  668. s.update(c.proxy_set)
  669. return s
  670. def _uncached_proxy_set(self):
  671. """An 'uncached' version of proxy set.
  672. This is so that we can read annotations from the list of columns
  673. without breaking the caching of the above proxy_set.
  674. """
  675. s = util.column_set([self])
  676. for c in self._proxies:
  677. s.update(c._uncached_proxy_set())
  678. return s
  679. def shares_lineage(self, othercolumn):
  680. """Return True if the given :class:`_expression.ColumnElement`
  681. has a common ancestor to this :class:`_expression.ColumnElement`."""
  682. return bool(self.proxy_set.intersection(othercolumn.proxy_set))
  683. def _compare_name_for_result(self, other):
  684. """Return True if the given column element compares to this one
  685. when targeting within a result row."""
  686. return (
  687. hasattr(other, "name")
  688. and hasattr(self, "name")
  689. and other.name == self.name
  690. )
  691. @util.memoized_property
  692. def _proxy_key(self):
  693. if self._annotations and "proxy_key" in self._annotations:
  694. return self._annotations["proxy_key"]
  695. elif self.key:
  696. return self.key
  697. else:
  698. return getattr(self, "name", "_no_label")
  699. def _make_proxy(
  700. self, selectable, name=None, key=None, name_is_truncatable=False, **kw
  701. ):
  702. """Create a new :class:`_expression.ColumnElement` representing this
  703. :class:`_expression.ColumnElement` as it appears in the select list of
  704. a descending selectable.
  705. """
  706. if name is None:
  707. name = self._anon_name_label
  708. if key is None:
  709. key = self._proxy_key
  710. else:
  711. key = name
  712. co = ColumnClause(
  713. coercions.expect(roles.TruncatedLabelRole, name)
  714. if name_is_truncatable
  715. else name,
  716. type_=getattr(self, "type", None),
  717. _selectable=selectable,
  718. )
  719. co._propagate_attrs = selectable._propagate_attrs
  720. co._proxies = [self]
  721. if selectable._is_clone_of is not None:
  722. co._is_clone_of = selectable._is_clone_of.columns.get(key)
  723. return key, co
  724. def cast(self, type_):
  725. """Produce a type cast, i.e. ``CAST(<expression> AS <type>)``.
  726. This is a shortcut to the :func:`_expression.cast` function.
  727. .. seealso::
  728. :ref:`coretutorial_casts`
  729. :func:`_expression.cast`
  730. :func:`_expression.type_coerce`
  731. .. versionadded:: 1.0.7
  732. """
  733. return Cast(self, type_)
  734. def label(self, name):
  735. """Produce a column label, i.e. ``<columnname> AS <name>``.
  736. This is a shortcut to the :func:`_expression.label` function.
  737. If 'name' is ``None``, an anonymous label name will be generated.
  738. """
  739. return Label(name, self, self.type)
  740. def _anon_label(self, seed):
  741. while self._is_clone_of is not None:
  742. self = self._is_clone_of
  743. # as of 1.4 anonymous label for ColumnElement uses hash(), not id(),
  744. # as the identifier, because a column and its annotated version are
  745. # the same thing in a SQL statement
  746. if isinstance(seed, _anonymous_label):
  747. return _anonymous_label.safe_construct(
  748. hash(self), "", enclosing_label=seed
  749. )
  750. return _anonymous_label.safe_construct(hash(self), seed or "anon")
  751. @util.memoized_property
  752. def _anon_name_label(self):
  753. """Provides a constant 'anonymous label' for this ColumnElement.
  754. This is a label() expression which will be named at compile time.
  755. The same label() is returned each time ``anon_label`` is called so
  756. that expressions can reference ``anon_label`` multiple times,
  757. producing the same label name at compile time.
  758. The compiler uses this function automatically at compile time
  759. for expressions that are known to be 'unnamed' like binary
  760. expressions and function calls.
  761. .. versionchanged:: 1.4.9 - this attribute was not intended to be
  762. public and is renamed to _anon_name_label. anon_name exists
  763. for backwards compat
  764. """
  765. name = getattr(self, "name", None)
  766. return self._anon_label(name)
  767. @util.memoized_property
  768. def _anon_key_label(self):
  769. """Provides a constant 'anonymous key label' for this ColumnElement.
  770. Compare to ``anon_label``, except that the "key" of the column,
  771. if available, is used to generate the label.
  772. This is used when a deduplicating key is placed into the columns
  773. collection of a selectable.
  774. .. versionchanged:: 1.4.9 - this attribute was not intended to be
  775. public and is renamed to _anon_key_label. anon_key_label exists
  776. for backwards compat
  777. """
  778. return self._anon_label(self._proxy_key)
  779. @property
  780. @util.deprecated(
  781. "1.4",
  782. "The :attr:`_expression.ColumnElement.anon_label` attribute is now "
  783. "private, and the public accessor is deprecated.",
  784. )
  785. def anon_label(self):
  786. return self._anon_name_label
  787. @property
  788. @util.deprecated(
  789. "1.4",
  790. "The :attr:`_expression.ColumnElement.anon_key_label` attribute is "
  791. "now private, and the public accessor is deprecated.",
  792. )
  793. def anon_key_label(self):
  794. return self._anon_key_label
  795. @util.memoized_property
  796. def _dedupe_anon_label(self):
  797. label = getattr(self, "name", None) or "anon"
  798. return self._anon_label(label + "_")
  799. @util.memoized_property
  800. def _label_anon_label(self):
  801. return self._anon_label(getattr(self, "_label", None))
  802. @util.memoized_property
  803. def _label_anon_key_label(self):
  804. return self._anon_label(getattr(self, "_key_label", None))
  805. @util.memoized_property
  806. def _dedupe_label_anon_label(self):
  807. label = getattr(self, "_label", None) or "anon"
  808. return self._anon_label(label + "_")
  809. class WrapsColumnExpression(object):
  810. """Mixin that defines a :class:`_expression.ColumnElement`
  811. as a wrapper with special
  812. labeling behavior for an expression that already has a name.
  813. .. versionadded:: 1.4
  814. .. seealso::
  815. :ref:`change_4449`
  816. """
  817. @property
  818. def wrapped_column_expression(self):
  819. raise NotImplementedError()
  820. @property
  821. def _label(self):
  822. wce = self.wrapped_column_expression
  823. if hasattr(wce, "_label"):
  824. return wce._label
  825. else:
  826. return None
  827. @property
  828. def _anon_name_label(self):
  829. wce = self.wrapped_column_expression
  830. if hasattr(wce, "name"):
  831. return wce.name
  832. elif hasattr(wce, "_anon_name_label"):
  833. return wce._anon_name_label
  834. else:
  835. return super(WrapsColumnExpression, self)._anon_name_label
  836. class BindParameter(roles.InElementRole, ColumnElement):
  837. r"""Represent a "bound expression".
  838. :class:`.BindParameter` is invoked explicitly using the
  839. :func:`.bindparam` function, as in::
  840. from sqlalchemy import bindparam
  841. stmt = select(users_table).\
  842. where(users_table.c.name == bindparam('username'))
  843. Detailed discussion of how :class:`.BindParameter` is used is
  844. at :func:`.bindparam`.
  845. .. seealso::
  846. :func:`.bindparam`
  847. """
  848. __visit_name__ = "bindparam"
  849. _traverse_internals = [
  850. ("key", InternalTraversal.dp_anon_name),
  851. ("type", InternalTraversal.dp_type),
  852. ("callable", InternalTraversal.dp_plain_dict),
  853. ("value", InternalTraversal.dp_plain_obj),
  854. ]
  855. _is_crud = False
  856. _is_bind_parameter = True
  857. _key_is_anon = False
  858. # bindparam implements its own _gen_cache_key() method however
  859. # we check subclasses for this flag, else no cache key is generated
  860. inherit_cache = True
  861. def __init__(
  862. self,
  863. key,
  864. value=NO_ARG,
  865. type_=None,
  866. unique=False,
  867. required=NO_ARG,
  868. quote=None,
  869. callable_=None,
  870. expanding=False,
  871. isoutparam=False,
  872. literal_execute=False,
  873. _compared_to_operator=None,
  874. _compared_to_type=None,
  875. _is_crud=False,
  876. ):
  877. r"""Produce a "bound expression".
  878. The return value is an instance of :class:`.BindParameter`; this
  879. is a :class:`_expression.ColumnElement`
  880. subclass which represents a so-called
  881. "placeholder" value in a SQL expression, the value of which is
  882. supplied at the point at which the statement in executed against a
  883. database connection.
  884. In SQLAlchemy, the :func:`.bindparam` construct has
  885. the ability to carry along the actual value that will be ultimately
  886. used at expression time. In this way, it serves not just as
  887. a "placeholder" for eventual population, but also as a means of
  888. representing so-called "unsafe" values which should not be rendered
  889. directly in a SQL statement, but rather should be passed along
  890. to the :term:`DBAPI` as values which need to be correctly escaped
  891. and potentially handled for type-safety.
  892. When using :func:`.bindparam` explicitly, the use case is typically
  893. one of traditional deferment of parameters; the :func:`.bindparam`
  894. construct accepts a name which can then be referred to at execution
  895. time::
  896. from sqlalchemy import bindparam
  897. stmt = select(users_table).\
  898. where(users_table.c.name == bindparam('username'))
  899. The above statement, when rendered, will produce SQL similar to::
  900. SELECT id, name FROM user WHERE name = :username
  901. In order to populate the value of ``:username`` above, the value
  902. would typically be applied at execution time to a method
  903. like :meth:`_engine.Connection.execute`::
  904. result = connection.execute(stmt, username='wendy')
  905. Explicit use of :func:`.bindparam` is also common when producing
  906. UPDATE or DELETE statements that are to be invoked multiple times,
  907. where the WHERE criterion of the statement is to change on each
  908. invocation, such as::
  909. stmt = (users_table.update().
  910. where(user_table.c.name == bindparam('username')).
  911. values(fullname=bindparam('fullname'))
  912. )
  913. connection.execute(
  914. stmt, [{"username": "wendy", "fullname": "Wendy Smith"},
  915. {"username": "jack", "fullname": "Jack Jones"},
  916. ]
  917. )
  918. SQLAlchemy's Core expression system makes wide use of
  919. :func:`.bindparam` in an implicit sense. It is typical that Python
  920. literal values passed to virtually all SQL expression functions are
  921. coerced into fixed :func:`.bindparam` constructs. For example, given
  922. a comparison operation such as::
  923. expr = users_table.c.name == 'Wendy'
  924. The above expression will produce a :class:`.BinaryExpression`
  925. construct, where the left side is the :class:`_schema.Column` object
  926. representing the ``name`` column, and the right side is a
  927. :class:`.BindParameter` representing the literal value::
  928. print(repr(expr.right))
  929. BindParameter('%(4327771088 name)s', 'Wendy', type_=String())
  930. The expression above will render SQL such as::
  931. user.name = :name_1
  932. Where the ``:name_1`` parameter name is an anonymous name. The
  933. actual string ``Wendy`` is not in the rendered string, but is carried
  934. along where it is later used within statement execution. If we
  935. invoke a statement like the following::
  936. stmt = select(users_table).where(users_table.c.name == 'Wendy')
  937. result = connection.execute(stmt)
  938. We would see SQL logging output as::
  939. SELECT "user".id, "user".name
  940. FROM "user"
  941. WHERE "user".name = %(name_1)s
  942. {'name_1': 'Wendy'}
  943. Above, we see that ``Wendy`` is passed as a parameter to the database,
  944. while the placeholder ``:name_1`` is rendered in the appropriate form
  945. for the target database, in this case the PostgreSQL database.
  946. Similarly, :func:`.bindparam` is invoked automatically when working
  947. with :term:`CRUD` statements as far as the "VALUES" portion is
  948. concerned. The :func:`_expression.insert` construct produces an
  949. ``INSERT`` expression which will, at statement execution time, generate
  950. bound placeholders based on the arguments passed, as in::
  951. stmt = users_table.insert()
  952. result = connection.execute(stmt, name='Wendy')
  953. The above will produce SQL output as::
  954. INSERT INTO "user" (name) VALUES (%(name)s)
  955. {'name': 'Wendy'}
  956. The :class:`_expression.Insert` construct, at
  957. compilation/execution time, rendered a single :func:`.bindparam`
  958. mirroring the column name ``name`` as a result of the single ``name``
  959. parameter we passed to the :meth:`_engine.Connection.execute` method.
  960. :param key:
  961. the key (e.g. the name) for this bind param.
  962. Will be used in the generated
  963. SQL statement for dialects that use named parameters. This
  964. value may be modified when part of a compilation operation,
  965. if other :class:`BindParameter` objects exist with the same
  966. key, or if its length is too long and truncation is
  967. required.
  968. :param value:
  969. Initial value for this bind param. Will be used at statement
  970. execution time as the value for this parameter passed to the
  971. DBAPI, if no other value is indicated to the statement execution
  972. method for this particular parameter name. Defaults to ``None``.
  973. :param callable\_:
  974. A callable function that takes the place of "value". The function
  975. will be called at statement execution time to determine the
  976. ultimate value. Used for scenarios where the actual bind
  977. value cannot be determined at the point at which the clause
  978. construct is created, but embedded bind values are still desirable.
  979. :param type\_:
  980. A :class:`.TypeEngine` class or instance representing an optional
  981. datatype for this :func:`.bindparam`. If not passed, a type
  982. may be determined automatically for the bind, based on the given
  983. value; for example, trivial Python types such as ``str``,
  984. ``int``, ``bool``
  985. may result in the :class:`.String`, :class:`.Integer` or
  986. :class:`.Boolean` types being automatically selected.
  987. The type of a :func:`.bindparam` is significant especially in that
  988. the type will apply pre-processing to the value before it is
  989. passed to the database. For example, a :func:`.bindparam` which
  990. refers to a datetime value, and is specified as holding the
  991. :class:`.DateTime` type, may apply conversion needed to the
  992. value (such as stringification on SQLite) before passing the value
  993. to the database.
  994. :param unique:
  995. if True, the key name of this :class:`.BindParameter` will be
  996. modified if another :class:`.BindParameter` of the same name
  997. already has been located within the containing
  998. expression. This flag is used generally by the internals
  999. when producing so-called "anonymous" bound expressions, it
  1000. isn't generally applicable to explicitly-named :func:`.bindparam`
  1001. constructs.
  1002. :param required:
  1003. If ``True``, a value is required at execution time. If not passed,
  1004. it defaults to ``True`` if neither :paramref:`.bindparam.value`
  1005. or :paramref:`.bindparam.callable` were passed. If either of these
  1006. parameters are present, then :paramref:`.bindparam.required`
  1007. defaults to ``False``.
  1008. :param quote:
  1009. True if this parameter name requires quoting and is not
  1010. currently known as a SQLAlchemy reserved word; this currently
  1011. only applies to the Oracle backend, where bound names must
  1012. sometimes be quoted.
  1013. :param isoutparam:
  1014. if True, the parameter should be treated like a stored procedure
  1015. "OUT" parameter. This applies to backends such as Oracle which
  1016. support OUT parameters.
  1017. :param expanding:
  1018. if True, this parameter will be treated as an "expanding" parameter
  1019. at execution time; the parameter value is expected to be a sequence,
  1020. rather than a scalar value, and the string SQL statement will
  1021. be transformed on a per-execution basis to accommodate the sequence
  1022. with a variable number of parameter slots passed to the DBAPI.
  1023. This is to allow statement caching to be used in conjunction with
  1024. an IN clause.
  1025. .. seealso::
  1026. :meth:`.ColumnOperators.in_`
  1027. :ref:`baked_in` - with baked queries
  1028. .. note:: The "expanding" feature does not support "executemany"-
  1029. style parameter sets.
  1030. .. versionadded:: 1.2
  1031. .. versionchanged:: 1.3 the "expanding" bound parameter feature now
  1032. supports empty lists.
  1033. .. seealso::
  1034. :ref:`coretutorial_bind_param`
  1035. :ref:`coretutorial_insert_expressions`
  1036. :func:`.outparam`
  1037. :param literal_execute:
  1038. if True, the bound parameter will be rendered in the compile phase
  1039. with a special "POSTCOMPILE" token, and the SQLAlchemy compiler will
  1040. render the final value of the parameter into the SQL statement at
  1041. statement execution time, omitting the value from the parameter
  1042. dictionary / list passed to DBAPI ``cursor.execute()``. This
  1043. produces a similar effect as that of using the ``literal_binds``,
  1044. compilation flag, however takes place as the statement is sent to
  1045. the DBAPI ``cursor.execute()`` method, rather than when the statement
  1046. is compiled. The primary use of this
  1047. capability is for rendering LIMIT / OFFSET clauses for database
  1048. drivers that can't accommodate for bound parameters in these
  1049. contexts, while allowing SQL constructs to be cacheable at the
  1050. compilation level.
  1051. .. versionadded:: 1.4 Added "post compile" bound parameters
  1052. .. seealso::
  1053. :ref:`change_4808`.
  1054. """
  1055. if required is NO_ARG:
  1056. required = value is NO_ARG and callable_ is None
  1057. if value is NO_ARG:
  1058. value = None
  1059. if quote is not None:
  1060. key = quoted_name(key, quote)
  1061. if unique:
  1062. self.key = _anonymous_label.safe_construct(
  1063. id(self),
  1064. key
  1065. if key is not None and not isinstance(key, _anonymous_label)
  1066. else "param",
  1067. sanitize_key=True,
  1068. )
  1069. self._key_is_anon = True
  1070. elif key:
  1071. self.key = key
  1072. else:
  1073. self.key = _anonymous_label.safe_construct(id(self), "param")
  1074. self._key_is_anon = True
  1075. # identifying key that won't change across
  1076. # clones, used to identify the bind's logical
  1077. # identity
  1078. self._identifying_key = self.key
  1079. # key that was passed in the first place, used to
  1080. # generate new keys
  1081. self._orig_key = key or "param"
  1082. self.unique = unique
  1083. self.value = value
  1084. self.callable = callable_
  1085. self.isoutparam = isoutparam
  1086. self.required = required
  1087. # indicate an "expanding" parameter; the compiler sets this
  1088. # automatically in the compiler _render_in_expr_w_bindparam method
  1089. # for an IN expression
  1090. self.expanding = expanding
  1091. # this is another hint to help w/ expanding and is typically
  1092. # set in the compiler _render_in_expr_w_bindparam method for an
  1093. # IN expression
  1094. self.expand_op = None
  1095. self.literal_execute = literal_execute
  1096. if _is_crud:
  1097. self._is_crud = True
  1098. if type_ is None:
  1099. if expanding and value:
  1100. check_value = value[0]
  1101. else:
  1102. check_value = value
  1103. if _compared_to_type is not None:
  1104. self.type = _compared_to_type.coerce_compared_value(
  1105. _compared_to_operator, check_value
  1106. )
  1107. else:
  1108. self.type = type_api._resolve_value_to_type(check_value)
  1109. elif isinstance(type_, type):
  1110. self.type = type_()
  1111. elif type_._is_tuple_type and value:
  1112. if expanding:
  1113. check_value = value[0]
  1114. else:
  1115. check_value = value
  1116. self.type = type_._resolve_values_to_types(check_value)
  1117. else:
  1118. self.type = type_
  1119. def _with_value(self, value, maintain_key=False, required=NO_ARG):
  1120. """Return a copy of this :class:`.BindParameter` with the given value
  1121. set.
  1122. """
  1123. cloned = self._clone(maintain_key=maintain_key)
  1124. cloned.value = value
  1125. cloned.callable = None
  1126. cloned.required = required if required is not NO_ARG else self.required
  1127. if cloned.type is type_api.NULLTYPE:
  1128. cloned.type = type_api._resolve_value_to_type(value)
  1129. return cloned
  1130. @property
  1131. def effective_value(self):
  1132. """Return the value of this bound parameter,
  1133. taking into account if the ``callable`` parameter
  1134. was set.
  1135. The ``callable`` value will be evaluated
  1136. and returned if present, else ``value``.
  1137. """
  1138. if self.callable:
  1139. return self.callable()
  1140. else:
  1141. return self.value
  1142. def render_literal_execute(self):
  1143. """Produce a copy of this bound parameter that will enable the
  1144. :paramref:`_sql.BindParameter.literal_execute` flag.
  1145. The :paramref:`_sql.BindParameter.literal_execute` flag will
  1146. have the effect of the parameter rendered in the compiled SQL
  1147. string using ``[POSTCOMPILE]`` form, which is a special form that
  1148. is converted to be a rendering of the literal value of the parameter
  1149. at SQL execution time. The rationale is to support caching
  1150. of SQL statement strings that can embed per-statement literal values,
  1151. such as LIMIT and OFFSET parameters, in the final SQL string that
  1152. is passed to the DBAPI. Dialects in particular may want to use
  1153. this method within custom compilation schemes.
  1154. .. versionadded:: 1.4.5
  1155. .. seealso::
  1156. :ref:`engine_thirdparty_caching`
  1157. """
  1158. return self.__class__(
  1159. self.key,
  1160. self.value,
  1161. type_=self.type,
  1162. literal_execute=True,
  1163. )
  1164. def _negate_in_binary(self, negated_op, original_op):
  1165. if self.expand_op is original_op:
  1166. bind = self._clone()
  1167. bind.expand_op = negated_op
  1168. return bind
  1169. else:
  1170. return self
  1171. def _with_binary_element_type(self, type_):
  1172. c = ClauseElement._clone(self)
  1173. c.type = type_
  1174. return c
  1175. def _clone(self, maintain_key=False, **kw):
  1176. c = ClauseElement._clone(self, **kw)
  1177. if not maintain_key and self.unique:
  1178. c.key = _anonymous_label.safe_construct(
  1179. id(c), c._orig_key or "param", sanitize_key=True
  1180. )
  1181. return c
  1182. def _gen_cache_key(self, anon_map, bindparams):
  1183. _gen_cache_ok = self.__class__.__dict__.get("inherit_cache", False)
  1184. if not _gen_cache_ok:
  1185. if anon_map is not None:
  1186. anon_map[NO_CACHE] = True
  1187. return None
  1188. idself = id(self)
  1189. if idself in anon_map:
  1190. return (anon_map[idself], self.__class__)
  1191. else:
  1192. # inline of
  1193. # id_ = anon_map[idself]
  1194. anon_map[idself] = id_ = str(anon_map.index)
  1195. anon_map.index += 1
  1196. if bindparams is not None:
  1197. bindparams.append(self)
  1198. return (
  1199. id_,
  1200. self.__class__,
  1201. self.type._static_cache_key,
  1202. self.key % anon_map if self._key_is_anon else self.key,
  1203. )
  1204. def _convert_to_unique(self):
  1205. if not self.unique:
  1206. self.unique = True
  1207. self.key = _anonymous_label.safe_construct(
  1208. id(self), self._orig_key or "param", sanitize_key=True
  1209. )
  1210. def __getstate__(self):
  1211. """execute a deferred value for serialization purposes."""
  1212. d = self.__dict__.copy()
  1213. v = self.value
  1214. if self.callable:
  1215. v = self.callable()
  1216. d["callable"] = None
  1217. d["value"] = v
  1218. return d
  1219. def __setstate__(self, state):
  1220. if state.get("unique", False):
  1221. state["key"] = _anonymous_label.safe_construct(
  1222. id(self), state.get("_orig_key", "param"), sanitize_key=True
  1223. )
  1224. self.__dict__.update(state)
  1225. def __repr__(self):
  1226. return "%s(%r, %r, type_=%r)" % (
  1227. self.__class__.__name__,
  1228. self.key,
  1229. self.value,
  1230. self.type,
  1231. )
  1232. class TypeClause(ClauseElement):
  1233. """Handle a type keyword in a SQL statement.
  1234. Used by the ``Case`` statement.
  1235. """
  1236. __visit_name__ = "typeclause"
  1237. _traverse_internals = [("type", InternalTraversal.dp_type)]
  1238. def __init__(self, type_):
  1239. self.type = type_
  1240. class TextClause(
  1241. roles.DDLConstraintColumnRole,
  1242. roles.DDLExpressionRole,
  1243. roles.StatementOptionRole,
  1244. roles.WhereHavingRole,
  1245. roles.OrderByRole,
  1246. roles.FromClauseRole,
  1247. roles.SelectStatementRole,
  1248. roles.BinaryElementRole,
  1249. roles.InElementRole,
  1250. Executable,
  1251. ClauseElement,
  1252. ):
  1253. """Represent a literal SQL text fragment.
  1254. E.g.::
  1255. from sqlalchemy import text
  1256. t = text("SELECT * FROM users")
  1257. result = connection.execute(t)
  1258. The :class:`_expression.TextClause` construct is produced using the
  1259. :func:`_expression.text`
  1260. function; see that function for full documentation.
  1261. .. seealso::
  1262. :func:`_expression.text`
  1263. """
  1264. __visit_name__ = "textclause"
  1265. _traverse_internals = [
  1266. ("_bindparams", InternalTraversal.dp_string_clauseelement_dict),
  1267. ("text", InternalTraversal.dp_string),
  1268. ]
  1269. _is_text_clause = True
  1270. _is_textual = True
  1271. _bind_params_regex = re.compile(r"(?<![:\w\x5c]):(\w+)(?!:)", re.UNICODE)
  1272. _execution_options = Executable._execution_options.union(
  1273. {"autocommit": PARSE_AUTOCOMMIT}
  1274. )
  1275. _is_implicitly_boolean = False
  1276. _render_label_in_columns_clause = False
  1277. _hide_froms = ()
  1278. def __and__(self, other):
  1279. # support use in select.where(), query.filter()
  1280. return and_(self, other)
  1281. @property
  1282. def _select_iterable(self):
  1283. return (self,)
  1284. # help in those cases where text() is
  1285. # interpreted in a column expression situation
  1286. key = _label = _resolve_label = None
  1287. _allow_label_resolve = False
  1288. def __init__(self, text, bind=None):
  1289. self._bind = bind
  1290. self._bindparams = {}
  1291. def repl(m):
  1292. self._bindparams[m.group(1)] = BindParameter(m.group(1))
  1293. return ":%s" % m.group(1)
  1294. # scan the string and search for bind parameter names, add them
  1295. # to the list of bindparams
  1296. self.text = self._bind_params_regex.sub(repl, text)
  1297. @classmethod
  1298. @_document_text_coercion("text", ":func:`.text`", ":paramref:`.text.text`")
  1299. @util.deprecated_params(
  1300. bind=(
  1301. "2.0",
  1302. "The :paramref:`_sql.text.bind` argument is deprecated and "
  1303. "will be removed in SQLAlchemy 2.0.",
  1304. ),
  1305. )
  1306. def _create_text(cls, text, bind=None):
  1307. r"""Construct a new :class:`_expression.TextClause` clause,
  1308. representing
  1309. a textual SQL string directly.
  1310. E.g.::
  1311. from sqlalchemy import text
  1312. t = text("SELECT * FROM users")
  1313. result = connection.execute(t)
  1314. The advantages :func:`_expression.text`
  1315. provides over a plain string are
  1316. backend-neutral support for bind parameters, per-statement
  1317. execution options, as well as
  1318. bind parameter and result-column typing behavior, allowing
  1319. SQLAlchemy type constructs to play a role when executing
  1320. a statement that is specified literally. The construct can also
  1321. be provided with a ``.c`` collection of column elements, allowing
  1322. it to be embedded in other SQL expression constructs as a subquery.
  1323. Bind parameters are specified by name, using the format ``:name``.
  1324. E.g.::
  1325. t = text("SELECT * FROM users WHERE id=:user_id")
  1326. result = connection.execute(t, user_id=12)
  1327. For SQL statements where a colon is required verbatim, as within
  1328. an inline string, use a backslash to escape::
  1329. t = text("SELECT * FROM users WHERE name='\:username'")
  1330. The :class:`_expression.TextClause`
  1331. construct includes methods which can
  1332. provide information about the bound parameters as well as the column
  1333. values which would be returned from the textual statement, assuming
  1334. it's an executable SELECT type of statement. The
  1335. :meth:`_expression.TextClause.bindparams`
  1336. method is used to provide bound
  1337. parameter detail, and :meth:`_expression.TextClause.columns`
  1338. method allows
  1339. specification of return columns including names and types::
  1340. t = text("SELECT * FROM users WHERE id=:user_id").\
  1341. bindparams(user_id=7).\
  1342. columns(id=Integer, name=String)
  1343. for id, name in connection.execute(t):
  1344. print(id, name)
  1345. The :func:`_expression.text` construct is used in cases when
  1346. a literal string SQL fragment is specified as part of a larger query,
  1347. such as for the WHERE clause of a SELECT statement::
  1348. s = select(users.c.id, users.c.name).where(text("id=:user_id"))
  1349. result = connection.execute(s, user_id=12)
  1350. :func:`_expression.text` is also used for the construction
  1351. of a full, standalone statement using plain text.
  1352. As such, SQLAlchemy refers
  1353. to it as an :class:`.Executable` object, and it supports
  1354. the :meth:`Executable.execution_options` method. For example,
  1355. a :func:`_expression.text`
  1356. construct that should be subject to "autocommit"
  1357. can be set explicitly so using the
  1358. :paramref:`.Connection.execution_options.autocommit` option::
  1359. t = text("EXEC my_procedural_thing()").\
  1360. execution_options(autocommit=True)
  1361. .. deprecated:: 1.4 The "autocommit" execution option is deprecated
  1362. and will be removed in SQLAlchemy 2.0. See
  1363. :ref:`migration_20_autocommit` for discussion.
  1364. :param text:
  1365. the text of the SQL statement to be created. Use ``:<param>``
  1366. to specify bind parameters; they will be compiled to their
  1367. engine-specific format.
  1368. :param bind:
  1369. an optional connection or engine to be used for this text query.
  1370. .. seealso::
  1371. :ref:`sqlexpression_text` - in the Core tutorial
  1372. """
  1373. return TextClause(text, bind=bind)
  1374. @_generative
  1375. def bindparams(self, *binds, **names_to_values):
  1376. """Establish the values and/or types of bound parameters within
  1377. this :class:`_expression.TextClause` construct.
  1378. Given a text construct such as::
  1379. from sqlalchemy import text
  1380. stmt = text("SELECT id, name FROM user WHERE name=:name "
  1381. "AND timestamp=:timestamp")
  1382. the :meth:`_expression.TextClause.bindparams`
  1383. method can be used to establish
  1384. the initial value of ``:name`` and ``:timestamp``,
  1385. using simple keyword arguments::
  1386. stmt = stmt.bindparams(name='jack',
  1387. timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5))
  1388. Where above, new :class:`.BindParameter` objects
  1389. will be generated with the names ``name`` and ``timestamp``, and
  1390. values of ``jack`` and ``datetime.datetime(2012, 10, 8, 15, 12, 5)``,
  1391. respectively. The types will be
  1392. inferred from the values given, in this case :class:`.String` and
  1393. :class:`.DateTime`.
  1394. When specific typing behavior is needed, the positional ``*binds``
  1395. argument can be used in which to specify :func:`.bindparam` constructs
  1396. directly. These constructs must include at least the ``key``
  1397. argument, then an optional value and type::
  1398. from sqlalchemy import bindparam
  1399. stmt = stmt.bindparams(
  1400. bindparam('name', value='jack', type_=String),
  1401. bindparam('timestamp', type_=DateTime)
  1402. )
  1403. Above, we specified the type of :class:`.DateTime` for the
  1404. ``timestamp`` bind, and the type of :class:`.String` for the ``name``
  1405. bind. In the case of ``name`` we also set the default value of
  1406. ``"jack"``.
  1407. Additional bound parameters can be supplied at statement execution
  1408. time, e.g.::
  1409. result = connection.execute(stmt,
  1410. timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5))
  1411. The :meth:`_expression.TextClause.bindparams`
  1412. method can be called repeatedly,
  1413. where it will re-use existing :class:`.BindParameter` objects to add
  1414. new information. For example, we can call
  1415. :meth:`_expression.TextClause.bindparams`
  1416. first with typing information, and a
  1417. second time with value information, and it will be combined::
  1418. stmt = text("SELECT id, name FROM user WHERE name=:name "
  1419. "AND timestamp=:timestamp")
  1420. stmt = stmt.bindparams(
  1421. bindparam('name', type_=String),
  1422. bindparam('timestamp', type_=DateTime)
  1423. )
  1424. stmt = stmt.bindparams(
  1425. name='jack',
  1426. timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5)
  1427. )
  1428. The :meth:`_expression.TextClause.bindparams`
  1429. method also supports the concept of
  1430. **unique** bound parameters. These are parameters that are
  1431. "uniquified" on name at statement compilation time, so that multiple
  1432. :func:`_expression.text`
  1433. constructs may be combined together without the names
  1434. conflicting. To use this feature, specify the
  1435. :paramref:`.BindParameter.unique` flag on each :func:`.bindparam`
  1436. object::
  1437. stmt1 = text("select id from table where name=:name").bindparams(
  1438. bindparam("name", value='name1', unique=True)
  1439. )
  1440. stmt2 = text("select id from table where name=:name").bindparams(
  1441. bindparam("name", value='name2', unique=True)
  1442. )
  1443. union = union_all(
  1444. stmt1.columns(column("id")),
  1445. stmt2.columns(column("id"))
  1446. )
  1447. The above statement will render as::
  1448. select id from table where name=:name_1
  1449. UNION ALL select id from table where name=:name_2
  1450. .. versionadded:: 1.3.11 Added support for the
  1451. :paramref:`.BindParameter.unique` flag to work with
  1452. :func:`_expression.text`
  1453. constructs.
  1454. """
  1455. self._bindparams = new_params = self._bindparams.copy()
  1456. for bind in binds:
  1457. try:
  1458. # the regex used for text() currently will not match
  1459. # a unique/anonymous key in any case, so use the _orig_key
  1460. # so that a text() construct can support unique parameters
  1461. existing = new_params[bind._orig_key]
  1462. except KeyError as err:
  1463. util.raise_(
  1464. exc.ArgumentError(
  1465. "This text() construct doesn't define a "
  1466. "bound parameter named %r" % bind._orig_key
  1467. ),
  1468. replace_context=err,
  1469. )
  1470. else:
  1471. new_params[existing._orig_key] = bind
  1472. for key, value in names_to_values.items():
  1473. try:
  1474. existing = new_params[key]
  1475. except KeyError as err:
  1476. util.raise_(
  1477. exc.ArgumentError(
  1478. "This text() construct doesn't define a "
  1479. "bound parameter named %r" % key
  1480. ),
  1481. replace_context=err,
  1482. )
  1483. else:
  1484. new_params[key] = existing._with_value(value, required=False)
  1485. @util.preload_module("sqlalchemy.sql.selectable")
  1486. def columns(self, *cols, **types):
  1487. r"""Turn this :class:`_expression.TextClause` object into a
  1488. :class:`_expression.TextualSelect`
  1489. object that serves the same role as a SELECT
  1490. statement.
  1491. The :class:`_expression.TextualSelect` is part of the
  1492. :class:`_expression.SelectBase`
  1493. hierarchy and can be embedded into another statement by using the
  1494. :meth:`_expression.TextualSelect.subquery` method to produce a
  1495. :class:`.Subquery`
  1496. object, which can then be SELECTed from.
  1497. This function essentially bridges the gap between an entirely
  1498. textual SELECT statement and the SQL expression language concept
  1499. of a "selectable"::
  1500. from sqlalchemy.sql import column, text
  1501. stmt = text("SELECT id, name FROM some_table")
  1502. stmt = stmt.columns(column('id'), column('name')).subquery('st')
  1503. stmt = select(mytable).\
  1504. select_from(
  1505. mytable.join(stmt, mytable.c.name == stmt.c.name)
  1506. ).where(stmt.c.id > 5)
  1507. Above, we pass a series of :func:`_expression.column` elements to the
  1508. :meth:`_expression.TextClause.columns` method positionally. These
  1509. :func:`_expression.column`
  1510. elements now become first class elements upon the
  1511. :attr:`_expression.TextualSelect.selected_columns` column collection,
  1512. which then
  1513. become part of the :attr:`.Subquery.c` collection after
  1514. :meth:`_expression.TextualSelect.subquery` is invoked.
  1515. The column expressions we pass to
  1516. :meth:`_expression.TextClause.columns` may
  1517. also be typed; when we do so, these :class:`.TypeEngine` objects become
  1518. the effective return type of the column, so that SQLAlchemy's
  1519. result-set-processing systems may be used on the return values.
  1520. This is often needed for types such as date or boolean types, as well
  1521. as for unicode processing on some dialect configurations::
  1522. stmt = text("SELECT id, name, timestamp FROM some_table")
  1523. stmt = stmt.columns(
  1524. column('id', Integer),
  1525. column('name', Unicode),
  1526. column('timestamp', DateTime)
  1527. )
  1528. for id, name, timestamp in connection.execute(stmt):
  1529. print(id, name, timestamp)
  1530. As a shortcut to the above syntax, keyword arguments referring to
  1531. types alone may be used, if only type conversion is needed::
  1532. stmt = text("SELECT id, name, timestamp FROM some_table")
  1533. stmt = stmt.columns(
  1534. id=Integer,
  1535. name=Unicode,
  1536. timestamp=DateTime
  1537. )
  1538. for id, name, timestamp in connection.execute(stmt):
  1539. print(id, name, timestamp)
  1540. The positional form of :meth:`_expression.TextClause.columns`
  1541. also provides the
  1542. unique feature of **positional column targeting**, which is
  1543. particularly useful when using the ORM with complex textual queries. If
  1544. we specify the columns from our model to
  1545. :meth:`_expression.TextClause.columns`,
  1546. the result set will match to those columns positionally, meaning the
  1547. name or origin of the column in the textual SQL doesn't matter::
  1548. stmt = text("SELECT users.id, addresses.id, users.id, "
  1549. "users.name, addresses.email_address AS email "
  1550. "FROM users JOIN addresses ON users.id=addresses.user_id "
  1551. "WHERE users.id = 1").columns(
  1552. User.id,
  1553. Address.id,
  1554. Address.user_id,
  1555. User.name,
  1556. Address.email_address
  1557. )
  1558. query = session.query(User).from_statement(stmt).options(
  1559. contains_eager(User.addresses))
  1560. .. versionadded:: 1.1 the :meth:`_expression.TextClause.columns`
  1561. method now
  1562. offers positional column targeting in the result set when
  1563. the column expressions are passed purely positionally.
  1564. The :meth:`_expression.TextClause.columns` method provides a direct
  1565. route to calling :meth:`_expression.FromClause.subquery` as well as
  1566. :meth:`_expression.SelectBase.cte`
  1567. against a textual SELECT statement::
  1568. stmt = stmt.columns(id=Integer, name=String).cte('st')
  1569. stmt = select(sometable).where(sometable.c.id == stmt.c.id)
  1570. :param \*cols: A series of :class:`_expression.ColumnElement` objects,
  1571. typically
  1572. :class:`_schema.Column` objects from a :class:`_schema.Table`
  1573. or ORM level
  1574. column-mapped attributes, representing a set of columns that this
  1575. textual string will SELECT from.
  1576. :param \**types: A mapping of string names to :class:`.TypeEngine`
  1577. type objects indicating the datatypes to use for names that are
  1578. SELECTed from the textual string. Prefer to use the ``*cols``
  1579. argument as it also indicates positional ordering.
  1580. """
  1581. selectable = util.preloaded.sql_selectable
  1582. positional_input_cols = [
  1583. ColumnClause(col.key, types.pop(col.key))
  1584. if col.key in types
  1585. else col
  1586. for col in cols
  1587. ]
  1588. keyed_input_cols = [
  1589. ColumnClause(key, type_) for key, type_ in types.items()
  1590. ]
  1591. return selectable.TextualSelect(
  1592. self,
  1593. positional_input_cols + keyed_input_cols,
  1594. positional=bool(positional_input_cols) and not keyed_input_cols,
  1595. )
  1596. @property
  1597. def type(self):
  1598. return type_api.NULLTYPE
  1599. @property
  1600. def comparator(self):
  1601. return self.type.comparator_factory(self)
  1602. def self_group(self, against=None):
  1603. if against is operators.in_op:
  1604. return Grouping(self)
  1605. else:
  1606. return self
  1607. class Null(SingletonConstant, roles.ConstExprRole, ColumnElement):
  1608. """Represent the NULL keyword in a SQL statement.
  1609. :class:`.Null` is accessed as a constant via the
  1610. :func:`.null` function.
  1611. """
  1612. __visit_name__ = "null"
  1613. _traverse_internals = []
  1614. @util.memoized_property
  1615. def type(self):
  1616. return type_api.NULLTYPE
  1617. @classmethod
  1618. def _instance(cls):
  1619. """Return a constant :class:`.Null` construct."""
  1620. return Null()
  1621. Null._create_singleton()
  1622. class False_(SingletonConstant, roles.ConstExprRole, ColumnElement):
  1623. """Represent the ``false`` keyword, or equivalent, in a SQL statement.
  1624. :class:`.False_` is accessed as a constant via the
  1625. :func:`.false` function.
  1626. """
  1627. __visit_name__ = "false"
  1628. _traverse_internals = []
  1629. @util.memoized_property
  1630. def type(self):
  1631. return type_api.BOOLEANTYPE
  1632. def _negate(self):
  1633. return True_()
  1634. @classmethod
  1635. def _instance(cls):
  1636. """Return a :class:`.False_` construct.
  1637. E.g.::
  1638. >>> from sqlalchemy import false
  1639. >>> print(select(t.c.x).where(false()))
  1640. SELECT x FROM t WHERE false
  1641. A backend which does not support true/false constants will render as
  1642. an expression against 1 or 0::
  1643. >>> print(select(t.c.x).where(false()))
  1644. SELECT x FROM t WHERE 0 = 1
  1645. The :func:`.true` and :func:`.false` constants also feature
  1646. "short circuit" operation within an :func:`.and_` or :func:`.or_`
  1647. conjunction::
  1648. >>> print(select(t.c.x).where(or_(t.c.x > 5, true())))
  1649. SELECT x FROM t WHERE true
  1650. >>> print(select(t.c.x).where(and_(t.c.x > 5, false())))
  1651. SELECT x FROM t WHERE false
  1652. .. versionchanged:: 0.9 :func:`.true` and :func:`.false` feature
  1653. better integrated behavior within conjunctions and on dialects
  1654. that don't support true/false constants.
  1655. .. seealso::
  1656. :func:`.true`
  1657. """
  1658. return False_()
  1659. False_._create_singleton()
  1660. class True_(SingletonConstant, roles.ConstExprRole, ColumnElement):
  1661. """Represent the ``true`` keyword, or equivalent, in a SQL statement.
  1662. :class:`.True_` is accessed as a constant via the
  1663. :func:`.true` function.
  1664. """
  1665. __visit_name__ = "true"
  1666. _traverse_internals = []
  1667. @util.memoized_property
  1668. def type(self):
  1669. return type_api.BOOLEANTYPE
  1670. def _negate(self):
  1671. return False_()
  1672. @classmethod
  1673. def _ifnone(cls, other):
  1674. if other is None:
  1675. return cls._instance()
  1676. else:
  1677. return other
  1678. @classmethod
  1679. def _instance(cls):
  1680. """Return a constant :class:`.True_` construct.
  1681. E.g.::
  1682. >>> from sqlalchemy import true
  1683. >>> print(select(t.c.x).where(true()))
  1684. SELECT x FROM t WHERE true
  1685. A backend which does not support true/false constants will render as
  1686. an expression against 1 or 0::
  1687. >>> print(select(t.c.x).where(true()))
  1688. SELECT x FROM t WHERE 1 = 1
  1689. The :func:`.true` and :func:`.false` constants also feature
  1690. "short circuit" operation within an :func:`.and_` or :func:`.or_`
  1691. conjunction::
  1692. >>> print(select(t.c.x).where(or_(t.c.x > 5, true())))
  1693. SELECT x FROM t WHERE true
  1694. >>> print(select(t.c.x).where(and_(t.c.x > 5, false())))
  1695. SELECT x FROM t WHERE false
  1696. .. versionchanged:: 0.9 :func:`.true` and :func:`.false` feature
  1697. better integrated behavior within conjunctions and on dialects
  1698. that don't support true/false constants.
  1699. .. seealso::
  1700. :func:`.false`
  1701. """
  1702. return True_()
  1703. True_._create_singleton()
  1704. class ClauseList(
  1705. roles.InElementRole,
  1706. roles.OrderByRole,
  1707. roles.ColumnsClauseRole,
  1708. roles.DMLColumnRole,
  1709. ClauseElement,
  1710. ):
  1711. """Describe a list of clauses, separated by an operator.
  1712. By default, is comma-separated, such as a column listing.
  1713. """
  1714. __visit_name__ = "clauselist"
  1715. _is_clause_list = True
  1716. _traverse_internals = [
  1717. ("clauses", InternalTraversal.dp_clauseelement_list),
  1718. ("operator", InternalTraversal.dp_operator),
  1719. ]
  1720. def __init__(self, *clauses, **kwargs):
  1721. self.operator = kwargs.pop("operator", operators.comma_op)
  1722. self.group = kwargs.pop("group", True)
  1723. self.group_contents = kwargs.pop("group_contents", True)
  1724. if kwargs.pop("_flatten_sub_clauses", False):
  1725. clauses = util.flatten_iterator(clauses)
  1726. self._text_converter_role = text_converter_role = kwargs.pop(
  1727. "_literal_as_text_role", roles.WhereHavingRole
  1728. )
  1729. if self.group_contents:
  1730. self.clauses = [
  1731. coercions.expect(
  1732. text_converter_role, clause, apply_propagate_attrs=self
  1733. ).self_group(against=self.operator)
  1734. for clause in clauses
  1735. ]
  1736. else:
  1737. self.clauses = [
  1738. coercions.expect(
  1739. text_converter_role, clause, apply_propagate_attrs=self
  1740. )
  1741. for clause in clauses
  1742. ]
  1743. self._is_implicitly_boolean = operators.is_boolean(self.operator)
  1744. @classmethod
  1745. def _construct_raw(cls, operator, clauses=None):
  1746. self = cls.__new__(cls)
  1747. self.clauses = clauses if clauses else []
  1748. self.group = True
  1749. self.operator = operator
  1750. self.group_contents = True
  1751. self._is_implicitly_boolean = False
  1752. return self
  1753. def __iter__(self):
  1754. return iter(self.clauses)
  1755. def __len__(self):
  1756. return len(self.clauses)
  1757. @property
  1758. def _select_iterable(self):
  1759. return itertools.chain.from_iterable(
  1760. [elem._select_iterable for elem in self.clauses]
  1761. )
  1762. def append(self, clause):
  1763. if self.group_contents:
  1764. self.clauses.append(
  1765. coercions.expect(self._text_converter_role, clause).self_group(
  1766. against=self.operator
  1767. )
  1768. )
  1769. else:
  1770. self.clauses.append(
  1771. coercions.expect(self._text_converter_role, clause)
  1772. )
  1773. @property
  1774. def _from_objects(self):
  1775. return list(itertools.chain(*[c._from_objects for c in self.clauses]))
  1776. def self_group(self, against=None):
  1777. if self.group and operators.is_precedent(self.operator, against):
  1778. return Grouping(self)
  1779. else:
  1780. return self
  1781. class BooleanClauseList(ClauseList, ColumnElement):
  1782. __visit_name__ = "clauselist"
  1783. inherit_cache = True
  1784. def __init__(self, *arg, **kw):
  1785. raise NotImplementedError(
  1786. "BooleanClauseList has a private constructor"
  1787. )
  1788. @classmethod
  1789. def _process_clauses_for_boolean(
  1790. cls, operator, continue_on, skip_on, clauses
  1791. ):
  1792. has_continue_on = None
  1793. convert_clauses = []
  1794. against = operators._asbool
  1795. lcc = 0
  1796. for clause in clauses:
  1797. if clause is continue_on:
  1798. # instance of continue_on, like and_(x, y, True, z), store it
  1799. # if we didn't find one already, we will use it if there
  1800. # are no other expressions here.
  1801. has_continue_on = clause
  1802. elif clause is skip_on:
  1803. # instance of skip_on, e.g. and_(x, y, False, z), cancels
  1804. # the rest out
  1805. convert_clauses = [clause]
  1806. lcc = 1
  1807. break
  1808. else:
  1809. if not lcc:
  1810. lcc = 1
  1811. else:
  1812. against = operator
  1813. # technically this would be len(convert_clauses) + 1
  1814. # however this only needs to indicate "greater than one"
  1815. lcc = 2
  1816. convert_clauses.append(clause)
  1817. if not convert_clauses and has_continue_on is not None:
  1818. convert_clauses = [has_continue_on]
  1819. lcc = 1
  1820. return lcc, [c.self_group(against=against) for c in convert_clauses]
  1821. @classmethod
  1822. def _construct(cls, operator, continue_on, skip_on, *clauses, **kw):
  1823. lcc, convert_clauses = cls._process_clauses_for_boolean(
  1824. operator,
  1825. continue_on,
  1826. skip_on,
  1827. [
  1828. coercions.expect(roles.WhereHavingRole, clause)
  1829. for clause in util.coerce_generator_arg(clauses)
  1830. ],
  1831. )
  1832. if lcc > 1:
  1833. # multiple elements. Return regular BooleanClauseList
  1834. # which will link elements against the operator.
  1835. return cls._construct_raw(operator, convert_clauses)
  1836. elif lcc == 1:
  1837. # just one element. return it as a single boolean element,
  1838. # not a list and discard the operator.
  1839. return convert_clauses[0]
  1840. else:
  1841. # no elements period. deprecated use case. return an empty
  1842. # ClauseList construct that generates nothing unless it has
  1843. # elements added to it.
  1844. util.warn_deprecated(
  1845. "Invoking %(name)s() without arguments is deprecated, and "
  1846. "will be disallowed in a future release. For an empty "
  1847. "%(name)s() construct, use %(name)s(%(continue_on)s, *args)."
  1848. % {
  1849. "name": operator.__name__,
  1850. "continue_on": "True"
  1851. if continue_on is True_._singleton
  1852. else "False",
  1853. },
  1854. version="1.4",
  1855. )
  1856. return cls._construct_raw(operator)
  1857. @classmethod
  1858. def _construct_for_whereclause(cls, clauses):
  1859. operator, continue_on, skip_on = (
  1860. operators.and_,
  1861. True_._singleton,
  1862. False_._singleton,
  1863. )
  1864. lcc, convert_clauses = cls._process_clauses_for_boolean(
  1865. operator,
  1866. continue_on,
  1867. skip_on,
  1868. clauses, # these are assumed to be coerced already
  1869. )
  1870. if lcc > 1:
  1871. # multiple elements. Return regular BooleanClauseList
  1872. # which will link elements against the operator.
  1873. return cls._construct_raw(operator, convert_clauses)
  1874. elif lcc == 1:
  1875. # just one element. return it as a single boolean element,
  1876. # not a list and discard the operator.
  1877. return convert_clauses[0]
  1878. else:
  1879. return None
  1880. @classmethod
  1881. def _construct_raw(cls, operator, clauses=None):
  1882. self = cls.__new__(cls)
  1883. self.clauses = clauses if clauses else []
  1884. self.group = True
  1885. self.operator = operator
  1886. self.group_contents = True
  1887. self.type = type_api.BOOLEANTYPE
  1888. self._is_implicitly_boolean = True
  1889. return self
  1890. @classmethod
  1891. def and_(cls, *clauses):
  1892. r"""Produce a conjunction of expressions joined by ``AND``.
  1893. E.g.::
  1894. from sqlalchemy import and_
  1895. stmt = select(users_table).where(
  1896. and_(
  1897. users_table.c.name == 'wendy',
  1898. users_table.c.enrolled == True
  1899. )
  1900. )
  1901. The :func:`.and_` conjunction is also available using the
  1902. Python ``&`` operator (though note that compound expressions
  1903. need to be parenthesized in order to function with Python
  1904. operator precedence behavior)::
  1905. stmt = select(users_table).where(
  1906. (users_table.c.name == 'wendy') &
  1907. (users_table.c.enrolled == True)
  1908. )
  1909. The :func:`.and_` operation is also implicit in some cases;
  1910. the :meth:`_expression.Select.where`
  1911. method for example can be invoked multiple
  1912. times against a statement, which will have the effect of each
  1913. clause being combined using :func:`.and_`::
  1914. stmt = select(users_table).\
  1915. where(users_table.c.name == 'wendy').\
  1916. where(users_table.c.enrolled == True)
  1917. The :func:`.and_` construct must be given at least one positional
  1918. argument in order to be valid; a :func:`.and_` construct with no
  1919. arguments is ambiguous. To produce an "empty" or dynamically
  1920. generated :func:`.and_` expression, from a given list of expressions,
  1921. a "default" element of ``True`` should be specified::
  1922. criteria = and_(True, *expressions)
  1923. The above expression will compile to SQL as the expression ``true``
  1924. or ``1 = 1``, depending on backend, if no other expressions are
  1925. present. If expressions are present, then the ``True`` value is
  1926. ignored as it does not affect the outcome of an AND expression that
  1927. has other elements.
  1928. .. deprecated:: 1.4 The :func:`.and_` element now requires that at
  1929. least one argument is passed; creating the :func:`.and_` construct
  1930. with no arguments is deprecated, and will emit a deprecation warning
  1931. while continuing to produce a blank SQL string.
  1932. .. seealso::
  1933. :func:`.or_`
  1934. """
  1935. return cls._construct(
  1936. operators.and_, True_._singleton, False_._singleton, *clauses
  1937. )
  1938. @classmethod
  1939. def or_(cls, *clauses):
  1940. """Produce a conjunction of expressions joined by ``OR``.
  1941. E.g.::
  1942. from sqlalchemy import or_
  1943. stmt = select(users_table).where(
  1944. or_(
  1945. users_table.c.name == 'wendy',
  1946. users_table.c.name == 'jack'
  1947. )
  1948. )
  1949. The :func:`.or_` conjunction is also available using the
  1950. Python ``|`` operator (though note that compound expressions
  1951. need to be parenthesized in order to function with Python
  1952. operator precedence behavior)::
  1953. stmt = select(users_table).where(
  1954. (users_table.c.name == 'wendy') |
  1955. (users_table.c.name == 'jack')
  1956. )
  1957. The :func:`.or_` construct must be given at least one positional
  1958. argument in order to be valid; a :func:`.or_` construct with no
  1959. arguments is ambiguous. To produce an "empty" or dynamically
  1960. generated :func:`.or_` expression, from a given list of expressions,
  1961. a "default" element of ``False`` should be specified::
  1962. or_criteria = or_(False, *expressions)
  1963. The above expression will compile to SQL as the expression ``false``
  1964. or ``0 = 1``, depending on backend, if no other expressions are
  1965. present. If expressions are present, then the ``False`` value is
  1966. ignored as it does not affect the outcome of an OR expression which
  1967. has other elements.
  1968. .. deprecated:: 1.4 The :func:`.or_` element now requires that at
  1969. least one argument is passed; creating the :func:`.or_` construct
  1970. with no arguments is deprecated, and will emit a deprecation warning
  1971. while continuing to produce a blank SQL string.
  1972. .. seealso::
  1973. :func:`.and_`
  1974. """
  1975. return cls._construct(
  1976. operators.or_, False_._singleton, True_._singleton, *clauses
  1977. )
  1978. @property
  1979. def _select_iterable(self):
  1980. return (self,)
  1981. def self_group(self, against=None):
  1982. if not self.clauses:
  1983. return self
  1984. else:
  1985. return super(BooleanClauseList, self).self_group(against=against)
  1986. def _negate(self):
  1987. return ClauseList._negate(self)
  1988. and_ = BooleanClauseList.and_
  1989. or_ = BooleanClauseList.or_
  1990. class Tuple(ClauseList, ColumnElement):
  1991. """Represent a SQL tuple."""
  1992. __visit_name__ = "tuple"
  1993. _traverse_internals = ClauseList._traverse_internals + []
  1994. @util.preload_module("sqlalchemy.sql.sqltypes")
  1995. def __init__(self, *clauses, **kw):
  1996. """Return a :class:`.Tuple`.
  1997. Main usage is to produce a composite IN construct using
  1998. :meth:`.ColumnOperators.in_` ::
  1999. from sqlalchemy import tuple_
  2000. tuple_(table.c.col1, table.c.col2).in_(
  2001. [(1, 2), (5, 12), (10, 19)]
  2002. )
  2003. .. versionchanged:: 1.3.6 Added support for SQLite IN tuples.
  2004. .. warning::
  2005. The composite IN construct is not supported by all backends, and is
  2006. currently known to work on PostgreSQL, MySQL, and SQLite.
  2007. Unsupported backends will raise a subclass of
  2008. :class:`~sqlalchemy.exc.DBAPIError` when such an expression is
  2009. invoked.
  2010. """
  2011. sqltypes = util.preloaded.sql_sqltypes
  2012. types = kw.pop("types", None)
  2013. if types is None:
  2014. clauses = [
  2015. coercions.expect(roles.ExpressionElementRole, c)
  2016. for c in clauses
  2017. ]
  2018. else:
  2019. if len(types) != len(clauses):
  2020. raise exc.ArgumentError(
  2021. "Wrong number of elements for %d-tuple: %r "
  2022. % (len(types), clauses)
  2023. )
  2024. clauses = [
  2025. coercions.expect(
  2026. roles.ExpressionElementRole,
  2027. c,
  2028. type_=typ if not typ._isnull else None,
  2029. )
  2030. for typ, c in zip(types, clauses)
  2031. ]
  2032. self.type = sqltypes.TupleType(*[arg.type for arg in clauses])
  2033. super(Tuple, self).__init__(*clauses, **kw)
  2034. @property
  2035. def _select_iterable(self):
  2036. return (self,)
  2037. def _bind_param(self, operator, obj, type_=None, expanding=False):
  2038. if expanding:
  2039. return BindParameter(
  2040. None,
  2041. value=obj,
  2042. _compared_to_operator=operator,
  2043. unique=True,
  2044. expanding=True,
  2045. type_=self.type,
  2046. )
  2047. else:
  2048. return Tuple(
  2049. *[
  2050. BindParameter(
  2051. None,
  2052. o,
  2053. _compared_to_operator=operator,
  2054. _compared_to_type=compared_to_type,
  2055. unique=True,
  2056. type_=type_,
  2057. )
  2058. for o, compared_to_type in zip(obj, self.type.types)
  2059. ]
  2060. )
  2061. def self_group(self, against=None):
  2062. # Tuple is parenthesized by definition.
  2063. return self
  2064. class Case(ColumnElement):
  2065. """Represent a ``CASE`` expression.
  2066. :class:`.Case` is produced using the :func:`.case` factory function,
  2067. as in::
  2068. from sqlalchemy import case
  2069. stmt = select(users_table).\
  2070. where(
  2071. case(
  2072. (users_table.c.name == 'wendy', 'W'),
  2073. (users_table.c.name == 'jack', 'J'),
  2074. else_='E'
  2075. )
  2076. )
  2077. Details on :class:`.Case` usage is at :func:`.case`.
  2078. .. seealso::
  2079. :func:`.case`
  2080. """
  2081. __visit_name__ = "case"
  2082. _traverse_internals = [
  2083. ("value", InternalTraversal.dp_clauseelement),
  2084. ("whens", InternalTraversal.dp_clauseelement_tuples),
  2085. ("else_", InternalTraversal.dp_clauseelement),
  2086. ]
  2087. # TODO: for Py2k removal, this will be:
  2088. # def __init__(self, *whens, value=None, else_=None):
  2089. def __init__(self, *whens, **kw):
  2090. r"""Produce a ``CASE`` expression.
  2091. The ``CASE`` construct in SQL is a conditional object that
  2092. acts somewhat analogously to an "if/then" construct in other
  2093. languages. It returns an instance of :class:`.Case`.
  2094. :func:`.case` in its usual form is passed a series of "when"
  2095. constructs, that is, a list of conditions and results as tuples::
  2096. from sqlalchemy import case
  2097. stmt = select(users_table).\
  2098. where(
  2099. case(
  2100. (users_table.c.name == 'wendy', 'W'),
  2101. (users_table.c.name == 'jack', 'J'),
  2102. else_='E'
  2103. )
  2104. )
  2105. The above statement will produce SQL resembling::
  2106. SELECT id, name FROM user
  2107. WHERE CASE
  2108. WHEN (name = :name_1) THEN :param_1
  2109. WHEN (name = :name_2) THEN :param_2
  2110. ELSE :param_3
  2111. END
  2112. When simple equality expressions of several values against a single
  2113. parent column are needed, :func:`.case` also has a "shorthand" format
  2114. used via the
  2115. :paramref:`.case.value` parameter, which is passed a column
  2116. expression to be compared. In this form, the :paramref:`.case.whens`
  2117. parameter is passed as a dictionary containing expressions to be
  2118. compared against keyed to result expressions. The statement below is
  2119. equivalent to the preceding statement::
  2120. stmt = select(users_table).\
  2121. where(
  2122. case(
  2123. whens={"wendy": "W", "jack": "J"},
  2124. value=users_table.c.name,
  2125. else_='E'
  2126. )
  2127. )
  2128. The values which are accepted as result values in
  2129. :paramref:`.case.whens` as well as with :paramref:`.case.else_` are
  2130. coerced from Python literals into :func:`.bindparam` constructs.
  2131. SQL expressions, e.g. :class:`_expression.ColumnElement` constructs,
  2132. are accepted
  2133. as well. To coerce a literal string expression into a constant
  2134. expression rendered inline, use the :func:`_expression.literal_column`
  2135. construct,
  2136. as in::
  2137. from sqlalchemy import case, literal_column
  2138. case(
  2139. (
  2140. orderline.c.qty > 100,
  2141. literal_column("'greaterthan100'")
  2142. ),
  2143. (
  2144. orderline.c.qty > 10,
  2145. literal_column("'greaterthan10'")
  2146. ),
  2147. else_=literal_column("'lessthan10'")
  2148. )
  2149. The above will render the given constants without using bound
  2150. parameters for the result values (but still for the comparison
  2151. values), as in::
  2152. CASE
  2153. WHEN (orderline.qty > :qty_1) THEN 'greaterthan100'
  2154. WHEN (orderline.qty > :qty_2) THEN 'greaterthan10'
  2155. ELSE 'lessthan10'
  2156. END
  2157. :param \*whens: The criteria to be compared against,
  2158. :paramref:`.case.whens` accepts two different forms, based on
  2159. whether or not :paramref:`.case.value` is used.
  2160. .. versionchanged:: 1.4 the :func:`_sql.case`
  2161. function now accepts the series of WHEN conditions positionally;
  2162. passing the expressions within a list is deprecated.
  2163. In the first form, it accepts a list of 2-tuples; each 2-tuple
  2164. consists of ``(<sql expression>, <value>)``, where the SQL
  2165. expression is a boolean expression and "value" is a resulting value,
  2166. e.g.::
  2167. case(
  2168. (users_table.c.name == 'wendy', 'W'),
  2169. (users_table.c.name == 'jack', 'J')
  2170. )
  2171. In the second form, it accepts a Python dictionary of comparison
  2172. values mapped to a resulting value; this form requires
  2173. :paramref:`.case.value` to be present, and values will be compared
  2174. using the ``==`` operator, e.g.::
  2175. case(
  2176. {"wendy": "W", "jack": "J"},
  2177. value=users_table.c.name
  2178. )
  2179. :param value: An optional SQL expression which will be used as a
  2180. fixed "comparison point" for candidate values within a dictionary
  2181. passed to :paramref:`.case.whens`.
  2182. :param else\_: An optional SQL expression which will be the evaluated
  2183. result of the ``CASE`` construct if all expressions within
  2184. :paramref:`.case.whens` evaluate to false. When omitted, most
  2185. databases will produce a result of NULL if none of the "when"
  2186. expressions evaluate to true.
  2187. """
  2188. if "whens" in kw:
  2189. util.warn_deprecated_20(
  2190. 'The "whens" argument to case() is now passed as a series of '
  2191. "positional "
  2192. "elements, rather than as a list. "
  2193. )
  2194. whens = kw.pop("whens")
  2195. else:
  2196. whens = coercions._expression_collection_was_a_list(
  2197. "whens", "case", whens
  2198. )
  2199. try:
  2200. whens = util.dictlike_iteritems(whens)
  2201. except TypeError:
  2202. pass
  2203. value = kw.pop("value", None)
  2204. if value is not None:
  2205. whenlist = [
  2206. (
  2207. coercions.expect(
  2208. roles.ExpressionElementRole,
  2209. c,
  2210. apply_propagate_attrs=self,
  2211. ).self_group(),
  2212. coercions.expect(roles.ExpressionElementRole, r),
  2213. )
  2214. for (c, r) in whens
  2215. ]
  2216. else:
  2217. whenlist = [
  2218. (
  2219. coercions.expect(
  2220. roles.ColumnArgumentRole, c, apply_propagate_attrs=self
  2221. ).self_group(),
  2222. coercions.expect(roles.ExpressionElementRole, r),
  2223. )
  2224. for (c, r) in whens
  2225. ]
  2226. if whenlist:
  2227. type_ = list(whenlist[-1])[-1].type
  2228. else:
  2229. type_ = None
  2230. if value is None:
  2231. self.value = None
  2232. else:
  2233. self.value = coercions.expect(roles.ExpressionElementRole, value)
  2234. self.type = type_
  2235. self.whens = whenlist
  2236. else_ = kw.pop("else_", None)
  2237. if else_ is not None:
  2238. self.else_ = coercions.expect(roles.ExpressionElementRole, else_)
  2239. else:
  2240. self.else_ = None
  2241. if kw:
  2242. raise TypeError("unknown arguments: %s" % (", ".join(sorted(kw))))
  2243. @property
  2244. def _from_objects(self):
  2245. return list(
  2246. itertools.chain(*[x._from_objects for x in self.get_children()])
  2247. )
  2248. def literal_column(text, type_=None):
  2249. r"""Produce a :class:`.ColumnClause` object that has the
  2250. :paramref:`_expression.column.is_literal` flag set to True.
  2251. :func:`_expression.literal_column` is similar to
  2252. :func:`_expression.column`, except that
  2253. it is more often used as a "standalone" column expression that renders
  2254. exactly as stated; while :func:`_expression.column`
  2255. stores a string name that
  2256. will be assumed to be part of a table and may be quoted as such,
  2257. :func:`_expression.literal_column` can be that,
  2258. or any other arbitrary column-oriented
  2259. expression.
  2260. :param text: the text of the expression; can be any SQL expression.
  2261. Quoting rules will not be applied. To specify a column-name expression
  2262. which should be subject to quoting rules, use the :func:`column`
  2263. function.
  2264. :param type\_: an optional :class:`~sqlalchemy.types.TypeEngine`
  2265. object which will
  2266. provide result-set translation and additional expression semantics for
  2267. this column. If left as ``None`` the type will be :class:`.NullType`.
  2268. .. seealso::
  2269. :func:`_expression.column`
  2270. :func:`_expression.text`
  2271. :ref:`sqlexpression_literal_column`
  2272. """
  2273. return ColumnClause(text, type_=type_, is_literal=True)
  2274. class Cast(WrapsColumnExpression, ColumnElement):
  2275. """Represent a ``CAST`` expression.
  2276. :class:`.Cast` is produced using the :func:`.cast` factory function,
  2277. as in::
  2278. from sqlalchemy import cast, Numeric
  2279. stmt = select(cast(product_table.c.unit_price, Numeric(10, 4)))
  2280. Details on :class:`.Cast` usage is at :func:`.cast`.
  2281. .. seealso::
  2282. :ref:`coretutorial_casts`
  2283. :func:`.cast`
  2284. :func:`.type_coerce` - an alternative to CAST that coerces the type
  2285. on the Python side only, which is often sufficient to generate the
  2286. correct SQL and data coercion.
  2287. """
  2288. __visit_name__ = "cast"
  2289. _traverse_internals = [
  2290. ("clause", InternalTraversal.dp_clauseelement),
  2291. ("typeclause", InternalTraversal.dp_clauseelement),
  2292. ]
  2293. def __init__(self, expression, type_):
  2294. r"""Produce a ``CAST`` expression.
  2295. :func:`.cast` returns an instance of :class:`.Cast`.
  2296. E.g.::
  2297. from sqlalchemy import cast, Numeric
  2298. stmt = select(cast(product_table.c.unit_price, Numeric(10, 4)))
  2299. The above statement will produce SQL resembling::
  2300. SELECT CAST(unit_price AS NUMERIC(10, 4)) FROM product
  2301. The :func:`.cast` function performs two distinct functions when
  2302. used. The first is that it renders the ``CAST`` expression within
  2303. the resulting SQL string. The second is that it associates the given
  2304. type (e.g. :class:`.TypeEngine` class or instance) with the column
  2305. expression on the Python side, which means the expression will take
  2306. on the expression operator behavior associated with that type,
  2307. as well as the bound-value handling and result-row-handling behavior
  2308. of the type.
  2309. .. versionchanged:: 0.9.0 :func:`.cast` now applies the given type
  2310. to the expression such that it takes effect on the bound-value,
  2311. e.g. the Python-to-database direction, in addition to the
  2312. result handling, e.g. database-to-Python, direction.
  2313. An alternative to :func:`.cast` is the :func:`.type_coerce` function.
  2314. This function performs the second task of associating an expression
  2315. with a specific type, but does not render the ``CAST`` expression
  2316. in SQL.
  2317. :param expression: A SQL expression, such as a
  2318. :class:`_expression.ColumnElement`
  2319. expression or a Python string which will be coerced into a bound
  2320. literal value.
  2321. :param type\_: A :class:`.TypeEngine` class or instance indicating
  2322. the type to which the ``CAST`` should apply.
  2323. .. seealso::
  2324. :ref:`coretutorial_casts`
  2325. :func:`.type_coerce` - an alternative to CAST that coerces the type
  2326. on the Python side only, which is often sufficient to generate the
  2327. correct SQL and data coercion.
  2328. """
  2329. self.type = type_api.to_instance(type_)
  2330. self.clause = coercions.expect(
  2331. roles.ExpressionElementRole,
  2332. expression,
  2333. type_=self.type,
  2334. apply_propagate_attrs=self,
  2335. )
  2336. self.typeclause = TypeClause(self.type)
  2337. @property
  2338. def _from_objects(self):
  2339. return self.clause._from_objects
  2340. @property
  2341. def wrapped_column_expression(self):
  2342. return self.clause
  2343. class TypeCoerce(WrapsColumnExpression, ColumnElement):
  2344. """Represent a Python-side type-coercion wrapper.
  2345. :class:`.TypeCoerce` supplies the :func:`_expression.type_coerce`
  2346. function; see that function for usage details.
  2347. .. versionchanged:: 1.1 The :func:`.type_coerce` function now produces
  2348. a persistent :class:`.TypeCoerce` wrapper object rather than
  2349. translating the given object in place.
  2350. .. seealso::
  2351. :func:`_expression.type_coerce`
  2352. :func:`.cast`
  2353. """
  2354. __visit_name__ = "type_coerce"
  2355. _traverse_internals = [
  2356. ("clause", InternalTraversal.dp_clauseelement),
  2357. ("type", InternalTraversal.dp_type),
  2358. ]
  2359. def __init__(self, expression, type_):
  2360. r"""Associate a SQL expression with a particular type, without rendering
  2361. ``CAST``.
  2362. E.g.::
  2363. from sqlalchemy import type_coerce
  2364. stmt = select(type_coerce(log_table.date_string, StringDateTime()))
  2365. The above construct will produce a :class:`.TypeCoerce` object, which
  2366. does not modify the rendering in any way on the SQL side, with the
  2367. possible exception of a generated label if used in a columns clause
  2368. context::
  2369. SELECT date_string AS date_string FROM log
  2370. When result rows are fetched, the ``StringDateTime`` type processor
  2371. will be applied to result rows on behalf of the ``date_string`` column.
  2372. .. note:: the :func:`.type_coerce` construct does not render any
  2373. SQL syntax of its own, including that it does not imply
  2374. parenthesization. Please use :meth:`.TypeCoerce.self_group`
  2375. if explicit parenthesization is required.
  2376. In order to provide a named label for the expression, use
  2377. :meth:`_expression.ColumnElement.label`::
  2378. stmt = select(
  2379. type_coerce(log_table.date_string, StringDateTime()).label('date')
  2380. )
  2381. A type that features bound-value handling will also have that behavior
  2382. take effect when literal values or :func:`.bindparam` constructs are
  2383. passed to :func:`.type_coerce` as targets.
  2384. For example, if a type implements the
  2385. :meth:`.TypeEngine.bind_expression`
  2386. method or :meth:`.TypeEngine.bind_processor` method or equivalent,
  2387. these functions will take effect at statement compilation/execution
  2388. time when a literal value is passed, as in::
  2389. # bound-value handling of MyStringType will be applied to the
  2390. # literal value "some string"
  2391. stmt = select(type_coerce("some string", MyStringType))
  2392. When using :func:`.type_coerce` with composed expressions, note that
  2393. **parenthesis are not applied**. If :func:`.type_coerce` is being
  2394. used in an operator context where the parenthesis normally present from
  2395. CAST are necessary, use the :meth:`.TypeCoerce.self_group` method::
  2396. >>> some_integer = column("someint", Integer)
  2397. >>> some_string = column("somestr", String)
  2398. >>> expr = type_coerce(some_integer + 5, String) + some_string
  2399. >>> print(expr)
  2400. someint + :someint_1 || somestr
  2401. >>> expr = type_coerce(some_integer + 5, String).self_group() + some_string
  2402. >>> print(expr)
  2403. (someint + :someint_1) || somestr
  2404. :param expression: A SQL expression, such as a
  2405. :class:`_expression.ColumnElement`
  2406. expression or a Python string which will be coerced into a bound
  2407. literal value.
  2408. :param type\_: A :class:`.TypeEngine` class or instance indicating
  2409. the type to which the expression is coerced.
  2410. .. seealso::
  2411. :ref:`coretutorial_casts`
  2412. :func:`.cast`
  2413. """ # noqa
  2414. self.type = type_api.to_instance(type_)
  2415. self.clause = coercions.expect(
  2416. roles.ExpressionElementRole,
  2417. expression,
  2418. type_=self.type,
  2419. apply_propagate_attrs=self,
  2420. )
  2421. @property
  2422. def _from_objects(self):
  2423. return self.clause._from_objects
  2424. @HasMemoized.memoized_attribute
  2425. def typed_expression(self):
  2426. if isinstance(self.clause, BindParameter):
  2427. bp = self.clause._clone()
  2428. bp.type = self.type
  2429. return bp
  2430. else:
  2431. return self.clause
  2432. @property
  2433. def wrapped_column_expression(self):
  2434. return self.clause
  2435. def self_group(self, against=None):
  2436. grouped = self.clause.self_group(against=against)
  2437. if grouped is not self.clause:
  2438. return TypeCoerce(grouped, self.type)
  2439. else:
  2440. return self
  2441. class Extract(ColumnElement):
  2442. """Represent a SQL EXTRACT clause, ``extract(field FROM expr)``."""
  2443. __visit_name__ = "extract"
  2444. _traverse_internals = [
  2445. ("expr", InternalTraversal.dp_clauseelement),
  2446. ("field", InternalTraversal.dp_string),
  2447. ]
  2448. def __init__(self, field, expr, **kwargs):
  2449. """Return a :class:`.Extract` construct.
  2450. This is typically available as :func:`.extract`
  2451. as well as ``func.extract`` from the
  2452. :data:`.func` namespace.
  2453. """
  2454. self.type = type_api.INTEGERTYPE
  2455. self.field = field
  2456. self.expr = coercions.expect(roles.ExpressionElementRole, expr)
  2457. @property
  2458. def _from_objects(self):
  2459. return self.expr._from_objects
  2460. class _label_reference(ColumnElement):
  2461. """Wrap a column expression as it appears in a 'reference' context.
  2462. This expression is any that includes an _order_by_label_element,
  2463. which is a Label, or a DESC / ASC construct wrapping a Label.
  2464. The production of _label_reference() should occur when an expression
  2465. is added to this context; this includes the ORDER BY or GROUP BY of a
  2466. SELECT statement, as well as a few other places, such as the ORDER BY
  2467. within an OVER clause.
  2468. """
  2469. __visit_name__ = "label_reference"
  2470. _traverse_internals = [("element", InternalTraversal.dp_clauseelement)]
  2471. def __init__(self, element):
  2472. self.element = element
  2473. @property
  2474. def _from_objects(self):
  2475. return ()
  2476. class _textual_label_reference(ColumnElement):
  2477. __visit_name__ = "textual_label_reference"
  2478. _traverse_internals = [("element", InternalTraversal.dp_string)]
  2479. def __init__(self, element):
  2480. self.element = element
  2481. @util.memoized_property
  2482. def _text_clause(self):
  2483. return TextClause._create_text(self.element)
  2484. class UnaryExpression(ColumnElement):
  2485. """Define a 'unary' expression.
  2486. A unary expression has a single column expression
  2487. and an operator. The operator can be placed on the left
  2488. (where it is called the 'operator') or right (where it is called the
  2489. 'modifier') of the column expression.
  2490. :class:`.UnaryExpression` is the basis for several unary operators
  2491. including those used by :func:`.desc`, :func:`.asc`, :func:`.distinct`,
  2492. :func:`.nulls_first` and :func:`.nulls_last`.
  2493. """
  2494. __visit_name__ = "unary"
  2495. _traverse_internals = [
  2496. ("element", InternalTraversal.dp_clauseelement),
  2497. ("operator", InternalTraversal.dp_operator),
  2498. ("modifier", InternalTraversal.dp_operator),
  2499. ]
  2500. def __init__(
  2501. self,
  2502. element,
  2503. operator=None,
  2504. modifier=None,
  2505. type_=None,
  2506. wraps_column_expression=False,
  2507. ):
  2508. self.operator = operator
  2509. self.modifier = modifier
  2510. self._propagate_attrs = element._propagate_attrs
  2511. self.element = element.self_group(
  2512. against=self.operator or self.modifier
  2513. )
  2514. self.type = type_api.to_instance(type_)
  2515. self.wraps_column_expression = wraps_column_expression
  2516. @classmethod
  2517. def _create_nulls_first(cls, column):
  2518. """Produce the ``NULLS FIRST`` modifier for an ``ORDER BY`` expression.
  2519. :func:`.nulls_first` is intended to modify the expression produced
  2520. by :func:`.asc` or :func:`.desc`, and indicates how NULL values
  2521. should be handled when they are encountered during ordering::
  2522. from sqlalchemy import desc, nulls_first
  2523. stmt = select(users_table).order_by(
  2524. nulls_first(desc(users_table.c.name)))
  2525. The SQL expression from the above would resemble::
  2526. SELECT id, name FROM user ORDER BY name DESC NULLS FIRST
  2527. Like :func:`.asc` and :func:`.desc`, :func:`.nulls_first` is typically
  2528. invoked from the column expression itself using
  2529. :meth:`_expression.ColumnElement.nulls_first`,
  2530. rather than as its standalone
  2531. function version, as in::
  2532. stmt = select(users_table).order_by(
  2533. users_table.c.name.desc().nulls_first())
  2534. .. versionchanged:: 1.4 :func:`.nulls_first` is renamed from
  2535. :func:`.nullsfirst` in previous releases.
  2536. The previous name remains available for backwards compatibility.
  2537. .. seealso::
  2538. :func:`.asc`
  2539. :func:`.desc`
  2540. :func:`.nulls_last`
  2541. :meth:`_expression.Select.order_by`
  2542. """
  2543. return UnaryExpression(
  2544. coercions.expect(roles.ByOfRole, column),
  2545. modifier=operators.nulls_first_op,
  2546. wraps_column_expression=False,
  2547. )
  2548. @classmethod
  2549. def _create_nulls_last(cls, column):
  2550. """Produce the ``NULLS LAST`` modifier for an ``ORDER BY`` expression.
  2551. :func:`.nulls_last` is intended to modify the expression produced
  2552. by :func:`.asc` or :func:`.desc`, and indicates how NULL values
  2553. should be handled when they are encountered during ordering::
  2554. from sqlalchemy import desc, nulls_last
  2555. stmt = select(users_table).order_by(
  2556. nulls_last(desc(users_table.c.name)))
  2557. The SQL expression from the above would resemble::
  2558. SELECT id, name FROM user ORDER BY name DESC NULLS LAST
  2559. Like :func:`.asc` and :func:`.desc`, :func:`.nulls_last` is typically
  2560. invoked from the column expression itself using
  2561. :meth:`_expression.ColumnElement.nulls_last`,
  2562. rather than as its standalone
  2563. function version, as in::
  2564. stmt = select(users_table).order_by(
  2565. users_table.c.name.desc().nulls_last())
  2566. .. versionchanged:: 1.4 :func:`.nulls_last` is renamed from
  2567. :func:`.nullslast` in previous releases.
  2568. The previous name remains available for backwards compatibility.
  2569. .. seealso::
  2570. :func:`.asc`
  2571. :func:`.desc`
  2572. :func:`.nulls_first`
  2573. :meth:`_expression.Select.order_by`
  2574. """
  2575. return UnaryExpression(
  2576. coercions.expect(roles.ByOfRole, column),
  2577. modifier=operators.nulls_last_op,
  2578. wraps_column_expression=False,
  2579. )
  2580. @classmethod
  2581. def _create_desc(cls, column):
  2582. """Produce a descending ``ORDER BY`` clause element.
  2583. e.g.::
  2584. from sqlalchemy import desc
  2585. stmt = select(users_table).order_by(desc(users_table.c.name))
  2586. will produce SQL as::
  2587. SELECT id, name FROM user ORDER BY name DESC
  2588. The :func:`.desc` function is a standalone version of the
  2589. :meth:`_expression.ColumnElement.desc`
  2590. method available on all SQL expressions,
  2591. e.g.::
  2592. stmt = select(users_table).order_by(users_table.c.name.desc())
  2593. :param column: A :class:`_expression.ColumnElement` (e.g.
  2594. scalar SQL expression)
  2595. with which to apply the :func:`.desc` operation.
  2596. .. seealso::
  2597. :func:`.asc`
  2598. :func:`.nulls_first`
  2599. :func:`.nulls_last`
  2600. :meth:`_expression.Select.order_by`
  2601. """
  2602. return UnaryExpression(
  2603. coercions.expect(roles.ByOfRole, column),
  2604. modifier=operators.desc_op,
  2605. wraps_column_expression=False,
  2606. )
  2607. @classmethod
  2608. def _create_asc(cls, column):
  2609. """Produce an ascending ``ORDER BY`` clause element.
  2610. e.g.::
  2611. from sqlalchemy import asc
  2612. stmt = select(users_table).order_by(asc(users_table.c.name))
  2613. will produce SQL as::
  2614. SELECT id, name FROM user ORDER BY name ASC
  2615. The :func:`.asc` function is a standalone version of the
  2616. :meth:`_expression.ColumnElement.asc`
  2617. method available on all SQL expressions,
  2618. e.g.::
  2619. stmt = select(users_table).order_by(users_table.c.name.asc())
  2620. :param column: A :class:`_expression.ColumnElement` (e.g.
  2621. scalar SQL expression)
  2622. with which to apply the :func:`.asc` operation.
  2623. .. seealso::
  2624. :func:`.desc`
  2625. :func:`.nulls_first`
  2626. :func:`.nulls_last`
  2627. :meth:`_expression.Select.order_by`
  2628. """
  2629. return UnaryExpression(
  2630. coercions.expect(roles.ByOfRole, column),
  2631. modifier=operators.asc_op,
  2632. wraps_column_expression=False,
  2633. )
  2634. @classmethod
  2635. def _create_distinct(cls, expr):
  2636. """Produce an column-expression-level unary ``DISTINCT`` clause.
  2637. This applies the ``DISTINCT`` keyword to an individual column
  2638. expression, and is typically contained within an aggregate function,
  2639. as in::
  2640. from sqlalchemy import distinct, func
  2641. stmt = select(func.count(distinct(users_table.c.name)))
  2642. The above would produce an expression resembling::
  2643. SELECT COUNT(DISTINCT name) FROM user
  2644. The :func:`.distinct` function is also available as a column-level
  2645. method, e.g. :meth:`_expression.ColumnElement.distinct`, as in::
  2646. stmt = select(func.count(users_table.c.name.distinct()))
  2647. The :func:`.distinct` operator is different from the
  2648. :meth:`_expression.Select.distinct` method of
  2649. :class:`_expression.Select`,
  2650. which produces a ``SELECT`` statement
  2651. with ``DISTINCT`` applied to the result set as a whole,
  2652. e.g. a ``SELECT DISTINCT`` expression. See that method for further
  2653. information.
  2654. .. seealso::
  2655. :meth:`_expression.ColumnElement.distinct`
  2656. :meth:`_expression.Select.distinct`
  2657. :data:`.func`
  2658. """
  2659. expr = coercions.expect(roles.ExpressionElementRole, expr)
  2660. return UnaryExpression(
  2661. expr,
  2662. operator=operators.distinct_op,
  2663. type_=expr.type,
  2664. wraps_column_expression=False,
  2665. )
  2666. @property
  2667. def _order_by_label_element(self):
  2668. if self.modifier in (operators.desc_op, operators.asc_op):
  2669. return self.element._order_by_label_element
  2670. else:
  2671. return None
  2672. @property
  2673. def _from_objects(self):
  2674. return self.element._from_objects
  2675. def _negate(self):
  2676. if self.type._type_affinity is type_api.BOOLEANTYPE._type_affinity:
  2677. return UnaryExpression(
  2678. self.self_group(against=operators.inv),
  2679. operator=operators.inv,
  2680. type_=type_api.BOOLEANTYPE,
  2681. wraps_column_expression=self.wraps_column_expression,
  2682. )
  2683. else:
  2684. return ClauseElement._negate(self)
  2685. def self_group(self, against=None):
  2686. if self.operator and operators.is_precedent(self.operator, against):
  2687. return Grouping(self)
  2688. else:
  2689. return self
  2690. class CollectionAggregate(UnaryExpression):
  2691. """Forms the basis for right-hand collection operator modifiers
  2692. ANY and ALL.
  2693. The ANY and ALL keywords are available in different ways on different
  2694. backends. On PostgreSQL, they only work for an ARRAY type. On
  2695. MySQL, they only work for subqueries.
  2696. """
  2697. @classmethod
  2698. def _create_any(cls, expr):
  2699. """Produce an ANY expression.
  2700. This may apply to an array type for some dialects (e.g. postgresql),
  2701. or to a subquery for others (e.g. mysql). e.g.::
  2702. # postgresql '5 = ANY (somearray)'
  2703. expr = 5 == any_(mytable.c.somearray)
  2704. # mysql '5 = ANY (SELECT value FROM table)'
  2705. expr = 5 == any_(select(table.c.value))
  2706. The operator is more conveniently available from any
  2707. :class:`_sql.ColumnElement` object that makes use of the
  2708. :class:`_types.ARRAY` datatype::
  2709. expr = mytable.c.somearray.any(5)
  2710. .. seealso::
  2711. :func:`_expression.all_`
  2712. :meth:`_types.ARRAY.any`
  2713. """
  2714. expr = coercions.expect(roles.ExpressionElementRole, expr)
  2715. expr = expr.self_group()
  2716. return CollectionAggregate(
  2717. expr,
  2718. operator=operators.any_op,
  2719. type_=type_api.NULLTYPE,
  2720. wraps_column_expression=False,
  2721. )
  2722. @classmethod
  2723. def _create_all(cls, expr):
  2724. """Produce an ALL expression.
  2725. This may apply to an array type for some dialects (e.g. postgresql),
  2726. or to a subquery for others (e.g. mysql). e.g.::
  2727. # postgresql '5 = ALL (somearray)'
  2728. expr = 5 == all_(mytable.c.somearray)
  2729. # mysql '5 = ALL (SELECT value FROM table)'
  2730. expr = 5 == all_(select(table.c.value))
  2731. The operator is more conveniently available from any
  2732. :class:`_sql.ColumnElement` object that makes use of the
  2733. :class:`_types.ARRAY` datatype::
  2734. expr = mytable.c.somearray.all(5)
  2735. .. seealso::
  2736. :func:`_expression.any_`
  2737. :meth:`_types.ARRAY.Comparator.all`
  2738. """
  2739. expr = coercions.expect(roles.ExpressionElementRole, expr)
  2740. expr = expr.self_group()
  2741. return CollectionAggregate(
  2742. expr,
  2743. operator=operators.all_op,
  2744. type_=type_api.NULLTYPE,
  2745. wraps_column_expression=False,
  2746. )
  2747. # operate and reverse_operate are hardwired to
  2748. # dispatch onto the type comparator directly, so that we can
  2749. # ensure "reversed" behavior.
  2750. def operate(self, op, *other, **kwargs):
  2751. if not operators.is_comparison(op):
  2752. raise exc.ArgumentError(
  2753. "Only comparison operators may be used with ANY/ALL"
  2754. )
  2755. kwargs["reverse"] = True
  2756. return self.comparator.operate(operators.mirror(op), *other, **kwargs)
  2757. def reverse_operate(self, op, other, **kwargs):
  2758. # comparison operators should never call reverse_operate
  2759. assert not operators.is_comparison(op)
  2760. raise exc.ArgumentError(
  2761. "Only comparison operators may be used with ANY/ALL"
  2762. )
  2763. class AsBoolean(WrapsColumnExpression, UnaryExpression):
  2764. inherit_cache = True
  2765. def __init__(self, element, operator, negate):
  2766. self.element = element
  2767. self.type = type_api.BOOLEANTYPE
  2768. self.operator = operator
  2769. self.negate = negate
  2770. self.modifier = None
  2771. self.wraps_column_expression = True
  2772. self._is_implicitly_boolean = element._is_implicitly_boolean
  2773. @property
  2774. def wrapped_column_expression(self):
  2775. return self.element
  2776. def self_group(self, against=None):
  2777. return self
  2778. def _negate(self):
  2779. if isinstance(self.element, (True_, False_)):
  2780. return self.element._negate()
  2781. else:
  2782. return AsBoolean(self.element, self.negate, self.operator)
  2783. class BinaryExpression(ColumnElement):
  2784. """Represent an expression that is ``LEFT <operator> RIGHT``.
  2785. A :class:`.BinaryExpression` is generated automatically
  2786. whenever two column expressions are used in a Python binary expression::
  2787. >>> from sqlalchemy.sql import column
  2788. >>> column('a') + column('b')
  2789. <sqlalchemy.sql.expression.BinaryExpression object at 0x101029dd0>
  2790. >>> print(column('a') + column('b'))
  2791. a + b
  2792. """
  2793. __visit_name__ = "binary"
  2794. _traverse_internals = [
  2795. ("left", InternalTraversal.dp_clauseelement),
  2796. ("right", InternalTraversal.dp_clauseelement),
  2797. ("operator", InternalTraversal.dp_operator),
  2798. ("negate", InternalTraversal.dp_operator),
  2799. ("modifiers", InternalTraversal.dp_plain_dict),
  2800. (
  2801. "type",
  2802. InternalTraversal.dp_type,
  2803. ), # affects JSON CAST operators
  2804. ]
  2805. _is_implicitly_boolean = True
  2806. """Indicates that any database will know this is a boolean expression
  2807. even if the database does not have an explicit boolean datatype.
  2808. """
  2809. def __init__(
  2810. self, left, right, operator, type_=None, negate=None, modifiers=None
  2811. ):
  2812. # allow compatibility with libraries that
  2813. # refer to BinaryExpression directly and pass strings
  2814. if isinstance(operator, util.string_types):
  2815. operator = operators.custom_op(operator)
  2816. self._orig = (left.__hash__(), right.__hash__())
  2817. self._propagate_attrs = left._propagate_attrs or right._propagate_attrs
  2818. self.left = left.self_group(against=operator)
  2819. self.right = right.self_group(against=operator)
  2820. self.operator = operator
  2821. self.type = type_api.to_instance(type_)
  2822. self.negate = negate
  2823. self._is_implicitly_boolean = operators.is_boolean(operator)
  2824. if modifiers is None:
  2825. self.modifiers = {}
  2826. else:
  2827. self.modifiers = modifiers
  2828. def __bool__(self):
  2829. if self.operator in (operator.eq, operator.ne):
  2830. return self.operator(*self._orig)
  2831. else:
  2832. raise TypeError("Boolean value of this clause is not defined")
  2833. __nonzero__ = __bool__
  2834. @property
  2835. def is_comparison(self):
  2836. return operators.is_comparison(self.operator)
  2837. @property
  2838. def _from_objects(self):
  2839. return self.left._from_objects + self.right._from_objects
  2840. def self_group(self, against=None):
  2841. if operators.is_precedent(self.operator, against):
  2842. return Grouping(self)
  2843. else:
  2844. return self
  2845. def _negate(self):
  2846. if self.negate is not None:
  2847. return BinaryExpression(
  2848. self.left,
  2849. self.right._negate_in_binary(self.negate, self.operator),
  2850. self.negate,
  2851. negate=self.operator,
  2852. type_=self.type,
  2853. modifiers=self.modifiers,
  2854. )
  2855. else:
  2856. return super(BinaryExpression, self)._negate()
  2857. class Slice(ColumnElement):
  2858. """Represent SQL for a Python array-slice object.
  2859. This is not a specific SQL construct at this level, but
  2860. may be interpreted by specific dialects, e.g. PostgreSQL.
  2861. """
  2862. __visit_name__ = "slice"
  2863. _traverse_internals = [
  2864. ("start", InternalTraversal.dp_clauseelement),
  2865. ("stop", InternalTraversal.dp_clauseelement),
  2866. ("step", InternalTraversal.dp_clauseelement),
  2867. ]
  2868. def __init__(self, start, stop, step, _name=None):
  2869. self.start = coercions.expect(
  2870. roles.ExpressionElementRole,
  2871. start,
  2872. name=_name,
  2873. type_=type_api.INTEGERTYPE,
  2874. )
  2875. self.stop = coercions.expect(
  2876. roles.ExpressionElementRole,
  2877. stop,
  2878. name=_name,
  2879. type_=type_api.INTEGERTYPE,
  2880. )
  2881. self.step = coercions.expect(
  2882. roles.ExpressionElementRole,
  2883. step,
  2884. name=_name,
  2885. type_=type_api.INTEGERTYPE,
  2886. )
  2887. self.type = type_api.NULLTYPE
  2888. def self_group(self, against=None):
  2889. assert against is operator.getitem
  2890. return self
  2891. class IndexExpression(BinaryExpression):
  2892. """Represent the class of expressions that are like an "index"
  2893. operation."""
  2894. pass
  2895. class GroupedElement(ClauseElement):
  2896. """Represent any parenthesized expression"""
  2897. __visit_name__ = "grouping"
  2898. def self_group(self, against=None):
  2899. return self
  2900. def _ungroup(self):
  2901. return self.element._ungroup()
  2902. class Grouping(GroupedElement, ColumnElement):
  2903. """Represent a grouping within a column expression"""
  2904. _traverse_internals = [
  2905. ("element", InternalTraversal.dp_clauseelement),
  2906. ("type", InternalTraversal.dp_type),
  2907. ]
  2908. def __init__(self, element):
  2909. self.element = element
  2910. self.type = getattr(element, "type", type_api.NULLTYPE)
  2911. def _with_binary_element_type(self, type_):
  2912. return self.__class__(self.element._with_binary_element_type(type_))
  2913. @util.memoized_property
  2914. def _is_implicitly_boolean(self):
  2915. return self.element._is_implicitly_boolean
  2916. @property
  2917. def _key_label(self):
  2918. return self._label
  2919. @property
  2920. def _label(self):
  2921. return getattr(self.element, "_label", None) or self._anon_name_label
  2922. @property
  2923. def _proxies(self):
  2924. if isinstance(self.element, ColumnElement):
  2925. return [self.element]
  2926. else:
  2927. return []
  2928. @property
  2929. def _from_objects(self):
  2930. return self.element._from_objects
  2931. def __getattr__(self, attr):
  2932. return getattr(self.element, attr)
  2933. def __getstate__(self):
  2934. return {"element": self.element, "type": self.type}
  2935. def __setstate__(self, state):
  2936. self.element = state["element"]
  2937. self.type = state["type"]
  2938. RANGE_UNBOUNDED = util.symbol("RANGE_UNBOUNDED")
  2939. RANGE_CURRENT = util.symbol("RANGE_CURRENT")
  2940. class Over(ColumnElement):
  2941. """Represent an OVER clause.
  2942. This is a special operator against a so-called
  2943. "window" function, as well as any aggregate function,
  2944. which produces results relative to the result set
  2945. itself. Most modern SQL backends now support window functions.
  2946. """
  2947. __visit_name__ = "over"
  2948. _traverse_internals = [
  2949. ("element", InternalTraversal.dp_clauseelement),
  2950. ("order_by", InternalTraversal.dp_clauseelement),
  2951. ("partition_by", InternalTraversal.dp_clauseelement),
  2952. ("range_", InternalTraversal.dp_plain_obj),
  2953. ("rows", InternalTraversal.dp_plain_obj),
  2954. ]
  2955. order_by = None
  2956. partition_by = None
  2957. element = None
  2958. """The underlying expression object to which this :class:`.Over`
  2959. object refers towards."""
  2960. def __init__(
  2961. self, element, partition_by=None, order_by=None, range_=None, rows=None
  2962. ):
  2963. r"""Produce an :class:`.Over` object against a function.
  2964. Used against aggregate or so-called "window" functions,
  2965. for database backends that support window functions.
  2966. :func:`_expression.over` is usually called using
  2967. the :meth:`.FunctionElement.over` method, e.g.::
  2968. func.row_number().over(order_by=mytable.c.some_column)
  2969. Would produce::
  2970. ROW_NUMBER() OVER(ORDER BY some_column)
  2971. Ranges are also possible using the :paramref:`.expression.over.range_`
  2972. and :paramref:`.expression.over.rows` parameters. These
  2973. mutually-exclusive parameters each accept a 2-tuple, which contains
  2974. a combination of integers and None::
  2975. func.row_number().over(
  2976. order_by=my_table.c.some_column, range_=(None, 0))
  2977. The above would produce::
  2978. ROW_NUMBER() OVER(ORDER BY some_column
  2979. RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
  2980. A value of ``None`` indicates "unbounded", a
  2981. value of zero indicates "current row", and negative / positive
  2982. integers indicate "preceding" and "following":
  2983. * RANGE BETWEEN 5 PRECEDING AND 10 FOLLOWING::
  2984. func.row_number().over(order_by='x', range_=(-5, 10))
  2985. * ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW::
  2986. func.row_number().over(order_by='x', rows=(None, 0))
  2987. * RANGE BETWEEN 2 PRECEDING AND UNBOUNDED FOLLOWING::
  2988. func.row_number().over(order_by='x', range_=(-2, None))
  2989. * RANGE BETWEEN 1 FOLLOWING AND 3 FOLLOWING::
  2990. func.row_number().over(order_by='x', range_=(1, 3))
  2991. .. versionadded:: 1.1 support for RANGE / ROWS within a window
  2992. :param element: a :class:`.FunctionElement`, :class:`.WithinGroup`,
  2993. or other compatible construct.
  2994. :param partition_by: a column element or string, or a list
  2995. of such, that will be used as the PARTITION BY clause
  2996. of the OVER construct.
  2997. :param order_by: a column element or string, or a list
  2998. of such, that will be used as the ORDER BY clause
  2999. of the OVER construct.
  3000. :param range\_: optional range clause for the window. This is a
  3001. tuple value which can contain integer values or ``None``,
  3002. and will render a RANGE BETWEEN PRECEDING / FOLLOWING clause.
  3003. .. versionadded:: 1.1
  3004. :param rows: optional rows clause for the window. This is a tuple
  3005. value which can contain integer values or None, and will render
  3006. a ROWS BETWEEN PRECEDING / FOLLOWING clause.
  3007. .. versionadded:: 1.1
  3008. This function is also available from the :data:`~.expression.func`
  3009. construct itself via the :meth:`.FunctionElement.over` method.
  3010. .. seealso::
  3011. :ref:`tutorial_window_functions` - in the :ref:`unified_tutorial`
  3012. :data:`.expression.func`
  3013. :func:`_expression.within_group`
  3014. """
  3015. self.element = element
  3016. if order_by is not None:
  3017. self.order_by = ClauseList(
  3018. *util.to_list(order_by), _literal_as_text_role=roles.ByOfRole
  3019. )
  3020. if partition_by is not None:
  3021. self.partition_by = ClauseList(
  3022. *util.to_list(partition_by),
  3023. _literal_as_text_role=roles.ByOfRole
  3024. )
  3025. if range_:
  3026. self.range_ = self._interpret_range(range_)
  3027. if rows:
  3028. raise exc.ArgumentError(
  3029. "'range_' and 'rows' are mutually exclusive"
  3030. )
  3031. else:
  3032. self.rows = None
  3033. elif rows:
  3034. self.rows = self._interpret_range(rows)
  3035. self.range_ = None
  3036. else:
  3037. self.rows = self.range_ = None
  3038. def __reduce__(self):
  3039. return self.__class__, (
  3040. self.element,
  3041. self.partition_by,
  3042. self.order_by,
  3043. self.range_,
  3044. self.rows,
  3045. )
  3046. def _interpret_range(self, range_):
  3047. if not isinstance(range_, tuple) or len(range_) != 2:
  3048. raise exc.ArgumentError("2-tuple expected for range/rows")
  3049. if range_[0] is None:
  3050. lower = RANGE_UNBOUNDED
  3051. else:
  3052. try:
  3053. lower = int(range_[0])
  3054. except ValueError as err:
  3055. util.raise_(
  3056. exc.ArgumentError(
  3057. "Integer or None expected for range value"
  3058. ),
  3059. replace_context=err,
  3060. )
  3061. else:
  3062. if lower == 0:
  3063. lower = RANGE_CURRENT
  3064. if range_[1] is None:
  3065. upper = RANGE_UNBOUNDED
  3066. else:
  3067. try:
  3068. upper = int(range_[1])
  3069. except ValueError as err:
  3070. util.raise_(
  3071. exc.ArgumentError(
  3072. "Integer or None expected for range value"
  3073. ),
  3074. replace_context=err,
  3075. )
  3076. else:
  3077. if upper == 0:
  3078. upper = RANGE_CURRENT
  3079. return lower, upper
  3080. @util.memoized_property
  3081. def type(self):
  3082. return self.element.type
  3083. @property
  3084. def _from_objects(self):
  3085. return list(
  3086. itertools.chain(
  3087. *[
  3088. c._from_objects
  3089. for c in (self.element, self.partition_by, self.order_by)
  3090. if c is not None
  3091. ]
  3092. )
  3093. )
  3094. class WithinGroup(ColumnElement):
  3095. """Represent a WITHIN GROUP (ORDER BY) clause.
  3096. This is a special operator against so-called
  3097. "ordered set aggregate" and "hypothetical
  3098. set aggregate" functions, including ``percentile_cont()``,
  3099. ``rank()``, ``dense_rank()``, etc.
  3100. It's supported only by certain database backends, such as PostgreSQL,
  3101. Oracle and MS SQL Server.
  3102. The :class:`.WithinGroup` construct extracts its type from the
  3103. method :meth:`.FunctionElement.within_group_type`. If this returns
  3104. ``None``, the function's ``.type`` is used.
  3105. """
  3106. __visit_name__ = "withingroup"
  3107. _traverse_internals = [
  3108. ("element", InternalTraversal.dp_clauseelement),
  3109. ("order_by", InternalTraversal.dp_clauseelement),
  3110. ]
  3111. order_by = None
  3112. def __init__(self, element, *order_by):
  3113. r"""Produce a :class:`.WithinGroup` object against a function.
  3114. Used against so-called "ordered set aggregate" and "hypothetical
  3115. set aggregate" functions, including :class:`.percentile_cont`,
  3116. :class:`.rank`, :class:`.dense_rank`, etc.
  3117. :func:`_expression.within_group` is usually called using
  3118. the :meth:`.FunctionElement.within_group` method, e.g.::
  3119. from sqlalchemy import within_group
  3120. stmt = select(
  3121. department.c.id,
  3122. func.percentile_cont(0.5).within_group(
  3123. department.c.salary.desc()
  3124. )
  3125. )
  3126. The above statement would produce SQL similar to
  3127. ``SELECT department.id, percentile_cont(0.5)
  3128. WITHIN GROUP (ORDER BY department.salary DESC)``.
  3129. :param element: a :class:`.FunctionElement` construct, typically
  3130. generated by :data:`~.expression.func`.
  3131. :param \*order_by: one or more column elements that will be used
  3132. as the ORDER BY clause of the WITHIN GROUP construct.
  3133. .. versionadded:: 1.1
  3134. .. seealso::
  3135. :ref:`tutorial_functions_within_group` - in the
  3136. :ref:`unified_tutorial`
  3137. :data:`.expression.func`
  3138. :func:`_expression.over`
  3139. """
  3140. self.element = element
  3141. if order_by is not None:
  3142. self.order_by = ClauseList(
  3143. *util.to_list(order_by), _literal_as_text_role=roles.ByOfRole
  3144. )
  3145. def over(self, partition_by=None, order_by=None, range_=None, rows=None):
  3146. """Produce an OVER clause against this :class:`.WithinGroup`
  3147. construct.
  3148. This function has the same signature as that of
  3149. :meth:`.FunctionElement.over`.
  3150. """
  3151. return Over(
  3152. self,
  3153. partition_by=partition_by,
  3154. order_by=order_by,
  3155. range_=range_,
  3156. rows=rows,
  3157. )
  3158. @util.memoized_property
  3159. def type(self):
  3160. wgt = self.element.within_group_type(self)
  3161. if wgt is not None:
  3162. return wgt
  3163. else:
  3164. return self.element.type
  3165. @property
  3166. def _from_objects(self):
  3167. return list(
  3168. itertools.chain(
  3169. *[
  3170. c._from_objects
  3171. for c in (self.element, self.order_by)
  3172. if c is not None
  3173. ]
  3174. )
  3175. )
  3176. class FunctionFilter(ColumnElement):
  3177. """Represent a function FILTER clause.
  3178. This is a special operator against aggregate and window functions,
  3179. which controls which rows are passed to it.
  3180. It's supported only by certain database backends.
  3181. Invocation of :class:`.FunctionFilter` is via
  3182. :meth:`.FunctionElement.filter`::
  3183. func.count(1).filter(True)
  3184. .. versionadded:: 1.0.0
  3185. .. seealso::
  3186. :meth:`.FunctionElement.filter`
  3187. """
  3188. __visit_name__ = "funcfilter"
  3189. _traverse_internals = [
  3190. ("func", InternalTraversal.dp_clauseelement),
  3191. ("criterion", InternalTraversal.dp_clauseelement),
  3192. ]
  3193. criterion = None
  3194. def __init__(self, func, *criterion):
  3195. """Produce a :class:`.FunctionFilter` object against a function.
  3196. Used against aggregate and window functions,
  3197. for database backends that support the "FILTER" clause.
  3198. E.g.::
  3199. from sqlalchemy import funcfilter
  3200. funcfilter(func.count(1), MyClass.name == 'some name')
  3201. Would produce "COUNT(1) FILTER (WHERE myclass.name = 'some name')".
  3202. This function is also available from the :data:`~.expression.func`
  3203. construct itself via the :meth:`.FunctionElement.filter` method.
  3204. .. versionadded:: 1.0.0
  3205. .. seealso::
  3206. :ref:`tutorial_functions_within_group` - in the
  3207. :ref:`unified_tutorial`
  3208. :meth:`.FunctionElement.filter`
  3209. """
  3210. self.func = func
  3211. self.filter(*criterion)
  3212. def filter(self, *criterion):
  3213. """Produce an additional FILTER against the function.
  3214. This method adds additional criteria to the initial criteria
  3215. set up by :meth:`.FunctionElement.filter`.
  3216. Multiple criteria are joined together at SQL render time
  3217. via ``AND``.
  3218. """
  3219. for criterion in list(criterion):
  3220. criterion = coercions.expect(roles.WhereHavingRole, criterion)
  3221. if self.criterion is not None:
  3222. self.criterion = self.criterion & criterion
  3223. else:
  3224. self.criterion = criterion
  3225. return self
  3226. def over(self, partition_by=None, order_by=None, range_=None, rows=None):
  3227. """Produce an OVER clause against this filtered function.
  3228. Used against aggregate or so-called "window" functions,
  3229. for database backends that support window functions.
  3230. The expression::
  3231. func.rank().filter(MyClass.y > 5).over(order_by='x')
  3232. is shorthand for::
  3233. from sqlalchemy import over, funcfilter
  3234. over(funcfilter(func.rank(), MyClass.y > 5), order_by='x')
  3235. See :func:`_expression.over` for a full description.
  3236. """
  3237. return Over(
  3238. self,
  3239. partition_by=partition_by,
  3240. order_by=order_by,
  3241. range_=range_,
  3242. rows=rows,
  3243. )
  3244. def self_group(self, against=None):
  3245. if operators.is_precedent(operators.filter_op, against):
  3246. return Grouping(self)
  3247. else:
  3248. return self
  3249. @util.memoized_property
  3250. def type(self):
  3251. return self.func.type
  3252. @property
  3253. def _from_objects(self):
  3254. return list(
  3255. itertools.chain(
  3256. *[
  3257. c._from_objects
  3258. for c in (self.func, self.criterion)
  3259. if c is not None
  3260. ]
  3261. )
  3262. )
  3263. class Label(roles.LabeledColumnExprRole, ColumnElement):
  3264. """Represents a column label (AS).
  3265. Represent a label, as typically applied to any column-level
  3266. element using the ``AS`` sql keyword.
  3267. """
  3268. __visit_name__ = "label"
  3269. _traverse_internals = [
  3270. ("name", InternalTraversal.dp_anon_name),
  3271. ("_type", InternalTraversal.dp_type),
  3272. ("_element", InternalTraversal.dp_clauseelement),
  3273. ]
  3274. def __init__(self, name, element, type_=None):
  3275. """Return a :class:`Label` object for the
  3276. given :class:`_expression.ColumnElement`.
  3277. A label changes the name of an element in the columns clause of a
  3278. ``SELECT`` statement, typically via the ``AS`` SQL keyword.
  3279. This functionality is more conveniently available via the
  3280. :meth:`_expression.ColumnElement.label` method on
  3281. :class:`_expression.ColumnElement`.
  3282. :param name: label name
  3283. :param obj: a :class:`_expression.ColumnElement`.
  3284. """
  3285. if isinstance(element, Label):
  3286. self._resolve_label = element._label
  3287. while isinstance(element, Label):
  3288. element = element.element
  3289. if name:
  3290. self.name = name
  3291. self._resolve_label = self.name
  3292. else:
  3293. self.name = _anonymous_label.safe_construct(
  3294. id(self), getattr(element, "name", "anon")
  3295. )
  3296. self.key = self._label = self._key_label = self.name
  3297. self._element = element
  3298. self._type = type_
  3299. self._proxies = [element]
  3300. def __reduce__(self):
  3301. return self.__class__, (self.name, self._element, self._type)
  3302. @util.memoized_property
  3303. def _is_implicitly_boolean(self):
  3304. return self.element._is_implicitly_boolean
  3305. @HasMemoized.memoized_attribute
  3306. def _allow_label_resolve(self):
  3307. return self.element._allow_label_resolve
  3308. @property
  3309. def _order_by_label_element(self):
  3310. return self
  3311. @util.memoized_property
  3312. def type(self):
  3313. return type_api.to_instance(
  3314. self._type or getattr(self._element, "type", None)
  3315. )
  3316. @HasMemoized.memoized_attribute
  3317. def element(self):
  3318. return self._element.self_group(against=operators.as_)
  3319. def self_group(self, against=None):
  3320. return self._apply_to_inner(self._element.self_group, against=against)
  3321. def _negate(self):
  3322. return self._apply_to_inner(self._element._negate)
  3323. def _apply_to_inner(self, fn, *arg, **kw):
  3324. sub_element = fn(*arg, **kw)
  3325. if sub_element is not self._element:
  3326. return Label(self.name, sub_element, type_=self._type)
  3327. else:
  3328. return self
  3329. @property
  3330. def primary_key(self):
  3331. return self.element.primary_key
  3332. @property
  3333. def foreign_keys(self):
  3334. return self.element.foreign_keys
  3335. def _copy_internals(self, clone=_clone, anonymize_labels=False, **kw):
  3336. self._reset_memoizations()
  3337. self._element = clone(self._element, **kw)
  3338. if anonymize_labels:
  3339. self.name = self._resolve_label = _anonymous_label.safe_construct(
  3340. id(self), getattr(self.element, "name", "anon")
  3341. )
  3342. self.key = self._label = self._key_label = self.name
  3343. @property
  3344. def _from_objects(self):
  3345. return self.element._from_objects
  3346. def _make_proxy(self, selectable, name=None, **kw):
  3347. name = self.name if not name else name
  3348. key, e = self.element._make_proxy(
  3349. selectable,
  3350. name=name,
  3351. disallow_is_literal=True,
  3352. name_is_truncatable=isinstance(name, _truncated_label),
  3353. )
  3354. # there was a note here to remove this assertion, which was here
  3355. # to determine if we later could support a use case where
  3356. # the key and name of a label are separate. But I don't know what
  3357. # that case was. For now, this is an unexpected case that occurs
  3358. # when a label name conflicts with other columns and select()
  3359. # is attempting to disambiguate an explicit label, which is not what
  3360. # the user would want. See issue #6090.
  3361. if key != self.name:
  3362. raise exc.InvalidRequestError(
  3363. "Label name %s is being renamed to an anonymous label due "
  3364. "to disambiguation "
  3365. "which is not supported right now. Please use unique names "
  3366. "for explicit labels." % (self.name)
  3367. )
  3368. e._propagate_attrs = selectable._propagate_attrs
  3369. e._proxies.append(self)
  3370. if self._type is not None:
  3371. e.type = self._type
  3372. return self.key, e
  3373. class NamedColumn(ColumnElement):
  3374. is_literal = False
  3375. table = None
  3376. def _compare_name_for_result(self, other):
  3377. return (hasattr(other, "name") and self.name == other.name) or (
  3378. hasattr(other, "_label") and self._label == other._label
  3379. )
  3380. @util.memoized_property
  3381. def description(self):
  3382. if util.py3k:
  3383. return self.name
  3384. else:
  3385. return self.name.encode("ascii", "backslashreplace")
  3386. @HasMemoized.memoized_attribute
  3387. def _key_label(self):
  3388. proxy_key = self._proxy_key
  3389. if proxy_key != self.name:
  3390. return self._gen_label(proxy_key)
  3391. else:
  3392. return self._label
  3393. @HasMemoized.memoized_attribute
  3394. def _label(self):
  3395. return self._gen_label(self.name)
  3396. @HasMemoized.memoized_attribute
  3397. def _render_label_in_columns_clause(self):
  3398. return True
  3399. def _gen_label(self, name, dedupe_on_key=True):
  3400. return name
  3401. def _bind_param(self, operator, obj, type_=None, expanding=False):
  3402. return BindParameter(
  3403. self.key,
  3404. obj,
  3405. _compared_to_operator=operator,
  3406. _compared_to_type=self.type,
  3407. type_=type_,
  3408. unique=True,
  3409. expanding=expanding,
  3410. )
  3411. def _make_proxy(
  3412. self,
  3413. selectable,
  3414. name=None,
  3415. name_is_truncatable=False,
  3416. disallow_is_literal=False,
  3417. **kw
  3418. ):
  3419. c = ColumnClause(
  3420. coercions.expect(roles.TruncatedLabelRole, name or self.name)
  3421. if name_is_truncatable
  3422. else (name or self.name),
  3423. type_=self.type,
  3424. _selectable=selectable,
  3425. is_literal=False,
  3426. )
  3427. c._propagate_attrs = selectable._propagate_attrs
  3428. if name is None:
  3429. c.key = self.key
  3430. c._proxies = [self]
  3431. if selectable._is_clone_of is not None:
  3432. c._is_clone_of = selectable._is_clone_of.columns.get(c.key)
  3433. return c.key, c
  3434. class ColumnClause(
  3435. roles.DDLReferredColumnRole,
  3436. roles.LabeledColumnExprRole,
  3437. roles.StrAsPlainColumnRole,
  3438. Immutable,
  3439. NamedColumn,
  3440. ):
  3441. """Represents a column expression from any textual string.
  3442. The :class:`.ColumnClause`, a lightweight analogue to the
  3443. :class:`_schema.Column` class, is typically invoked using the
  3444. :func:`_expression.column` function, as in::
  3445. from sqlalchemy import column
  3446. id, name = column("id"), column("name")
  3447. stmt = select(id, name).select_from("user")
  3448. The above statement would produce SQL like::
  3449. SELECT id, name FROM user
  3450. :class:`.ColumnClause` is the immediate superclass of the schema-specific
  3451. :class:`_schema.Column` object. While the :class:`_schema.Column`
  3452. class has all the
  3453. same capabilities as :class:`.ColumnClause`, the :class:`.ColumnClause`
  3454. class is usable by itself in those cases where behavioral requirements
  3455. are limited to simple SQL expression generation. The object has none of
  3456. the associations with schema-level metadata or with execution-time
  3457. behavior that :class:`_schema.Column` does,
  3458. so in that sense is a "lightweight"
  3459. version of :class:`_schema.Column`.
  3460. Full details on :class:`.ColumnClause` usage is at
  3461. :func:`_expression.column`.
  3462. .. seealso::
  3463. :func:`_expression.column`
  3464. :class:`_schema.Column`
  3465. """
  3466. table = None
  3467. is_literal = False
  3468. __visit_name__ = "column"
  3469. _traverse_internals = [
  3470. ("name", InternalTraversal.dp_anon_name),
  3471. ("type", InternalTraversal.dp_type),
  3472. ("table", InternalTraversal.dp_clauseelement),
  3473. ("is_literal", InternalTraversal.dp_boolean),
  3474. ]
  3475. onupdate = default = server_default = server_onupdate = None
  3476. _is_multiparam_column = False
  3477. def __init__(self, text, type_=None, is_literal=False, _selectable=None):
  3478. """Produce a :class:`.ColumnClause` object.
  3479. The :class:`.ColumnClause` is a lightweight analogue to the
  3480. :class:`_schema.Column` class. The :func:`_expression.column`
  3481. function can
  3482. be invoked with just a name alone, as in::
  3483. from sqlalchemy import column
  3484. id, name = column("id"), column("name")
  3485. stmt = select(id, name).select_from("user")
  3486. The above statement would produce SQL like::
  3487. SELECT id, name FROM user
  3488. Once constructed, :func:`_expression.column`
  3489. may be used like any other SQL
  3490. expression element such as within :func:`_expression.select`
  3491. constructs::
  3492. from sqlalchemy.sql import column
  3493. id, name = column("id"), column("name")
  3494. stmt = select(id, name).select_from("user")
  3495. The text handled by :func:`_expression.column`
  3496. is assumed to be handled
  3497. like the name of a database column; if the string contains mixed case,
  3498. special characters, or matches a known reserved word on the target
  3499. backend, the column expression will render using the quoting
  3500. behavior determined by the backend. To produce a textual SQL
  3501. expression that is rendered exactly without any quoting,
  3502. use :func:`_expression.literal_column` instead,
  3503. or pass ``True`` as the
  3504. value of :paramref:`_expression.column.is_literal`. Additionally,
  3505. full SQL
  3506. statements are best handled using the :func:`_expression.text`
  3507. construct.
  3508. :func:`_expression.column` can be used in a table-like
  3509. fashion by combining it with the :func:`.table` function
  3510. (which is the lightweight analogue to :class:`_schema.Table`
  3511. ) to produce
  3512. a working table construct with minimal boilerplate::
  3513. from sqlalchemy import table, column, select
  3514. user = table("user",
  3515. column("id"),
  3516. column("name"),
  3517. column("description"),
  3518. )
  3519. stmt = select(user.c.description).where(user.c.name == 'wendy')
  3520. A :func:`_expression.column` / :func:`.table`
  3521. construct like that illustrated
  3522. above can be created in an
  3523. ad-hoc fashion and is not associated with any
  3524. :class:`_schema.MetaData`, DDL, or events, unlike its
  3525. :class:`_schema.Table` counterpart.
  3526. .. versionchanged:: 1.0.0 :func:`_expression.column` can now
  3527. be imported from the plain ``sqlalchemy`` namespace like any
  3528. other SQL element.
  3529. :param text: the text of the element.
  3530. :param type: :class:`_types.TypeEngine` object which can associate
  3531. this :class:`.ColumnClause` with a type.
  3532. :param is_literal: if True, the :class:`.ColumnClause` is assumed to
  3533. be an exact expression that will be delivered to the output with no
  3534. quoting rules applied regardless of case sensitive settings. the
  3535. :func:`_expression.literal_column()` function essentially invokes
  3536. :func:`_expression.column` while passing ``is_literal=True``.
  3537. .. seealso::
  3538. :class:`_schema.Column`
  3539. :func:`_expression.literal_column`
  3540. :func:`.table`
  3541. :func:`_expression.text`
  3542. :ref:`sqlexpression_literal_column`
  3543. """
  3544. self.key = self.name = text
  3545. self.table = _selectable
  3546. self.type = type_api.to_instance(type_)
  3547. self.is_literal = is_literal
  3548. def get_children(self, column_tables=False, **kw):
  3549. # override base get_children() to not return the Table
  3550. # or selectable that is parent to this column. Traversals
  3551. # expect the columns of tables and subqueries to be leaf nodes.
  3552. return []
  3553. @property
  3554. def entity_namespace(self):
  3555. if self.table is not None:
  3556. return self.table.entity_namespace
  3557. else:
  3558. return super(ColumnClause, self).entity_namespace
  3559. @HasMemoized.memoized_attribute
  3560. def _from_objects(self):
  3561. t = self.table
  3562. if t is not None:
  3563. return [t]
  3564. else:
  3565. return []
  3566. @HasMemoized.memoized_attribute
  3567. def _render_label_in_columns_clause(self):
  3568. return self.table is not None
  3569. @property
  3570. def _ddl_label(self):
  3571. return self._gen_label(self.name, dedupe_on_key=False)
  3572. def _compare_name_for_result(self, other):
  3573. if (
  3574. self.is_literal
  3575. or self.table is None
  3576. or self.table._is_textual
  3577. or not hasattr(other, "proxy_set")
  3578. or (
  3579. isinstance(other, ColumnClause)
  3580. and (
  3581. other.is_literal
  3582. or other.table is None
  3583. or other.table._is_textual
  3584. )
  3585. )
  3586. ):
  3587. return (hasattr(other, "name") and self.name == other.name) or (
  3588. hasattr(other, "_label") and self._label == other._label
  3589. )
  3590. else:
  3591. return other.proxy_set.intersection(self.proxy_set)
  3592. def _gen_label(self, name, dedupe_on_key=True):
  3593. t = self.table
  3594. if self.is_literal:
  3595. return None
  3596. elif t is not None and t.named_with_column:
  3597. if getattr(t, "schema", None):
  3598. label = t.schema.replace(".", "_") + "_" + t.name + "_" + name
  3599. else:
  3600. label = t.name + "_" + name
  3601. # propagate name quoting rules for labels.
  3602. if getattr(name, "quote", None) is not None:
  3603. if isinstance(label, quoted_name):
  3604. label.quote = name.quote
  3605. else:
  3606. label = quoted_name(label, name.quote)
  3607. elif getattr(t.name, "quote", None) is not None:
  3608. # can't get this situation to occur, so let's
  3609. # assert false on it for now
  3610. assert not isinstance(label, quoted_name)
  3611. label = quoted_name(label, t.name.quote)
  3612. if dedupe_on_key:
  3613. # ensure the label name doesn't conflict with that of an
  3614. # existing column. note that this implies that any Column
  3615. # must **not** set up its _label before its parent table has
  3616. # all of its other Column objects set up. There are several
  3617. # tables in the test suite which will fail otherwise; example:
  3618. # table "owner" has columns "name" and "owner_name". Therefore
  3619. # column owner.name cannot use the label "owner_name", it has
  3620. # to be "owner_name_1".
  3621. if label in t.c:
  3622. _label = label
  3623. counter = 1
  3624. while _label in t.c:
  3625. _label = label + "_" + str(counter)
  3626. counter += 1
  3627. label = _label
  3628. return coercions.expect(roles.TruncatedLabelRole, label)
  3629. else:
  3630. return name
  3631. def _make_proxy(
  3632. self,
  3633. selectable,
  3634. name=None,
  3635. name_is_truncatable=False,
  3636. disallow_is_literal=False,
  3637. **kw
  3638. ):
  3639. # the "is_literal" flag normally should never be propagated; a proxied
  3640. # column is always a SQL identifier and never the actual expression
  3641. # being evaluated. however, there is a case where the "is_literal" flag
  3642. # might be used to allow the given identifier to have a fixed quoting
  3643. # pattern already, so maintain the flag for the proxy unless a
  3644. # :class:`.Label` object is creating the proxy. See [ticket:4730].
  3645. is_literal = (
  3646. not disallow_is_literal
  3647. and self.is_literal
  3648. and (
  3649. # note this does not accommodate for quoted_name differences
  3650. # right now
  3651. name is None
  3652. or name == self.name
  3653. )
  3654. )
  3655. c = self._constructor(
  3656. coercions.expect(roles.TruncatedLabelRole, name or self.name)
  3657. if name_is_truncatable
  3658. else (name or self.name),
  3659. type_=self.type,
  3660. _selectable=selectable,
  3661. is_literal=is_literal,
  3662. )
  3663. c._propagate_attrs = selectable._propagate_attrs
  3664. if name is None:
  3665. c.key = self.key
  3666. c._proxies = [self]
  3667. if selectable._is_clone_of is not None:
  3668. c._is_clone_of = selectable._is_clone_of.columns.get(c.key)
  3669. return c.key, c
  3670. class TableValuedColumn(NamedColumn):
  3671. __visit_name__ = "table_valued_column"
  3672. _traverse_internals = [
  3673. ("name", InternalTraversal.dp_anon_name),
  3674. ("type", InternalTraversal.dp_type),
  3675. ("scalar_alias", InternalTraversal.dp_clauseelement),
  3676. ]
  3677. def __init__(self, scalar_alias, type_):
  3678. self.scalar_alias = scalar_alias
  3679. self.key = self.name = scalar_alias.name
  3680. self.type = type_
  3681. @property
  3682. def _from_objects(self):
  3683. return [self.scalar_alias]
  3684. class CollationClause(ColumnElement):
  3685. __visit_name__ = "collation"
  3686. _traverse_internals = [("collation", InternalTraversal.dp_string)]
  3687. def __init__(self, collation):
  3688. self.collation = collation
  3689. class _IdentifiedClause(Executable, ClauseElement):
  3690. __visit_name__ = "identified"
  3691. _execution_options = Executable._execution_options.union(
  3692. {"autocommit": False}
  3693. )
  3694. def __init__(self, ident):
  3695. self.ident = ident
  3696. class SavepointClause(_IdentifiedClause):
  3697. __visit_name__ = "savepoint"
  3698. class RollbackToSavepointClause(_IdentifiedClause):
  3699. __visit_name__ = "rollback_to_savepoint"
  3700. class ReleaseSavepointClause(_IdentifiedClause):
  3701. __visit_name__ = "release_savepoint"
  3702. class quoted_name(util.MemoizedSlots, util.text_type):
  3703. """Represent a SQL identifier combined with quoting preferences.
  3704. :class:`.quoted_name` is a Python unicode/str subclass which
  3705. represents a particular identifier name along with a
  3706. ``quote`` flag. This ``quote`` flag, when set to
  3707. ``True`` or ``False``, overrides automatic quoting behavior
  3708. for this identifier in order to either unconditionally quote
  3709. or to not quote the name. If left at its default of ``None``,
  3710. quoting behavior is applied to the identifier on a per-backend basis
  3711. based on an examination of the token itself.
  3712. A :class:`.quoted_name` object with ``quote=True`` is also
  3713. prevented from being modified in the case of a so-called
  3714. "name normalize" option. Certain database backends, such as
  3715. Oracle, Firebird, and DB2 "normalize" case-insensitive names
  3716. as uppercase. The SQLAlchemy dialects for these backends
  3717. convert from SQLAlchemy's lower-case-means-insensitive convention
  3718. to the upper-case-means-insensitive conventions of those backends.
  3719. The ``quote=True`` flag here will prevent this conversion from occurring
  3720. to support an identifier that's quoted as all lower case against
  3721. such a backend.
  3722. The :class:`.quoted_name` object is normally created automatically
  3723. when specifying the name for key schema constructs such as
  3724. :class:`_schema.Table`, :class:`_schema.Column`, and others.
  3725. The class can also be
  3726. passed explicitly as the name to any function that receives a name which
  3727. can be quoted. Such as to use the :meth:`_engine.Engine.has_table`
  3728. method with
  3729. an unconditionally quoted name::
  3730. from sqlalchemy import create_engine
  3731. from sqlalchemy.sql import quoted_name
  3732. engine = create_engine("oracle+cx_oracle://some_dsn")
  3733. engine.has_table(quoted_name("some_table", True))
  3734. The above logic will run the "has table" logic against the Oracle backend,
  3735. passing the name exactly as ``"some_table"`` without converting to
  3736. upper case.
  3737. .. versionadded:: 0.9.0
  3738. .. versionchanged:: 1.2 The :class:`.quoted_name` construct is now
  3739. importable from ``sqlalchemy.sql``, in addition to the previous
  3740. location of ``sqlalchemy.sql.elements``.
  3741. """
  3742. __slots__ = "quote", "lower", "upper"
  3743. def __new__(cls, value, quote):
  3744. if value is None:
  3745. return None
  3746. # experimental - don't bother with quoted_name
  3747. # if quote flag is None. doesn't seem to make any dent
  3748. # in performance however
  3749. # elif not sprcls and quote is None:
  3750. # return value
  3751. elif isinstance(value, cls) and (
  3752. quote is None or value.quote == quote
  3753. ):
  3754. return value
  3755. self = super(quoted_name, cls).__new__(cls, value)
  3756. self.quote = quote
  3757. return self
  3758. def __reduce__(self):
  3759. return quoted_name, (util.text_type(self), self.quote)
  3760. def _memoized_method_lower(self):
  3761. if self.quote:
  3762. return self
  3763. else:
  3764. return util.text_type(self).lower()
  3765. def _memoized_method_upper(self):
  3766. if self.quote:
  3767. return self
  3768. else:
  3769. return util.text_type(self).upper()
  3770. def __repr__(self):
  3771. if util.py2k:
  3772. backslashed = self.encode("ascii", "backslashreplace")
  3773. if not util.py2k:
  3774. backslashed = backslashed.decode("ascii")
  3775. return "'%s'" % backslashed
  3776. else:
  3777. return str.__repr__(self)
  3778. def _find_columns(clause):
  3779. """locate Column objects within the given expression."""
  3780. cols = util.column_set()
  3781. traverse(clause, {}, {"column": cols.add})
  3782. return cols
  3783. def _type_from_args(args):
  3784. for a in args:
  3785. if not a.type._isnull:
  3786. return a.type
  3787. else:
  3788. return type_api.NULLTYPE
  3789. def _corresponding_column_or_error(fromclause, column, require_embedded=False):
  3790. c = fromclause.corresponding_column(
  3791. column, require_embedded=require_embedded
  3792. )
  3793. if c is None:
  3794. raise exc.InvalidRequestError(
  3795. "Given column '%s', attached to table '%s', "
  3796. "failed to locate a corresponding column from table '%s'"
  3797. % (column, getattr(column, "table", None), fromclause.description)
  3798. )
  3799. return c
  3800. class AnnotatedColumnElement(Annotated):
  3801. def __init__(self, element, values):
  3802. Annotated.__init__(self, element, values)
  3803. for attr in ("comparator", "_proxy_key", "_key_label"):
  3804. self.__dict__.pop(attr, None)
  3805. for attr in ("name", "key", "table"):
  3806. if self.__dict__.get(attr, False) is None:
  3807. self.__dict__.pop(attr)
  3808. def _with_annotations(self, values):
  3809. clone = super(AnnotatedColumnElement, self)._with_annotations(values)
  3810. clone.__dict__.pop("comparator", None)
  3811. return clone
  3812. @util.memoized_property
  3813. def name(self):
  3814. """pull 'name' from parent, if not present"""
  3815. return self._Annotated__element.name
  3816. @util.memoized_property
  3817. def table(self):
  3818. """pull 'table' from parent, if not present"""
  3819. return self._Annotated__element.table
  3820. @util.memoized_property
  3821. def key(self):
  3822. """pull 'key' from parent, if not present"""
  3823. return self._Annotated__element.key
  3824. @util.memoized_property
  3825. def info(self):
  3826. return self._Annotated__element.info
  3827. @util.memoized_property
  3828. def _anon_name_label(self):
  3829. return self._Annotated__element._anon_name_label
  3830. class _truncated_label(quoted_name):
  3831. """A unicode subclass used to identify symbolic "
  3832. "names that may require truncation."""
  3833. __slots__ = ()
  3834. def __new__(cls, value, quote=None):
  3835. quote = getattr(value, "quote", quote)
  3836. # return super(_truncated_label, cls).__new__(cls, value, quote, True)
  3837. return super(_truncated_label, cls).__new__(cls, value, quote)
  3838. def __reduce__(self):
  3839. return self.__class__, (util.text_type(self), self.quote)
  3840. def apply_map(self, map_):
  3841. return self
  3842. class conv(_truncated_label):
  3843. """Mark a string indicating that a name has already been converted
  3844. by a naming convention.
  3845. This is a string subclass that indicates a name that should not be
  3846. subject to any further naming conventions.
  3847. E.g. when we create a :class:`.Constraint` using a naming convention
  3848. as follows::
  3849. m = MetaData(naming_convention={
  3850. "ck": "ck_%(table_name)s_%(constraint_name)s"
  3851. })
  3852. t = Table('t', m, Column('x', Integer),
  3853. CheckConstraint('x > 5', name='x5'))
  3854. The name of the above constraint will be rendered as ``"ck_t_x5"``.
  3855. That is, the existing name ``x5`` is used in the naming convention as the
  3856. ``constraint_name`` token.
  3857. In some situations, such as in migration scripts, we may be rendering
  3858. the above :class:`.CheckConstraint` with a name that's already been
  3859. converted. In order to make sure the name isn't double-modified, the
  3860. new name is applied using the :func:`_schema.conv` marker. We can
  3861. use this explicitly as follows::
  3862. m = MetaData(naming_convention={
  3863. "ck": "ck_%(table_name)s_%(constraint_name)s"
  3864. })
  3865. t = Table('t', m, Column('x', Integer),
  3866. CheckConstraint('x > 5', name=conv('ck_t_x5')))
  3867. Where above, the :func:`_schema.conv` marker indicates that the constraint
  3868. name here is final, and the name will render as ``"ck_t_x5"`` and not
  3869. ``"ck_t_ck_t_x5"``
  3870. .. versionadded:: 0.9.4
  3871. .. seealso::
  3872. :ref:`constraint_naming_conventions`
  3873. """
  3874. __slots__ = ()
  3875. _NONE_NAME = util.symbol("NONE_NAME")
  3876. """indicate a 'deferred' name that was ultimately the value None."""
  3877. # for backwards compatibility in case
  3878. # someone is re-implementing the
  3879. # _truncated_identifier() sequence in a custom
  3880. # compiler
  3881. _generated_label = _truncated_label
  3882. class _anonymous_label(_truncated_label):
  3883. """A unicode subclass used to identify anonymously
  3884. generated names."""
  3885. __slots__ = ()
  3886. @classmethod
  3887. def safe_construct(
  3888. cls, seed, body, enclosing_label=None, sanitize_key=False
  3889. ):
  3890. if sanitize_key:
  3891. body = re.sub(r"[%\(\) \$]+", "_", body).strip("_")
  3892. label = "%%(%d %s)s" % (seed, body.replace("%", "%%"))
  3893. if enclosing_label:
  3894. label = "%s%s" % (enclosing_label, label)
  3895. return _anonymous_label(label)
  3896. def __add__(self, other):
  3897. if "%" in other and not isinstance(other, _anonymous_label):
  3898. other = util.text_type(other).replace("%", "%%")
  3899. else:
  3900. other = util.text_type(other)
  3901. return _anonymous_label(
  3902. quoted_name(
  3903. util.text_type.__add__(self, other),
  3904. self.quote,
  3905. )
  3906. )
  3907. def __radd__(self, other):
  3908. if "%" in other and not isinstance(other, _anonymous_label):
  3909. other = util.text_type(other).replace("%", "%%")
  3910. else:
  3911. other = util.text_type(other)
  3912. return _anonymous_label(
  3913. quoted_name(
  3914. util.text_type.__add__(other, self),
  3915. self.quote,
  3916. )
  3917. )
  3918. def apply_map(self, map_):
  3919. if self.quote is not None:
  3920. # preserve quoting only if necessary
  3921. return quoted_name(self % map_, self.quote)
  3922. else:
  3923. # else skip the constructor call
  3924. return self % map_