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.

6423 lines
213KB

  1. # sql/selectable.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. """The :class:`_expression.FromClause` class of SQL expression elements,
  8. representing
  9. SQL tables and derived rowsets.
  10. """
  11. import collections
  12. import itertools
  13. from operator import attrgetter
  14. from . import coercions
  15. from . import operators
  16. from . import roles
  17. from . import traversals
  18. from . import type_api
  19. from . import visitors
  20. from .annotation import Annotated
  21. from .annotation import SupportsCloneAnnotations
  22. from .base import _clone
  23. from .base import _cloned_difference
  24. from .base import _cloned_intersection
  25. from .base import _entity_namespace_key
  26. from .base import _expand_cloned
  27. from .base import _from_objects
  28. from .base import _generative
  29. from .base import _select_iterables
  30. from .base import CacheableOptions
  31. from .base import ColumnCollection
  32. from .base import ColumnSet
  33. from .base import CompileState
  34. from .base import DedupeColumnCollection
  35. from .base import Executable
  36. from .base import Generative
  37. from .base import HasCompileState
  38. from .base import HasMemoized
  39. from .base import Immutable
  40. from .base import prefix_anon_map
  41. from .coercions import _document_text_coercion
  42. from .elements import _anonymous_label
  43. from .elements import and_
  44. from .elements import BindParameter
  45. from .elements import BooleanClauseList
  46. from .elements import ClauseElement
  47. from .elements import ClauseList
  48. from .elements import ColumnClause
  49. from .elements import GroupedElement
  50. from .elements import Grouping
  51. from .elements import literal_column
  52. from .elements import TableValuedColumn
  53. from .elements import UnaryExpression
  54. from .visitors import InternalTraversal
  55. from .. import exc
  56. from .. import util
  57. from ..inspection import inspect
  58. class _OffsetLimitParam(BindParameter):
  59. inherit_cache = True
  60. @property
  61. def _limit_offset_value(self):
  62. return self.effective_value
  63. @util.deprecated(
  64. "1.4",
  65. "The standalone :func:`.subquery` function is deprecated "
  66. "and will be removed in a future release. Use select().subquery().",
  67. )
  68. def subquery(alias, *args, **kwargs):
  69. r"""Return an :class:`.Subquery` object derived
  70. from a :class:`_expression.Select`.
  71. :param alias: the alias name for the subquery
  72. :param \*args, \**kwargs: all other arguments are passed through to the
  73. :func:`_expression.select` function.
  74. """
  75. return Select.create_legacy_select(*args, **kwargs).subquery(alias)
  76. class ReturnsRows(roles.ReturnsRowsRole, ClauseElement):
  77. """The base-most class for Core constructs that have some concept of
  78. columns that can represent rows.
  79. While the SELECT statement and TABLE are the primary things we think
  80. of in this category, DML like INSERT, UPDATE and DELETE can also specify
  81. RETURNING which means they can be used in CTEs and other forms, and
  82. PostgreSQL has functions that return rows also.
  83. .. versionadded:: 1.4
  84. """
  85. _is_returns_rows = True
  86. # sub-elements of returns_rows
  87. _is_from_clause = False
  88. _is_select_statement = False
  89. _is_lateral = False
  90. @property
  91. def selectable(self):
  92. return self
  93. @property
  94. def _all_selected_columns(self):
  95. """A sequence of column expression objects that represents the
  96. "selected" columns of this :class:`_expression.ReturnsRows`.
  97. This is typically equivalent to .exported_columns except it is
  98. delivered in the form of a straight sequence and not keyed
  99. :class:`_expression.ColumnCollection`.
  100. """
  101. raise NotImplementedError()
  102. @property
  103. def exported_columns(self):
  104. """A :class:`_expression.ColumnCollection`
  105. that represents the "exported"
  106. columns of this :class:`_expression.ReturnsRows`.
  107. The "exported" columns represent the collection of
  108. :class:`_expression.ColumnElement`
  109. expressions that are rendered by this SQL
  110. construct. There are primary varieties which are the
  111. "FROM clause columns" of a FROM clause, such as a table, join,
  112. or subquery, the "SELECTed columns", which are the columns in
  113. the "columns clause" of a SELECT statement, and the RETURNING
  114. columns in a DML statement..
  115. .. versionadded:: 1.4
  116. .. seealso::
  117. :attr:`_expression.FromClause.exported_columns`
  118. :attr:`_expression.SelectBase.exported_columns`
  119. """
  120. raise NotImplementedError()
  121. class Selectable(ReturnsRows):
  122. """Mark a class as being selectable."""
  123. __visit_name__ = "selectable"
  124. is_selectable = True
  125. def _refresh_for_new_column(self, column):
  126. raise NotImplementedError()
  127. def lateral(self, name=None):
  128. """Return a LATERAL alias of this :class:`_expression.Selectable`.
  129. The return value is the :class:`_expression.Lateral` construct also
  130. provided by the top-level :func:`_expression.lateral` function.
  131. .. versionadded:: 1.1
  132. .. seealso::
  133. :ref:`lateral_selects` - overview of usage.
  134. """
  135. return Lateral._construct(self, name)
  136. @util.deprecated(
  137. "1.4",
  138. message="The :meth:`.Selectable.replace_selectable` method is "
  139. "deprecated, and will be removed in a future release. Similar "
  140. "functionality is available via the sqlalchemy.sql.visitors module.",
  141. )
  142. @util.preload_module("sqlalchemy.sql.util")
  143. def replace_selectable(self, old, alias):
  144. """Replace all occurrences of :class:`_expression.FromClause`
  145. 'old' with the given :class:`_expression.Alias`
  146. object, returning a copy of this :class:`_expression.FromClause`.
  147. """
  148. return util.preloaded.sql_util.ClauseAdapter(alias).traverse(self)
  149. def corresponding_column(self, column, require_embedded=False):
  150. """Given a :class:`_expression.ColumnElement`, return the exported
  151. :class:`_expression.ColumnElement` object from the
  152. :attr:`_expression.Selectable.exported_columns`
  153. collection of this :class:`_expression.Selectable`
  154. which corresponds to that
  155. original :class:`_expression.ColumnElement` via a common ancestor
  156. column.
  157. :param column: the target :class:`_expression.ColumnElement`
  158. to be matched.
  159. :param require_embedded: only return corresponding columns for
  160. the given :class:`_expression.ColumnElement`, if the given
  161. :class:`_expression.ColumnElement`
  162. is actually present within a sub-element
  163. of this :class:`_expression.Selectable`.
  164. Normally the column will match if
  165. it merely shares a common ancestor with one of the exported
  166. columns of this :class:`_expression.Selectable`.
  167. .. seealso::
  168. :attr:`_expression.Selectable.exported_columns` - the
  169. :class:`_expression.ColumnCollection`
  170. that is used for the operation.
  171. :meth:`_expression.ColumnCollection.corresponding_column`
  172. - implementation
  173. method.
  174. """
  175. return self.exported_columns.corresponding_column(
  176. column, require_embedded
  177. )
  178. class HasPrefixes(object):
  179. _prefixes = ()
  180. _has_prefixes_traverse_internals = [
  181. ("_prefixes", InternalTraversal.dp_prefix_sequence)
  182. ]
  183. @_generative
  184. @_document_text_coercion(
  185. "expr",
  186. ":meth:`_expression.HasPrefixes.prefix_with`",
  187. ":paramref:`.HasPrefixes.prefix_with.*expr`",
  188. )
  189. def prefix_with(self, *expr, **kw):
  190. r"""Add one or more expressions following the statement keyword, i.e.
  191. SELECT, INSERT, UPDATE, or DELETE. Generative.
  192. This is used to support backend-specific prefix keywords such as those
  193. provided by MySQL.
  194. E.g.::
  195. stmt = table.insert().prefix_with("LOW_PRIORITY", dialect="mysql")
  196. # MySQL 5.7 optimizer hints
  197. stmt = select(table).prefix_with(
  198. "/*+ BKA(t1) */", dialect="mysql")
  199. Multiple prefixes can be specified by multiple calls
  200. to :meth:`_expression.HasPrefixes.prefix_with`.
  201. :param \*expr: textual or :class:`_expression.ClauseElement`
  202. construct which
  203. will be rendered following the INSERT, UPDATE, or DELETE
  204. keyword.
  205. :param \**kw: A single keyword 'dialect' is accepted. This is an
  206. optional string dialect name which will
  207. limit rendering of this prefix to only that dialect.
  208. """
  209. dialect = kw.pop("dialect", None)
  210. if kw:
  211. raise exc.ArgumentError(
  212. "Unsupported argument(s): %s" % ",".join(kw)
  213. )
  214. self._setup_prefixes(expr, dialect)
  215. def _setup_prefixes(self, prefixes, dialect=None):
  216. self._prefixes = self._prefixes + tuple(
  217. [
  218. (coercions.expect(roles.StatementOptionRole, p), dialect)
  219. for p in prefixes
  220. ]
  221. )
  222. class HasSuffixes(object):
  223. _suffixes = ()
  224. _has_suffixes_traverse_internals = [
  225. ("_suffixes", InternalTraversal.dp_prefix_sequence)
  226. ]
  227. @_generative
  228. @_document_text_coercion(
  229. "expr",
  230. ":meth:`_expression.HasSuffixes.suffix_with`",
  231. ":paramref:`.HasSuffixes.suffix_with.*expr`",
  232. )
  233. def suffix_with(self, *expr, **kw):
  234. r"""Add one or more expressions following the statement as a whole.
  235. This is used to support backend-specific suffix keywords on
  236. certain constructs.
  237. E.g.::
  238. stmt = select(col1, col2).cte().suffix_with(
  239. "cycle empno set y_cycle to 1 default 0", dialect="oracle")
  240. Multiple suffixes can be specified by multiple calls
  241. to :meth:`_expression.HasSuffixes.suffix_with`.
  242. :param \*expr: textual or :class:`_expression.ClauseElement`
  243. construct which
  244. will be rendered following the target clause.
  245. :param \**kw: A single keyword 'dialect' is accepted. This is an
  246. optional string dialect name which will
  247. limit rendering of this suffix to only that dialect.
  248. """
  249. dialect = kw.pop("dialect", None)
  250. if kw:
  251. raise exc.ArgumentError(
  252. "Unsupported argument(s): %s" % ",".join(kw)
  253. )
  254. self._setup_suffixes(expr, dialect)
  255. def _setup_suffixes(self, suffixes, dialect=None):
  256. self._suffixes = self._suffixes + tuple(
  257. [
  258. (coercions.expect(roles.StatementOptionRole, p), dialect)
  259. for p in suffixes
  260. ]
  261. )
  262. class HasHints(object):
  263. _hints = util.immutabledict()
  264. _statement_hints = ()
  265. _has_hints_traverse_internals = [
  266. ("_statement_hints", InternalTraversal.dp_statement_hint_list),
  267. ("_hints", InternalTraversal.dp_table_hint_list),
  268. ]
  269. def with_statement_hint(self, text, dialect_name="*"):
  270. """Add a statement hint to this :class:`_expression.Select` or
  271. other selectable object.
  272. This method is similar to :meth:`_expression.Select.with_hint`
  273. except that
  274. it does not require an individual table, and instead applies to the
  275. statement as a whole.
  276. Hints here are specific to the backend database and may include
  277. directives such as isolation levels, file directives, fetch directives,
  278. etc.
  279. .. versionadded:: 1.0.0
  280. .. seealso::
  281. :meth:`_expression.Select.with_hint`
  282. :meth:`_expression.Select.prefix_with` - generic SELECT prefixing
  283. which also can suit some database-specific HINT syntaxes such as
  284. MySQL optimizer hints
  285. """
  286. return self.with_hint(None, text, dialect_name)
  287. @_generative
  288. def with_hint(self, selectable, text, dialect_name="*"):
  289. r"""Add an indexing or other executional context hint for the given
  290. selectable to this :class:`_expression.Select` or other selectable
  291. object.
  292. The text of the hint is rendered in the appropriate
  293. location for the database backend in use, relative
  294. to the given :class:`_schema.Table` or :class:`_expression.Alias`
  295. passed as the
  296. ``selectable`` argument. The dialect implementation
  297. typically uses Python string substitution syntax
  298. with the token ``%(name)s`` to render the name of
  299. the table or alias. E.g. when using Oracle, the
  300. following::
  301. select(mytable).\
  302. with_hint(mytable, "index(%(name)s ix_mytable)")
  303. Would render SQL as::
  304. select /*+ index(mytable ix_mytable) */ ... from mytable
  305. The ``dialect_name`` option will limit the rendering of a particular
  306. hint to a particular backend. Such as, to add hints for both Oracle
  307. and Sybase simultaneously::
  308. select(mytable).\
  309. with_hint(mytable, "index(%(name)s ix_mytable)", 'oracle').\
  310. with_hint(mytable, "WITH INDEX ix_mytable", 'sybase')
  311. .. seealso::
  312. :meth:`_expression.Select.with_statement_hint`
  313. """
  314. if selectable is None:
  315. self._statement_hints += ((dialect_name, text),)
  316. else:
  317. self._hints = self._hints.union(
  318. {
  319. (
  320. coercions.expect(roles.FromClauseRole, selectable),
  321. dialect_name,
  322. ): text
  323. }
  324. )
  325. class FromClause(roles.AnonymizedFromClauseRole, Selectable):
  326. """Represent an element that can be used within the ``FROM``
  327. clause of a ``SELECT`` statement.
  328. The most common forms of :class:`_expression.FromClause` are the
  329. :class:`_schema.Table` and the :func:`_expression.select` constructs. Key
  330. features common to all :class:`_expression.FromClause` objects include:
  331. * a :attr:`.c` collection, which provides per-name access to a collection
  332. of :class:`_expression.ColumnElement` objects.
  333. * a :attr:`.primary_key` attribute, which is a collection of all those
  334. :class:`_expression.ColumnElement`
  335. objects that indicate the ``primary_key`` flag.
  336. * Methods to generate various derivations of a "from" clause, including
  337. :meth:`_expression.FromClause.alias`,
  338. :meth:`_expression.FromClause.join`,
  339. :meth:`_expression.FromClause.select`.
  340. """
  341. __visit_name__ = "fromclause"
  342. named_with_column = False
  343. _hide_froms = []
  344. schema = None
  345. """Define the 'schema' attribute for this :class:`_expression.FromClause`.
  346. This is typically ``None`` for most objects except that of
  347. :class:`_schema.Table`, where it is taken as the value of the
  348. :paramref:`_schema.Table.schema` argument.
  349. """
  350. is_selectable = True
  351. _is_from_clause = True
  352. _is_join = False
  353. _use_schema_map = False
  354. @util.deprecated_params(
  355. whereclause=(
  356. "2.0",
  357. "The :paramref:`_sql.FromClause.select().whereclause` parameter "
  358. "is deprecated and will be removed in version 2.0. "
  359. "Please make use of "
  360. "the :meth:`.Select.where` "
  361. "method to add WHERE criteria to the SELECT statement.",
  362. ),
  363. kwargs=(
  364. "2.0",
  365. "The :meth:`_sql.FromClause.select` method will no longer accept "
  366. "keyword arguments in version 2.0. Please use generative methods "
  367. "from the "
  368. ":class:`_sql.Select` construct in order to apply additional "
  369. "modifications.",
  370. ),
  371. )
  372. def select(self, whereclause=None, **kwargs):
  373. r"""Return a SELECT of this :class:`_expression.FromClause`.
  374. e.g.::
  375. stmt = some_table.select().where(some_table.c.id == 5)
  376. :param whereclause: a WHERE clause, equivalent to calling the
  377. :meth:`_sql.Select.where` method.
  378. :param \**kwargs: additional keyword arguments are passed to the
  379. legacy constructor for :class:`_sql.Select` described at
  380. :meth:`_sql.Select.create_legacy_select`.
  381. .. seealso::
  382. :func:`_expression.select` - general purpose
  383. method which allows for arbitrary column lists.
  384. """
  385. if whereclause is not None:
  386. kwargs["whereclause"] = whereclause
  387. return Select._create_select_from_fromclause(self, [self], **kwargs)
  388. def join(self, right, onclause=None, isouter=False, full=False):
  389. """Return a :class:`_expression.Join` from this
  390. :class:`_expression.FromClause`
  391. to another :class:`FromClause`.
  392. E.g.::
  393. from sqlalchemy import join
  394. j = user_table.join(address_table,
  395. user_table.c.id == address_table.c.user_id)
  396. stmt = select(user_table).select_from(j)
  397. would emit SQL along the lines of::
  398. SELECT user.id, user.name FROM user
  399. JOIN address ON user.id = address.user_id
  400. :param right: the right side of the join; this is any
  401. :class:`_expression.FromClause` object such as a
  402. :class:`_schema.Table` object, and
  403. may also be a selectable-compatible object such as an ORM-mapped
  404. class.
  405. :param onclause: a SQL expression representing the ON clause of the
  406. join. If left at ``None``, :meth:`_expression.FromClause.join`
  407. will attempt to
  408. join the two tables based on a foreign key relationship.
  409. :param isouter: if True, render a LEFT OUTER JOIN, instead of JOIN.
  410. :param full: if True, render a FULL OUTER JOIN, instead of LEFT OUTER
  411. JOIN. Implies :paramref:`.FromClause.join.isouter`.
  412. .. versionadded:: 1.1
  413. .. seealso::
  414. :func:`_expression.join` - standalone function
  415. :class:`_expression.Join` - the type of object produced
  416. """
  417. return Join(self, right, onclause, isouter, full)
  418. def outerjoin(self, right, onclause=None, full=False):
  419. """Return a :class:`_expression.Join` from this
  420. :class:`_expression.FromClause`
  421. to another :class:`FromClause`, with the "isouter" flag set to
  422. True.
  423. E.g.::
  424. from sqlalchemy import outerjoin
  425. j = user_table.outerjoin(address_table,
  426. user_table.c.id == address_table.c.user_id)
  427. The above is equivalent to::
  428. j = user_table.join(
  429. address_table,
  430. user_table.c.id == address_table.c.user_id,
  431. isouter=True)
  432. :param right: the right side of the join; this is any
  433. :class:`_expression.FromClause` object such as a
  434. :class:`_schema.Table` object, and
  435. may also be a selectable-compatible object such as an ORM-mapped
  436. class.
  437. :param onclause: a SQL expression representing the ON clause of the
  438. join. If left at ``None``, :meth:`_expression.FromClause.join`
  439. will attempt to
  440. join the two tables based on a foreign key relationship.
  441. :param full: if True, render a FULL OUTER JOIN, instead of
  442. LEFT OUTER JOIN.
  443. .. versionadded:: 1.1
  444. .. seealso::
  445. :meth:`_expression.FromClause.join`
  446. :class:`_expression.Join`
  447. """
  448. return Join(self, right, onclause, True, full)
  449. def alias(self, name=None, flat=False):
  450. """Return an alias of this :class:`_expression.FromClause`.
  451. E.g.::
  452. a2 = some_table.alias('a2')
  453. The above code creates an :class:`_expression.Alias`
  454. object which can be used
  455. as a FROM clause in any SELECT statement.
  456. .. seealso::
  457. :ref:`core_tutorial_aliases`
  458. :func:`_expression.alias`
  459. """
  460. return Alias._construct(self, name)
  461. @util.preload_module("sqlalchemy.sql.sqltypes")
  462. def table_valued(self):
  463. """Return a :class:`_sql.TableValuedColumn` object for this
  464. :class:`_expression.FromClause`.
  465. A :class:`_sql.TableValuedColumn` is a :class:`_sql.ColumnElement` that
  466. represents a complete row in a table. Support for this construct is
  467. backend dependent, and is supported in various forms by backends
  468. such as PostgreSQL, Oracle and SQL Server.
  469. E.g.::
  470. >>> from sqlalchemy import select, column, func, table
  471. >>> a = table("a", column("id"), column("x"), column("y"))
  472. >>> stmt = select(func.row_to_json(a.table_valued()))
  473. >>> print(stmt)
  474. SELECT row_to_json(a) AS row_to_json_1
  475. FROM a
  476. .. versionadded:: 1.4.0b2
  477. .. seealso::
  478. :ref:`tutorial_functions` - in the :ref:`unified_tutorial`
  479. """
  480. return TableValuedColumn(self, type_api.TABLEVALUE)
  481. def tablesample(self, sampling, name=None, seed=None):
  482. """Return a TABLESAMPLE alias of this :class:`_expression.FromClause`.
  483. The return value is the :class:`_expression.TableSample`
  484. construct also
  485. provided by the top-level :func:`_expression.tablesample` function.
  486. .. versionadded:: 1.1
  487. .. seealso::
  488. :func:`_expression.tablesample` - usage guidelines and parameters
  489. """
  490. return TableSample._construct(self, sampling, name, seed)
  491. def is_derived_from(self, fromclause):
  492. """Return ``True`` if this :class:`_expression.FromClause` is
  493. 'derived' from the given ``FromClause``.
  494. An example would be an Alias of a Table is derived from that Table.
  495. """
  496. # this is essentially an "identity" check in the base class.
  497. # Other constructs override this to traverse through
  498. # contained elements.
  499. return fromclause in self._cloned_set
  500. def _is_lexical_equivalent(self, other):
  501. """Return ``True`` if this :class:`_expression.FromClause` and
  502. the other represent the same lexical identity.
  503. This tests if either one is a copy of the other, or
  504. if they are the same via annotation identity.
  505. """
  506. return self._cloned_set.intersection(other._cloned_set)
  507. @property
  508. def description(self):
  509. """A brief description of this :class:`_expression.FromClause`.
  510. Used primarily for error message formatting.
  511. """
  512. return getattr(self, "name", self.__class__.__name__ + " object")
  513. def _generate_fromclause_column_proxies(self, fromclause):
  514. fromclause._columns._populate_separate_keys(
  515. col._make_proxy(fromclause) for col in self.c
  516. )
  517. @property
  518. def exported_columns(self):
  519. """A :class:`_expression.ColumnCollection`
  520. that represents the "exported"
  521. columns of this :class:`_expression.Selectable`.
  522. The "exported" columns for a :class:`_expression.FromClause`
  523. object are synonymous
  524. with the :attr:`_expression.FromClause.columns` collection.
  525. .. versionadded:: 1.4
  526. .. seealso::
  527. :attr:`_expression.Selectable.exported_columns`
  528. :attr:`_expression.SelectBase.exported_columns`
  529. """
  530. return self.columns
  531. @util.memoized_property
  532. def columns(self):
  533. """A named-based collection of :class:`_expression.ColumnElement`
  534. objects maintained by this :class:`_expression.FromClause`.
  535. The :attr:`.columns`, or :attr:`.c` collection, is the gateway
  536. to the construction of SQL expressions using table-bound or
  537. other selectable-bound columns::
  538. select(mytable).where(mytable.c.somecolumn == 5)
  539. :return: a :class:`.ColumnCollection` object.
  540. """
  541. if "_columns" not in self.__dict__:
  542. self._init_collections()
  543. self._populate_column_collection()
  544. return self._columns.as_immutable()
  545. @property
  546. def entity_namespace(self):
  547. """Return a namespace used for name-based access in SQL expressions.
  548. This is the namespace that is used to resolve "filter_by()" type
  549. expressions, such as::
  550. stmt.filter_by(address='some address')
  551. It defaults to the ``.c`` collection, however internally it can
  552. be overridden using the "entity_namespace" annotation to deliver
  553. alternative results.
  554. """
  555. return self.columns
  556. @util.memoized_property
  557. def primary_key(self):
  558. """Return the iterable collection of :class:`_schema.Column` objects
  559. which comprise the primary key of this :class:`_selectable.FromClause`.
  560. For a :class:`_schema.Table` object, this collection is represented
  561. by the :class:`_schema.PrimaryKeyConstraint` which itself is an
  562. iterable collection of :class:`_schema.Column` objects.
  563. """
  564. self._init_collections()
  565. self._populate_column_collection()
  566. return self.primary_key
  567. @util.memoized_property
  568. def foreign_keys(self):
  569. """Return the collection of :class:`_schema.ForeignKey` marker objects
  570. which this FromClause references.
  571. Each :class:`_schema.ForeignKey` is a member of a
  572. :class:`_schema.Table`-wide
  573. :class:`_schema.ForeignKeyConstraint`.
  574. .. seealso::
  575. :attr:`_schema.Table.foreign_key_constraints`
  576. """
  577. self._init_collections()
  578. self._populate_column_collection()
  579. return self.foreign_keys
  580. def _reset_column_collection(self):
  581. """Reset the attributes linked to the ``FromClause.c`` attribute.
  582. This collection is separate from all the other memoized things
  583. as it has shown to be sensitive to being cleared out in situations
  584. where enclosing code, typically in a replacement traversal scenario,
  585. has already established strong relationships
  586. with the exported columns.
  587. The collection is cleared for the case where a table is having a
  588. column added to it as well as within a Join during copy internals.
  589. """
  590. for key in ["_columns", "columns", "primary_key", "foreign_keys"]:
  591. self.__dict__.pop(key, None)
  592. c = property(
  593. attrgetter("columns"),
  594. doc="""
  595. A named-based collection of :class:`_expression.ColumnElement`
  596. objects maintained by this :class:`_expression.FromClause`.
  597. The :attr:`_sql.FromClause.c` attribute is an alias for the
  598. :attr:`_sql.FromClause.columns` atttribute.
  599. :return: a :class:`.ColumnCollection`
  600. """,
  601. )
  602. _select_iterable = property(attrgetter("columns"))
  603. def _init_collections(self):
  604. assert "_columns" not in self.__dict__
  605. assert "primary_key" not in self.__dict__
  606. assert "foreign_keys" not in self.__dict__
  607. self._columns = ColumnCollection()
  608. self.primary_key = ColumnSet()
  609. self.foreign_keys = set()
  610. @property
  611. def _cols_populated(self):
  612. return "_columns" in self.__dict__
  613. def _populate_column_collection(self):
  614. """Called on subclasses to establish the .c collection.
  615. Each implementation has a different way of establishing
  616. this collection.
  617. """
  618. def _refresh_for_new_column(self, column):
  619. """Given a column added to the .c collection of an underlying
  620. selectable, produce the local version of that column, assuming this
  621. selectable ultimately should proxy this column.
  622. this is used to "ping" a derived selectable to add a new column
  623. to its .c. collection when a Column has been added to one of the
  624. Table objects it ultimately derives from.
  625. If the given selectable hasn't populated its .c. collection yet,
  626. it should at least pass on the message to the contained selectables,
  627. but it will return None.
  628. This method is currently used by Declarative to allow Table
  629. columns to be added to a partially constructed inheritance
  630. mapping that may have already produced joins. The method
  631. isn't public right now, as the full span of implications
  632. and/or caveats aren't yet clear.
  633. It's also possible that this functionality could be invoked by
  634. default via an event, which would require that
  635. selectables maintain a weak referencing collection of all
  636. derivations.
  637. """
  638. self._reset_column_collection()
  639. def _anonymous_fromclause(self, name=None, flat=False):
  640. return self.alias(name=name)
  641. LABEL_STYLE_NONE = util.symbol(
  642. "LABEL_STYLE_NONE",
  643. """Label style indicating no automatic labeling should be applied to the
  644. columns clause of a SELECT statement.
  645. Below, the columns named ``columna`` are both rendered as is, meaning that
  646. the name ``columna`` can only refer to the first occurrence of this name
  647. within a result set, as well as if the statement were used as a subquery::
  648. >>> from sqlalchemy import table, column, select, true, LABEL_STYLE_NONE
  649. >>> table1 = table("table1", column("columna"), column("columnb"))
  650. >>> table2 = table("table2", column("columna"), column("columnc"))
  651. >>> print(select(table1, table2).join(table2, true()).set_label_style(LABEL_STYLE_NONE))
  652. SELECT table1.columna, table1.columnb, table2.columna, table2.columnc
  653. FROM table1 JOIN table2 ON true
  654. Used with the :meth:`_sql.Select.set_label_style` method.
  655. .. versionadded:: 1.4
  656. """, # noqa E501
  657. )
  658. LABEL_STYLE_TABLENAME_PLUS_COL = util.symbol(
  659. "LABEL_STYLE_TABLENAME_PLUS_COL",
  660. """Label style indicating all columns should be labeled as
  661. ``<tablename>_<columnname>`` when generating the columns clause of a SELECT
  662. statement, to disambiguate same-named columns referenced from different
  663. tables, aliases, or subqueries.
  664. Below, all column names are given a label so that the two same-named
  665. columns ``columna`` are disambiguated as ``table1_columna`` and
  666. ``table2_columna`::
  667. >>> from sqlalchemy import table, column, select, true, LABEL_STYLE_TABLENAME_PLUS_COL
  668. >>> table1 = table("table1", column("columna"), column("columnb"))
  669. >>> table2 = table("table2", column("columna"), column("columnc"))
  670. >>> print(select(table1, table2).join(table2, true()).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL))
  671. SELECT table1.columna AS table1_columna, table1.columnb AS table1_columnb, table2.columna AS table2_columna, table2.columnc AS table2_columnc
  672. FROM table1 JOIN table2 ON true
  673. Used with the :meth:`_sql.GenerativeSelect.set_label_style` method.
  674. Equivalent to the legacy method ``Select.apply_labels()``;
  675. :data:`_sql.LABEL_STYLE_TABLENAME_PLUS_COL` is SQLAlchemy's legacy
  676. auto-labeling style. :data:`_sql.LABEL_STYLE_DISAMBIGUATE_ONLY` provides a
  677. less intrusive approach to disambiguation of same-named column expressions.
  678. .. versionadded:: 1.4
  679. """, # noqa E501
  680. )
  681. LABEL_STYLE_DISAMBIGUATE_ONLY = util.symbol(
  682. "LABEL_STYLE_DISAMBIGUATE_ONLY",
  683. """Label style indicating that columns with a name that conflicts with
  684. an existing name should be labeled with a semi-anonymizing label
  685. when generating the columns clause of a SELECT statement.
  686. Below, most column names are left unaffected, except for the second
  687. occurrence of the name ``columna``, which is labeled using the
  688. label ``columna_1`` to disambiguate it from that of ``tablea.columna``::
  689. >>> from sqlalchemy import table, column, select, true, LABEL_STYLE_DISAMBIGUATE_ONLY
  690. >>> table1 = table("table1", column("columna"), column("columnb"))
  691. >>> table2 = table("table2", column("columna"), column("columnc"))
  692. >>> print(select(table1, table2).join(table2, true()).set_label_style(LABEL_STYLE_DISAMBIGUATE_ONLY))
  693. SELECT table1.columna, table1.columnb, table2.columna AS columna_1, table2.columnc
  694. FROM table1 JOIN table2 ON true
  695. Used with the :meth:`_sql.GenerativeSelect.set_label_style` method,
  696. :data:`_sql.LABEL_STYLE_DISAMBIGUATE_ONLY` is the default labeling style
  697. for all SELECT statements outside of :term:`1.x style` ORM queries.
  698. .. versionadded:: 1.4
  699. """, # noqa: E501,
  700. )
  701. LABEL_STYLE_DEFAULT = LABEL_STYLE_DISAMBIGUATE_ONLY
  702. """The default label style, refers to
  703. :data:`_sql.LABEL_STYLE_DISAMBIGUATE_ONLY`.
  704. .. versionadded:: 1.4
  705. """
  706. class Join(roles.DMLTableRole, FromClause):
  707. """Represent a ``JOIN`` construct between two
  708. :class:`_expression.FromClause`
  709. elements.
  710. The public constructor function for :class:`_expression.Join`
  711. is the module-level
  712. :func:`_expression.join()` function, as well as the
  713. :meth:`_expression.FromClause.join` method
  714. of any :class:`_expression.FromClause` (e.g. such as
  715. :class:`_schema.Table`).
  716. .. seealso::
  717. :func:`_expression.join`
  718. :meth:`_expression.FromClause.join`
  719. """
  720. __visit_name__ = "join"
  721. _traverse_internals = [
  722. ("left", InternalTraversal.dp_clauseelement),
  723. ("right", InternalTraversal.dp_clauseelement),
  724. ("onclause", InternalTraversal.dp_clauseelement),
  725. ("isouter", InternalTraversal.dp_boolean),
  726. ("full", InternalTraversal.dp_boolean),
  727. ]
  728. _is_join = True
  729. def __init__(self, left, right, onclause=None, isouter=False, full=False):
  730. """Construct a new :class:`_expression.Join`.
  731. The usual entrypoint here is the :func:`_expression.join`
  732. function or the :meth:`_expression.FromClause.join` method of any
  733. :class:`_expression.FromClause` object.
  734. """
  735. self.left = coercions.expect(
  736. roles.FromClauseRole, left, deannotate=True
  737. )
  738. self.right = coercions.expect(
  739. roles.FromClauseRole, right, deannotate=True
  740. ).self_group()
  741. if onclause is None:
  742. self.onclause = self._match_primaries(self.left, self.right)
  743. else:
  744. # note: taken from If91f61527236fd4d7ae3cad1f24c38be921c90ba
  745. # not merged yet
  746. self.onclause = coercions.expect(
  747. roles.OnClauseRole, onclause
  748. ).self_group(against=operators._asbool)
  749. self.isouter = isouter
  750. self.full = full
  751. @classmethod
  752. def _create_outerjoin(cls, left, right, onclause=None, full=False):
  753. """Return an ``OUTER JOIN`` clause element.
  754. The returned object is an instance of :class:`_expression.Join`.
  755. Similar functionality is also available via the
  756. :meth:`_expression.FromClause.outerjoin` method on any
  757. :class:`_expression.FromClause`.
  758. :param left: The left side of the join.
  759. :param right: The right side of the join.
  760. :param onclause: Optional criterion for the ``ON`` clause, is
  761. derived from foreign key relationships established between
  762. left and right otherwise.
  763. To chain joins together, use the :meth:`_expression.FromClause.join`
  764. or
  765. :meth:`_expression.FromClause.outerjoin` methods on the resulting
  766. :class:`_expression.Join` object.
  767. """
  768. return cls(left, right, onclause, isouter=True, full=full)
  769. @classmethod
  770. def _create_join(
  771. cls, left, right, onclause=None, isouter=False, full=False
  772. ):
  773. """Produce a :class:`_expression.Join` object, given two
  774. :class:`_expression.FromClause`
  775. expressions.
  776. E.g.::
  777. j = join(user_table, address_table,
  778. user_table.c.id == address_table.c.user_id)
  779. stmt = select(user_table).select_from(j)
  780. would emit SQL along the lines of::
  781. SELECT user.id, user.name FROM user
  782. JOIN address ON user.id = address.user_id
  783. Similar functionality is available given any
  784. :class:`_expression.FromClause` object (e.g. such as a
  785. :class:`_schema.Table`) using
  786. the :meth:`_expression.FromClause.join` method.
  787. :param left: The left side of the join.
  788. :param right: the right side of the join; this is any
  789. :class:`_expression.FromClause` object such as a
  790. :class:`_schema.Table` object, and
  791. may also be a selectable-compatible object such as an ORM-mapped
  792. class.
  793. :param onclause: a SQL expression representing the ON clause of the
  794. join. If left at ``None``, :meth:`_expression.FromClause.join`
  795. will attempt to
  796. join the two tables based on a foreign key relationship.
  797. :param isouter: if True, render a LEFT OUTER JOIN, instead of JOIN.
  798. :param full: if True, render a FULL OUTER JOIN, instead of JOIN.
  799. .. versionadded:: 1.1
  800. .. seealso::
  801. :meth:`_expression.FromClause.join` - method form,
  802. based on a given left side.
  803. :class:`_expression.Join` - the type of object produced.
  804. """
  805. return cls(left, right, onclause, isouter, full)
  806. @property
  807. def description(self):
  808. return "Join object on %s(%d) and %s(%d)" % (
  809. self.left.description,
  810. id(self.left),
  811. self.right.description,
  812. id(self.right),
  813. )
  814. def is_derived_from(self, fromclause):
  815. return (
  816. # use hash() to ensure direct comparison to annotated works
  817. # as well
  818. hash(fromclause) == hash(self)
  819. or self.left.is_derived_from(fromclause)
  820. or self.right.is_derived_from(fromclause)
  821. )
  822. def self_group(self, against=None):
  823. return FromGrouping(self)
  824. @util.preload_module("sqlalchemy.sql.util")
  825. def _populate_column_collection(self):
  826. sqlutil = util.preloaded.sql_util
  827. columns = [c for c in self.left.columns] + [
  828. c for c in self.right.columns
  829. ]
  830. self.primary_key.extend(
  831. sqlutil.reduce_columns(
  832. (c for c in columns if c.primary_key), self.onclause
  833. )
  834. )
  835. self._columns._populate_separate_keys(
  836. (col._key_label, col) for col in columns
  837. )
  838. self.foreign_keys.update(
  839. itertools.chain(*[col.foreign_keys for col in columns])
  840. )
  841. def _refresh_for_new_column(self, column):
  842. super(Join, self)._refresh_for_new_column(column)
  843. self.left._refresh_for_new_column(column)
  844. self.right._refresh_for_new_column(column)
  845. def _match_primaries(self, left, right):
  846. if isinstance(left, Join):
  847. left_right = left.right
  848. else:
  849. left_right = None
  850. return self._join_condition(left, right, a_subset=left_right)
  851. @classmethod
  852. def _join_condition(
  853. cls, a, b, a_subset=None, consider_as_foreign_keys=None
  854. ):
  855. """Create a join condition between two tables or selectables.
  856. e.g.::
  857. join_condition(tablea, tableb)
  858. would produce an expression along the lines of::
  859. tablea.c.id==tableb.c.tablea_id
  860. The join is determined based on the foreign key relationships
  861. between the two selectables. If there are multiple ways
  862. to join, or no way to join, an error is raised.
  863. :param a_subset: An optional expression that is a sub-component
  864. of ``a``. An attempt will be made to join to just this sub-component
  865. first before looking at the full ``a`` construct, and if found
  866. will be successful even if there are other ways to join to ``a``.
  867. This allows the "right side" of a join to be passed thereby
  868. providing a "natural join".
  869. """
  870. constraints = cls._joincond_scan_left_right(
  871. a, a_subset, b, consider_as_foreign_keys
  872. )
  873. if len(constraints) > 1:
  874. cls._joincond_trim_constraints(
  875. a, b, constraints, consider_as_foreign_keys
  876. )
  877. if len(constraints) == 0:
  878. if isinstance(b, FromGrouping):
  879. hint = (
  880. " Perhaps you meant to convert the right side to a "
  881. "subquery using alias()?"
  882. )
  883. else:
  884. hint = ""
  885. raise exc.NoForeignKeysError(
  886. "Can't find any foreign key relationships "
  887. "between '%s' and '%s'.%s"
  888. % (a.description, b.description, hint)
  889. )
  890. crit = [(x == y) for x, y in list(constraints.values())[0]]
  891. if len(crit) == 1:
  892. return crit[0]
  893. else:
  894. return and_(*crit)
  895. @classmethod
  896. def _can_join(cls, left, right, consider_as_foreign_keys=None):
  897. if isinstance(left, Join):
  898. left_right = left.right
  899. else:
  900. left_right = None
  901. constraints = cls._joincond_scan_left_right(
  902. a=left,
  903. b=right,
  904. a_subset=left_right,
  905. consider_as_foreign_keys=consider_as_foreign_keys,
  906. )
  907. return bool(constraints)
  908. @classmethod
  909. @util.preload_module("sqlalchemy.sql.util")
  910. def _joincond_scan_left_right(
  911. cls, a, a_subset, b, consider_as_foreign_keys
  912. ):
  913. sql_util = util.preloaded.sql_util
  914. a = coercions.expect(roles.FromClauseRole, a)
  915. b = coercions.expect(roles.FromClauseRole, b)
  916. constraints = collections.defaultdict(list)
  917. for left in (a_subset, a):
  918. if left is None:
  919. continue
  920. for fk in sorted(
  921. b.foreign_keys, key=lambda fk: fk.parent._creation_order
  922. ):
  923. if (
  924. consider_as_foreign_keys is not None
  925. and fk.parent not in consider_as_foreign_keys
  926. ):
  927. continue
  928. try:
  929. col = fk.get_referent(left)
  930. except exc.NoReferenceError as nrte:
  931. table_names = {t.name for t in sql_util.find_tables(left)}
  932. if nrte.table_name in table_names:
  933. raise
  934. else:
  935. continue
  936. if col is not None:
  937. constraints[fk.constraint].append((col, fk.parent))
  938. if left is not b:
  939. for fk in sorted(
  940. left.foreign_keys, key=lambda fk: fk.parent._creation_order
  941. ):
  942. if (
  943. consider_as_foreign_keys is not None
  944. and fk.parent not in consider_as_foreign_keys
  945. ):
  946. continue
  947. try:
  948. col = fk.get_referent(b)
  949. except exc.NoReferenceError as nrte:
  950. table_names = {t.name for t in sql_util.find_tables(b)}
  951. if nrte.table_name in table_names:
  952. raise
  953. else:
  954. continue
  955. if col is not None:
  956. constraints[fk.constraint].append((col, fk.parent))
  957. if constraints:
  958. break
  959. return constraints
  960. @classmethod
  961. def _joincond_trim_constraints(
  962. cls, a, b, constraints, consider_as_foreign_keys
  963. ):
  964. # more than one constraint matched. narrow down the list
  965. # to include just those FKCs that match exactly to
  966. # "consider_as_foreign_keys".
  967. if consider_as_foreign_keys:
  968. for const in list(constraints):
  969. if set(f.parent for f in const.elements) != set(
  970. consider_as_foreign_keys
  971. ):
  972. del constraints[const]
  973. # if still multiple constraints, but
  974. # they all refer to the exact same end result, use it.
  975. if len(constraints) > 1:
  976. dedupe = set(tuple(crit) for crit in constraints.values())
  977. if len(dedupe) == 1:
  978. key = list(constraints)[0]
  979. constraints = {key: constraints[key]}
  980. if len(constraints) != 1:
  981. raise exc.AmbiguousForeignKeysError(
  982. "Can't determine join between '%s' and '%s'; "
  983. "tables have more than one foreign key "
  984. "constraint relationship between them. "
  985. "Please specify the 'onclause' of this "
  986. "join explicitly." % (a.description, b.description)
  987. )
  988. @util.deprecated_params(
  989. whereclause=(
  990. "2.0",
  991. "The :paramref:`_sql.Join.select().whereclause` parameter "
  992. "is deprecated and will be removed in version 2.0. "
  993. "Please make use of "
  994. "the :meth:`.Select.where` "
  995. "method to add WHERE criteria to the SELECT statement.",
  996. ),
  997. kwargs=(
  998. "2.0",
  999. "The :meth:`_sql.Join.select` method will no longer accept "
  1000. "keyword arguments in version 2.0. Please use generative "
  1001. "methods from the "
  1002. ":class:`_sql.Select` construct in order to apply additional "
  1003. "modifications.",
  1004. ),
  1005. )
  1006. def select(self, whereclause=None, **kwargs):
  1007. r"""Create a :class:`_expression.Select` from this
  1008. :class:`_expression.Join`.
  1009. E.g.::
  1010. stmt = table_a.join(table_b, table_a.c.id == table_b.c.a_id)
  1011. stmt = stmt.select()
  1012. The above will produce a SQL string resembling::
  1013. SELECT table_a.id, table_a.col, table_b.id, table_b.a_id
  1014. FROM table_a JOIN table_b ON table_a.id = table_b.a_id
  1015. :param whereclause: WHERE criteria, same as calling
  1016. :meth:`_sql.Select.where` on the resulting statement
  1017. :param \**kwargs: additional keyword arguments are passed to the
  1018. legacy constructor for :class:`_sql.Select` described at
  1019. :meth:`_sql.Select.create_legacy_select`.
  1020. """
  1021. collist = [self.left, self.right]
  1022. if whereclause is not None:
  1023. kwargs["whereclause"] = whereclause
  1024. return Select._create_select_from_fromclause(
  1025. self, collist, **kwargs
  1026. ).select_from(self)
  1027. @property
  1028. @util.deprecated_20(
  1029. ":attr:`.Executable.bind`",
  1030. alternative="Bound metadata is being removed as of SQLAlchemy 2.0.",
  1031. enable_warnings=False,
  1032. )
  1033. def bind(self):
  1034. """Return the bound engine associated with either the left or right
  1035. side of this :class:`_sql.Join`.
  1036. """
  1037. return self.left.bind or self.right.bind
  1038. @util.preload_module("sqlalchemy.sql.util")
  1039. def _anonymous_fromclause(self, name=None, flat=False):
  1040. sqlutil = util.preloaded.sql_util
  1041. if flat:
  1042. if name is not None:
  1043. raise exc.ArgumentError("Can't send name argument with flat")
  1044. left_a, right_a = (
  1045. self.left._anonymous_fromclause(flat=True),
  1046. self.right._anonymous_fromclause(flat=True),
  1047. )
  1048. adapter = sqlutil.ClauseAdapter(left_a).chain(
  1049. sqlutil.ClauseAdapter(right_a)
  1050. )
  1051. return left_a.join(
  1052. right_a,
  1053. adapter.traverse(self.onclause),
  1054. isouter=self.isouter,
  1055. full=self.full,
  1056. )
  1057. else:
  1058. return (
  1059. self.select()
  1060. .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
  1061. .correlate(None)
  1062. .alias(name)
  1063. )
  1064. @util.deprecated_20(
  1065. ":meth:`_sql.Join.alias`",
  1066. alternative="Create a select + subquery, or alias the "
  1067. "individual tables inside the join, instead.",
  1068. )
  1069. def alias(self, name=None, flat=False):
  1070. r"""Return an alias of this :class:`_expression.Join`.
  1071. The default behavior here is to first produce a SELECT
  1072. construct from this :class:`_expression.Join`, then to produce an
  1073. :class:`_expression.Alias` from that. So given a join of the form::
  1074. j = table_a.join(table_b, table_a.c.id == table_b.c.a_id)
  1075. The JOIN by itself would look like::
  1076. table_a JOIN table_b ON table_a.id = table_b.a_id
  1077. Whereas the alias of the above, ``j.alias()``, would in a
  1078. SELECT context look like::
  1079. (SELECT table_a.id AS table_a_id, table_b.id AS table_b_id,
  1080. table_b.a_id AS table_b_a_id
  1081. FROM table_a
  1082. JOIN table_b ON table_a.id = table_b.a_id) AS anon_1
  1083. The equivalent long-hand form, given a :class:`_expression.Join`
  1084. object ``j``, is::
  1085. from sqlalchemy import select, alias
  1086. j = alias(
  1087. select(j.left, j.right).\
  1088. select_from(j).\
  1089. set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL).\
  1090. correlate(False),
  1091. name=name
  1092. )
  1093. The selectable produced by :meth:`_expression.Join.alias`
  1094. features the same
  1095. columns as that of the two individual selectables presented under
  1096. a single name - the individual columns are "auto-labeled", meaning
  1097. the ``.c.`` collection of the resulting :class:`_expression.Alias`
  1098. represents
  1099. the names of the individual columns using a
  1100. ``<tablename>_<columname>`` scheme::
  1101. j.c.table_a_id
  1102. j.c.table_b_a_id
  1103. :meth:`_expression.Join.alias` also features an alternate
  1104. option for aliasing joins which produces no enclosing SELECT and
  1105. does not normally apply labels to the column names. The
  1106. ``flat=True`` option will call :meth:`_expression.FromClause.alias`
  1107. against the left and right sides individually.
  1108. Using this option, no new ``SELECT`` is produced;
  1109. we instead, from a construct as below::
  1110. j = table_a.join(table_b, table_a.c.id == table_b.c.a_id)
  1111. j = j.alias(flat=True)
  1112. we get a result like this::
  1113. table_a AS table_a_1 JOIN table_b AS table_b_1 ON
  1114. table_a_1.id = table_b_1.a_id
  1115. The ``flat=True`` argument is also propagated to the contained
  1116. selectables, so that a composite join such as::
  1117. j = table_a.join(
  1118. table_b.join(table_c,
  1119. table_b.c.id == table_c.c.b_id),
  1120. table_b.c.a_id == table_a.c.id
  1121. ).alias(flat=True)
  1122. Will produce an expression like::
  1123. table_a AS table_a_1 JOIN (
  1124. table_b AS table_b_1 JOIN table_c AS table_c_1
  1125. ON table_b_1.id = table_c_1.b_id
  1126. ) ON table_a_1.id = table_b_1.a_id
  1127. The standalone :func:`_expression.alias` function as well as the
  1128. base :meth:`_expression.FromClause.alias`
  1129. method also support the ``flat=True``
  1130. argument as a no-op, so that the argument can be passed to the
  1131. ``alias()`` method of any selectable.
  1132. :param name: name given to the alias.
  1133. :param flat: if True, produce an alias of the left and right
  1134. sides of this :class:`_expression.Join` and return the join of those
  1135. two selectables. This produces join expression that does not
  1136. include an enclosing SELECT.
  1137. .. seealso::
  1138. :ref:`core_tutorial_aliases`
  1139. :func:`_expression.alias`
  1140. """
  1141. return self._anonymous_fromclause(flat=flat, name=name)
  1142. @property
  1143. def _hide_froms(self):
  1144. return itertools.chain(
  1145. *[_from_objects(x.left, x.right) for x in self._cloned_set]
  1146. )
  1147. @property
  1148. def _from_objects(self):
  1149. return [self] + self.left._from_objects + self.right._from_objects
  1150. class NoInit(object):
  1151. def __init__(self, *arg, **kw):
  1152. raise NotImplementedError(
  1153. "The %s class is not intended to be constructed "
  1154. "directly. Please use the %s() standalone "
  1155. "function or the %s() method available from appropriate "
  1156. "selectable objects."
  1157. % (
  1158. self.__class__.__name__,
  1159. self.__class__.__name__.lower(),
  1160. self.__class__.__name__.lower(),
  1161. )
  1162. )
  1163. # FromClause ->
  1164. # AliasedReturnsRows
  1165. # -> Alias only for FromClause
  1166. # -> Subquery only for SelectBase
  1167. # -> CTE only for HasCTE -> SelectBase, DML
  1168. # -> Lateral -> FromClause, but we accept SelectBase
  1169. # w/ non-deprecated coercion
  1170. # -> TableSample -> only for FromClause
  1171. class AliasedReturnsRows(NoInit, FromClause):
  1172. """Base class of aliases against tables, subqueries, and other
  1173. selectables."""
  1174. _is_from_container = True
  1175. named_with_column = True
  1176. _supports_derived_columns = False
  1177. _traverse_internals = [
  1178. ("element", InternalTraversal.dp_clauseelement),
  1179. ("name", InternalTraversal.dp_anon_name),
  1180. ]
  1181. @classmethod
  1182. def _construct(cls, *arg, **kw):
  1183. obj = cls.__new__(cls)
  1184. obj._init(*arg, **kw)
  1185. return obj
  1186. @classmethod
  1187. def _factory(cls, returnsrows, name=None):
  1188. """Base factory method. Subclasses need to provide this."""
  1189. raise NotImplementedError()
  1190. def _init(self, selectable, name=None):
  1191. self.element = coercions.expect(
  1192. roles.ReturnsRowsRole, selectable, apply_propagate_attrs=self
  1193. )
  1194. self.element = selectable
  1195. self._orig_name = name
  1196. if name is None:
  1197. if (
  1198. isinstance(selectable, FromClause)
  1199. and selectable.named_with_column
  1200. ):
  1201. name = getattr(selectable, "name", None)
  1202. if isinstance(name, _anonymous_label):
  1203. name = None
  1204. name = _anonymous_label.safe_construct(id(self), name or "anon")
  1205. self.name = name
  1206. def _refresh_for_new_column(self, column):
  1207. super(AliasedReturnsRows, self)._refresh_for_new_column(column)
  1208. self.element._refresh_for_new_column(column)
  1209. @property
  1210. def description(self):
  1211. name = self.name
  1212. if isinstance(name, _anonymous_label):
  1213. name = "anon_1"
  1214. if util.py3k:
  1215. return name
  1216. else:
  1217. return name.encode("ascii", "backslashreplace")
  1218. @property
  1219. def original(self):
  1220. """Legacy for dialects that are referring to Alias.original."""
  1221. return self.element
  1222. def is_derived_from(self, fromclause):
  1223. if fromclause in self._cloned_set:
  1224. return True
  1225. return self.element.is_derived_from(fromclause)
  1226. def _populate_column_collection(self):
  1227. self.element._generate_fromclause_column_proxies(self)
  1228. def _copy_internals(self, clone=_clone, **kw):
  1229. existing_element = self.element
  1230. super(AliasedReturnsRows, self)._copy_internals(clone=clone, **kw)
  1231. # the element clone is usually against a Table that returns the
  1232. # same object. don't reset exported .c. collections and other
  1233. # memoized details if it was not changed. this saves a lot on
  1234. # performance.
  1235. if existing_element is not self.element:
  1236. self._reset_column_collection()
  1237. @property
  1238. def _from_objects(self):
  1239. return [self]
  1240. @property
  1241. def bind(self):
  1242. return self.element.bind
  1243. class Alias(roles.DMLTableRole, AliasedReturnsRows):
  1244. """Represents an table or selectable alias (AS).
  1245. Represents an alias, as typically applied to any table or
  1246. sub-select within a SQL statement using the ``AS`` keyword (or
  1247. without the keyword on certain databases such as Oracle).
  1248. This object is constructed from the :func:`_expression.alias` module
  1249. level function as well as the :meth:`_expression.FromClause.alias`
  1250. method available
  1251. on all :class:`_expression.FromClause` subclasses.
  1252. .. seealso::
  1253. :meth:`_expression.FromClause.alias`
  1254. """
  1255. __visit_name__ = "alias"
  1256. inherit_cache = True
  1257. @classmethod
  1258. def _factory(cls, selectable, name=None, flat=False):
  1259. """Return an :class:`_expression.Alias` object.
  1260. An :class:`_expression.Alias` represents any
  1261. :class:`_expression.FromClause`
  1262. with an alternate name assigned within SQL, typically using the ``AS``
  1263. clause when generated, e.g. ``SELECT * FROM table AS aliasname``.
  1264. Similar functionality is available via the
  1265. :meth:`_expression.FromClause.alias`
  1266. method available on all :class:`_expression.FromClause` subclasses.
  1267. In terms of
  1268. a SELECT object as generated from the :func:`_expression.select`
  1269. function, the :meth:`_expression.SelectBase.alias` method returns an
  1270. :class:`_expression.Alias` or similar object which represents a named,
  1271. parenthesized subquery.
  1272. When an :class:`_expression.Alias` is created from a
  1273. :class:`_schema.Table` object,
  1274. this has the effect of the table being rendered
  1275. as ``tablename AS aliasname`` in a SELECT statement.
  1276. For :func:`_expression.select` objects, the effect is that of
  1277. creating a named subquery, i.e. ``(select ...) AS aliasname``.
  1278. The ``name`` parameter is optional, and provides the name
  1279. to use in the rendered SQL. If blank, an "anonymous" name
  1280. will be deterministically generated at compile time.
  1281. Deterministic means the name is guaranteed to be unique against
  1282. other constructs used in the same statement, and will also be the
  1283. same name for each successive compilation of the same statement
  1284. object.
  1285. :param selectable: any :class:`_expression.FromClause` subclass,
  1286. such as a table, select statement, etc.
  1287. :param name: string name to be assigned as the alias.
  1288. If ``None``, a name will be deterministically generated
  1289. at compile time.
  1290. :param flat: Will be passed through to if the given selectable
  1291. is an instance of :class:`_expression.Join` - see
  1292. :meth:`_expression.Join.alias`
  1293. for details.
  1294. """
  1295. return coercions.expect(
  1296. roles.FromClauseRole, selectable, allow_select=True
  1297. ).alias(name=name, flat=flat)
  1298. class TableValuedAlias(Alias):
  1299. """An alias against a "table valued" SQL function.
  1300. This construct provides for a SQL function that returns columns
  1301. to be used in the FROM clause of a SELECT statement. The
  1302. object is generated using the :meth:`_functions.FunctionElement.table_valued`
  1303. method, e.g.::
  1304. >>> from sqlalchemy import select, func
  1305. >>> fn = func.json_array_elements_text('["one", "two", "three"]').table_valued("value")
  1306. >>> print(select(fn.c.value))
  1307. SELECT anon_1.value
  1308. FROM json_array_elements_text(:json_array_elements_text_1) AS anon_1
  1309. .. versionadded:: 1.4.0b2
  1310. .. seealso::
  1311. :ref:`tutorial_functions_table_valued` - in the :ref:`unified_tutorial`
  1312. """ # noqa E501
  1313. __visit_name__ = "table_valued_alias"
  1314. _supports_derived_columns = True
  1315. _render_derived = False
  1316. _render_derived_w_types = False
  1317. _traverse_internals = [
  1318. ("element", InternalTraversal.dp_clauseelement),
  1319. ("name", InternalTraversal.dp_anon_name),
  1320. ("_tableval_type", InternalTraversal.dp_type),
  1321. ("_render_derived", InternalTraversal.dp_boolean),
  1322. ("_render_derived_w_types", InternalTraversal.dp_boolean),
  1323. ]
  1324. def _init(self, selectable, name=None, table_value_type=None):
  1325. super(TableValuedAlias, self)._init(selectable, name=name)
  1326. self._tableval_type = (
  1327. type_api.TABLEVALUE
  1328. if table_value_type is None
  1329. else table_value_type
  1330. )
  1331. @HasMemoized.memoized_attribute
  1332. def column(self):
  1333. """Return a column expression representing this
  1334. :class:`_sql.TableValuedAlias`.
  1335. This accessor is used to implement the
  1336. :meth:`_functions.FunctionElement.column_valued` method. See that
  1337. method for further details.
  1338. E.g.::
  1339. >>> print(select(func.some_func().table_valued("value").column))
  1340. SELECT anon_1 FROM some_func() AS anon_1
  1341. .. seealso::
  1342. :meth:`_functions.FunctionElement.column_valued`
  1343. """
  1344. return TableValuedColumn(self, self._tableval_type)
  1345. def alias(self, name=None):
  1346. """Return a new alias of this :class:`_sql.TableValuedAlias`.
  1347. This creates a distinct FROM object that will be distinguished
  1348. from the original one when used in a SQL statement.
  1349. """
  1350. tva = TableValuedAlias._construct(self, name=name)
  1351. if self._render_derived:
  1352. tva._render_derived = True
  1353. tva._render_derived_w_types = self._render_derived_w_types
  1354. return tva
  1355. def lateral(self, name=None):
  1356. """Return a new :class:`_sql.TableValuedAlias` with the lateral flag set,
  1357. so that it renders as LATERAL.
  1358. .. seealso::
  1359. :func:`_expression.lateral`
  1360. """
  1361. tva = self.alias(name=name)
  1362. tva._is_lateral = True
  1363. return tva
  1364. def render_derived(self, name=None, with_types=False):
  1365. """Apply "render derived" to this :class:`_sql.TableValuedAlias`.
  1366. This has the effect of the individual column names listed out
  1367. after the alias name in the "AS" sequence, e.g.::
  1368. >>> print(
  1369. ... select(
  1370. ... func.unnest(array(["one", "two", "three"])).
  1371. table_valued("x", with_ordinality="o").render_derived()
  1372. ... )
  1373. ... )
  1374. SELECT anon_1.x, anon_1.o
  1375. FROM unnest(ARRAY[%(param_1)s, %(param_2)s, %(param_3)s]) WITH ORDINALITY AS anon_1(x, o)
  1376. The ``with_types`` keyword will render column types inline within
  1377. the alias expression (this syntax currently applies to the
  1378. PostgreSQL database)::
  1379. >>> print(
  1380. ... select(
  1381. ... func.json_to_recordset(
  1382. ... '[{"a":1,"b":"foo"},{"a":"2","c":"bar"}]'
  1383. ... )
  1384. ... .table_valued(column("a", Integer), column("b", String))
  1385. ... .render_derived(with_types=True)
  1386. ... )
  1387. ... )
  1388. SELECT anon_1.a, anon_1.b FROM json_to_recordset(:json_to_recordset_1)
  1389. AS anon_1(a INTEGER, b VARCHAR)
  1390. :param name: optional string name that will be applied to the alias
  1391. generated. If left as None, a unique anonymizing name will be used.
  1392. :param with_types: if True, the derived columns will include the
  1393. datatype specification with each column. This is a special syntax
  1394. currently known to be required by PostgreSQL for some SQL functions.
  1395. """ # noqa E501
  1396. # note: don't use the @_generative system here, keep a reference
  1397. # to the original object. otherwise you can have re-use of the
  1398. # python id() of the original which can cause name conflicts if
  1399. # a new anon-name grabs the same identifier as the local anon-name
  1400. # (just saw it happen on CI)
  1401. new_alias = TableValuedAlias._construct(self, name=name)
  1402. new_alias._render_derived = True
  1403. new_alias._render_derived_w_types = with_types
  1404. return new_alias
  1405. class Lateral(AliasedReturnsRows):
  1406. """Represent a LATERAL subquery.
  1407. This object is constructed from the :func:`_expression.lateral` module
  1408. level function as well as the :meth:`_expression.FromClause.lateral`
  1409. method available
  1410. on all :class:`_expression.FromClause` subclasses.
  1411. While LATERAL is part of the SQL standard, currently only more recent
  1412. PostgreSQL versions provide support for this keyword.
  1413. .. versionadded:: 1.1
  1414. .. seealso::
  1415. :ref:`lateral_selects` - overview of usage.
  1416. """
  1417. __visit_name__ = "lateral"
  1418. _is_lateral = True
  1419. inherit_cache = True
  1420. @classmethod
  1421. def _factory(cls, selectable, name=None):
  1422. """Return a :class:`_expression.Lateral` object.
  1423. :class:`_expression.Lateral` is an :class:`_expression.Alias`
  1424. subclass that represents
  1425. a subquery with the LATERAL keyword applied to it.
  1426. The special behavior of a LATERAL subquery is that it appears in the
  1427. FROM clause of an enclosing SELECT, but may correlate to other
  1428. FROM clauses of that SELECT. It is a special case of subquery
  1429. only supported by a small number of backends, currently more recent
  1430. PostgreSQL versions.
  1431. .. versionadded:: 1.1
  1432. .. seealso::
  1433. :ref:`lateral_selects` - overview of usage.
  1434. """
  1435. return coercions.expect(
  1436. roles.FromClauseRole, selectable, explicit_subquery=True
  1437. ).lateral(name=name)
  1438. class TableSample(AliasedReturnsRows):
  1439. """Represent a TABLESAMPLE clause.
  1440. This object is constructed from the :func:`_expression.tablesample` module
  1441. level function as well as the :meth:`_expression.FromClause.tablesample`
  1442. method
  1443. available on all :class:`_expression.FromClause` subclasses.
  1444. .. versionadded:: 1.1
  1445. .. seealso::
  1446. :func:`_expression.tablesample`
  1447. """
  1448. __visit_name__ = "tablesample"
  1449. _traverse_internals = AliasedReturnsRows._traverse_internals + [
  1450. ("sampling", InternalTraversal.dp_clauseelement),
  1451. ("seed", InternalTraversal.dp_clauseelement),
  1452. ]
  1453. @classmethod
  1454. def _factory(cls, selectable, sampling, name=None, seed=None):
  1455. """Return a :class:`_expression.TableSample` object.
  1456. :class:`_expression.TableSample` is an :class:`_expression.Alias`
  1457. subclass that represents
  1458. a table with the TABLESAMPLE clause applied to it.
  1459. :func:`_expression.tablesample`
  1460. is also available from the :class:`_expression.FromClause`
  1461. class via the
  1462. :meth:`_expression.FromClause.tablesample` method.
  1463. The TABLESAMPLE clause allows selecting a randomly selected approximate
  1464. percentage of rows from a table. It supports multiple sampling methods,
  1465. most commonly BERNOULLI and SYSTEM.
  1466. e.g.::
  1467. from sqlalchemy import func
  1468. selectable = people.tablesample(
  1469. func.bernoulli(1),
  1470. name='alias',
  1471. seed=func.random())
  1472. stmt = select(selectable.c.people_id)
  1473. Assuming ``people`` with a column ``people_id``, the above
  1474. statement would render as::
  1475. SELECT alias.people_id FROM
  1476. people AS alias TABLESAMPLE bernoulli(:bernoulli_1)
  1477. REPEATABLE (random())
  1478. .. versionadded:: 1.1
  1479. :param sampling: a ``float`` percentage between 0 and 100 or
  1480. :class:`_functions.Function`.
  1481. :param name: optional alias name
  1482. :param seed: any real-valued SQL expression. When specified, the
  1483. REPEATABLE sub-clause is also rendered.
  1484. """
  1485. return coercions.expect(roles.FromClauseRole, selectable).tablesample(
  1486. sampling, name=name, seed=seed
  1487. )
  1488. def _init(self, selectable, sampling, name=None, seed=None):
  1489. self.sampling = sampling
  1490. self.seed = seed
  1491. super(TableSample, self)._init(selectable, name=name)
  1492. @util.preload_module("sqlalchemy.sql.functions")
  1493. def _get_method(self):
  1494. functions = util.preloaded.sql_functions
  1495. if isinstance(self.sampling, functions.Function):
  1496. return self.sampling
  1497. else:
  1498. return functions.func.system(self.sampling)
  1499. class CTE(
  1500. roles.DMLTableRole,
  1501. Generative,
  1502. HasPrefixes,
  1503. HasSuffixes,
  1504. AliasedReturnsRows,
  1505. ):
  1506. """Represent a Common Table Expression.
  1507. The :class:`_expression.CTE` object is obtained using the
  1508. :meth:`_sql.SelectBase.cte` method from any SELECT statement. A less often
  1509. available syntax also allows use of the :meth:`_sql.HasCTE.cte` method
  1510. present on :term:`DML` constructs such as :class:`_sql.Insert`,
  1511. :class:`_sql.Update` and
  1512. :class:`_sql.Delete`. See the :meth:`_sql.HasCTE.cte` method for
  1513. usage details on CTEs.
  1514. .. seealso::
  1515. :ref:`tutorial_subqueries_ctes` - in the 2.0 tutorial
  1516. :meth:`_sql.HasCTE.cte` - examples of calling styles
  1517. """
  1518. __visit_name__ = "cte"
  1519. _traverse_internals = (
  1520. AliasedReturnsRows._traverse_internals
  1521. + [
  1522. ("_cte_alias", InternalTraversal.dp_clauseelement),
  1523. ("_restates", InternalTraversal.dp_clauseelement_list),
  1524. ("recursive", InternalTraversal.dp_boolean),
  1525. ]
  1526. + HasPrefixes._has_prefixes_traverse_internals
  1527. + HasSuffixes._has_suffixes_traverse_internals
  1528. )
  1529. @classmethod
  1530. def _factory(cls, selectable, name=None, recursive=False):
  1531. r"""Return a new :class:`_expression.CTE`,
  1532. or Common Table Expression instance.
  1533. Please see :meth:`_expression.HasCTE.cte` for detail on CTE usage.
  1534. """
  1535. return coercions.expect(roles.HasCTERole, selectable).cte(
  1536. name=name, recursive=recursive
  1537. )
  1538. def _init(
  1539. self,
  1540. selectable,
  1541. name=None,
  1542. recursive=False,
  1543. _cte_alias=None,
  1544. _restates=(),
  1545. _prefixes=None,
  1546. _suffixes=None,
  1547. ):
  1548. self.recursive = recursive
  1549. self._cte_alias = _cte_alias
  1550. self._restates = _restates
  1551. if _prefixes:
  1552. self._prefixes = _prefixes
  1553. if _suffixes:
  1554. self._suffixes = _suffixes
  1555. super(CTE, self)._init(selectable, name=name)
  1556. def _populate_column_collection(self):
  1557. if self._cte_alias is not None:
  1558. self._cte_alias._generate_fromclause_column_proxies(self)
  1559. else:
  1560. self.element._generate_fromclause_column_proxies(self)
  1561. def alias(self, name=None, flat=False):
  1562. """Return an :class:`_expression.Alias` of this
  1563. :class:`_expression.CTE`.
  1564. This method is a CTE-specific specialization of the
  1565. :meth:`_expression.FromClause.alias` method.
  1566. .. seealso::
  1567. :ref:`core_tutorial_aliases`
  1568. :func:`_expression.alias`
  1569. """
  1570. return CTE._construct(
  1571. self.element,
  1572. name=name,
  1573. recursive=self.recursive,
  1574. _cte_alias=self,
  1575. _prefixes=self._prefixes,
  1576. _suffixes=self._suffixes,
  1577. )
  1578. def union(self, other):
  1579. return CTE._construct(
  1580. self.element.union(other),
  1581. name=self.name,
  1582. recursive=self.recursive,
  1583. _restates=self._restates + (self,),
  1584. _prefixes=self._prefixes,
  1585. _suffixes=self._suffixes,
  1586. )
  1587. def union_all(self, other):
  1588. return CTE._construct(
  1589. self.element.union_all(other),
  1590. name=self.name,
  1591. recursive=self.recursive,
  1592. _restates=self._restates + (self,),
  1593. _prefixes=self._prefixes,
  1594. _suffixes=self._suffixes,
  1595. )
  1596. class HasCTE(roles.HasCTERole):
  1597. """Mixin that declares a class to include CTE support.
  1598. .. versionadded:: 1.1
  1599. """
  1600. def cte(self, name=None, recursive=False):
  1601. r"""Return a new :class:`_expression.CTE`,
  1602. or Common Table Expression instance.
  1603. Common table expressions are a SQL standard whereby SELECT
  1604. statements can draw upon secondary statements specified along
  1605. with the primary statement, using a clause called "WITH".
  1606. Special semantics regarding UNION can also be employed to
  1607. allow "recursive" queries, where a SELECT statement can draw
  1608. upon the set of rows that have previously been selected.
  1609. CTEs can also be applied to DML constructs UPDATE, INSERT
  1610. and DELETE on some databases, both as a source of CTE rows
  1611. when combined with RETURNING, as well as a consumer of
  1612. CTE rows.
  1613. .. versionchanged:: 1.1 Added support for UPDATE/INSERT/DELETE as
  1614. CTE, CTEs added to UPDATE/INSERT/DELETE.
  1615. SQLAlchemy detects :class:`_expression.CTE` objects, which are treated
  1616. similarly to :class:`_expression.Alias` objects, as special elements
  1617. to be delivered to the FROM clause of the statement as well
  1618. as to a WITH clause at the top of the statement.
  1619. For special prefixes such as PostgreSQL "MATERIALIZED" and
  1620. "NOT MATERIALIZED", the :meth:`_expression.CTE.prefix_with`
  1621. method may be
  1622. used to establish these.
  1623. .. versionchanged:: 1.3.13 Added support for prefixes.
  1624. In particular - MATERIALIZED and NOT MATERIALIZED.
  1625. :param name: name given to the common table expression. Like
  1626. :meth:`_expression.FromClause.alias`, the name can be left as
  1627. ``None`` in which case an anonymous symbol will be used at query
  1628. compile time.
  1629. :param recursive: if ``True``, will render ``WITH RECURSIVE``.
  1630. A recursive common table expression is intended to be used in
  1631. conjunction with UNION ALL in order to derive rows
  1632. from those already selected.
  1633. The following examples include two from PostgreSQL's documentation at
  1634. http://www.postgresql.org/docs/current/static/queries-with.html,
  1635. as well as additional examples.
  1636. Example 1, non recursive::
  1637. from sqlalchemy import (Table, Column, String, Integer,
  1638. MetaData, select, func)
  1639. metadata = MetaData()
  1640. orders = Table('orders', metadata,
  1641. Column('region', String),
  1642. Column('amount', Integer),
  1643. Column('product', String),
  1644. Column('quantity', Integer)
  1645. )
  1646. regional_sales = select(
  1647. orders.c.region,
  1648. func.sum(orders.c.amount).label('total_sales')
  1649. ).group_by(orders.c.region).cte("regional_sales")
  1650. top_regions = select(regional_sales.c.region).\
  1651. where(
  1652. regional_sales.c.total_sales >
  1653. select(
  1654. func.sum(regional_sales.c.total_sales) / 10
  1655. )
  1656. ).cte("top_regions")
  1657. statement = select(
  1658. orders.c.region,
  1659. orders.c.product,
  1660. func.sum(orders.c.quantity).label("product_units"),
  1661. func.sum(orders.c.amount).label("product_sales")
  1662. ).where(orders.c.region.in_(
  1663. select(top_regions.c.region)
  1664. )).group_by(orders.c.region, orders.c.product)
  1665. result = conn.execute(statement).fetchall()
  1666. Example 2, WITH RECURSIVE::
  1667. from sqlalchemy import (Table, Column, String, Integer,
  1668. MetaData, select, func)
  1669. metadata = MetaData()
  1670. parts = Table('parts', metadata,
  1671. Column('part', String),
  1672. Column('sub_part', String),
  1673. Column('quantity', Integer),
  1674. )
  1675. included_parts = select(\
  1676. parts.c.sub_part, parts.c.part, parts.c.quantity\
  1677. ).\
  1678. where(parts.c.part=='our part').\
  1679. cte(recursive=True)
  1680. incl_alias = included_parts.alias()
  1681. parts_alias = parts.alias()
  1682. included_parts = included_parts.union_all(
  1683. select(
  1684. parts_alias.c.sub_part,
  1685. parts_alias.c.part,
  1686. parts_alias.c.quantity
  1687. ).\
  1688. where(parts_alias.c.part==incl_alias.c.sub_part)
  1689. )
  1690. statement = select(
  1691. included_parts.c.sub_part,
  1692. func.sum(included_parts.c.quantity).
  1693. label('total_quantity')
  1694. ).\
  1695. group_by(included_parts.c.sub_part)
  1696. result = conn.execute(statement).fetchall()
  1697. Example 3, an upsert using UPDATE and INSERT with CTEs::
  1698. from datetime import date
  1699. from sqlalchemy import (MetaData, Table, Column, Integer,
  1700. Date, select, literal, and_, exists)
  1701. metadata = MetaData()
  1702. visitors = Table('visitors', metadata,
  1703. Column('product_id', Integer, primary_key=True),
  1704. Column('date', Date, primary_key=True),
  1705. Column('count', Integer),
  1706. )
  1707. # add 5 visitors for the product_id == 1
  1708. product_id = 1
  1709. day = date.today()
  1710. count = 5
  1711. update_cte = (
  1712. visitors.update()
  1713. .where(and_(visitors.c.product_id == product_id,
  1714. visitors.c.date == day))
  1715. .values(count=visitors.c.count + count)
  1716. .returning(literal(1))
  1717. .cte('update_cte')
  1718. )
  1719. upsert = visitors.insert().from_select(
  1720. [visitors.c.product_id, visitors.c.date, visitors.c.count],
  1721. select(literal(product_id), literal(day), literal(count))
  1722. .where(~exists(update_cte.select()))
  1723. )
  1724. connection.execute(upsert)
  1725. .. seealso::
  1726. :meth:`_orm.Query.cte` - ORM version of
  1727. :meth:`_expression.HasCTE.cte`.
  1728. """
  1729. return CTE._construct(self, name=name, recursive=recursive)
  1730. class Subquery(AliasedReturnsRows):
  1731. """Represent a subquery of a SELECT.
  1732. A :class:`.Subquery` is created by invoking the
  1733. :meth:`_expression.SelectBase.subquery` method, or for convenience the
  1734. :meth:`_expression.SelectBase.alias` method, on any
  1735. :class:`_expression.SelectBase` subclass
  1736. which includes :class:`_expression.Select`,
  1737. :class:`_expression.CompoundSelect`, and
  1738. :class:`_expression.TextualSelect`. As rendered in a FROM clause,
  1739. it represents the
  1740. body of the SELECT statement inside of parenthesis, followed by the usual
  1741. "AS <somename>" that defines all "alias" objects.
  1742. The :class:`.Subquery` object is very similar to the
  1743. :class:`_expression.Alias`
  1744. object and can be used in an equivalent way. The difference between
  1745. :class:`_expression.Alias` and :class:`.Subquery` is that
  1746. :class:`_expression.Alias` always
  1747. contains a :class:`_expression.FromClause` object whereas
  1748. :class:`.Subquery`
  1749. always contains a :class:`_expression.SelectBase` object.
  1750. .. versionadded:: 1.4 The :class:`.Subquery` class was added which now
  1751. serves the purpose of providing an aliased version of a SELECT
  1752. statement.
  1753. """
  1754. __visit_name__ = "subquery"
  1755. _is_subquery = True
  1756. inherit_cache = True
  1757. @classmethod
  1758. def _factory(cls, selectable, name=None):
  1759. """Return a :class:`.Subquery` object."""
  1760. return coercions.expect(
  1761. roles.SelectStatementRole, selectable
  1762. ).subquery(name=name)
  1763. @util.deprecated(
  1764. "1.4",
  1765. "The :meth:`.Subquery.as_scalar` method, which was previously "
  1766. "``Alias.as_scalar()`` prior to version 1.4, is deprecated and "
  1767. "will be removed in a future release; Please use the "
  1768. ":meth:`_expression.Select.scalar_subquery` method of the "
  1769. ":func:`_expression.select` "
  1770. "construct before constructing a subquery object, or with the ORM "
  1771. "use the :meth:`_query.Query.scalar_subquery` method.",
  1772. )
  1773. def as_scalar(self):
  1774. return self.element.set_label_style(LABEL_STYLE_NONE).scalar_subquery()
  1775. def _execute_on_connection(
  1776. self,
  1777. connection,
  1778. multiparams,
  1779. params,
  1780. execution_options,
  1781. ):
  1782. util.warn_deprecated(
  1783. "Executing a subquery object is deprecated and will raise "
  1784. "ObjectNotExecutableError in an upcoming release. Please "
  1785. "execute the underlying select() statement directly.",
  1786. "1.4",
  1787. )
  1788. return self.element._execute_on_connection(
  1789. connection, multiparams, params, execution_options, _force=True
  1790. )
  1791. class FromGrouping(GroupedElement, FromClause):
  1792. """Represent a grouping of a FROM clause"""
  1793. _traverse_internals = [("element", InternalTraversal.dp_clauseelement)]
  1794. def __init__(self, element):
  1795. self.element = coercions.expect(roles.FromClauseRole, element)
  1796. def _init_collections(self):
  1797. pass
  1798. @property
  1799. def columns(self):
  1800. return self.element.columns
  1801. @property
  1802. def primary_key(self):
  1803. return self.element.primary_key
  1804. @property
  1805. def foreign_keys(self):
  1806. return self.element.foreign_keys
  1807. def is_derived_from(self, element):
  1808. return self.element.is_derived_from(element)
  1809. def alias(self, **kw):
  1810. return FromGrouping(self.element.alias(**kw))
  1811. def _anonymous_fromclause(self, **kw):
  1812. return FromGrouping(self.element._anonymous_fromclause(**kw))
  1813. @property
  1814. def _hide_froms(self):
  1815. return self.element._hide_froms
  1816. @property
  1817. def _from_objects(self):
  1818. return self.element._from_objects
  1819. def __getstate__(self):
  1820. return {"element": self.element}
  1821. def __setstate__(self, state):
  1822. self.element = state["element"]
  1823. class TableClause(roles.DMLTableRole, Immutable, FromClause):
  1824. """Represents a minimal "table" construct.
  1825. This is a lightweight table object that has only a name, a
  1826. collection of columns, which are typically produced
  1827. by the :func:`_expression.column` function, and a schema::
  1828. from sqlalchemy import table, column
  1829. user = table("user",
  1830. column("id"),
  1831. column("name"),
  1832. column("description"),
  1833. )
  1834. The :class:`_expression.TableClause` construct serves as the base for
  1835. the more commonly used :class:`_schema.Table` object, providing
  1836. the usual set of :class:`_expression.FromClause` services including
  1837. the ``.c.`` collection and statement generation methods.
  1838. It does **not** provide all the additional schema-level services
  1839. of :class:`_schema.Table`, including constraints, references to other
  1840. tables, or support for :class:`_schema.MetaData`-level services.
  1841. It's useful
  1842. on its own as an ad-hoc construct used to generate quick SQL
  1843. statements when a more fully fledged :class:`_schema.Table`
  1844. is not on hand.
  1845. """
  1846. __visit_name__ = "table"
  1847. _traverse_internals = [
  1848. (
  1849. "columns",
  1850. InternalTraversal.dp_fromclause_canonical_column_collection,
  1851. ),
  1852. ("name", InternalTraversal.dp_string),
  1853. ]
  1854. named_with_column = True
  1855. implicit_returning = False
  1856. """:class:`_expression.TableClause`
  1857. doesn't support having a primary key or column
  1858. -level defaults, so implicit returning doesn't apply."""
  1859. _autoincrement_column = None
  1860. """No PK or default support so no autoincrement column."""
  1861. def __init__(self, name, *columns, **kw):
  1862. """Produce a new :class:`_expression.TableClause`.
  1863. The object returned is an instance of
  1864. :class:`_expression.TableClause`, which
  1865. represents the "syntactical" portion of the schema-level
  1866. :class:`_schema.Table` object.
  1867. It may be used to construct lightweight table constructs.
  1868. .. versionchanged:: 1.0.0 :func:`_expression.table` can now
  1869. be imported from the plain ``sqlalchemy`` namespace like any
  1870. other SQL element.
  1871. :param name: Name of the table.
  1872. :param columns: A collection of :func:`_expression.column` constructs.
  1873. :param schema: The schema name for this table.
  1874. .. versionadded:: 1.3.18 :func:`_expression.table` can now
  1875. accept a ``schema`` argument.
  1876. """
  1877. super(TableClause, self).__init__()
  1878. self.name = self.fullname = name
  1879. self._columns = DedupeColumnCollection()
  1880. self.primary_key = ColumnSet()
  1881. self.foreign_keys = set()
  1882. for c in columns:
  1883. self.append_column(c)
  1884. schema = kw.pop("schema", None)
  1885. if schema is not None:
  1886. self.schema = schema
  1887. if kw:
  1888. raise exc.ArgumentError("Unsupported argument(s): %s" % list(kw))
  1889. def __str__(self):
  1890. if self.schema is not None:
  1891. return self.schema + "." + self.name
  1892. else:
  1893. return self.name
  1894. def _refresh_for_new_column(self, column):
  1895. pass
  1896. def _init_collections(self):
  1897. pass
  1898. @util.memoized_property
  1899. def description(self):
  1900. if util.py3k:
  1901. return self.name
  1902. else:
  1903. return self.name.encode("ascii", "backslashreplace")
  1904. def append_column(self, c, **kw):
  1905. existing = c.table
  1906. if existing is not None and existing is not self:
  1907. raise exc.ArgumentError(
  1908. "column object '%s' already assigned to table '%s'"
  1909. % (c.key, existing)
  1910. )
  1911. self._columns.add(c)
  1912. c.table = self
  1913. @util.preload_module("sqlalchemy.sql.dml")
  1914. def insert(self, values=None, inline=False, **kwargs):
  1915. """Generate an :func:`_expression.insert` construct against this
  1916. :class:`_expression.TableClause`.
  1917. E.g.::
  1918. table.insert().values(name='foo')
  1919. See :func:`_expression.insert` for argument and usage information.
  1920. """
  1921. return util.preloaded.sql_dml.Insert(
  1922. self, values=values, inline=inline, **kwargs
  1923. )
  1924. @util.preload_module("sqlalchemy.sql.dml")
  1925. def update(self, whereclause=None, values=None, inline=False, **kwargs):
  1926. """Generate an :func:`_expression.update` construct against this
  1927. :class:`_expression.TableClause`.
  1928. E.g.::
  1929. table.update().where(table.c.id==7).values(name='foo')
  1930. See :func:`_expression.update` for argument and usage information.
  1931. """
  1932. return util.preloaded.sql_dml.Update(
  1933. self,
  1934. whereclause=whereclause,
  1935. values=values,
  1936. inline=inline,
  1937. **kwargs
  1938. )
  1939. @util.preload_module("sqlalchemy.sql.dml")
  1940. def delete(self, whereclause=None, **kwargs):
  1941. """Generate a :func:`_expression.delete` construct against this
  1942. :class:`_expression.TableClause`.
  1943. E.g.::
  1944. table.delete().where(table.c.id==7)
  1945. See :func:`_expression.delete` for argument and usage information.
  1946. """
  1947. return util.preloaded.sql_dml.Delete(self, whereclause, **kwargs)
  1948. @property
  1949. def _from_objects(self):
  1950. return [self]
  1951. class ForUpdateArg(ClauseElement):
  1952. _traverse_internals = [
  1953. ("of", InternalTraversal.dp_clauseelement_list),
  1954. ("nowait", InternalTraversal.dp_boolean),
  1955. ("read", InternalTraversal.dp_boolean),
  1956. ("skip_locked", InternalTraversal.dp_boolean),
  1957. ]
  1958. @classmethod
  1959. def _from_argument(cls, with_for_update):
  1960. if isinstance(with_for_update, ForUpdateArg):
  1961. return with_for_update
  1962. elif with_for_update in (None, False):
  1963. return None
  1964. elif with_for_update is True:
  1965. return ForUpdateArg()
  1966. else:
  1967. return ForUpdateArg(**with_for_update)
  1968. def __eq__(self, other):
  1969. return (
  1970. isinstance(other, ForUpdateArg)
  1971. and other.nowait == self.nowait
  1972. and other.read == self.read
  1973. and other.skip_locked == self.skip_locked
  1974. and other.key_share == self.key_share
  1975. and other.of is self.of
  1976. )
  1977. def __ne__(self, other):
  1978. return not self.__eq__(other)
  1979. def __hash__(self):
  1980. return id(self)
  1981. def __init__(
  1982. self,
  1983. nowait=False,
  1984. read=False,
  1985. of=None,
  1986. skip_locked=False,
  1987. key_share=False,
  1988. ):
  1989. """Represents arguments specified to
  1990. :meth:`_expression.Select.for_update`.
  1991. """
  1992. self.nowait = nowait
  1993. self.read = read
  1994. self.skip_locked = skip_locked
  1995. self.key_share = key_share
  1996. if of is not None:
  1997. self.of = [
  1998. coercions.expect(roles.ColumnsClauseRole, elem)
  1999. for elem in util.to_list(of)
  2000. ]
  2001. else:
  2002. self.of = None
  2003. class Values(Generative, FromClause):
  2004. """Represent a ``VALUES`` construct that can be used as a FROM element
  2005. in a statement.
  2006. The :class:`_expression.Values` object is created from the
  2007. :func:`_expression.values` function.
  2008. .. versionadded:: 1.4
  2009. """
  2010. named_with_column = True
  2011. __visit_name__ = "values"
  2012. _data = ()
  2013. _traverse_internals = [
  2014. ("_column_args", InternalTraversal.dp_clauseelement_list),
  2015. ("_data", InternalTraversal.dp_dml_multi_values),
  2016. ("name", InternalTraversal.dp_string),
  2017. ("literal_binds", InternalTraversal.dp_boolean),
  2018. ]
  2019. def __init__(self, *columns, **kw):
  2020. r"""Construct a :class:`_expression.Values` construct.
  2021. The column expressions and the actual data for
  2022. :class:`_expression.Values` are given in two separate steps. The
  2023. constructor receives the column expressions typically as
  2024. :func:`_expression.column` constructs,
  2025. and the data is then passed via the
  2026. :meth:`_expression.Values.data` method as a list,
  2027. which can be called multiple
  2028. times to add more data, e.g.::
  2029. from sqlalchemy import column
  2030. from sqlalchemy import values
  2031. value_expr = values(
  2032. column('id', Integer),
  2033. column('name', String),
  2034. name="my_values"
  2035. ).data(
  2036. [(1, 'name1'), (2, 'name2'), (3, 'name3')]
  2037. )
  2038. :param \*columns: column expressions, typically composed using
  2039. :func:`_expression.column` objects.
  2040. :param name: the name for this VALUES construct. If omitted, the
  2041. VALUES construct will be unnamed in a SQL expression. Different
  2042. backends may have different requirements here.
  2043. :param literal_binds: Defaults to False. Whether or not to render
  2044. the data values inline in the SQL output, rather than using bound
  2045. parameters.
  2046. """
  2047. super(Values, self).__init__()
  2048. self._column_args = columns
  2049. self.name = kw.pop("name", None)
  2050. self.literal_binds = kw.pop("literal_binds", False)
  2051. self.named_with_column = self.name is not None
  2052. @property
  2053. def _column_types(self):
  2054. return [col.type for col in self._column_args]
  2055. @_generative
  2056. def alias(self, name, **kw):
  2057. """Return a new :class:`_expression.Values`
  2058. construct that is a copy of this
  2059. one with the given name.
  2060. This method is a VALUES-specific specialization of the
  2061. :meth:`_expression.FromClause.alias` method.
  2062. .. seealso::
  2063. :ref:`core_tutorial_aliases`
  2064. :func:`_expression.alias`
  2065. """
  2066. self.name = name
  2067. self.named_with_column = self.name is not None
  2068. @_generative
  2069. def lateral(self, name=None):
  2070. """Return a new :class:`_expression.Values` with the lateral flag set,
  2071. so that
  2072. it renders as LATERAL.
  2073. .. seealso::
  2074. :func:`_expression.lateral`
  2075. """
  2076. self._is_lateral = True
  2077. if name is not None:
  2078. self.name = name
  2079. @_generative
  2080. def data(self, values):
  2081. """Return a new :class:`_expression.Values` construct,
  2082. adding the given data
  2083. to the data list.
  2084. E.g.::
  2085. my_values = my_values.data([(1, 'value 1'), (2, 'value2')])
  2086. :param values: a sequence (i.e. list) of tuples that map to the
  2087. column expressions given in the :class:`_expression.Values`
  2088. constructor.
  2089. """
  2090. self._data += (values,)
  2091. def _populate_column_collection(self):
  2092. for c in self._column_args:
  2093. self._columns.add(c)
  2094. c.table = self
  2095. @property
  2096. def _from_objects(self):
  2097. return [self]
  2098. class SelectBase(
  2099. roles.SelectStatementRole,
  2100. roles.DMLSelectRole,
  2101. roles.CompoundElementRole,
  2102. roles.InElementRole,
  2103. HasCTE,
  2104. Executable,
  2105. SupportsCloneAnnotations,
  2106. Selectable,
  2107. ):
  2108. """Base class for SELECT statements.
  2109. This includes :class:`_expression.Select`,
  2110. :class:`_expression.CompoundSelect` and
  2111. :class:`_expression.TextualSelect`.
  2112. """
  2113. _is_select_statement = True
  2114. is_select = True
  2115. def _generate_fromclause_column_proxies(self, fromclause):
  2116. raise NotImplementedError()
  2117. def _refresh_for_new_column(self, column):
  2118. self._reset_memoizations()
  2119. @property
  2120. def selected_columns(self):
  2121. """A :class:`_expression.ColumnCollection`
  2122. representing the columns that
  2123. this SELECT statement or similar construct returns in its result set.
  2124. This collection differs from the :attr:`_expression.FromClause.columns`
  2125. collection of a :class:`_expression.FromClause` in that the columns
  2126. within this collection cannot be directly nested inside another SELECT
  2127. statement; a subquery must be applied first which provides for the
  2128. necessary parenthesization required by SQL.
  2129. .. note::
  2130. The :attr:`_sql.SelectBase.selected_columns` collection does not
  2131. include expressions established in the columns clause using the
  2132. :func:`_sql.text` construct; these are silently omitted from the
  2133. collection. To use plain textual column expressions inside of a
  2134. :class:`_sql.Select` construct, use the :func:`_sql.literal_column`
  2135. construct.
  2136. .. seealso::
  2137. :attr:`_sql.Select.selected_columns`
  2138. .. versionadded:: 1.4
  2139. """
  2140. raise NotImplementedError()
  2141. @property
  2142. def _all_selected_columns(self):
  2143. """A sequence of expressions that correspond to what is rendered
  2144. in the columns clause, including :class:`_sql.TextClause`
  2145. constructs.
  2146. .. versionadded:: 1.4.12
  2147. .. seealso::
  2148. :attr:`_sql.SelectBase.exported_columns`
  2149. """
  2150. raise NotImplementedError()
  2151. @property
  2152. def exported_columns(self):
  2153. """A :class:`_expression.ColumnCollection`
  2154. that represents the "exported"
  2155. columns of this :class:`_expression.Selectable`, not including
  2156. :class:`_sql.TextClause` constructs.
  2157. The "exported" columns for a :class:`_expression.SelectBase`
  2158. object are synonymous
  2159. with the :attr:`_expression.SelectBase.selected_columns` collection.
  2160. .. versionadded:: 1.4
  2161. .. seealso::
  2162. :attr:`_expression.Select.exported_columns`
  2163. :attr:`_expression.Selectable.exported_columns`
  2164. :attr:`_expression.FromClause.exported_columns`
  2165. """
  2166. return self.selected_columns
  2167. @property
  2168. @util.deprecated(
  2169. "1.4",
  2170. "The :attr:`_expression.SelectBase.c` and "
  2171. ":attr:`_expression.SelectBase.columns` attributes "
  2172. "are deprecated and will be removed in a future release; these "
  2173. "attributes implicitly create a subquery that should be explicit. "
  2174. "Please call :meth:`_expression.SelectBase.subquery` "
  2175. "first in order to create "
  2176. "a subquery, which then contains this attribute. To access the "
  2177. "columns that this SELECT object SELECTs "
  2178. "from, use the :attr:`_expression.SelectBase.selected_columns` "
  2179. "attribute.",
  2180. )
  2181. def c(self):
  2182. return self._implicit_subquery.columns
  2183. @property
  2184. def columns(self):
  2185. return self.c
  2186. @util.deprecated(
  2187. "1.4",
  2188. "The :meth:`_expression.SelectBase.select` method is deprecated "
  2189. "and will be removed in a future release; this method implicitly "
  2190. "creates a subquery that should be explicit. "
  2191. "Please call :meth:`_expression.SelectBase.subquery` "
  2192. "first in order to create "
  2193. "a subquery, which then can be selected.",
  2194. )
  2195. def select(self, *arg, **kw):
  2196. return self._implicit_subquery.select(*arg, **kw)
  2197. @HasMemoized.memoized_attribute
  2198. def _implicit_subquery(self):
  2199. return self.subquery()
  2200. @util.deprecated(
  2201. "1.4",
  2202. "The :meth:`_expression.SelectBase.as_scalar` "
  2203. "method is deprecated and will be "
  2204. "removed in a future release. Please refer to "
  2205. ":meth:`_expression.SelectBase.scalar_subquery`.",
  2206. )
  2207. def as_scalar(self):
  2208. return self.scalar_subquery()
  2209. def exists(self):
  2210. """Return an :class:`_sql.Exists` representation of this selectable,
  2211. which can be used as a column expression.
  2212. The returned object is an instance of :class:`_sql.Exists`.
  2213. .. seealso::
  2214. :func:`_sql.exists`
  2215. :ref:`tutorial_exists` - in the :term:`2.0 style` tutorial.
  2216. .. versionadded:: 1.4
  2217. """
  2218. return Exists(self)
  2219. def scalar_subquery(self):
  2220. """Return a 'scalar' representation of this selectable, which can be
  2221. used as a column expression.
  2222. The returned object is an instance of :class:`_sql.ScalarSelect`.
  2223. Typically, a select statement which has only one column in its columns
  2224. clause is eligible to be used as a scalar expression. The scalar
  2225. subquery can then be used in the WHERE clause or columns clause of
  2226. an enclosing SELECT.
  2227. Note that the scalar subquery differentiates from the FROM-level
  2228. subquery that can be produced using the
  2229. :meth:`_expression.SelectBase.subquery`
  2230. method.
  2231. .. versionchanged: 1.4 - the ``.as_scalar()`` method was renamed to
  2232. :meth:`_expression.SelectBase.scalar_subquery`.
  2233. .. seealso::
  2234. :ref:`tutorial_scalar_subquery` - in the 2.0 tutorial
  2235. :ref:`scalar_selects` - in the 1.x tutorial
  2236. """
  2237. if self._label_style is not LABEL_STYLE_NONE:
  2238. self = self.set_label_style(LABEL_STYLE_NONE)
  2239. return ScalarSelect(self)
  2240. def label(self, name):
  2241. """Return a 'scalar' representation of this selectable, embedded as a
  2242. subquery with a label.
  2243. .. seealso::
  2244. :meth:`_expression.SelectBase.as_scalar`.
  2245. """
  2246. return self.scalar_subquery().label(name)
  2247. def lateral(self, name=None):
  2248. """Return a LATERAL alias of this :class:`_expression.Selectable`.
  2249. The return value is the :class:`_expression.Lateral` construct also
  2250. provided by the top-level :func:`_expression.lateral` function.
  2251. .. versionadded:: 1.1
  2252. .. seealso::
  2253. :ref:`lateral_selects` - overview of usage.
  2254. """
  2255. return Lateral._factory(self, name)
  2256. @property
  2257. def _from_objects(self):
  2258. return [self]
  2259. def subquery(self, name=None):
  2260. """Return a subquery of this :class:`_expression.SelectBase`.
  2261. A subquery is from a SQL perspective a parenthesized, named
  2262. construct that can be placed in the FROM clause of another
  2263. SELECT statement.
  2264. Given a SELECT statement such as::
  2265. stmt = select(table.c.id, table.c.name)
  2266. The above statement might look like::
  2267. SELECT table.id, table.name FROM table
  2268. The subquery form by itself renders the same way, however when
  2269. embedded into the FROM clause of another SELECT statement, it becomes
  2270. a named sub-element::
  2271. subq = stmt.subquery()
  2272. new_stmt = select(subq)
  2273. The above renders as::
  2274. SELECT anon_1.id, anon_1.name
  2275. FROM (SELECT table.id, table.name FROM table) AS anon_1
  2276. Historically, :meth:`_expression.SelectBase.subquery`
  2277. is equivalent to calling
  2278. the :meth:`_expression.FromClause.alias`
  2279. method on a FROM object; however,
  2280. as a :class:`_expression.SelectBase`
  2281. object is not directly FROM object,
  2282. the :meth:`_expression.SelectBase.subquery`
  2283. method provides clearer semantics.
  2284. .. versionadded:: 1.4
  2285. """
  2286. return Subquery._construct(self._ensure_disambiguated_names(), name)
  2287. def _ensure_disambiguated_names(self):
  2288. """Ensure that the names generated by this selectbase will be
  2289. disambiguated in some way, if possible.
  2290. """
  2291. raise NotImplementedError()
  2292. def alias(self, name=None, flat=False):
  2293. """Return a named subquery against this
  2294. :class:`_expression.SelectBase`.
  2295. For a :class:`_expression.SelectBase` (as opposed to a
  2296. :class:`_expression.FromClause`),
  2297. this returns a :class:`.Subquery` object which behaves mostly the
  2298. same as the :class:`_expression.Alias` object that is used with a
  2299. :class:`_expression.FromClause`.
  2300. .. versionchanged:: 1.4 The :meth:`_expression.SelectBase.alias`
  2301. method is now
  2302. a synonym for the :meth:`_expression.SelectBase.subquery` method.
  2303. """
  2304. return self.subquery(name=name)
  2305. class SelectStatementGrouping(GroupedElement, SelectBase):
  2306. """Represent a grouping of a :class:`_expression.SelectBase`.
  2307. This differs from :class:`.Subquery` in that we are still
  2308. an "inner" SELECT statement, this is strictly for grouping inside of
  2309. compound selects.
  2310. """
  2311. __visit_name__ = "grouping"
  2312. _traverse_internals = [("element", InternalTraversal.dp_clauseelement)]
  2313. _is_select_container = True
  2314. def __init__(self, element):
  2315. self.element = coercions.expect(roles.SelectStatementRole, element)
  2316. def _ensure_disambiguated_names(self):
  2317. new_element = self.element._ensure_disambiguated_names()
  2318. if new_element is not self.element:
  2319. return SelectStatementGrouping(new_element)
  2320. else:
  2321. return self
  2322. def get_label_style(self):
  2323. return self._label_style
  2324. def set_label_style(self, label_style):
  2325. return SelectStatementGrouping(
  2326. self.element.set_label_style(label_style)
  2327. )
  2328. @property
  2329. def _label_style(self):
  2330. return self.element._label_style
  2331. @property
  2332. def select_statement(self):
  2333. return self.element
  2334. def self_group(self, against=None):
  2335. return self
  2336. def _generate_fromclause_column_proxies(self, subquery):
  2337. self.element._generate_fromclause_column_proxies(subquery)
  2338. def _generate_proxy_for_new_column(self, column, subquery):
  2339. return self.element._generate_proxy_for_new_column(subquery)
  2340. @property
  2341. def _all_selected_columns(self):
  2342. return self.element._all_selected_columns
  2343. @property
  2344. def selected_columns(self):
  2345. """A :class:`_expression.ColumnCollection`
  2346. representing the columns that
  2347. the embedded SELECT statement returns in its result set, not including
  2348. :class:`_sql.TextClause` constructs.
  2349. .. versionadded:: 1.4
  2350. .. seealso::
  2351. :attr:`_sql.Select.selected_columns`
  2352. """
  2353. return self.element.selected_columns
  2354. @property
  2355. def _from_objects(self):
  2356. return self.element._from_objects
  2357. class DeprecatedSelectBaseGenerations(object):
  2358. """A collection of methods available on :class:`_sql.Select` and
  2359. :class:`_sql.CompoundSelect`, these are all **deprecated** methods as they
  2360. modify the object in-place.
  2361. """
  2362. @util.deprecated(
  2363. "1.4",
  2364. "The :meth:`_expression.GenerativeSelect.append_order_by` "
  2365. "method is deprecated "
  2366. "and will be removed in a future release. Use the generative method "
  2367. ":meth:`_expression.GenerativeSelect.order_by`.",
  2368. )
  2369. def append_order_by(self, *clauses):
  2370. """Append the given ORDER BY criterion applied to this selectable.
  2371. The criterion will be appended to any pre-existing ORDER BY criterion.
  2372. This is an **in-place** mutation method; the
  2373. :meth:`_expression.GenerativeSelect.order_by` method is preferred,
  2374. as it
  2375. provides standard :term:`method chaining`.
  2376. .. seealso::
  2377. :meth:`_expression.GenerativeSelect.order_by`
  2378. """
  2379. self.order_by.non_generative(self, *clauses)
  2380. @util.deprecated(
  2381. "1.4",
  2382. "The :meth:`_expression.GenerativeSelect.append_group_by` "
  2383. "method is deprecated "
  2384. "and will be removed in a future release. Use the generative method "
  2385. ":meth:`_expression.GenerativeSelect.group_by`.",
  2386. )
  2387. def append_group_by(self, *clauses):
  2388. """Append the given GROUP BY criterion applied to this selectable.
  2389. The criterion will be appended to any pre-existing GROUP BY criterion.
  2390. This is an **in-place** mutation method; the
  2391. :meth:`_expression.GenerativeSelect.group_by` method is preferred,
  2392. as it
  2393. provides standard :term:`method chaining`.
  2394. """
  2395. self.group_by.non_generative(self, *clauses)
  2396. class GenerativeSelect(DeprecatedSelectBaseGenerations, SelectBase):
  2397. """Base class for SELECT statements where additional elements can be
  2398. added.
  2399. This serves as the base for :class:`_expression.Select` and
  2400. :class:`_expression.CompoundSelect`
  2401. where elements such as ORDER BY, GROUP BY can be added and column
  2402. rendering can be controlled. Compare to
  2403. :class:`_expression.TextualSelect`, which,
  2404. while it subclasses :class:`_expression.SelectBase`
  2405. and is also a SELECT construct,
  2406. represents a fixed textual string which cannot be altered at this level,
  2407. only wrapped as a subquery.
  2408. """
  2409. _order_by_clauses = ()
  2410. _group_by_clauses = ()
  2411. _limit_clause = None
  2412. _offset_clause = None
  2413. _fetch_clause = None
  2414. _fetch_clause_options = None
  2415. _for_update_arg = None
  2416. @util.deprecated_params(
  2417. bind=(
  2418. "2.0",
  2419. "The :paramref:`_sql.select.bind` argument is deprecated and "
  2420. "will be removed in SQLAlchemy 2.0.",
  2421. ),
  2422. )
  2423. def __init__(
  2424. self,
  2425. _label_style=LABEL_STYLE_DEFAULT,
  2426. use_labels=False,
  2427. limit=None,
  2428. offset=None,
  2429. order_by=None,
  2430. group_by=None,
  2431. bind=None,
  2432. ):
  2433. if use_labels:
  2434. if util.SQLALCHEMY_WARN_20:
  2435. util.warn_deprecated_20(
  2436. "The use_labels=True keyword argument to GenerativeSelect "
  2437. "is deprecated and will be removed in version 2.0. Please "
  2438. "use "
  2439. "select.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) "
  2440. "if you need to replicate this legacy behavior.",
  2441. stacklevel=4,
  2442. )
  2443. _label_style = LABEL_STYLE_TABLENAME_PLUS_COL
  2444. self._label_style = _label_style
  2445. if limit is not None:
  2446. self.limit.non_generative(self, limit)
  2447. if offset is not None:
  2448. self.offset.non_generative(self, offset)
  2449. if order_by is not None:
  2450. self.order_by.non_generative(self, *util.to_list(order_by))
  2451. if group_by is not None:
  2452. self.group_by.non_generative(self, *util.to_list(group_by))
  2453. self._bind = bind
  2454. @_generative
  2455. def with_for_update(
  2456. self,
  2457. nowait=False,
  2458. read=False,
  2459. of=None,
  2460. skip_locked=False,
  2461. key_share=False,
  2462. ):
  2463. """Specify a ``FOR UPDATE`` clause for this
  2464. :class:`_expression.GenerativeSelect`.
  2465. E.g.::
  2466. stmt = select(table).with_for_update(nowait=True)
  2467. On a database like PostgreSQL or Oracle, the above would render a
  2468. statement like::
  2469. SELECT table.a, table.b FROM table FOR UPDATE NOWAIT
  2470. on other backends, the ``nowait`` option is ignored and instead
  2471. would produce::
  2472. SELECT table.a, table.b FROM table FOR UPDATE
  2473. When called with no arguments, the statement will render with
  2474. the suffix ``FOR UPDATE``. Additional arguments can then be
  2475. provided which allow for common database-specific
  2476. variants.
  2477. :param nowait: boolean; will render ``FOR UPDATE NOWAIT`` on Oracle
  2478. and PostgreSQL dialects.
  2479. :param read: boolean; will render ``LOCK IN SHARE MODE`` on MySQL,
  2480. ``FOR SHARE`` on PostgreSQL. On PostgreSQL, when combined with
  2481. ``nowait``, will render ``FOR SHARE NOWAIT``.
  2482. :param of: SQL expression or list of SQL expression elements
  2483. (typically :class:`_schema.Column`
  2484. objects or a compatible expression) which
  2485. will render into a ``FOR UPDATE OF`` clause; supported by PostgreSQL
  2486. and Oracle. May render as a table or as a column depending on
  2487. backend.
  2488. :param skip_locked: boolean, will render ``FOR UPDATE SKIP LOCKED``
  2489. on Oracle and PostgreSQL dialects or ``FOR SHARE SKIP LOCKED`` if
  2490. ``read=True`` is also specified.
  2491. :param key_share: boolean, will render ``FOR NO KEY UPDATE``,
  2492. or if combined with ``read=True`` will render ``FOR KEY SHARE``,
  2493. on the PostgreSQL dialect.
  2494. """
  2495. self._for_update_arg = ForUpdateArg(
  2496. nowait=nowait,
  2497. read=read,
  2498. of=of,
  2499. skip_locked=skip_locked,
  2500. key_share=key_share,
  2501. )
  2502. def get_label_style(self):
  2503. """
  2504. Retrieve the current label style.
  2505. .. versionadded:: 1.4
  2506. """
  2507. return self._label_style
  2508. def set_label_style(self, style):
  2509. """Return a new selectable with the specified label style.
  2510. There are three "label styles" available,
  2511. :data:`_sql.LABEL_STYLE_DISAMBIGUATE_ONLY`,
  2512. :data:`_sql.LABEL_STYLE_TABLENAME_PLUS_COL`, and
  2513. :data:`_sql.LABEL_STYLE_NONE`. The default style is
  2514. :data:`_sql.LABEL_STYLE_TABLENAME_PLUS_COL`.
  2515. In modern SQLAlchemy, there is not generally a need to change the
  2516. labeling style, as per-expression labels are more effectively used by
  2517. making use of the :meth:`_sql.ColumnElement.label` method. In past
  2518. versions, :data:`_sql.LABEL_STYLE_TABLENAME_PLUS_COL` was used to
  2519. disambiguate same-named columns from different tables, aliases, or
  2520. subqueries; the newer :data:`_sql.LABEL_STYLE_DISAMBIGUATE_ONLY` now
  2521. applies labels only to names that conflict with an existing name so
  2522. that the impact of this labeling is minimal.
  2523. The rationale for disambiguation is mostly so that all column
  2524. expressions are available from a given :attr:`_sql.FromClause.c`
  2525. collection when a subquery is created.
  2526. .. versionadded:: 1.4 - the
  2527. :meth:`_sql.GenerativeSelect.set_label_style` method replaces the
  2528. previous combination of ``.apply_labels()``, ``.with_labels()`` and
  2529. ``use_labels=True`` methods and/or parameters.
  2530. .. seealso::
  2531. :data:`_sql.LABEL_STYLE_DISAMBIGUATE_ONLY`
  2532. :data:`_sql.LABEL_STYLE_TABLENAME_PLUS_COL`
  2533. :data:`_sql.LABEL_STYLE_NONE`
  2534. :data:`_sql.LABEL_STYLE_DEFAULT`
  2535. """
  2536. if self._label_style is not style:
  2537. self = self._generate()
  2538. self._label_style = style
  2539. return self
  2540. @util.deprecated_20(
  2541. ":meth:`_sql.GenerativeSelect.apply_labels`",
  2542. alternative="Use set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) "
  2543. "instead.",
  2544. )
  2545. def apply_labels(self):
  2546. return self.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
  2547. @property
  2548. def _group_by_clause(self):
  2549. """ClauseList access to group_by_clauses for legacy dialects"""
  2550. return ClauseList._construct_raw(
  2551. operators.comma_op, self._group_by_clauses
  2552. )
  2553. @property
  2554. def _order_by_clause(self):
  2555. """ClauseList access to order_by_clauses for legacy dialects"""
  2556. return ClauseList._construct_raw(
  2557. operators.comma_op, self._order_by_clauses
  2558. )
  2559. def _offset_or_limit_clause(self, element, name=None, type_=None):
  2560. """Convert the given value to an "offset or limit" clause.
  2561. This handles incoming integers and converts to an expression; if
  2562. an expression is already given, it is passed through.
  2563. """
  2564. return coercions.expect(
  2565. roles.LimitOffsetRole, element, name=name, type_=type_
  2566. )
  2567. def _offset_or_limit_clause_asint(self, clause, attrname):
  2568. """Convert the "offset or limit" clause of a select construct to an
  2569. integer.
  2570. This is only possible if the value is stored as a simple bound
  2571. parameter. Otherwise, a compilation error is raised.
  2572. """
  2573. if clause is None:
  2574. return None
  2575. try:
  2576. value = clause._limit_offset_value
  2577. except AttributeError as err:
  2578. util.raise_(
  2579. exc.CompileError(
  2580. "This SELECT structure does not use a simple "
  2581. "integer value for %s" % attrname
  2582. ),
  2583. replace_context=err,
  2584. )
  2585. else:
  2586. return util.asint(value)
  2587. @property
  2588. def _limit(self):
  2589. """Get an integer value for the limit. This should only be used
  2590. by code that cannot support a limit as a BindParameter or
  2591. other custom clause as it will throw an exception if the limit
  2592. isn't currently set to an integer.
  2593. """
  2594. return self._offset_or_limit_clause_asint(self._limit_clause, "limit")
  2595. def _simple_int_clause(self, clause):
  2596. """True if the clause is a simple integer, False
  2597. if it is not present or is a SQL expression.
  2598. """
  2599. return isinstance(clause, _OffsetLimitParam)
  2600. @property
  2601. def _offset(self):
  2602. """Get an integer value for the offset. This should only be used
  2603. by code that cannot support an offset as a BindParameter or
  2604. other custom clause as it will throw an exception if the
  2605. offset isn't currently set to an integer.
  2606. """
  2607. return self._offset_or_limit_clause_asint(
  2608. self._offset_clause, "offset"
  2609. )
  2610. @property
  2611. def _has_row_limiting_clause(self):
  2612. return (
  2613. self._limit_clause is not None
  2614. or self._offset_clause is not None
  2615. or self._fetch_clause is not None
  2616. )
  2617. @_generative
  2618. def limit(self, limit):
  2619. """Return a new selectable with the given LIMIT criterion
  2620. applied.
  2621. This is a numerical value which usually renders as a ``LIMIT``
  2622. expression in the resulting select. Backends that don't
  2623. support ``LIMIT`` will attempt to provide similar
  2624. functionality.
  2625. .. note::
  2626. The :meth:`_sql.GenerativeSelect.limit` method will replace
  2627. any clause applied with :meth:`_sql.GenerativeSelect.fetch`.
  2628. .. versionchanged:: 1.0.0 - :meth:`_expression.Select.limit` can now
  2629. accept arbitrary SQL expressions as well as integer values.
  2630. :param limit: an integer LIMIT parameter, or a SQL expression
  2631. that provides an integer result. Pass ``None`` to reset it.
  2632. .. seealso::
  2633. :meth:`_sql.GenerativeSelect.fetch`
  2634. :meth:`_sql.GenerativeSelect.offset`
  2635. """
  2636. self._fetch_clause = self._fetch_clause_options = None
  2637. self._limit_clause = self._offset_or_limit_clause(limit)
  2638. @_generative
  2639. def fetch(self, count, with_ties=False, percent=False):
  2640. """Return a new selectable with the given FETCH FIRST criterion
  2641. applied.
  2642. This is a numeric value which usually renders as
  2643. ``FETCH {FIRST | NEXT} [ count ] {ROW | ROWS} {ONLY | WITH TIES}``
  2644. expression in the resulting select. This functionality is
  2645. is currently implemented for Oracle, PostgreSQL, MSSQL.
  2646. Use :meth:`_sql.GenerativeSelect.offset` to specify the offset.
  2647. .. note::
  2648. The :meth:`_sql.GenerativeSelect.fetch` method will replace
  2649. any clause applied with :meth:`_sql.GenerativeSelect.limit`.
  2650. .. versionadded:: 1.4
  2651. :param count: an integer COUNT parameter, or a SQL expression
  2652. that provides an integer result. When ``percent=True`` this will
  2653. represent the percentage of rows to return, not the absolute value.
  2654. Pass ``None`` to reset it.
  2655. :param with_ties: When ``True``, the WITH TIES option is used
  2656. to return any additional rows that tie for the last place in the
  2657. result set according to the ``ORDER BY`` clause. The
  2658. ``ORDER BY`` may be mandatory in this case. Defaults to ``False``
  2659. :param percent: When ``True``, ``count`` represents the percentage
  2660. of the total number of selected rows to return. Defaults to ``False``
  2661. .. seealso::
  2662. :meth:`_sql.GenerativeSelect.limit`
  2663. :meth:`_sql.GenerativeSelect.offset`
  2664. """
  2665. self._limit_clause = None
  2666. if count is None:
  2667. self._fetch_clause = self._fetch_clause_options = None
  2668. else:
  2669. self._fetch_clause = self._offset_or_limit_clause(count)
  2670. self._fetch_clause_options = {
  2671. "with_ties": with_ties,
  2672. "percent": percent,
  2673. }
  2674. @_generative
  2675. def offset(self, offset):
  2676. """Return a new selectable with the given OFFSET criterion
  2677. applied.
  2678. This is a numeric value which usually renders as an ``OFFSET``
  2679. expression in the resulting select. Backends that don't
  2680. support ``OFFSET`` will attempt to provide similar
  2681. functionality.
  2682. .. versionchanged:: 1.0.0 - :meth:`_expression.Select.offset` can now
  2683. accept arbitrary SQL expressions as well as integer values.
  2684. :param offset: an integer OFFSET parameter, or a SQL expression
  2685. that provides an integer result. Pass ``None`` to reset it.
  2686. .. seealso::
  2687. :meth:`_sql.GenerativeSelect.limit`
  2688. :meth:`_sql.GenerativeSelect.fetch`
  2689. """
  2690. self._offset_clause = self._offset_or_limit_clause(offset)
  2691. @_generative
  2692. @util.preload_module("sqlalchemy.sql.util")
  2693. def slice(self, start, stop):
  2694. """Apply LIMIT / OFFSET to this statement based on a slice.
  2695. The start and stop indices behave like the argument to Python's
  2696. built-in :func:`range` function. This method provides an
  2697. alternative to using ``LIMIT``/``OFFSET`` to get a slice of the
  2698. query.
  2699. For example, ::
  2700. stmt = select(User).order_by(User).id.slice(1, 3)
  2701. renders as
  2702. .. sourcecode:: sql
  2703. SELECT users.id AS users_id,
  2704. users.name AS users_name
  2705. FROM users ORDER BY users.id
  2706. LIMIT ? OFFSET ?
  2707. (2, 1)
  2708. .. note::
  2709. The :meth:`_sql.GenerativeSelect.slice` method will replace
  2710. any clause applied with :meth:`_sql.GenerativeSelect.fetch`.
  2711. .. versionadded:: 1.4 Added the :meth:`_sql.GenerativeSelect.slice`
  2712. method generalized from the ORM.
  2713. .. seealso::
  2714. :meth:`_sql.GenerativeSelect.limit`
  2715. :meth:`_sql.GenerativeSelect.offset`
  2716. :meth:`_sql.GenerativeSelect.fetch`
  2717. """
  2718. sql_util = util.preloaded.sql_util
  2719. self._fetch_clause = self._fetch_clause_options = None
  2720. self._limit_clause, self._offset_clause = sql_util._make_slice(
  2721. self._limit_clause, self._offset_clause, start, stop
  2722. )
  2723. @_generative
  2724. def order_by(self, *clauses):
  2725. r"""Return a new selectable with the given list of ORDER BY
  2726. criterion applied.
  2727. e.g.::
  2728. stmt = select(table).order_by(table.c.id, table.c.name)
  2729. :param \*clauses: a series of :class:`_expression.ColumnElement`
  2730. constructs
  2731. which will be used to generate an ORDER BY clause.
  2732. .. seealso::
  2733. :ref:`tutorial_order_by` - in the :ref:`unified_tutorial`
  2734. :ref:`tutorial_order_by_label` - in the :ref:`unified_tutorial`
  2735. """
  2736. if len(clauses) == 1 and clauses[0] is None:
  2737. self._order_by_clauses = ()
  2738. else:
  2739. self._order_by_clauses += tuple(
  2740. coercions.expect(roles.OrderByRole, clause)
  2741. for clause in clauses
  2742. )
  2743. @_generative
  2744. def group_by(self, *clauses):
  2745. r"""Return a new selectable with the given list of GROUP BY
  2746. criterion applied.
  2747. e.g.::
  2748. stmt = select(table.c.name, func.max(table.c.stat)).\
  2749. group_by(table.c.name)
  2750. :param \*clauses: a series of :class:`_expression.ColumnElement`
  2751. constructs
  2752. which will be used to generate an GROUP BY clause.
  2753. .. seealso::
  2754. :ref:`tutorial_group_by_w_aggregates` - in the
  2755. :ref:`unified_tutorial`
  2756. :ref:`tutorial_order_by_label` - in the :ref:`unified_tutorial`
  2757. """
  2758. if len(clauses) == 1 and clauses[0] is None:
  2759. self._group_by_clauses = ()
  2760. else:
  2761. self._group_by_clauses += tuple(
  2762. coercions.expect(roles.GroupByRole, clause)
  2763. for clause in clauses
  2764. )
  2765. @CompileState.plugin_for("default", "compound_select")
  2766. class CompoundSelectState(CompileState):
  2767. @util.memoized_property
  2768. def _label_resolve_dict(self):
  2769. # TODO: this is hacky and slow
  2770. hacky_subquery = self.statement.subquery()
  2771. hacky_subquery.named_with_column = False
  2772. d = dict((c.key, c) for c in hacky_subquery.c)
  2773. return d, d, d
  2774. class CompoundSelect(HasCompileState, GenerativeSelect):
  2775. """Forms the basis of ``UNION``, ``UNION ALL``, and other
  2776. SELECT-based set operations.
  2777. .. seealso::
  2778. :func:`_expression.union`
  2779. :func:`_expression.union_all`
  2780. :func:`_expression.intersect`
  2781. :func:`_expression.intersect_all`
  2782. :func:`_expression.except`
  2783. :func:`_expression.except_all`
  2784. """
  2785. __visit_name__ = "compound_select"
  2786. _traverse_internals = [
  2787. ("selects", InternalTraversal.dp_clauseelement_list),
  2788. ("_limit_clause", InternalTraversal.dp_clauseelement),
  2789. ("_offset_clause", InternalTraversal.dp_clauseelement),
  2790. ("_fetch_clause", InternalTraversal.dp_clauseelement),
  2791. ("_fetch_clause_options", InternalTraversal.dp_plain_dict),
  2792. ("_order_by_clauses", InternalTraversal.dp_clauseelement_list),
  2793. ("_group_by_clauses", InternalTraversal.dp_clauseelement_list),
  2794. ("_for_update_arg", InternalTraversal.dp_clauseelement),
  2795. ("keyword", InternalTraversal.dp_string),
  2796. ] + SupportsCloneAnnotations._clone_annotations_traverse_internals
  2797. UNION = util.symbol("UNION")
  2798. UNION_ALL = util.symbol("UNION ALL")
  2799. EXCEPT = util.symbol("EXCEPT")
  2800. EXCEPT_ALL = util.symbol("EXCEPT ALL")
  2801. INTERSECT = util.symbol("INTERSECT")
  2802. INTERSECT_ALL = util.symbol("INTERSECT ALL")
  2803. _is_from_container = True
  2804. def __init__(self, keyword, *selects, **kwargs):
  2805. self._auto_correlate = kwargs.pop("correlate", False)
  2806. self.keyword = keyword
  2807. self.selects = [
  2808. coercions.expect(roles.CompoundElementRole, s).self_group(
  2809. against=self
  2810. )
  2811. for s in selects
  2812. ]
  2813. if kwargs and util.SQLALCHEMY_WARN_20:
  2814. util.warn_deprecated_20(
  2815. "Set functions such as union(), union_all(), extract(), etc. "
  2816. "in SQLAlchemy 2.0 will accept a "
  2817. "series of SELECT statements only. "
  2818. "Please use generative methods such as order_by() for "
  2819. "additional modifications to this CompoundSelect.",
  2820. stacklevel=4,
  2821. )
  2822. GenerativeSelect.__init__(self, **kwargs)
  2823. @classmethod
  2824. def _create_union(cls, *selects, **kwargs):
  2825. r"""Return a ``UNION`` of multiple selectables.
  2826. The returned object is an instance of
  2827. :class:`_expression.CompoundSelect`.
  2828. A similar :func:`union()` method is available on all
  2829. :class:`_expression.FromClause` subclasses.
  2830. :param \*selects:
  2831. a list of :class:`_expression.Select` instances.
  2832. :param \**kwargs:
  2833. available keyword arguments are the same as those of
  2834. :func:`select`.
  2835. """
  2836. return CompoundSelect(CompoundSelect.UNION, *selects, **kwargs)
  2837. @classmethod
  2838. def _create_union_all(cls, *selects, **kwargs):
  2839. r"""Return a ``UNION ALL`` of multiple selectables.
  2840. The returned object is an instance of
  2841. :class:`_expression.CompoundSelect`.
  2842. A similar :func:`union_all()` method is available on all
  2843. :class:`_expression.FromClause` subclasses.
  2844. :param \*selects:
  2845. a list of :class:`_expression.Select` instances.
  2846. :param \**kwargs:
  2847. available keyword arguments are the same as those of
  2848. :func:`select`.
  2849. """
  2850. return CompoundSelect(CompoundSelect.UNION_ALL, *selects, **kwargs)
  2851. @classmethod
  2852. def _create_except(cls, *selects, **kwargs):
  2853. r"""Return an ``EXCEPT`` of multiple selectables.
  2854. The returned object is an instance of
  2855. :class:`_expression.CompoundSelect`.
  2856. :param \*selects:
  2857. a list of :class:`_expression.Select` instances.
  2858. :param \**kwargs:
  2859. available keyword arguments are the same as those of
  2860. :func:`select`.
  2861. """
  2862. return CompoundSelect(CompoundSelect.EXCEPT, *selects, **kwargs)
  2863. @classmethod
  2864. def _create_except_all(cls, *selects, **kwargs):
  2865. r"""Return an ``EXCEPT ALL`` of multiple selectables.
  2866. The returned object is an instance of
  2867. :class:`_expression.CompoundSelect`.
  2868. :param \*selects:
  2869. a list of :class:`_expression.Select` instances.
  2870. :param \**kwargs:
  2871. available keyword arguments are the same as those of
  2872. :func:`select`.
  2873. """
  2874. return CompoundSelect(CompoundSelect.EXCEPT_ALL, *selects, **kwargs)
  2875. @classmethod
  2876. def _create_intersect(cls, *selects, **kwargs):
  2877. r"""Return an ``INTERSECT`` of multiple selectables.
  2878. The returned object is an instance of
  2879. :class:`_expression.CompoundSelect`.
  2880. :param \*selects:
  2881. a list of :class:`_expression.Select` instances.
  2882. :param \**kwargs:
  2883. available keyword arguments are the same as those of
  2884. :func:`select`.
  2885. """
  2886. return CompoundSelect(CompoundSelect.INTERSECT, *selects, **kwargs)
  2887. @classmethod
  2888. def _create_intersect_all(cls, *selects, **kwargs):
  2889. r"""Return an ``INTERSECT ALL`` of multiple selectables.
  2890. The returned object is an instance of
  2891. :class:`_expression.CompoundSelect`.
  2892. :param \*selects:
  2893. a list of :class:`_expression.Select` instances.
  2894. :param \**kwargs:
  2895. available keyword arguments are the same as those of
  2896. :func:`select`.
  2897. """
  2898. return CompoundSelect(CompoundSelect.INTERSECT_ALL, *selects, **kwargs)
  2899. def _scalar_type(self):
  2900. return self.selects[0]._scalar_type()
  2901. def self_group(self, against=None):
  2902. return SelectStatementGrouping(self)
  2903. def is_derived_from(self, fromclause):
  2904. for s in self.selects:
  2905. if s.is_derived_from(fromclause):
  2906. return True
  2907. return False
  2908. def _set_label_style(self, style):
  2909. if self._label_style is not style:
  2910. self = self._generate()
  2911. select_0 = self.selects[0]._set_label_style(style)
  2912. self.selects = [select_0] + self.selects[1:]
  2913. return self
  2914. def _ensure_disambiguated_names(self):
  2915. new_select = self.selects[0]._ensure_disambiguated_names()
  2916. if new_select is not self.selects[0]:
  2917. self = self._generate()
  2918. self.selects = [new_select] + self.selects[1:]
  2919. return self
  2920. def _generate_fromclause_column_proxies(self, subquery):
  2921. # this is a slightly hacky thing - the union exports a
  2922. # column that resembles just that of the *first* selectable.
  2923. # to get at a "composite" column, particularly foreign keys,
  2924. # you have to dig through the proxies collection which we
  2925. # generate below. We may want to improve upon this, such as
  2926. # perhaps _make_proxy can accept a list of other columns
  2927. # that are "shared" - schema.column can then copy all the
  2928. # ForeignKeys in. this would allow the union() to have all
  2929. # those fks too.
  2930. select_0 = self.selects[0]
  2931. if self._label_style is not LABEL_STYLE_DEFAULT:
  2932. select_0 = select_0.set_label_style(self._label_style)
  2933. select_0._generate_fromclause_column_proxies(subquery)
  2934. # hand-construct the "_proxies" collection to include all
  2935. # derived columns place a 'weight' annotation corresponding
  2936. # to how low in the list of select()s the column occurs, so
  2937. # that the corresponding_column() operation can resolve
  2938. # conflicts
  2939. for subq_col, select_cols in zip(
  2940. subquery.c._all_columns,
  2941. zip(*[s.selected_columns for s in self.selects]),
  2942. ):
  2943. subq_col._proxies = [
  2944. c._annotate({"weight": i + 1})
  2945. for (i, c) in enumerate(select_cols)
  2946. ]
  2947. def _refresh_for_new_column(self, column):
  2948. super(CompoundSelect, self)._refresh_for_new_column(column)
  2949. for select in self.selects:
  2950. select._refresh_for_new_column(column)
  2951. @property
  2952. def _all_selected_columns(self):
  2953. return self.selects[0]._all_selected_columns
  2954. @property
  2955. def selected_columns(self):
  2956. """A :class:`_expression.ColumnCollection`
  2957. representing the columns that
  2958. this SELECT statement or similar construct returns in its result set,
  2959. not including :class:`_sql.TextClause` constructs.
  2960. For a :class:`_expression.CompoundSelect`, the
  2961. :attr:`_expression.CompoundSelect.selected_columns`
  2962. attribute returns the selected
  2963. columns of the first SELECT statement contained within the series of
  2964. statements within the set operation.
  2965. .. seealso::
  2966. :attr:`_sql.Select.selected_columns`
  2967. .. versionadded:: 1.4
  2968. """
  2969. return self.selects[0].selected_columns
  2970. @property
  2971. @util.deprecated_20(
  2972. ":attr:`.Executable.bind`",
  2973. alternative="Bound metadata is being removed as of SQLAlchemy 2.0.",
  2974. enable_warnings=False,
  2975. )
  2976. def bind(self):
  2977. """Returns the :class:`_engine.Engine` or :class:`_engine.Connection`
  2978. to which this :class:`.Executable` is bound, or None if none found.
  2979. """
  2980. if self._bind:
  2981. return self._bind
  2982. for s in self.selects:
  2983. e = s.bind
  2984. if e:
  2985. return e
  2986. else:
  2987. return None
  2988. @bind.setter
  2989. def bind(self, bind):
  2990. self._bind = bind
  2991. class DeprecatedSelectGenerations(object):
  2992. """A collection of methods available on :class:`_sql.Select`, these
  2993. are all **deprecated** methods as they modify the :class:`_sql.Select`
  2994. object in -place.
  2995. """
  2996. @util.deprecated(
  2997. "1.4",
  2998. "The :meth:`_expression.Select.append_correlation` "
  2999. "method is deprecated "
  3000. "and will be removed in a future release. Use the generative "
  3001. "method :meth:`_expression.Select.correlate`.",
  3002. )
  3003. def append_correlation(self, fromclause):
  3004. """Append the given correlation expression to this select()
  3005. construct.
  3006. This is an **in-place** mutation method; the
  3007. :meth:`_expression.Select.correlate` method is preferred,
  3008. as it provides
  3009. standard :term:`method chaining`.
  3010. """
  3011. self.correlate.non_generative(self, fromclause)
  3012. @util.deprecated(
  3013. "1.4",
  3014. "The :meth:`_expression.Select.append_column` method is deprecated "
  3015. "and will be removed in a future release. Use the generative "
  3016. "method :meth:`_expression.Select.add_columns`.",
  3017. )
  3018. def append_column(self, column):
  3019. """Append the given column expression to the columns clause of this
  3020. select() construct.
  3021. E.g.::
  3022. my_select.append_column(some_table.c.new_column)
  3023. This is an **in-place** mutation method; the
  3024. :meth:`_expression.Select.add_columns` method is preferred,
  3025. as it provides standard
  3026. :term:`method chaining`.
  3027. """
  3028. self.add_columns.non_generative(self, column)
  3029. @util.deprecated(
  3030. "1.4",
  3031. "The :meth:`_expression.Select.append_prefix` method is deprecated "
  3032. "and will be removed in a future release. Use the generative "
  3033. "method :meth:`_expression.Select.prefix_with`.",
  3034. )
  3035. def append_prefix(self, clause):
  3036. """Append the given columns clause prefix expression to this select()
  3037. construct.
  3038. This is an **in-place** mutation method; the
  3039. :meth:`_expression.Select.prefix_with` method is preferred,
  3040. as it provides
  3041. standard :term:`method chaining`.
  3042. """
  3043. self.prefix_with.non_generative(self, clause)
  3044. @util.deprecated(
  3045. "1.4",
  3046. "The :meth:`_expression.Select.append_whereclause` "
  3047. "method is deprecated "
  3048. "and will be removed in a future release. Use the generative "
  3049. "method :meth:`_expression.Select.where`.",
  3050. )
  3051. def append_whereclause(self, whereclause):
  3052. """Append the given expression to this select() construct's WHERE
  3053. criterion.
  3054. The expression will be joined to existing WHERE criterion via AND.
  3055. This is an **in-place** mutation method; the
  3056. :meth:`_expression.Select.where` method is preferred,
  3057. as it provides standard
  3058. :term:`method chaining`.
  3059. """
  3060. self.where.non_generative(self, whereclause)
  3061. @util.deprecated(
  3062. "1.4",
  3063. "The :meth:`_expression.Select.append_having` method is deprecated "
  3064. "and will be removed in a future release. Use the generative "
  3065. "method :meth:`_expression.Select.having`.",
  3066. )
  3067. def append_having(self, having):
  3068. """Append the given expression to this select() construct's HAVING
  3069. criterion.
  3070. The expression will be joined to existing HAVING criterion via AND.
  3071. This is an **in-place** mutation method; the
  3072. :meth:`_expression.Select.having` method is preferred,
  3073. as it provides standard
  3074. :term:`method chaining`.
  3075. """
  3076. self.having.non_generative(self, having)
  3077. @util.deprecated(
  3078. "1.4",
  3079. "The :meth:`_expression.Select.append_from` method is deprecated "
  3080. "and will be removed in a future release. Use the generative "
  3081. "method :meth:`_expression.Select.select_from`.",
  3082. )
  3083. def append_from(self, fromclause):
  3084. """Append the given :class:`_expression.FromClause` expression
  3085. to this select() construct's FROM clause.
  3086. This is an **in-place** mutation method; the
  3087. :meth:`_expression.Select.select_from` method is preferred,
  3088. as it provides
  3089. standard :term:`method chaining`.
  3090. """
  3091. self.select_from.non_generative(self, fromclause)
  3092. @CompileState.plugin_for("default", "select")
  3093. class SelectState(util.MemoizedSlots, CompileState):
  3094. __slots__ = (
  3095. "from_clauses",
  3096. "froms",
  3097. "columns_plus_names",
  3098. "_label_resolve_dict",
  3099. )
  3100. class default_select_compile_options(CacheableOptions):
  3101. _cache_key_traversal = []
  3102. def __init__(self, statement, compiler, **kw):
  3103. self.statement = statement
  3104. self.from_clauses = statement._from_obj
  3105. for memoized_entities in statement._memoized_select_entities:
  3106. self._setup_joins(
  3107. memoized_entities._setup_joins, memoized_entities._raw_columns
  3108. )
  3109. if statement._setup_joins:
  3110. self._setup_joins(statement._setup_joins, statement._raw_columns)
  3111. self.froms = self._get_froms(statement)
  3112. self.columns_plus_names = statement._generate_columns_plus_names(True)
  3113. @classmethod
  3114. def _plugin_not_implemented(cls):
  3115. raise NotImplementedError(
  3116. "The default SELECT construct without plugins does not "
  3117. "implement this method."
  3118. )
  3119. @classmethod
  3120. def get_column_descriptions(cls, statement):
  3121. cls._plugin_not_implemented()
  3122. @classmethod
  3123. def from_statement(cls, statement, from_statement):
  3124. cls._plugin_not_implemented()
  3125. @classmethod
  3126. def _column_naming_convention(cls, label_style):
  3127. # note: these functions won't work for TextClause objects,
  3128. # which should be omitted when iterating through
  3129. # _raw_columns.
  3130. if label_style is LABEL_STYLE_NONE:
  3131. def go(c, col_name=None):
  3132. return c._proxy_key
  3133. elif label_style is LABEL_STYLE_TABLENAME_PLUS_COL:
  3134. names = set()
  3135. pa = [] # late-constructed as needed, python 2 has no "nonlocal"
  3136. def go(c, col_name=None):
  3137. # we use key_label since this name is intended for targeting
  3138. # within the ColumnCollection only, it's not related to SQL
  3139. # rendering which always uses column name for SQL label names
  3140. name = c._key_label
  3141. if name in names:
  3142. if not pa:
  3143. pa.append(prefix_anon_map())
  3144. name = c._label_anon_key_label % pa[0]
  3145. else:
  3146. names.add(name)
  3147. return name
  3148. else:
  3149. names = set()
  3150. pa = [] # late-constructed as needed, python 2 has no "nonlocal"
  3151. def go(c, col_name=None):
  3152. name = c._proxy_key
  3153. if name in names:
  3154. if not pa:
  3155. pa.append(prefix_anon_map())
  3156. name = c._anon_key_label % pa[0]
  3157. else:
  3158. names.add(name)
  3159. return name
  3160. return go
  3161. def _get_froms(self, statement):
  3162. return self._normalize_froms(
  3163. itertools.chain(
  3164. itertools.chain.from_iterable(
  3165. [
  3166. element._from_objects
  3167. for element in statement._raw_columns
  3168. ]
  3169. ),
  3170. itertools.chain.from_iterable(
  3171. [
  3172. element._from_objects
  3173. for element in statement._where_criteria
  3174. ]
  3175. ),
  3176. self.from_clauses,
  3177. ),
  3178. check_statement=statement,
  3179. )
  3180. def _normalize_froms(self, iterable_of_froms, check_statement=None):
  3181. """given an iterable of things to select FROM, reduce them to what
  3182. would actually render in the FROM clause of a SELECT.
  3183. This does the job of checking for JOINs, tables, etc. that are in fact
  3184. overlapping due to cloning, adaption, present in overlapping joins,
  3185. etc.
  3186. """
  3187. seen = set()
  3188. froms = []
  3189. for item in iterable_of_froms:
  3190. if item._is_subquery and item.element is check_statement:
  3191. raise exc.InvalidRequestError(
  3192. "select() construct refers to itself as a FROM"
  3193. )
  3194. if not seen.intersection(item._cloned_set):
  3195. froms.append(item)
  3196. seen.update(item._cloned_set)
  3197. if froms:
  3198. toremove = set(
  3199. itertools.chain.from_iterable(
  3200. [_expand_cloned(f._hide_froms) for f in froms]
  3201. )
  3202. )
  3203. if toremove:
  3204. # filter out to FROM clauses not in the list,
  3205. # using a list to maintain ordering
  3206. froms = [f for f in froms if f not in toremove]
  3207. return froms
  3208. def _get_display_froms(
  3209. self, explicit_correlate_froms=None, implicit_correlate_froms=None
  3210. ):
  3211. """Return the full list of 'from' clauses to be displayed.
  3212. Takes into account a set of existing froms which may be
  3213. rendered in the FROM clause of enclosing selects; this Select
  3214. may want to leave those absent if it is automatically
  3215. correlating.
  3216. """
  3217. froms = self.froms
  3218. if self.statement._correlate:
  3219. to_correlate = self.statement._correlate
  3220. if to_correlate:
  3221. froms = [
  3222. f
  3223. for f in froms
  3224. if f
  3225. not in _cloned_intersection(
  3226. _cloned_intersection(
  3227. froms, explicit_correlate_froms or ()
  3228. ),
  3229. to_correlate,
  3230. )
  3231. ]
  3232. if self.statement._correlate_except is not None:
  3233. froms = [
  3234. f
  3235. for f in froms
  3236. if f
  3237. not in _cloned_difference(
  3238. _cloned_intersection(
  3239. froms, explicit_correlate_froms or ()
  3240. ),
  3241. self.statement._correlate_except,
  3242. )
  3243. ]
  3244. if (
  3245. self.statement._auto_correlate
  3246. and implicit_correlate_froms
  3247. and len(froms) > 1
  3248. ):
  3249. froms = [
  3250. f
  3251. for f in froms
  3252. if f
  3253. not in _cloned_intersection(froms, implicit_correlate_froms)
  3254. ]
  3255. if not len(froms):
  3256. raise exc.InvalidRequestError(
  3257. "Select statement '%r"
  3258. "' returned no FROM clauses "
  3259. "due to auto-correlation; "
  3260. "specify correlate(<tables>) "
  3261. "to control correlation "
  3262. "manually." % self.statement
  3263. )
  3264. return froms
  3265. def _memoized_attr__label_resolve_dict(self):
  3266. with_cols = dict(
  3267. (c._resolve_label or c._label or c.key, c)
  3268. for c in self.statement._all_selected_columns
  3269. if c._allow_label_resolve
  3270. )
  3271. only_froms = dict(
  3272. (c.key, c)
  3273. for c in _select_iterables(self.froms)
  3274. if c._allow_label_resolve
  3275. )
  3276. only_cols = with_cols.copy()
  3277. for key, value in only_froms.items():
  3278. with_cols.setdefault(key, value)
  3279. return with_cols, only_froms, only_cols
  3280. @classmethod
  3281. def determine_last_joined_entity(cls, stmt):
  3282. if stmt._setup_joins:
  3283. return stmt._setup_joins[-1][0]
  3284. else:
  3285. return None
  3286. @classmethod
  3287. def all_selected_columns(cls, statement):
  3288. return [c for c in _select_iterables(statement._raw_columns)]
  3289. def _setup_joins(self, args, raw_columns):
  3290. for (right, onclause, left, flags) in args:
  3291. isouter = flags["isouter"]
  3292. full = flags["full"]
  3293. if left is None:
  3294. (
  3295. left,
  3296. replace_from_obj_index,
  3297. ) = self._join_determine_implicit_left_side(
  3298. raw_columns, left, right, onclause
  3299. )
  3300. else:
  3301. (replace_from_obj_index) = self._join_place_explicit_left_side(
  3302. left
  3303. )
  3304. if replace_from_obj_index is not None:
  3305. # splice into an existing element in the
  3306. # self._from_obj list
  3307. left_clause = self.from_clauses[replace_from_obj_index]
  3308. self.from_clauses = (
  3309. self.from_clauses[:replace_from_obj_index]
  3310. + (
  3311. Join(
  3312. left_clause,
  3313. right,
  3314. onclause,
  3315. isouter=isouter,
  3316. full=full,
  3317. ),
  3318. )
  3319. + self.from_clauses[replace_from_obj_index + 1 :]
  3320. )
  3321. else:
  3322. self.from_clauses = self.from_clauses + (
  3323. Join(left, right, onclause, isouter=isouter, full=full),
  3324. )
  3325. @util.preload_module("sqlalchemy.sql.util")
  3326. def _join_determine_implicit_left_side(
  3327. self, raw_columns, left, right, onclause
  3328. ):
  3329. """When join conditions don't express the left side explicitly,
  3330. determine if an existing FROM or entity in this query
  3331. can serve as the left hand side.
  3332. """
  3333. sql_util = util.preloaded.sql_util
  3334. replace_from_obj_index = None
  3335. from_clauses = self.from_clauses
  3336. if from_clauses:
  3337. indexes = sql_util.find_left_clause_to_join_from(
  3338. from_clauses, right, onclause
  3339. )
  3340. if len(indexes) == 1:
  3341. replace_from_obj_index = indexes[0]
  3342. left = from_clauses[replace_from_obj_index]
  3343. else:
  3344. potential = {}
  3345. statement = self.statement
  3346. for from_clause in itertools.chain(
  3347. itertools.chain.from_iterable(
  3348. [element._from_objects for element in raw_columns]
  3349. ),
  3350. itertools.chain.from_iterable(
  3351. [
  3352. element._from_objects
  3353. for element in statement._where_criteria
  3354. ]
  3355. ),
  3356. ):
  3357. potential[from_clause] = ()
  3358. all_clauses = list(potential.keys())
  3359. indexes = sql_util.find_left_clause_to_join_from(
  3360. all_clauses, right, onclause
  3361. )
  3362. if len(indexes) == 1:
  3363. left = all_clauses[indexes[0]]
  3364. if len(indexes) > 1:
  3365. raise exc.InvalidRequestError(
  3366. "Can't determine which FROM clause to join "
  3367. "from, there are multiple FROMS which can "
  3368. "join to this entity. Please use the .select_from() "
  3369. "method to establish an explicit left side, as well as "
  3370. "providing an explicit ON clause if not present already to "
  3371. "help resolve the ambiguity."
  3372. )
  3373. elif not indexes:
  3374. raise exc.InvalidRequestError(
  3375. "Don't know how to join to %r. "
  3376. "Please use the .select_from() "
  3377. "method to establish an explicit left side, as well as "
  3378. "providing an explicit ON clause if not present already to "
  3379. "help resolve the ambiguity." % (right,)
  3380. )
  3381. return left, replace_from_obj_index
  3382. @util.preload_module("sqlalchemy.sql.util")
  3383. def _join_place_explicit_left_side(self, left):
  3384. replace_from_obj_index = None
  3385. sql_util = util.preloaded.sql_util
  3386. from_clauses = list(self.statement._iterate_from_elements())
  3387. if from_clauses:
  3388. indexes = sql_util.find_left_clause_that_matches_given(
  3389. self.from_clauses, left
  3390. )
  3391. else:
  3392. indexes = []
  3393. if len(indexes) > 1:
  3394. raise exc.InvalidRequestError(
  3395. "Can't identify which entity in which to assign the "
  3396. "left side of this join. Please use a more specific "
  3397. "ON clause."
  3398. )
  3399. # have an index, means the left side is already present in
  3400. # an existing FROM in the self._from_obj tuple
  3401. if indexes:
  3402. replace_from_obj_index = indexes[0]
  3403. # no index, means we need to add a new element to the
  3404. # self._from_obj tuple
  3405. return replace_from_obj_index
  3406. class _SelectFromElements(object):
  3407. def _iterate_from_elements(self):
  3408. # note this does not include elements
  3409. # in _setup_joins or _legacy_setup_joins
  3410. seen = set()
  3411. for element in self._raw_columns:
  3412. for fr in element._from_objects:
  3413. if fr in seen:
  3414. continue
  3415. seen.add(fr)
  3416. yield fr
  3417. for element in self._where_criteria:
  3418. for fr in element._from_objects:
  3419. if fr in seen:
  3420. continue
  3421. seen.add(fr)
  3422. yield fr
  3423. for element in self._from_obj:
  3424. if element in seen:
  3425. continue
  3426. seen.add(element)
  3427. yield element
  3428. class _MemoizedSelectEntities(
  3429. traversals.HasCacheKey, traversals.HasCopyInternals, visitors.Traversible
  3430. ):
  3431. __visit_name__ = "memoized_select_entities"
  3432. _traverse_internals = [
  3433. ("_raw_columns", InternalTraversal.dp_clauseelement_list),
  3434. ("_setup_joins", InternalTraversal.dp_setup_join_tuple),
  3435. ("_legacy_setup_joins", InternalTraversal.dp_setup_join_tuple),
  3436. ("_with_options", InternalTraversal.dp_executable_options),
  3437. ]
  3438. _annotations = util.EMPTY_DICT
  3439. def _clone(self, **kw):
  3440. c = self.__class__.__new__(self.__class__)
  3441. c.__dict__ = {k: v for k, v in self.__dict__.items()}
  3442. c._is_clone_of = self
  3443. return c
  3444. @classmethod
  3445. def _generate_for_statement(cls, select_stmt):
  3446. if (
  3447. select_stmt._setup_joins
  3448. or select_stmt._legacy_setup_joins
  3449. or select_stmt._with_options
  3450. ):
  3451. self = _MemoizedSelectEntities()
  3452. self._raw_columns = select_stmt._raw_columns
  3453. self._setup_joins = select_stmt._setup_joins
  3454. self._legacy_setup_joins = select_stmt._legacy_setup_joins
  3455. self._with_options = select_stmt._with_options
  3456. select_stmt._memoized_select_entities += (self,)
  3457. select_stmt._raw_columns = (
  3458. select_stmt._setup_joins
  3459. ) = (
  3460. select_stmt._legacy_setup_joins
  3461. ) = select_stmt._with_options = ()
  3462. class Select(
  3463. HasPrefixes,
  3464. HasSuffixes,
  3465. HasHints,
  3466. HasCompileState,
  3467. DeprecatedSelectGenerations,
  3468. _SelectFromElements,
  3469. GenerativeSelect,
  3470. ):
  3471. """Represents a ``SELECT`` statement.
  3472. The :class:`_sql.Select` object is normally constructed using the
  3473. :func:`_sql.select` function. See that function for details.
  3474. .. seealso::
  3475. :func:`_sql.select`
  3476. :ref:`coretutorial_selecting` - in the 1.x tutorial
  3477. :ref:`tutorial_selecting_data` - in the 2.0 tutorial
  3478. """
  3479. __visit_name__ = "select"
  3480. _setup_joins = ()
  3481. _legacy_setup_joins = ()
  3482. _memoized_select_entities = ()
  3483. _distinct = False
  3484. _distinct_on = ()
  3485. _correlate = ()
  3486. _correlate_except = None
  3487. _where_criteria = ()
  3488. _having_criteria = ()
  3489. _from_obj = ()
  3490. _auto_correlate = True
  3491. _compile_options = SelectState.default_select_compile_options
  3492. _traverse_internals = (
  3493. [
  3494. ("_raw_columns", InternalTraversal.dp_clauseelement_list),
  3495. (
  3496. "_memoized_select_entities",
  3497. InternalTraversal.dp_memoized_select_entities,
  3498. ),
  3499. ("_from_obj", InternalTraversal.dp_clauseelement_list),
  3500. ("_where_criteria", InternalTraversal.dp_clauseelement_tuple),
  3501. ("_having_criteria", InternalTraversal.dp_clauseelement_tuple),
  3502. ("_order_by_clauses", InternalTraversal.dp_clauseelement_tuple),
  3503. ("_group_by_clauses", InternalTraversal.dp_clauseelement_tuple),
  3504. ("_setup_joins", InternalTraversal.dp_setup_join_tuple),
  3505. ("_legacy_setup_joins", InternalTraversal.dp_setup_join_tuple),
  3506. ("_correlate", InternalTraversal.dp_clauseelement_tuple),
  3507. ("_correlate_except", InternalTraversal.dp_clauseelement_tuple),
  3508. ("_limit_clause", InternalTraversal.dp_clauseelement),
  3509. ("_offset_clause", InternalTraversal.dp_clauseelement),
  3510. ("_fetch_clause", InternalTraversal.dp_clauseelement),
  3511. ("_fetch_clause_options", InternalTraversal.dp_plain_dict),
  3512. ("_for_update_arg", InternalTraversal.dp_clauseelement),
  3513. ("_distinct", InternalTraversal.dp_boolean),
  3514. ("_distinct_on", InternalTraversal.dp_clauseelement_tuple),
  3515. ("_label_style", InternalTraversal.dp_plain_obj),
  3516. ]
  3517. + HasPrefixes._has_prefixes_traverse_internals
  3518. + HasSuffixes._has_suffixes_traverse_internals
  3519. + HasHints._has_hints_traverse_internals
  3520. + SupportsCloneAnnotations._clone_annotations_traverse_internals
  3521. + Executable._executable_traverse_internals
  3522. )
  3523. _cache_key_traversal = _traverse_internals + [
  3524. ("_compile_options", InternalTraversal.dp_has_cache_key)
  3525. ]
  3526. @classmethod
  3527. def _create_select_from_fromclause(cls, target, entities, *arg, **kw):
  3528. if arg or kw:
  3529. return Select.create_legacy_select(entities, *arg, **kw)
  3530. else:
  3531. return Select._create_select(*entities)
  3532. @classmethod
  3533. @util.deprecated(
  3534. "2.0",
  3535. "The legacy calling style of :func:`_sql.select` is deprecated and "
  3536. "will be removed in SQLAlchemy 2.0. Please use the new calling "
  3537. "style described at :func:`_sql.select`.",
  3538. )
  3539. def create_legacy_select(
  3540. cls,
  3541. columns=None,
  3542. whereclause=None,
  3543. from_obj=None,
  3544. distinct=False,
  3545. having=None,
  3546. correlate=True,
  3547. prefixes=None,
  3548. suffixes=None,
  3549. **kwargs
  3550. ):
  3551. """Construct a new :class:`_expression.Select` using the 1.x style API.
  3552. This method is called implicitly when the :func:`_expression.select`
  3553. construct is used and the first argument is a Python list or other
  3554. plain sequence object, which is taken to refer to the columns
  3555. collection.
  3556. .. versionchanged:: 1.4 Added the :meth:`.Select.create_legacy_select`
  3557. constructor which documents the calling style in use when the
  3558. :func:`.select` construct is invoked using 1.x-style arguments.
  3559. Similar functionality is also available via the
  3560. :meth:`_expression.FromClause.select` method on any
  3561. :class:`_expression.FromClause`.
  3562. All arguments which accept :class:`_expression.ClauseElement` arguments
  3563. also accept string arguments, which will be converted as appropriate
  3564. into either :func:`_expression.text()` or
  3565. :func:`_expression.literal_column()` constructs.
  3566. .. seealso::
  3567. :ref:`coretutorial_selecting` - Core Tutorial description of
  3568. :func:`_expression.select`.
  3569. :param columns:
  3570. A list of :class:`_expression.ColumnElement` or
  3571. :class:`_expression.FromClause`
  3572. objects which will form the columns clause of the resulting
  3573. statement. For those objects that are instances of
  3574. :class:`_expression.FromClause` (typically :class:`_schema.Table`
  3575. or :class:`_expression.Alias`
  3576. objects), the :attr:`_expression.FromClause.c`
  3577. collection is extracted
  3578. to form a collection of :class:`_expression.ColumnElement` objects.
  3579. This parameter will also accept :class:`_expression.TextClause`
  3580. constructs as
  3581. given, as well as ORM-mapped classes.
  3582. .. note::
  3583. The :paramref:`_expression.select.columns`
  3584. parameter is not available
  3585. in the method form of :func:`_expression.select`, e.g.
  3586. :meth:`_expression.FromClause.select`.
  3587. .. seealso::
  3588. :meth:`_expression.Select.column`
  3589. :meth:`_expression.Select.with_only_columns`
  3590. :param whereclause:
  3591. A :class:`_expression.ClauseElement`
  3592. expression which will be used to form the
  3593. ``WHERE`` clause. It is typically preferable to add WHERE
  3594. criterion to an existing :class:`_expression.Select`
  3595. using method chaining
  3596. with :meth:`_expression.Select.where`.
  3597. .. seealso::
  3598. :meth:`_expression.Select.where`
  3599. :param from_obj:
  3600. A list of :class:`_expression.ClauseElement`
  3601. objects which will be added to the
  3602. ``FROM`` clause of the resulting statement. This is equivalent
  3603. to calling :meth:`_expression.Select.select_from`
  3604. using method chaining on
  3605. an existing :class:`_expression.Select` object.
  3606. .. seealso::
  3607. :meth:`_expression.Select.select_from`
  3608. - full description of explicit
  3609. FROM clause specification.
  3610. :param bind=None:
  3611. an :class:`_engine.Engine` or :class:`_engine.Connection` instance
  3612. to which the
  3613. resulting :class:`_expression.Select` object will be bound. The
  3614. :class:`_expression.Select`
  3615. object will otherwise automatically bind to
  3616. whatever :class:`~.base.Connectable` instances can be located within
  3617. its contained :class:`_expression.ClauseElement` members.
  3618. :param correlate=True:
  3619. indicates that this :class:`_expression.Select`
  3620. object should have its
  3621. contained :class:`_expression.FromClause`
  3622. elements "correlated" to an enclosing
  3623. :class:`_expression.Select` object.
  3624. It is typically preferable to specify
  3625. correlations on an existing :class:`_expression.Select`
  3626. construct using
  3627. :meth:`_expression.Select.correlate`.
  3628. .. seealso::
  3629. :meth:`_expression.Select.correlate`
  3630. - full description of correlation.
  3631. :param distinct=False:
  3632. when ``True``, applies a ``DISTINCT`` qualifier to the columns
  3633. clause of the resulting statement.
  3634. The boolean argument may also be a column expression or list
  3635. of column expressions - this is a special calling form which
  3636. is understood by the PostgreSQL dialect to render the
  3637. ``DISTINCT ON (<columns>)`` syntax.
  3638. ``distinct`` is also available on an existing
  3639. :class:`_expression.Select`
  3640. object via the :meth:`_expression.Select.distinct` method.
  3641. .. seealso::
  3642. :meth:`_expression.Select.distinct`
  3643. :param group_by:
  3644. a list of :class:`_expression.ClauseElement`
  3645. objects which will comprise the
  3646. ``GROUP BY`` clause of the resulting select. This parameter
  3647. is typically specified more naturally using the
  3648. :meth:`_expression.Select.group_by` method on an existing
  3649. :class:`_expression.Select`.
  3650. .. seealso::
  3651. :meth:`_expression.Select.group_by`
  3652. :param having:
  3653. a :class:`_expression.ClauseElement`
  3654. that will comprise the ``HAVING`` clause
  3655. of the resulting select when ``GROUP BY`` is used. This parameter
  3656. is typically specified more naturally using the
  3657. :meth:`_expression.Select.having` method on an existing
  3658. :class:`_expression.Select`.
  3659. .. seealso::
  3660. :meth:`_expression.Select.having`
  3661. :param limit=None:
  3662. a numerical value which usually renders as a ``LIMIT``
  3663. expression in the resulting select. Backends that don't
  3664. support ``LIMIT`` will attempt to provide similar
  3665. functionality. This parameter is typically specified more
  3666. naturally using the :meth:`_expression.Select.limit`
  3667. method on an existing
  3668. :class:`_expression.Select`.
  3669. .. seealso::
  3670. :meth:`_expression.Select.limit`
  3671. :param offset=None:
  3672. a numeric value which usually renders as an ``OFFSET``
  3673. expression in the resulting select. Backends that don't
  3674. support ``OFFSET`` will attempt to provide similar
  3675. functionality. This parameter is typically specified more naturally
  3676. using the :meth:`_expression.Select.offset` method on an existing
  3677. :class:`_expression.Select`.
  3678. .. seealso::
  3679. :meth:`_expression.Select.offset`
  3680. :param order_by:
  3681. a scalar or list of :class:`_expression.ClauseElement`
  3682. objects which will
  3683. comprise the ``ORDER BY`` clause of the resulting select.
  3684. This parameter is typically specified more naturally using the
  3685. :meth:`_expression.Select.order_by` method on an existing
  3686. :class:`_expression.Select`.
  3687. .. seealso::
  3688. :meth:`_expression.Select.order_by`
  3689. :param use_labels=False:
  3690. when ``True``, the statement will be generated using labels
  3691. for each column in the columns clause, which qualify each
  3692. column with its parent table's (or aliases) name so that name
  3693. conflicts between columns in different tables don't occur.
  3694. The format of the label is ``<tablename>_<column>``. The "c"
  3695. collection of a :class:`_expression.Subquery` created
  3696. against this :class:`_expression.Select`
  3697. object, as well as the :attr:`_expression.Select.selected_columns`
  3698. collection of the :class:`_expression.Select` itself, will use these
  3699. names for targeting column members.
  3700. This parameter can also be specified on an existing
  3701. :class:`_expression.Select` object using the
  3702. :meth:`_expression.Select.set_label_style`
  3703. method.
  3704. .. seealso::
  3705. :meth:`_expression.Select.set_label_style`
  3706. """
  3707. self = cls.__new__(cls)
  3708. self._auto_correlate = correlate
  3709. if distinct is not False:
  3710. if distinct is True:
  3711. self.distinct.non_generative(self)
  3712. else:
  3713. self.distinct.non_generative(self, *util.to_list(distinct))
  3714. if from_obj is not None:
  3715. self.select_from.non_generative(self, *util.to_list(from_obj))
  3716. try:
  3717. cols_present = bool(columns)
  3718. except TypeError as err:
  3719. util.raise_(
  3720. exc.ArgumentError(
  3721. "select() construct created in legacy mode, i.e. with "
  3722. "keyword arguments, must provide the columns argument as "
  3723. "a Python list or other iterable.",
  3724. code="c9ae",
  3725. ),
  3726. from_=err,
  3727. )
  3728. if cols_present:
  3729. self._raw_columns = [
  3730. coercions.expect(
  3731. roles.ColumnsClauseRole, c, apply_propagate_attrs=self
  3732. )
  3733. for c in columns
  3734. ]
  3735. else:
  3736. self._raw_columns = []
  3737. if whereclause is not None:
  3738. self.where.non_generative(self, whereclause)
  3739. if having is not None:
  3740. self.having.non_generative(self, having)
  3741. if prefixes:
  3742. self._setup_prefixes(prefixes)
  3743. if suffixes:
  3744. self._setup_suffixes(suffixes)
  3745. GenerativeSelect.__init__(self, **kwargs)
  3746. return self
  3747. @classmethod
  3748. def _create_future_select(cls, *entities):
  3749. r"""Construct a new :class:`_expression.Select` using the 2.
  3750. x style API.
  3751. .. versionadded:: 1.4 - The :func:`_sql.select` function now accepts
  3752. column arguments positionally. The top-level :func:`_sql.select`
  3753. function will automatically use the 1.x or 2.x style API based on
  3754. the incoming arguments; using :func:`_future.select` from the
  3755. ``sqlalchemy.future`` module will enforce that only the 2.x style
  3756. constructor is used.
  3757. Similar functionality is also available via the
  3758. :meth:`_expression.FromClause.select` method on any
  3759. :class:`_expression.FromClause`.
  3760. .. seealso::
  3761. :ref:`coretutorial_selecting` - Core Tutorial description of
  3762. :func:`_expression.select`.
  3763. :param \*entities:
  3764. Entities to SELECT from. For Core usage, this is typically a series
  3765. of :class:`_expression.ColumnElement` and / or
  3766. :class:`_expression.FromClause`
  3767. objects which will form the columns clause of the resulting
  3768. statement. For those objects that are instances of
  3769. :class:`_expression.FromClause` (typically :class:`_schema.Table`
  3770. or :class:`_expression.Alias`
  3771. objects), the :attr:`_expression.FromClause.c`
  3772. collection is extracted
  3773. to form a collection of :class:`_expression.ColumnElement` objects.
  3774. This parameter will also accept :class:`_expression.TextClause`
  3775. constructs as
  3776. given, as well as ORM-mapped classes.
  3777. """
  3778. self = cls.__new__(cls)
  3779. self._raw_columns = [
  3780. coercions.expect(
  3781. roles.ColumnsClauseRole, ent, apply_propagate_attrs=self
  3782. )
  3783. for ent in entities
  3784. ]
  3785. GenerativeSelect.__init__(self)
  3786. return self
  3787. _create_select = _create_future_select
  3788. @classmethod
  3789. def _create(cls, *args, **kw):
  3790. r"""Create a :class:`.Select` using either the 1.x or 2.0 constructor
  3791. style.
  3792. For the legacy calling style, see :meth:`.Select.create_legacy_select`.
  3793. If the first argument passed is a Python sequence or if keyword
  3794. arguments are present, this style is used.
  3795. .. versionadded:: 2.0 - the :func:`_future.select` construct is
  3796. the same construct as the one returned by
  3797. :func:`_expression.select`, except that the function only
  3798. accepts the "columns clause" entities up front; the rest of the
  3799. state of the SELECT should be built up using generative methods.
  3800. Similar functionality is also available via the
  3801. :meth:`_expression.FromClause.select` method on any
  3802. :class:`_expression.FromClause`.
  3803. .. seealso::
  3804. :ref:`coretutorial_selecting` - Core Tutorial description of
  3805. :func:`_expression.select`.
  3806. :param \*entities:
  3807. Entities to SELECT from. For Core usage, this is typically a series
  3808. of :class:`_expression.ColumnElement` and / or
  3809. :class:`_expression.FromClause`
  3810. objects which will form the columns clause of the resulting
  3811. statement. For those objects that are instances of
  3812. :class:`_expression.FromClause` (typically :class:`_schema.Table`
  3813. or :class:`_expression.Alias`
  3814. objects), the :attr:`_expression.FromClause.c`
  3815. collection is extracted
  3816. to form a collection of :class:`_expression.ColumnElement` objects.
  3817. This parameter will also accept :class:`_expression.TextClause`
  3818. constructs as given, as well as ORM-mapped classes.
  3819. """
  3820. if (
  3821. args
  3822. and (
  3823. isinstance(args[0], list)
  3824. or (
  3825. hasattr(args[0], "__iter__")
  3826. and not isinstance(
  3827. args[0], util.string_types + (ClauseElement,)
  3828. )
  3829. and inspect(args[0], raiseerr=False) is None
  3830. and not hasattr(args[0], "__clause_element__")
  3831. )
  3832. )
  3833. ) or kw:
  3834. return cls.create_legacy_select(*args, **kw)
  3835. else:
  3836. return cls._create_future_select(*args)
  3837. def __init__(self):
  3838. raise NotImplementedError()
  3839. def _scalar_type(self):
  3840. elem = self._raw_columns[0]
  3841. cols = list(elem._select_iterable)
  3842. return cols[0].type
  3843. def filter(self, *criteria):
  3844. """A synonym for the :meth:`_future.Select.where` method."""
  3845. return self.where(*criteria)
  3846. def _filter_by_zero(self):
  3847. if self._setup_joins:
  3848. meth = SelectState.get_plugin_class(
  3849. self
  3850. ).determine_last_joined_entity
  3851. _last_joined_entity = meth(self)
  3852. if _last_joined_entity is not None:
  3853. return _last_joined_entity
  3854. if self._from_obj:
  3855. return self._from_obj[0]
  3856. return self._raw_columns[0]
  3857. def filter_by(self, **kwargs):
  3858. r"""apply the given filtering criterion as a WHERE clause
  3859. to this select.
  3860. """
  3861. from_entity = self._filter_by_zero()
  3862. clauses = [
  3863. _entity_namespace_key(from_entity, key) == value
  3864. for key, value in kwargs.items()
  3865. ]
  3866. return self.filter(*clauses)
  3867. @property
  3868. def column_descriptions(self):
  3869. """Return a 'column descriptions' structure which may be
  3870. :term:`plugin-specific`.
  3871. """
  3872. meth = SelectState.get_plugin_class(self).get_column_descriptions
  3873. return meth(self)
  3874. def from_statement(self, statement):
  3875. """Apply the columns which this :class:`.Select` would select
  3876. onto another statement.
  3877. This operation is :term:`plugin-specific` and will raise a not
  3878. supported exception if this :class:`_sql.Select` does not select from
  3879. plugin-enabled entities.
  3880. The statement is typically either a :func:`_expression.text` or
  3881. :func:`_expression.select` construct, and should return the set of
  3882. columns appropriate to the entities represented by this
  3883. :class:`.Select`.
  3884. .. seealso::
  3885. :ref:`orm_queryguide_selecting_text` - usage examples in the
  3886. ORM Querying Guide
  3887. """
  3888. meth = SelectState.get_plugin_class(self).from_statement
  3889. return meth(self, statement)
  3890. @_generative
  3891. def join(self, target, onclause=None, isouter=False, full=False):
  3892. r"""Create a SQL JOIN against this :class:`_expression.Select`
  3893. object's criterion
  3894. and apply generatively, returning the newly resulting
  3895. :class:`_expression.Select`.
  3896. E.g.::
  3897. stmt = select(user_table).join(address_table, user_table.c.id == address_table.c.user_id)
  3898. The above statement generates SQL similar to::
  3899. SELECT user.id, user.name FROM user JOIN address ON user.id = address.user_id
  3900. .. versionchanged:: 1.4 :meth:`_expression.Select.join` now creates
  3901. a :class:`_sql.Join` object between a :class:`_sql.FromClause`
  3902. source that is within the FROM clause of the existing SELECT,
  3903. and a given target :class:`_sql.FromClause`, and then adds
  3904. this :class:`_sql.Join` to the FROM clause of the newly generated
  3905. SELECT statement. This is completely reworked from the behavior
  3906. in 1.3, which would instead create a subquery of the entire
  3907. :class:`_expression.Select` and then join that subquery to the
  3908. target.
  3909. This is a **backwards incompatible change** as the previous behavior
  3910. was mostly useless, producing an unnamed subquery rejected by
  3911. most databases in any case. The new behavior is modeled after
  3912. that of the very successful :meth:`_orm.Query.join` method in the
  3913. ORM, in order to support the functionality of :class:`_orm.Query`
  3914. being available by using a :class:`_sql.Select` object with an
  3915. :class:`_orm.Session`.
  3916. See the notes for this change at :ref:`change_select_join`.
  3917. :param target: target table to join towards
  3918. :param onclause: ON clause of the join. If omitted, an ON clause
  3919. is generated automatically based on the :class:`_schema.ForeignKey`
  3920. linkages between the two tables, if one can be unambiguously
  3921. determined, otherwise an error is raised.
  3922. :param isouter: if True, generate LEFT OUTER join. Same as
  3923. :meth:`_expression.Select.outerjoin`.
  3924. :param full: if True, generate FULL OUTER join.
  3925. .. seealso::
  3926. :ref:`tutorial_select_join` - in the :doc:`/tutorial/index`
  3927. :ref:`orm_queryguide_joins` - in the :ref:`queryguide_toplevel`
  3928. :meth:`_expression.Select.join_from`
  3929. :meth:`_expression.Select.outerjoin`
  3930. """ # noqa: E501
  3931. target = coercions.expect(
  3932. roles.JoinTargetRole, target, apply_propagate_attrs=self
  3933. )
  3934. if onclause is not None:
  3935. onclause = coercions.expect(roles.OnClauseRole, onclause)
  3936. self._setup_joins += (
  3937. (target, onclause, None, {"isouter": isouter, "full": full}),
  3938. )
  3939. def outerjoin_from(self, from_, target, onclause=None, full=False):
  3940. r"""Create a SQL LEFT OUTER JOIN against this :class:`_expression.Select`
  3941. object's criterion
  3942. and apply generatively, returning the newly resulting
  3943. :class:`_expression.Select`.
  3944. Usage is the same as that of :meth:`_selectable.Select.join_from`.
  3945. """
  3946. return self.join_from(
  3947. from_, target, onclause=onclause, isouter=True, full=full
  3948. )
  3949. @_generative
  3950. def join_from(
  3951. self, from_, target, onclause=None, isouter=False, full=False
  3952. ):
  3953. r"""Create a SQL JOIN against this :class:`_expression.Select`
  3954. object's criterion
  3955. and apply generatively, returning the newly resulting
  3956. :class:`_expression.Select`.
  3957. E.g.::
  3958. stmt = select(user_table, address_table).join_from(
  3959. user_table, address_table, user_table.c.id == address_table.c.user_id
  3960. )
  3961. The above statement generates SQL similar to::
  3962. SELECT user.id, user.name, address.id, address.email, address.user_id
  3963. FROM user JOIN address ON user.id = address.user_id
  3964. .. versionadded:: 1.4
  3965. :param from\_: the left side of the join, will be rendered in the
  3966. FROM clause and is roughly equivalent to using the
  3967. :meth:`.Select.select_from` method.
  3968. :param target: target table to join towards
  3969. :param onclause: ON clause of the join.
  3970. :param isouter: if True, generate LEFT OUTER join. Same as
  3971. :meth:`_expression.Select.outerjoin`.
  3972. :param full: if True, generate FULL OUTER join.
  3973. .. seealso::
  3974. :ref:`tutorial_select_join` - in the :doc:`/tutorial/index`
  3975. :ref:`orm_queryguide_joins` - in the :ref:`queryguide_toplevel`
  3976. :meth:`_expression.Select.join`
  3977. """ # noqa: E501
  3978. # note the order of parsing from vs. target is important here, as we
  3979. # are also deriving the source of the plugin (i.e. the subject mapper
  3980. # in an ORM query) which should favor the "from_" over the "target"
  3981. from_ = coercions.expect(
  3982. roles.FromClauseRole, from_, apply_propagate_attrs=self
  3983. )
  3984. target = coercions.expect(
  3985. roles.JoinTargetRole, target, apply_propagate_attrs=self
  3986. )
  3987. if onclause is not None:
  3988. onclause = coercions.expect(roles.OnClauseRole, onclause)
  3989. self._setup_joins += (
  3990. (target, onclause, from_, {"isouter": isouter, "full": full}),
  3991. )
  3992. def outerjoin(self, target, onclause=None, full=False):
  3993. """Create a left outer join.
  3994. Parameters are the same as that of :meth:`_expression.Select.join`.
  3995. .. versionchanged:: 1.4 :meth:`_expression.Select.outerjoin` now
  3996. creates a :class:`_sql.Join` object between a
  3997. :class:`_sql.FromClause` source that is within the FROM clause of
  3998. the existing SELECT, and a given target :class:`_sql.FromClause`,
  3999. and then adds this :class:`_sql.Join` to the FROM clause of the
  4000. newly generated SELECT statement. This is completely reworked
  4001. from the behavior in 1.3, which would instead create a subquery of
  4002. the entire
  4003. :class:`_expression.Select` and then join that subquery to the
  4004. target.
  4005. This is a **backwards incompatible change** as the previous behavior
  4006. was mostly useless, producing an unnamed subquery rejected by
  4007. most databases in any case. The new behavior is modeled after
  4008. that of the very successful :meth:`_orm.Query.join` method in the
  4009. ORM, in order to support the functionality of :class:`_orm.Query`
  4010. being available by using a :class:`_sql.Select` object with an
  4011. :class:`_orm.Session`.
  4012. See the notes for this change at :ref:`change_select_join`.
  4013. .. seealso::
  4014. :ref:`tutorial_select_join` - in the :doc:`/tutorial/index`
  4015. :ref:`orm_queryguide_joins` - in the :ref:`queryguide_toplevel`
  4016. :meth:`_expression.Select.join`
  4017. """
  4018. return self.join(target, onclause=onclause, isouter=True, full=full)
  4019. @property
  4020. def froms(self):
  4021. """Return the displayed list of :class:`_expression.FromClause`
  4022. elements.
  4023. """
  4024. return self._compile_state_factory(self, None)._get_display_froms()
  4025. @property
  4026. def inner_columns(self):
  4027. """An iterator of all :class:`_expression.ColumnElement`
  4028. expressions which would
  4029. be rendered into the columns clause of the resulting SELECT statement.
  4030. This method is legacy as of 1.4 and is superseded by the
  4031. :attr:`_expression.Select.exported_columns` collection.
  4032. """
  4033. return iter(self._all_selected_columns)
  4034. def is_derived_from(self, fromclause):
  4035. if self in fromclause._cloned_set:
  4036. return True
  4037. for f in self._iterate_from_elements():
  4038. if f.is_derived_from(fromclause):
  4039. return True
  4040. return False
  4041. def _copy_internals(self, clone=_clone, **kw):
  4042. # Select() object has been cloned and probably adapted by the
  4043. # given clone function. Apply the cloning function to internal
  4044. # objects
  4045. # 1. keep a dictionary of the froms we've cloned, and what
  4046. # they've become. This allows us to ensure the same cloned from
  4047. # is used when other items such as columns are "cloned"
  4048. all_the_froms = set(
  4049. itertools.chain(
  4050. _from_objects(*self._raw_columns),
  4051. _from_objects(*self._where_criteria),
  4052. )
  4053. )
  4054. # do a clone for the froms we've gathered. what is important here
  4055. # is if any of the things we are selecting from, like tables,
  4056. # were converted into Join objects. if so, these need to be
  4057. # added to _from_obj explicitly, because otherwise they won't be
  4058. # part of the new state, as they don't associate themselves with
  4059. # their columns.
  4060. new_froms = {f: clone(f, **kw) for f in all_the_froms}
  4061. # 2. copy FROM collections, adding in joins that we've created.
  4062. existing_from_obj = [clone(f, **kw) for f in self._from_obj]
  4063. add_froms = (
  4064. set(f for f in new_froms.values() if isinstance(f, Join))
  4065. .difference(all_the_froms)
  4066. .difference(existing_from_obj)
  4067. )
  4068. self._from_obj = tuple(existing_from_obj) + tuple(add_froms)
  4069. # 3. clone everything else, making sure we use columns
  4070. # corresponding to the froms we just made.
  4071. def replace(obj, **kw):
  4072. if isinstance(obj, ColumnClause) and obj.table in new_froms:
  4073. newelem = new_froms[obj.table].corresponding_column(obj)
  4074. return newelem
  4075. kw["replace"] = replace
  4076. # copy everything else. for table-ish things like correlate,
  4077. # correlate_except, setup_joins, these clone normally. For
  4078. # column-expression oriented things like raw_columns, where_criteria,
  4079. # order by, we get this from the new froms.
  4080. super(Select, self)._copy_internals(
  4081. clone=clone, omit_attrs=("_from_obj",), **kw
  4082. )
  4083. self._reset_memoizations()
  4084. def get_children(self, **kwargs):
  4085. return itertools.chain(
  4086. super(Select, self).get_children(
  4087. omit_attrs=["_from_obj", "_correlate", "_correlate_except"]
  4088. ),
  4089. self._iterate_from_elements(),
  4090. )
  4091. @_generative
  4092. def add_columns(self, *columns):
  4093. """Return a new :func:`_expression.select` construct with
  4094. the given column expressions added to its columns clause.
  4095. E.g.::
  4096. my_select = my_select.add_columns(table.c.new_column)
  4097. See the documentation for
  4098. :meth:`_expression.Select.with_only_columns`
  4099. for guidelines on adding /replacing the columns of a
  4100. :class:`_expression.Select` object.
  4101. """
  4102. self._reset_memoizations()
  4103. self._raw_columns = self._raw_columns + [
  4104. coercions.expect(
  4105. roles.ColumnsClauseRole, column, apply_propagate_attrs=self
  4106. )
  4107. for column in columns
  4108. ]
  4109. def _set_entities(self, entities):
  4110. self._raw_columns = [
  4111. coercions.expect(
  4112. roles.ColumnsClauseRole, ent, apply_propagate_attrs=self
  4113. )
  4114. for ent in util.to_list(entities)
  4115. ]
  4116. @util.deprecated(
  4117. "1.4",
  4118. "The :meth:`_expression.Select.column` method is deprecated and will "
  4119. "be removed in a future release. Please use "
  4120. ":meth:`_expression.Select.add_columns`",
  4121. )
  4122. def column(self, column):
  4123. """Return a new :func:`_expression.select` construct with
  4124. the given column expression added to its columns clause.
  4125. E.g.::
  4126. my_select = my_select.column(table.c.new_column)
  4127. See the documentation for
  4128. :meth:`_expression.Select.with_only_columns`
  4129. for guidelines on adding /replacing the columns of a
  4130. :class:`_expression.Select` object.
  4131. """
  4132. return self.add_columns(column)
  4133. @util.preload_module("sqlalchemy.sql.util")
  4134. def reduce_columns(self, only_synonyms=True):
  4135. """Return a new :func:`_expression.select` construct with redundantly
  4136. named, equivalently-valued columns removed from the columns clause.
  4137. "Redundant" here means two columns where one refers to the
  4138. other either based on foreign key, or via a simple equality
  4139. comparison in the WHERE clause of the statement. The primary purpose
  4140. of this method is to automatically construct a select statement
  4141. with all uniquely-named columns, without the need to use
  4142. table-qualified labels as
  4143. :meth:`_expression.Select.set_label_style`
  4144. does.
  4145. When columns are omitted based on foreign key, the referred-to
  4146. column is the one that's kept. When columns are omitted based on
  4147. WHERE equivalence, the first column in the columns clause is the
  4148. one that's kept.
  4149. :param only_synonyms: when True, limit the removal of columns
  4150. to those which have the same name as the equivalent. Otherwise,
  4151. all columns that are equivalent to another are removed.
  4152. """
  4153. return self.with_only_columns(
  4154. *util.preloaded.sql_util.reduce_columns(
  4155. self._all_selected_columns,
  4156. only_synonyms=only_synonyms,
  4157. *(self._where_criteria + self._from_obj)
  4158. )
  4159. )
  4160. @_generative
  4161. def with_only_columns(self, *columns):
  4162. r"""Return a new :func:`_expression.select` construct with its columns
  4163. clause replaced with the given columns.
  4164. This method is exactly equivalent to as if the original
  4165. :func:`_expression.select` had been called with the given columns
  4166. clause. I.e. a statement::
  4167. s = select(table1.c.a, table1.c.b)
  4168. s = s.with_only_columns(table1.c.b)
  4169. should be exactly equivalent to::
  4170. s = select(table1.c.b)
  4171. Note that this will also dynamically alter the FROM clause of the
  4172. statement if it is not explicitly stated. To maintain the FROM
  4173. clause, ensure the :meth:`_sql.Select.select_from` method is
  4174. used appropriately::
  4175. s = select(table1.c.a, table2.c.b)
  4176. s = s.select_from(table2.c.b).with_only_columns(table1.c.a)
  4177. :param \*columns: column expressions to be used.
  4178. .. versionchanged:: 1.4 the :meth:`_sql.Select.with_only_columns`
  4179. method accepts the list of column expressions positionally;
  4180. passing the expressions as a list is deprecated.
  4181. """
  4182. # memoizations should be cleared here as of
  4183. # I95c560ffcbfa30b26644999412fb6a385125f663 , asserting this
  4184. # is the case for now.
  4185. self._assert_no_memoizations()
  4186. _MemoizedSelectEntities._generate_for_statement(self)
  4187. self._raw_columns = [
  4188. coercions.expect(roles.ColumnsClauseRole, c)
  4189. for c in coercions._expression_collection_was_a_list(
  4190. "columns", "Select.with_only_columns", columns
  4191. )
  4192. ]
  4193. @property
  4194. def whereclause(self):
  4195. """Return the completed WHERE clause for this
  4196. :class:`_expression.Select` statement.
  4197. This assembles the current collection of WHERE criteria
  4198. into a single :class:`_expression.BooleanClauseList` construct.
  4199. .. versionadded:: 1.4
  4200. """
  4201. return BooleanClauseList._construct_for_whereclause(
  4202. self._where_criteria
  4203. )
  4204. _whereclause = whereclause
  4205. @_generative
  4206. def where(self, *whereclause):
  4207. """Return a new :func:`_expression.select` construct with
  4208. the given expression added to
  4209. its WHERE clause, joined to the existing clause via AND, if any.
  4210. """
  4211. assert isinstance(self._where_criteria, tuple)
  4212. for criterion in whereclause:
  4213. where_criteria = coercions.expect(roles.WhereHavingRole, criterion)
  4214. self._where_criteria += (where_criteria,)
  4215. @_generative
  4216. def having(self, having):
  4217. """Return a new :func:`_expression.select` construct with
  4218. the given expression added to
  4219. its HAVING clause, joined to the existing clause via AND, if any.
  4220. """
  4221. self._having_criteria += (
  4222. coercions.expect(roles.WhereHavingRole, having),
  4223. )
  4224. @_generative
  4225. def distinct(self, *expr):
  4226. r"""Return a new :func:`_expression.select` construct which
  4227. will apply DISTINCT to its columns clause.
  4228. :param \*expr: optional column expressions. When present,
  4229. the PostgreSQL dialect will render a ``DISTINCT ON (<expressions>>)``
  4230. construct.
  4231. .. deprecated:: 1.4 Using \*expr in other dialects is deprecated
  4232. and will raise :class:`_exc.CompileError` in a future version.
  4233. """
  4234. if expr:
  4235. self._distinct = True
  4236. self._distinct_on = self._distinct_on + tuple(
  4237. coercions.expect(roles.ByOfRole, e) for e in expr
  4238. )
  4239. else:
  4240. self._distinct = True
  4241. @_generative
  4242. def select_from(self, *froms):
  4243. r"""Return a new :func:`_expression.select` construct with the
  4244. given FROM expression(s)
  4245. merged into its list of FROM objects.
  4246. E.g.::
  4247. table1 = table('t1', column('a'))
  4248. table2 = table('t2', column('b'))
  4249. s = select(table1.c.a).\
  4250. select_from(
  4251. table1.join(table2, table1.c.a==table2.c.b)
  4252. )
  4253. The "from" list is a unique set on the identity of each element,
  4254. so adding an already present :class:`_schema.Table`
  4255. or other selectable
  4256. will have no effect. Passing a :class:`_expression.Join` that refers
  4257. to an already present :class:`_schema.Table`
  4258. or other selectable will have
  4259. the effect of concealing the presence of that selectable as
  4260. an individual element in the rendered FROM list, instead
  4261. rendering it into a JOIN clause.
  4262. While the typical purpose of :meth:`_expression.Select.select_from`
  4263. is to
  4264. replace the default, derived FROM clause with a join, it can
  4265. also be called with individual table elements, multiple times
  4266. if desired, in the case that the FROM clause cannot be fully
  4267. derived from the columns clause::
  4268. select(func.count('*')).select_from(table1)
  4269. """
  4270. self._from_obj += tuple(
  4271. coercions.expect(
  4272. roles.FromClauseRole, fromclause, apply_propagate_attrs=self
  4273. )
  4274. for fromclause in froms
  4275. )
  4276. @_generative
  4277. def correlate(self, *fromclauses):
  4278. r"""Return a new :class:`_expression.Select`
  4279. which will correlate the given FROM
  4280. clauses to that of an enclosing :class:`_expression.Select`.
  4281. Calling this method turns off the :class:`_expression.Select` object's
  4282. default behavior of "auto-correlation". Normally, FROM elements
  4283. which appear in a :class:`_expression.Select`
  4284. that encloses this one via
  4285. its :term:`WHERE clause`, ORDER BY, HAVING or
  4286. :term:`columns clause` will be omitted from this
  4287. :class:`_expression.Select`
  4288. object's :term:`FROM clause`.
  4289. Setting an explicit correlation collection using the
  4290. :meth:`_expression.Select.correlate`
  4291. method provides a fixed list of FROM objects
  4292. that can potentially take place in this process.
  4293. When :meth:`_expression.Select.correlate`
  4294. is used to apply specific FROM clauses
  4295. for correlation, the FROM elements become candidates for
  4296. correlation regardless of how deeply nested this
  4297. :class:`_expression.Select`
  4298. object is, relative to an enclosing :class:`_expression.Select`
  4299. which refers to
  4300. the same FROM object. This is in contrast to the behavior of
  4301. "auto-correlation" which only correlates to an immediate enclosing
  4302. :class:`_expression.Select`.
  4303. Multi-level correlation ensures that the link
  4304. between enclosed and enclosing :class:`_expression.Select`
  4305. is always via
  4306. at least one WHERE/ORDER BY/HAVING/columns clause in order for
  4307. correlation to take place.
  4308. If ``None`` is passed, the :class:`_expression.Select`
  4309. object will correlate
  4310. none of its FROM entries, and all will render unconditionally
  4311. in the local FROM clause.
  4312. :param \*fromclauses: a list of one or more
  4313. :class:`_expression.FromClause`
  4314. constructs, or other compatible constructs (i.e. ORM-mapped
  4315. classes) to become part of the correlate collection.
  4316. .. seealso::
  4317. :meth:`_expression.Select.correlate_except`
  4318. :ref:`correlated_subqueries`
  4319. """
  4320. self._auto_correlate = False
  4321. if fromclauses and fromclauses[0] in {None, False}:
  4322. self._correlate = ()
  4323. else:
  4324. self._correlate = self._correlate + tuple(
  4325. coercions.expect(roles.FromClauseRole, f) for f in fromclauses
  4326. )
  4327. @_generative
  4328. def correlate_except(self, *fromclauses):
  4329. r"""Return a new :class:`_expression.Select`
  4330. which will omit the given FROM
  4331. clauses from the auto-correlation process.
  4332. Calling :meth:`_expression.Select.correlate_except` turns off the
  4333. :class:`_expression.Select` object's default behavior of
  4334. "auto-correlation" for the given FROM elements. An element
  4335. specified here will unconditionally appear in the FROM list, while
  4336. all other FROM elements remain subject to normal auto-correlation
  4337. behaviors.
  4338. If ``None`` is passed, the :class:`_expression.Select`
  4339. object will correlate
  4340. all of its FROM entries.
  4341. :param \*fromclauses: a list of one or more
  4342. :class:`_expression.FromClause`
  4343. constructs, or other compatible constructs (i.e. ORM-mapped
  4344. classes) to become part of the correlate-exception collection.
  4345. .. seealso::
  4346. :meth:`_expression.Select.correlate`
  4347. :ref:`correlated_subqueries`
  4348. """
  4349. self._auto_correlate = False
  4350. if fromclauses and fromclauses[0] in {None, False}:
  4351. self._correlate_except = ()
  4352. else:
  4353. self._correlate_except = (self._correlate_except or ()) + tuple(
  4354. coercions.expect(roles.FromClauseRole, f) for f in fromclauses
  4355. )
  4356. @HasMemoized.memoized_attribute
  4357. def selected_columns(self):
  4358. """A :class:`_expression.ColumnCollection`
  4359. representing the columns that
  4360. this SELECT statement or similar construct returns in its result set,
  4361. not including :class:`_sql.TextClause` constructs.
  4362. This collection differs from the :attr:`_expression.FromClause.columns`
  4363. collection of a :class:`_expression.FromClause` in that the columns
  4364. within this collection cannot be directly nested inside another SELECT
  4365. statement; a subquery must be applied first which provides for the
  4366. necessary parenthesization required by SQL.
  4367. For a :func:`_expression.select` construct, the collection here is
  4368. exactly what would be rendered inside the "SELECT" statement, and the
  4369. :class:`_expression.ColumnElement` objects are directly present as they
  4370. were given, e.g.::
  4371. col1 = column('q', Integer)
  4372. col2 = column('p', Integer)
  4373. stmt = select(col1, col2)
  4374. Above, ``stmt.selected_columns`` would be a collection that contains
  4375. the ``col1`` and ``col2`` objects directly. For a statement that is
  4376. against a :class:`_schema.Table` or other
  4377. :class:`_expression.FromClause`, the collection will use the
  4378. :class:`_expression.ColumnElement` objects that are in the
  4379. :attr:`_expression.FromClause.c` collection of the from element.
  4380. .. note::
  4381. The :attr:`_sql.Select.selected_columns` collection does not
  4382. include expressions established in the columns clause using the
  4383. :func:`_sql.text` construct; these are silently omitted from the
  4384. collection. To use plain textual column expressions inside of a
  4385. :class:`_sql.Select` construct, use the :func:`_sql.literal_column`
  4386. construct.
  4387. .. versionadded:: 1.4
  4388. """
  4389. # compare to SelectState._generate_columns_plus_names, which
  4390. # generates the actual names used in the SELECT string. that
  4391. # method is more complex because it also renders columns that are
  4392. # fully ambiguous, e.g. same column more than once.
  4393. conv = SelectState._column_naming_convention(self._label_style)
  4394. return ColumnCollection(
  4395. [
  4396. (conv(c), c)
  4397. for c in self._all_selected_columns
  4398. if not c._is_text_clause
  4399. ]
  4400. ).as_immutable()
  4401. @HasMemoized.memoized_attribute
  4402. def _all_selected_columns(self):
  4403. meth = SelectState.get_plugin_class(self).all_selected_columns
  4404. return list(meth(self))
  4405. def _ensure_disambiguated_names(self):
  4406. if self._label_style is LABEL_STYLE_NONE:
  4407. self = self.set_label_style(LABEL_STYLE_DISAMBIGUATE_ONLY)
  4408. return self
  4409. def _generate_columns_plus_names(self, anon_for_dupe_key):
  4410. """Generate column names as rendered in a SELECT statement by
  4411. the compiler.
  4412. This is distinct from other name generators that are intended for
  4413. population of .c collections and similar, which may have slightly
  4414. different rules.
  4415. """
  4416. cols = self._all_selected_columns
  4417. # when use_labels is on:
  4418. # in all cases == if we see the same label name, use _label_anon_label
  4419. # for subsequent occurrences of that label
  4420. #
  4421. # anon_for_dupe_key == if we see the same column object multiple
  4422. # times under a particular name, whether it's the _label name or the
  4423. # anon label, apply _dedupe_label_anon_label to the subsequent
  4424. # occurrences of it.
  4425. if self._label_style is LABEL_STYLE_NONE:
  4426. # don't generate any labels
  4427. same_cols = set()
  4428. return [
  4429. (None, c, c in same_cols or same_cols.add(c)) for c in cols
  4430. ]
  4431. else:
  4432. names = {}
  4433. use_tablename_labels = (
  4434. self._label_style is LABEL_STYLE_TABLENAME_PLUS_COL
  4435. )
  4436. def name_for_col(c):
  4437. if not c._render_label_in_columns_clause:
  4438. return (None, c, False)
  4439. elif use_tablename_labels:
  4440. if c._label is None:
  4441. repeated = c._anon_name_label in names
  4442. names[c._anon_name_label] = c
  4443. return (None, c, repeated)
  4444. elif getattr(c, "name", None) is None:
  4445. # this is a scalar_select(). need to improve this case
  4446. repeated = c._anon_name_label in names
  4447. names[c._anon_name_label] = c
  4448. return (None, c, repeated)
  4449. if use_tablename_labels:
  4450. name = effective_name = c._label
  4451. else:
  4452. name = None
  4453. effective_name = c.name
  4454. repeated = False
  4455. if effective_name in names:
  4456. # when looking to see if names[name] is the same column as
  4457. # c, use hash(), so that an annotated version of the column
  4458. # is seen as the same as the non-annotated
  4459. if hash(names[effective_name]) != hash(c):
  4460. # different column under the same name. apply
  4461. # disambiguating label
  4462. if use_tablename_labels:
  4463. name = c._label_anon_label
  4464. else:
  4465. name = c._anon_name_label
  4466. if anon_for_dupe_key and name in names:
  4467. # here, c._label_anon_label is definitely unique to
  4468. # that column identity (or annotated version), so
  4469. # this should always be true.
  4470. # this is also an infrequent codepath because
  4471. # you need two levels of duplication to be here
  4472. assert hash(names[name]) == hash(c)
  4473. # the column under the disambiguating label is
  4474. # already present. apply the "dedupe" label to
  4475. # subsequent occurrences of the column so that the
  4476. # original stays non-ambiguous
  4477. if use_tablename_labels:
  4478. name = c._dedupe_label_anon_label
  4479. else:
  4480. name = c._dedupe_anon_label
  4481. repeated = True
  4482. else:
  4483. names[name] = c
  4484. elif anon_for_dupe_key:
  4485. # same column under the same name. apply the "dedupe"
  4486. # label so that the original stays non-ambiguous
  4487. if use_tablename_labels:
  4488. name = c._dedupe_label_anon_label
  4489. else:
  4490. name = c._dedupe_anon_label
  4491. repeated = True
  4492. else:
  4493. names[effective_name] = c
  4494. return name, c, repeated
  4495. return [name_for_col(c) for c in cols]
  4496. def _generate_fromclause_column_proxies(self, subquery):
  4497. """Generate column proxies to place in the exported ``.c``
  4498. collection of a subquery."""
  4499. keys_seen = set()
  4500. prox = []
  4501. pa = None
  4502. tablename_plus_col = (
  4503. self._label_style is LABEL_STYLE_TABLENAME_PLUS_COL
  4504. )
  4505. disambiguate_only = self._label_style is LABEL_STYLE_DISAMBIGUATE_ONLY
  4506. for name, c, repeated in self._generate_columns_plus_names(False):
  4507. if c._is_text_clause:
  4508. continue
  4509. elif tablename_plus_col:
  4510. key = c._key_label
  4511. if key is not None and key in keys_seen:
  4512. if pa is None:
  4513. pa = prefix_anon_map()
  4514. key = c._label_anon_key_label % pa
  4515. keys_seen.add(key)
  4516. elif disambiguate_only:
  4517. key = c._proxy_key
  4518. if key is not None and key in keys_seen:
  4519. if pa is None:
  4520. pa = prefix_anon_map()
  4521. key = c._anon_key_label % pa
  4522. keys_seen.add(key)
  4523. else:
  4524. key = c._proxy_key
  4525. prox.append(
  4526. c._make_proxy(
  4527. subquery, key=key, name=name, name_is_truncatable=True
  4528. )
  4529. )
  4530. subquery._columns._populate_separate_keys(prox)
  4531. def _needs_parens_for_grouping(self):
  4532. return self._has_row_limiting_clause or bool(
  4533. self._order_by_clause.clauses
  4534. )
  4535. def self_group(self, against=None):
  4536. """Return a 'grouping' construct as per the
  4537. :class:`_expression.ClauseElement` specification.
  4538. This produces an element that can be embedded in an expression. Note
  4539. that this method is called automatically as needed when constructing
  4540. expressions and should not require explicit use.
  4541. """
  4542. if (
  4543. isinstance(against, CompoundSelect)
  4544. and not self._needs_parens_for_grouping()
  4545. ):
  4546. return self
  4547. else:
  4548. return SelectStatementGrouping(self)
  4549. def union(self, other, **kwargs):
  4550. """Return a SQL ``UNION`` of this select() construct against
  4551. the given selectable.
  4552. """
  4553. return CompoundSelect._create_union(self, other, **kwargs)
  4554. def union_all(self, other, **kwargs):
  4555. """Return a SQL ``UNION ALL`` of this select() construct against
  4556. the given selectable.
  4557. """
  4558. return CompoundSelect._create_union_all(self, other, **kwargs)
  4559. def except_(self, other, **kwargs):
  4560. """Return a SQL ``EXCEPT`` of this select() construct against
  4561. the given selectable.
  4562. """
  4563. return CompoundSelect._create_except(self, other, **kwargs)
  4564. def except_all(self, other, **kwargs):
  4565. """Return a SQL ``EXCEPT ALL`` of this select() construct against
  4566. the given selectable.
  4567. """
  4568. return CompoundSelect._create_except_all(self, other, **kwargs)
  4569. def intersect(self, other, **kwargs):
  4570. """Return a SQL ``INTERSECT`` of this select() construct against
  4571. the given selectable.
  4572. """
  4573. return CompoundSelect._create_intersect(self, other, **kwargs)
  4574. def intersect_all(self, other, **kwargs):
  4575. """Return a SQL ``INTERSECT ALL`` of this select() construct
  4576. against the given selectable.
  4577. """
  4578. return CompoundSelect._create_intersect_all(self, other, **kwargs)
  4579. @property
  4580. @util.deprecated_20(
  4581. ":attr:`.Executable.bind`",
  4582. alternative="Bound metadata is being removed as of SQLAlchemy 2.0.",
  4583. enable_warnings=False,
  4584. )
  4585. def bind(self):
  4586. """Returns the :class:`_engine.Engine` or :class:`_engine.Connection`
  4587. to which this :class:`.Executable` is bound, or None if none found.
  4588. """
  4589. if self._bind:
  4590. return self._bind
  4591. for item in self._iterate_from_elements():
  4592. if item._is_subquery and item.element is self:
  4593. raise exc.InvalidRequestError(
  4594. "select() construct refers to itself as a FROM"
  4595. )
  4596. e = item.bind
  4597. if e:
  4598. self._bind = e
  4599. return e
  4600. else:
  4601. break
  4602. for c in self._raw_columns:
  4603. e = c.bind
  4604. if e:
  4605. self._bind = e
  4606. return e
  4607. @bind.setter
  4608. def bind(self, bind):
  4609. self._bind = bind
  4610. class ScalarSelect(roles.InElementRole, Generative, Grouping):
  4611. """Represent a scalar subquery.
  4612. A :class:`_sql.ScalarSelect` is created by invoking the
  4613. :meth:`_sql.SelectBase.scalar_subquery` method. The object
  4614. then participates in other SQL expressions as a SQL column expression
  4615. within the :class:`_sql.ColumnElement` hierarchy.
  4616. .. seealso::
  4617. :meth:`_sql.SelectBase.scalar_subquery`
  4618. :ref:`tutorial_scalar_subquery` - in the 2.0 tutorial
  4619. :ref:`scalar_selects` - in the 1.x tutorial
  4620. """
  4621. _from_objects = []
  4622. _is_from_container = True
  4623. _is_implicitly_boolean = False
  4624. inherit_cache = True
  4625. def __init__(self, element):
  4626. self.element = element
  4627. self.type = element._scalar_type()
  4628. @property
  4629. def columns(self):
  4630. raise exc.InvalidRequestError(
  4631. "Scalar Select expression has no "
  4632. "columns; use this object directly "
  4633. "within a column-level expression."
  4634. )
  4635. c = columns
  4636. @_generative
  4637. def where(self, crit):
  4638. """Apply a WHERE clause to the SELECT statement referred to
  4639. by this :class:`_expression.ScalarSelect`.
  4640. """
  4641. self.element = self.element.where(crit)
  4642. def self_group(self, **kwargs):
  4643. return self
  4644. @_generative
  4645. def correlate(self, *fromclauses):
  4646. r"""Return a new :class:`_expression.ScalarSelect`
  4647. which will correlate the given FROM
  4648. clauses to that of an enclosing :class:`_expression.Select`.
  4649. This method is mirrored from the :meth:`_sql.Select.correlate` method
  4650. of the underlying :class:`_sql.Select`. The method applies the
  4651. :meth:_sql.Select.correlate` method, then returns a new
  4652. :class:`_sql.ScalarSelect` against that statement.
  4653. .. versionadded:: 1.4 Previously, the
  4654. :meth:`_sql.ScalarSelect.correlate`
  4655. method was only available from :class:`_sql.Select`.
  4656. :param \*fromclauses: a list of one or more
  4657. :class:`_expression.FromClause`
  4658. constructs, or other compatible constructs (i.e. ORM-mapped
  4659. classes) to become part of the correlate collection.
  4660. .. seealso::
  4661. :meth:`_expression.ScalarSelect.correlate_except`
  4662. :ref:`tutorial_scalar_subquery` - in the 2.0 tutorial
  4663. :ref:`correlated_subqueries` - in the 1.x tutorial
  4664. """
  4665. self.element = self.element.correlate(*fromclauses)
  4666. @_generative
  4667. def correlate_except(self, *fromclauses):
  4668. r"""Return a new :class:`_expression.ScalarSelect`
  4669. which will omit the given FROM
  4670. clauses from the auto-correlation process.
  4671. This method is mirrored from the
  4672. :meth:`_sql.Select.correlate_except` method of the underlying
  4673. :class:`_sql.Select`. The method applies the
  4674. :meth:_sql.Select.correlate_except` method, then returns a new
  4675. :class:`_sql.ScalarSelect` against that statement.
  4676. .. versionadded:: 1.4 Previously, the
  4677. :meth:`_sql.ScalarSelect.correlate_except`
  4678. method was only available from :class:`_sql.Select`.
  4679. :param \*fromclauses: a list of one or more
  4680. :class:`_expression.FromClause`
  4681. constructs, or other compatible constructs (i.e. ORM-mapped
  4682. classes) to become part of the correlate-exception collection.
  4683. .. seealso::
  4684. :meth:`_expression.ScalarSelect.correlate`
  4685. :ref:`tutorial_scalar_subquery` - in the 2.0 tutorial
  4686. :ref:`correlated_subqueries` - in the 1.x tutorial
  4687. """
  4688. self.element = self.element.correlate_except(*fromclauses)
  4689. class Exists(UnaryExpression):
  4690. """Represent an ``EXISTS`` clause.
  4691. See :func:`_sql.exists` for a description of usage.
  4692. """
  4693. _from_objects = []
  4694. inherit_cache = True
  4695. def __init__(self, *args, **kwargs):
  4696. """Construct a new :class:`_expression.Exists` construct.
  4697. The :func:`_sql.exists` can be invoked by itself to produce an
  4698. :class:`_sql.Exists` construct, which will accept simple WHERE
  4699. criteria::
  4700. exists_criteria = exists().where(table1.c.col1 == table2.c.col2)
  4701. However, for greater flexibility in constructing the SELECT, an
  4702. existing :class:`_sql.Select` construct may be converted to an
  4703. :class:`_sql.Exists`, most conveniently by making use of the
  4704. :meth:`_sql.SelectBase.exists` method::
  4705. exists_criteria = (
  4706. select(table2.c.col2).
  4707. where(table1.c.col1 == table2.c.col2).
  4708. exists()
  4709. )
  4710. The EXISTS criteria is then used inside of an enclosing SELECT::
  4711. stmt = select(table1.c.col1).where(exists_criteria)
  4712. The above statement will then be of the form::
  4713. SELECT col1 FROM table1 WHERE EXISTS
  4714. (SELECT table2.col2 FROM table2 WHERE table2.col2 = table1.col1)
  4715. .. seealso::
  4716. :ref:`tutorial_exists` - in the :term:`2.0 style` tutorial.
  4717. """ # noqa E501
  4718. if args and isinstance(args[0], (SelectBase, ScalarSelect)):
  4719. s = args[0]
  4720. else:
  4721. if not args:
  4722. args = (literal_column("*"),)
  4723. s = Select._create(*args, **kwargs).scalar_subquery()
  4724. UnaryExpression.__init__(
  4725. self,
  4726. s,
  4727. operator=operators.exists,
  4728. type_=type_api.BOOLEANTYPE,
  4729. wraps_column_expression=True,
  4730. )
  4731. def _regroup(self, fn):
  4732. element = self.element._ungroup()
  4733. element = fn(element)
  4734. return element.self_group(against=operators.exists)
  4735. @util.deprecated_params(
  4736. whereclause=(
  4737. "2.0",
  4738. "The :paramref:`_sql.Exists.select().whereclause` parameter "
  4739. "is deprecated and will be removed in version 2.0. "
  4740. "Please make use "
  4741. "of the :meth:`.Select.where` "
  4742. "method to add WHERE criteria to the SELECT statement.",
  4743. ),
  4744. kwargs=(
  4745. "2.0",
  4746. "The :meth:`_sql.Exists.select` method will no longer accept "
  4747. "keyword arguments in version 2.0. "
  4748. "Please use generative methods from the "
  4749. ":class:`_sql.Select` construct in order to apply additional "
  4750. "modifications.",
  4751. ),
  4752. )
  4753. def select(self, whereclause=None, **kwargs):
  4754. r"""Return a SELECT of this :class:`_expression.Exists`.
  4755. e.g.::
  4756. stmt = exists(some_table.c.id).where(some_table.c.id == 5).select()
  4757. This will produce a statement resembling::
  4758. SELECT EXISTS (SELECT id FROM some_table WHERE some_table = :param) AS anon_1
  4759. :param whereclause: a WHERE clause, equivalent to calling the
  4760. :meth:`_sql.Select.where` method.
  4761. :param **kwargs: additional keyword arguments are passed to the
  4762. legacy constructor for :class:`_sql.Select` described at
  4763. :meth:`_sql.Select.create_legacy_select`.
  4764. .. seealso::
  4765. :func:`_expression.select` - general purpose
  4766. method which allows for arbitrary column lists.
  4767. """ # noqa
  4768. if whereclause is not None:
  4769. kwargs["whereclause"] = whereclause
  4770. return Select._create_select_from_fromclause(self, [self], **kwargs)
  4771. def correlate(self, *fromclause):
  4772. """Apply correlation to the subquery noted by this :class:`_sql.Exists`.
  4773. .. seealso::
  4774. :meth:`_sql.ScalarSelect.correlate`
  4775. """
  4776. e = self._clone()
  4777. e.element = self._regroup(
  4778. lambda element: element.correlate(*fromclause)
  4779. )
  4780. return e
  4781. def correlate_except(self, *fromclause):
  4782. """Apply correlation to the subquery noted by this :class:`_sql.Exists`.
  4783. .. seealso::
  4784. :meth:`_sql.ScalarSelect.correlate_except`
  4785. """
  4786. e = self._clone()
  4787. e.element = self._regroup(
  4788. lambda element: element.correlate_except(*fromclause)
  4789. )
  4790. return e
  4791. def select_from(self, *froms):
  4792. """Return a new :class:`_expression.Exists` construct,
  4793. applying the given
  4794. expression to the :meth:`_expression.Select.select_from`
  4795. method of the select
  4796. statement contained.
  4797. .. note:: it is typically preferable to build a :class:`_sql.Select`
  4798. statement first, including the desired WHERE clause, then use the
  4799. :meth:`_sql.SelectBase.exists` method to produce an
  4800. :class:`_sql.Exists` object at once.
  4801. """
  4802. e = self._clone()
  4803. e.element = self._regroup(lambda element: element.select_from(*froms))
  4804. return e
  4805. def where(self, clause):
  4806. """Return a new :func:`_expression.exists` construct with the
  4807. given expression added to
  4808. its WHERE clause, joined to the existing clause via AND, if any.
  4809. .. note:: it is typically preferable to build a :class:`_sql.Select`
  4810. statement first, including the desired WHERE clause, then use the
  4811. :meth:`_sql.SelectBase.exists` method to produce an
  4812. :class:`_sql.Exists` object at once.
  4813. """
  4814. e = self._clone()
  4815. e.element = self._regroup(lambda element: element.where(clause))
  4816. return e
  4817. class TextualSelect(SelectBase):
  4818. """Wrap a :class:`_expression.TextClause` construct within a
  4819. :class:`_expression.SelectBase`
  4820. interface.
  4821. This allows the :class:`_expression.TextClause` object to gain a
  4822. ``.c`` collection
  4823. and other FROM-like capabilities such as
  4824. :meth:`_expression.FromClause.alias`,
  4825. :meth:`_expression.SelectBase.cte`, etc.
  4826. The :class:`_expression.TextualSelect` construct is produced via the
  4827. :meth:`_expression.TextClause.columns`
  4828. method - see that method for details.
  4829. .. versionchanged:: 1.4 the :class:`_expression.TextualSelect`
  4830. class was renamed
  4831. from ``TextAsFrom``, to more correctly suit its role as a
  4832. SELECT-oriented object and not a FROM clause.
  4833. .. seealso::
  4834. :func:`_expression.text`
  4835. :meth:`_expression.TextClause.columns` - primary creation interface.
  4836. """
  4837. __visit_name__ = "textual_select"
  4838. _label_style = LABEL_STYLE_NONE
  4839. _traverse_internals = [
  4840. ("element", InternalTraversal.dp_clauseelement),
  4841. ("column_args", InternalTraversal.dp_clauseelement_list),
  4842. ] + SupportsCloneAnnotations._clone_annotations_traverse_internals
  4843. _is_textual = True
  4844. is_text = True
  4845. is_select = True
  4846. def __init__(self, text, columns, positional=False):
  4847. self.element = text
  4848. # convert for ORM attributes->columns, etc
  4849. self.column_args = [
  4850. coercions.expect(roles.ColumnsClauseRole, c) for c in columns
  4851. ]
  4852. self.positional = positional
  4853. @HasMemoized.memoized_attribute
  4854. def selected_columns(self):
  4855. """A :class:`_expression.ColumnCollection`
  4856. representing the columns that
  4857. this SELECT statement or similar construct returns in its result set,
  4858. not including :class:`_sql.TextClause` constructs.
  4859. This collection differs from the :attr:`_expression.FromClause.columns`
  4860. collection of a :class:`_expression.FromClause` in that the columns
  4861. within this collection cannot be directly nested inside another SELECT
  4862. statement; a subquery must be applied first which provides for the
  4863. necessary parenthesization required by SQL.
  4864. For a :class:`_expression.TextualSelect` construct, the collection
  4865. contains the :class:`_expression.ColumnElement` objects that were
  4866. passed to the constructor, typically via the
  4867. :meth:`_expression.TextClause.columns` method.
  4868. .. versionadded:: 1.4
  4869. """
  4870. return ColumnCollection(
  4871. (c.key, c) for c in self.column_args
  4872. ).as_immutable()
  4873. @property
  4874. def _all_selected_columns(self):
  4875. return self.column_args
  4876. def _set_label_style(self, style):
  4877. return self
  4878. def _ensure_disambiguated_names(self):
  4879. return self
  4880. @property
  4881. def _bind(self):
  4882. return self.element._bind
  4883. @_generative
  4884. def bindparams(self, *binds, **bind_as_values):
  4885. self.element = self.element.bindparams(*binds, **bind_as_values)
  4886. def _generate_fromclause_column_proxies(self, fromclause):
  4887. fromclause._columns._populate_separate_keys(
  4888. c._make_proxy(fromclause) for c in self.column_args
  4889. )
  4890. def _scalar_type(self):
  4891. return self.column_args[0].type
  4892. TextAsFrom = TextualSelect
  4893. """Backwards compatibility with the previous name"""
  4894. class AnnotatedFromClause(Annotated):
  4895. def __init__(self, element, values):
  4896. # force FromClause to generate their internal
  4897. # collections into __dict__
  4898. element.c
  4899. Annotated.__init__(self, element, values)