_selectable_constructors.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. # sql/_selectable_constructors.py
  2. # Copyright (C) 2005-2025 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: https://www.opensource.org/licenses/mit-license.php
  7. from __future__ import annotations
  8. from typing import Any
  9. from typing import Optional
  10. from typing import overload
  11. from typing import Tuple
  12. from typing import TYPE_CHECKING
  13. from typing import Union
  14. from . import coercions
  15. from . import roles
  16. from ._typing import _ColumnsClauseArgument
  17. from ._typing import _no_kw
  18. from .elements import ColumnClause
  19. from .selectable import Alias
  20. from .selectable import CompoundSelect
  21. from .selectable import Exists
  22. from .selectable import FromClause
  23. from .selectable import Join
  24. from .selectable import Lateral
  25. from .selectable import LateralFromClause
  26. from .selectable import NamedFromClause
  27. from .selectable import Select
  28. from .selectable import TableClause
  29. from .selectable import TableSample
  30. from .selectable import Values
  31. if TYPE_CHECKING:
  32. from ._typing import _FromClauseArgument
  33. from ._typing import _OnClauseArgument
  34. from ._typing import _SelectStatementForCompoundArgument
  35. from ._typing import _T0
  36. from ._typing import _T1
  37. from ._typing import _T2
  38. from ._typing import _T3
  39. from ._typing import _T4
  40. from ._typing import _T5
  41. from ._typing import _T6
  42. from ._typing import _T7
  43. from ._typing import _T8
  44. from ._typing import _T9
  45. from ._typing import _TP
  46. from ._typing import _TypedColumnClauseArgument as _TCCA
  47. from .functions import Function
  48. from .selectable import CTE
  49. from .selectable import HasCTE
  50. from .selectable import ScalarSelect
  51. from .selectable import SelectBase
  52. def alias(
  53. selectable: FromClause, name: Optional[str] = None, flat: bool = False
  54. ) -> NamedFromClause:
  55. """Return a named alias of the given :class:`.FromClause`.
  56. For :class:`.Table` and :class:`.Join` objects, the return type is the
  57. :class:`_expression.Alias` object. Other kinds of :class:`.NamedFromClause`
  58. objects may be returned for other kinds of :class:`.FromClause` objects.
  59. The named alias represents any :class:`_expression.FromClause` with an
  60. alternate name assigned within SQL, typically using the ``AS`` clause when
  61. generated, e.g. ``SELECT * FROM table AS aliasname``.
  62. Equivalent functionality is available via the
  63. :meth:`_expression.FromClause.alias`
  64. method available on all :class:`_expression.FromClause` objects.
  65. :param selectable: any :class:`_expression.FromClause` subclass,
  66. such as a table, select statement, etc.
  67. :param name: string name to be assigned as the alias.
  68. If ``None``, a name will be deterministically generated at compile
  69. time. Deterministic means the name is guaranteed to be unique against
  70. other constructs used in the same statement, and will also be the same
  71. name for each successive compilation of the same statement object.
  72. :param flat: Will be passed through to if the given selectable
  73. is an instance of :class:`_expression.Join` - see
  74. :meth:`_expression.Join.alias` for details.
  75. """
  76. return Alias._factory(selectable, name=name, flat=flat)
  77. def cte(
  78. selectable: HasCTE, name: Optional[str] = None, recursive: bool = False
  79. ) -> CTE:
  80. r"""Return a new :class:`_expression.CTE`,
  81. or Common Table Expression instance.
  82. Please see :meth:`_expression.HasCTE.cte` for detail on CTE usage.
  83. """
  84. return coercions.expect(roles.HasCTERole, selectable).cte(
  85. name=name, recursive=recursive
  86. )
  87. # TODO: mypy requires the _TypedSelectable overloads in all compound select
  88. # constructors since _SelectStatementForCompoundArgument includes
  89. # untyped args that make it return CompoundSelect[Unpack[tuple[Never, ...]]]
  90. # pyright does not have this issue
  91. _TypedSelectable = Union["Select[_TP]", "CompoundSelect[_TP]"]
  92. @overload
  93. def except_(
  94. *selects: _TypedSelectable[_TP],
  95. ) -> CompoundSelect[_TP]: ...
  96. @overload
  97. def except_(
  98. *selects: _SelectStatementForCompoundArgument[_TP],
  99. ) -> CompoundSelect[_TP]: ...
  100. def except_(
  101. *selects: _SelectStatementForCompoundArgument[_TP],
  102. ) -> CompoundSelect[_TP]:
  103. r"""Return an ``EXCEPT`` of multiple selectables.
  104. The returned object is an instance of
  105. :class:`_expression.CompoundSelect`.
  106. :param \*selects:
  107. a list of :class:`_expression.Select` instances.
  108. """
  109. return CompoundSelect._create_except(*selects)
  110. @overload
  111. def except_all(
  112. *selects: _TypedSelectable[_TP],
  113. ) -> CompoundSelect[_TP]: ...
  114. @overload
  115. def except_all(
  116. *selects: _SelectStatementForCompoundArgument[_TP],
  117. ) -> CompoundSelect[_TP]: ...
  118. def except_all(
  119. *selects: _SelectStatementForCompoundArgument[_TP],
  120. ) -> CompoundSelect[_TP]:
  121. r"""Return an ``EXCEPT ALL`` of multiple selectables.
  122. The returned object is an instance of
  123. :class:`_expression.CompoundSelect`.
  124. :param \*selects:
  125. a list of :class:`_expression.Select` instances.
  126. """
  127. return CompoundSelect._create_except_all(*selects)
  128. def exists(
  129. __argument: Optional[
  130. Union[_ColumnsClauseArgument[Any], SelectBase, ScalarSelect[Any]]
  131. ] = None,
  132. ) -> Exists:
  133. """Construct a new :class:`_expression.Exists` construct.
  134. The :func:`_sql.exists` can be invoked by itself to produce an
  135. :class:`_sql.Exists` construct, which will accept simple WHERE
  136. criteria::
  137. exists_criteria = exists().where(table1.c.col1 == table2.c.col2)
  138. However, for greater flexibility in constructing the SELECT, an
  139. existing :class:`_sql.Select` construct may be converted to an
  140. :class:`_sql.Exists`, most conveniently by making use of the
  141. :meth:`_sql.SelectBase.exists` method::
  142. exists_criteria = (
  143. select(table2.c.col2).where(table1.c.col1 == table2.c.col2).exists()
  144. )
  145. The EXISTS criteria is then used inside of an enclosing SELECT::
  146. stmt = select(table1.c.col1).where(exists_criteria)
  147. The above statement will then be of the form:
  148. .. sourcecode:: sql
  149. SELECT col1 FROM table1 WHERE EXISTS
  150. (SELECT table2.col2 FROM table2 WHERE table2.col2 = table1.col1)
  151. .. seealso::
  152. :ref:`tutorial_exists` - in the :term:`2.0 style` tutorial.
  153. :meth:`_sql.SelectBase.exists` - method to transform a ``SELECT`` to an
  154. ``EXISTS`` clause.
  155. """ # noqa: E501
  156. return Exists(__argument)
  157. @overload
  158. def intersect(
  159. *selects: _TypedSelectable[_TP],
  160. ) -> CompoundSelect[_TP]: ...
  161. @overload
  162. def intersect(
  163. *selects: _SelectStatementForCompoundArgument[_TP],
  164. ) -> CompoundSelect[_TP]: ...
  165. def intersect(
  166. *selects: _SelectStatementForCompoundArgument[_TP],
  167. ) -> CompoundSelect[_TP]:
  168. r"""Return an ``INTERSECT`` of multiple selectables.
  169. The returned object is an instance of
  170. :class:`_expression.CompoundSelect`.
  171. :param \*selects:
  172. a list of :class:`_expression.Select` instances.
  173. """
  174. return CompoundSelect._create_intersect(*selects)
  175. @overload
  176. def intersect_all(
  177. *selects: _TypedSelectable[_TP],
  178. ) -> CompoundSelect[_TP]: ...
  179. @overload
  180. def intersect_all(
  181. *selects: _SelectStatementForCompoundArgument[_TP],
  182. ) -> CompoundSelect[_TP]: ...
  183. def intersect_all(
  184. *selects: _SelectStatementForCompoundArgument[_TP],
  185. ) -> CompoundSelect[_TP]:
  186. r"""Return an ``INTERSECT ALL`` of multiple selectables.
  187. The returned object is an instance of
  188. :class:`_expression.CompoundSelect`.
  189. :param \*selects:
  190. a list of :class:`_expression.Select` instances.
  191. """
  192. return CompoundSelect._create_intersect_all(*selects)
  193. def join(
  194. left: _FromClauseArgument,
  195. right: _FromClauseArgument,
  196. onclause: Optional[_OnClauseArgument] = None,
  197. isouter: bool = False,
  198. full: bool = False,
  199. ) -> Join:
  200. """Produce a :class:`_expression.Join` object, given two
  201. :class:`_expression.FromClause`
  202. expressions.
  203. E.g.::
  204. j = join(
  205. user_table, address_table, user_table.c.id == address_table.c.user_id
  206. )
  207. stmt = select(user_table).select_from(j)
  208. would emit SQL along the lines of:
  209. .. sourcecode:: sql
  210. SELECT user.id, user.name FROM user
  211. JOIN address ON user.id = address.user_id
  212. Similar functionality is available given any
  213. :class:`_expression.FromClause` object (e.g. such as a
  214. :class:`_schema.Table`) using
  215. the :meth:`_expression.FromClause.join` method.
  216. :param left: The left side of the join.
  217. :param right: the right side of the join; this is any
  218. :class:`_expression.FromClause` object such as a
  219. :class:`_schema.Table` object, and
  220. may also be a selectable-compatible object such as an ORM-mapped
  221. class.
  222. :param onclause: a SQL expression representing the ON clause of the
  223. join. If left at ``None``, :meth:`_expression.FromClause.join`
  224. will attempt to
  225. join the two tables based on a foreign key relationship.
  226. :param isouter: if True, render a LEFT OUTER JOIN, instead of JOIN.
  227. :param full: if True, render a FULL OUTER JOIN, instead of JOIN.
  228. .. seealso::
  229. :meth:`_expression.FromClause.join` - method form,
  230. based on a given left side.
  231. :class:`_expression.Join` - the type of object produced.
  232. """ # noqa: E501
  233. return Join(left, right, onclause, isouter, full)
  234. def lateral(
  235. selectable: Union[SelectBase, _FromClauseArgument],
  236. name: Optional[str] = None,
  237. ) -> LateralFromClause:
  238. """Return a :class:`_expression.Lateral` object.
  239. :class:`_expression.Lateral` is an :class:`_expression.Alias`
  240. subclass that represents
  241. a subquery with the LATERAL keyword applied to it.
  242. The special behavior of a LATERAL subquery is that it appears in the
  243. FROM clause of an enclosing SELECT, but may correlate to other
  244. FROM clauses of that SELECT. It is a special case of subquery
  245. only supported by a small number of backends, currently more recent
  246. PostgreSQL versions.
  247. .. seealso::
  248. :ref:`tutorial_lateral_correlation` - overview of usage.
  249. """
  250. return Lateral._factory(selectable, name=name)
  251. def outerjoin(
  252. left: _FromClauseArgument,
  253. right: _FromClauseArgument,
  254. onclause: Optional[_OnClauseArgument] = None,
  255. full: bool = False,
  256. ) -> Join:
  257. """Return an ``OUTER JOIN`` clause element.
  258. The returned object is an instance of :class:`_expression.Join`.
  259. Similar functionality is also available via the
  260. :meth:`_expression.FromClause.outerjoin` method on any
  261. :class:`_expression.FromClause`.
  262. :param left: The left side of the join.
  263. :param right: The right side of the join.
  264. :param onclause: Optional criterion for the ``ON`` clause, is
  265. derived from foreign key relationships established between
  266. left and right otherwise.
  267. To chain joins together, use the :meth:`_expression.FromClause.join`
  268. or
  269. :meth:`_expression.FromClause.outerjoin` methods on the resulting
  270. :class:`_expression.Join` object.
  271. """
  272. return Join(left, right, onclause, isouter=True, full=full)
  273. # START OVERLOADED FUNCTIONS select Select 1-10
  274. # code within this block is **programmatically,
  275. # statically generated** by tools/generate_tuple_map_overloads.py
  276. @overload
  277. def select(__ent0: _TCCA[_T0]) -> Select[Tuple[_T0]]: ...
  278. @overload
  279. def select(
  280. __ent0: _TCCA[_T0], __ent1: _TCCA[_T1]
  281. ) -> Select[Tuple[_T0, _T1]]: ...
  282. @overload
  283. def select(
  284. __ent0: _TCCA[_T0], __ent1: _TCCA[_T1], __ent2: _TCCA[_T2]
  285. ) -> Select[Tuple[_T0, _T1, _T2]]: ...
  286. @overload
  287. def select(
  288. __ent0: _TCCA[_T0],
  289. __ent1: _TCCA[_T1],
  290. __ent2: _TCCA[_T2],
  291. __ent3: _TCCA[_T3],
  292. ) -> Select[Tuple[_T0, _T1, _T2, _T3]]: ...
  293. @overload
  294. def select(
  295. __ent0: _TCCA[_T0],
  296. __ent1: _TCCA[_T1],
  297. __ent2: _TCCA[_T2],
  298. __ent3: _TCCA[_T3],
  299. __ent4: _TCCA[_T4],
  300. ) -> Select[Tuple[_T0, _T1, _T2, _T3, _T4]]: ...
  301. @overload
  302. def select(
  303. __ent0: _TCCA[_T0],
  304. __ent1: _TCCA[_T1],
  305. __ent2: _TCCA[_T2],
  306. __ent3: _TCCA[_T3],
  307. __ent4: _TCCA[_T4],
  308. __ent5: _TCCA[_T5],
  309. ) -> Select[Tuple[_T0, _T1, _T2, _T3, _T4, _T5]]: ...
  310. @overload
  311. def select(
  312. __ent0: _TCCA[_T0],
  313. __ent1: _TCCA[_T1],
  314. __ent2: _TCCA[_T2],
  315. __ent3: _TCCA[_T3],
  316. __ent4: _TCCA[_T4],
  317. __ent5: _TCCA[_T5],
  318. __ent6: _TCCA[_T6],
  319. ) -> Select[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6]]: ...
  320. @overload
  321. def select(
  322. __ent0: _TCCA[_T0],
  323. __ent1: _TCCA[_T1],
  324. __ent2: _TCCA[_T2],
  325. __ent3: _TCCA[_T3],
  326. __ent4: _TCCA[_T4],
  327. __ent5: _TCCA[_T5],
  328. __ent6: _TCCA[_T6],
  329. __ent7: _TCCA[_T7],
  330. ) -> Select[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7]]: ...
  331. @overload
  332. def select(
  333. __ent0: _TCCA[_T0],
  334. __ent1: _TCCA[_T1],
  335. __ent2: _TCCA[_T2],
  336. __ent3: _TCCA[_T3],
  337. __ent4: _TCCA[_T4],
  338. __ent5: _TCCA[_T5],
  339. __ent6: _TCCA[_T6],
  340. __ent7: _TCCA[_T7],
  341. __ent8: _TCCA[_T8],
  342. ) -> Select[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8]]: ...
  343. @overload
  344. def select(
  345. __ent0: _TCCA[_T0],
  346. __ent1: _TCCA[_T1],
  347. __ent2: _TCCA[_T2],
  348. __ent3: _TCCA[_T3],
  349. __ent4: _TCCA[_T4],
  350. __ent5: _TCCA[_T5],
  351. __ent6: _TCCA[_T6],
  352. __ent7: _TCCA[_T7],
  353. __ent8: _TCCA[_T8],
  354. __ent9: _TCCA[_T9],
  355. ) -> Select[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8, _T9]]: ...
  356. # END OVERLOADED FUNCTIONS select
  357. @overload
  358. def select(
  359. *entities: _ColumnsClauseArgument[Any], **__kw: Any
  360. ) -> Select[Any]: ...
  361. def select(*entities: _ColumnsClauseArgument[Any], **__kw: Any) -> Select[Any]:
  362. r"""Construct a new :class:`_expression.Select`.
  363. .. versionadded:: 1.4 - The :func:`_sql.select` function now accepts
  364. column arguments positionally. The top-level :func:`_sql.select`
  365. function will automatically use the 1.x or 2.x style API based on
  366. the incoming arguments; using :func:`_sql.select` from the
  367. ``sqlalchemy.future`` module will enforce that only the 2.x style
  368. constructor is used.
  369. Similar functionality is also available via the
  370. :meth:`_expression.FromClause.select` method on any
  371. :class:`_expression.FromClause`.
  372. .. seealso::
  373. :ref:`tutorial_selecting_data` - in the :ref:`unified_tutorial`
  374. :param \*entities:
  375. Entities to SELECT from. For Core usage, this is typically a series
  376. of :class:`_expression.ColumnElement` and / or
  377. :class:`_expression.FromClause`
  378. objects which will form the columns clause of the resulting
  379. statement. For those objects that are instances of
  380. :class:`_expression.FromClause` (typically :class:`_schema.Table`
  381. or :class:`_expression.Alias`
  382. objects), the :attr:`_expression.FromClause.c`
  383. collection is extracted
  384. to form a collection of :class:`_expression.ColumnElement` objects.
  385. This parameter will also accept :class:`_expression.TextClause`
  386. constructs as
  387. given, as well as ORM-mapped classes.
  388. """
  389. # the keyword args are a necessary element in order for the typing
  390. # to work out w/ the varargs vs. having named "keyword" arguments that
  391. # aren't always present.
  392. if __kw:
  393. raise _no_kw()
  394. return Select(*entities)
  395. def table(name: str, *columns: ColumnClause[Any], **kw: Any) -> TableClause:
  396. """Produce a new :class:`_expression.TableClause`.
  397. The object returned is an instance of
  398. :class:`_expression.TableClause`, which
  399. represents the "syntactical" portion of the schema-level
  400. :class:`_schema.Table` object.
  401. It may be used to construct lightweight table constructs.
  402. :param name: Name of the table.
  403. :param columns: A collection of :func:`_expression.column` constructs.
  404. :param schema: The schema name for this table.
  405. .. versionadded:: 1.3.18 :func:`_expression.table` can now
  406. accept a ``schema`` argument.
  407. """
  408. return TableClause(name, *columns, **kw)
  409. def tablesample(
  410. selectable: _FromClauseArgument,
  411. sampling: Union[float, Function[Any]],
  412. name: Optional[str] = None,
  413. seed: Optional[roles.ExpressionElementRole[Any]] = None,
  414. ) -> TableSample:
  415. """Return a :class:`_expression.TableSample` object.
  416. :class:`_expression.TableSample` is an :class:`_expression.Alias`
  417. subclass that represents
  418. a table with the TABLESAMPLE clause applied to it.
  419. :func:`_expression.tablesample`
  420. is also available from the :class:`_expression.FromClause`
  421. class via the
  422. :meth:`_expression.FromClause.tablesample` method.
  423. The TABLESAMPLE clause allows selecting a randomly selected approximate
  424. percentage of rows from a table. It supports multiple sampling methods,
  425. most commonly BERNOULLI and SYSTEM.
  426. e.g.::
  427. from sqlalchemy import func
  428. selectable = people.tablesample(
  429. func.bernoulli(1), name="alias", seed=func.random()
  430. )
  431. stmt = select(selectable.c.people_id)
  432. Assuming ``people`` with a column ``people_id``, the above
  433. statement would render as:
  434. .. sourcecode:: sql
  435. SELECT alias.people_id FROM
  436. people AS alias TABLESAMPLE bernoulli(:bernoulli_1)
  437. REPEATABLE (random())
  438. :param sampling: a ``float`` percentage between 0 and 100 or
  439. :class:`_functions.Function`.
  440. :param name: optional alias name
  441. :param seed: any real-valued SQL expression. When specified, the
  442. REPEATABLE sub-clause is also rendered.
  443. """
  444. return TableSample._factory(selectable, sampling, name=name, seed=seed)
  445. @overload
  446. def union(
  447. *selects: _TypedSelectable[_TP],
  448. ) -> CompoundSelect[_TP]: ...
  449. @overload
  450. def union(
  451. *selects: _SelectStatementForCompoundArgument[_TP],
  452. ) -> CompoundSelect[_TP]: ...
  453. def union(
  454. *selects: _SelectStatementForCompoundArgument[_TP],
  455. ) -> CompoundSelect[_TP]:
  456. r"""Return a ``UNION`` of multiple selectables.
  457. The returned object is an instance of
  458. :class:`_expression.CompoundSelect`.
  459. A similar :func:`union()` method is available on all
  460. :class:`_expression.FromClause` subclasses.
  461. :param \*selects:
  462. a list of :class:`_expression.Select` instances.
  463. :param \**kwargs:
  464. available keyword arguments are the same as those of
  465. :func:`select`.
  466. """
  467. return CompoundSelect._create_union(*selects)
  468. @overload
  469. def union_all(
  470. *selects: _TypedSelectable[_TP],
  471. ) -> CompoundSelect[_TP]: ...
  472. @overload
  473. def union_all(
  474. *selects: _SelectStatementForCompoundArgument[_TP],
  475. ) -> CompoundSelect[_TP]: ...
  476. def union_all(
  477. *selects: _SelectStatementForCompoundArgument[_TP],
  478. ) -> CompoundSelect[_TP]:
  479. r"""Return a ``UNION ALL`` of multiple selectables.
  480. The returned object is an instance of
  481. :class:`_expression.CompoundSelect`.
  482. A similar :func:`union_all()` method is available on all
  483. :class:`_expression.FromClause` subclasses.
  484. :param \*selects:
  485. a list of :class:`_expression.Select` instances.
  486. """
  487. return CompoundSelect._create_union_all(*selects)
  488. def values(
  489. *columns: ColumnClause[Any],
  490. name: Optional[str] = None,
  491. literal_binds: bool = False,
  492. ) -> Values:
  493. r"""Construct a :class:`_expression.Values` construct representing the
  494. SQL ``VALUES`` clause.
  495. The column expressions and the actual data for :class:`_expression.Values`
  496. are given in two separate steps. The constructor receives the column
  497. expressions typically as :func:`_expression.column` constructs, and the
  498. data is then passed via the :meth:`_expression.Values.data` method as a
  499. list, which can be called multiple times to add more data, e.g.::
  500. from sqlalchemy import column
  501. from sqlalchemy import values
  502. from sqlalchemy import Integer
  503. from sqlalchemy import String
  504. value_expr = (
  505. values(
  506. column("id", Integer),
  507. column("name", String),
  508. )
  509. .data([(1, "name1"), (2, "name2")])
  510. .data([(3, "name3")])
  511. )
  512. Would represent a SQL fragment like::
  513. VALUES(1, "name1"), (2, "name2"), (3, "name3")
  514. The :class:`_sql.values` construct has an optional
  515. :paramref:`_sql.values.name` field; when using this field, the
  516. PostgreSQL-specific "named VALUES" clause may be generated::
  517. value_expr = values(
  518. column("id", Integer), column("name", String), name="somename"
  519. ).data([(1, "name1"), (2, "name2"), (3, "name3")])
  520. When selecting from the above construct, the name and column names will
  521. be listed out using a PostgreSQL-specific syntax::
  522. >>> print(value_expr.select())
  523. SELECT somename.id, somename.name
  524. FROM (VALUES (:param_1, :param_2), (:param_3, :param_4),
  525. (:param_5, :param_6)) AS somename (id, name)
  526. For a more database-agnostic means of SELECTing named columns from a
  527. VALUES expression, the :meth:`.Values.cte` method may be used, which
  528. produces a named CTE with explicit column names against the VALUES
  529. construct within; this syntax works on PostgreSQL, SQLite, and MariaDB::
  530. value_expr = (
  531. values(
  532. column("id", Integer),
  533. column("name", String),
  534. )
  535. .data([(1, "name1"), (2, "name2"), (3, "name3")])
  536. .cte()
  537. )
  538. Rendering as::
  539. >>> print(value_expr.select())
  540. WITH anon_1(id, name) AS
  541. (VALUES (:param_1, :param_2), (:param_3, :param_4), (:param_5, :param_6))
  542. SELECT anon_1.id, anon_1.name
  543. FROM anon_1
  544. .. versionadded:: 2.0.42 Added the :meth:`.Values.cte` method to
  545. :class:`.Values`
  546. :param \*columns: column expressions, typically composed using
  547. :func:`_expression.column` objects.
  548. :param name: the name for this VALUES construct. If omitted, the
  549. VALUES construct will be unnamed in a SQL expression. Different
  550. backends may have different requirements here.
  551. :param literal_binds: Defaults to False. Whether or not to render
  552. the data values inline in the SQL output, rather than using bound
  553. parameters.
  554. """ # noqa: E501
  555. return Values(*columns, literal_binds=literal_binds, name=name)