r"""Construct a new :class:`_expression.TextClause` clause, representing a textual SQL string directly. E.g.:: from sqlalchemy import text t = text("SELECT * FROM users") result = connection.execute(t) The advantages :func:`_expression.text` provides o
(text: str)
| 1759 | |
| 1760 | @_document_text_coercion("text", ":func:`.text`", ":paramref:`.text.text`") |
| 1761 | def text(text: str) -> TextClause: |
| 1762 | r"""Construct a new :class:`_expression.TextClause` clause, |
| 1763 | representing |
| 1764 | a textual SQL string directly. |
| 1765 | |
| 1766 | E.g.:: |
| 1767 | |
| 1768 | from sqlalchemy import text |
| 1769 | |
| 1770 | t = text("SELECT * FROM users") |
| 1771 | result = connection.execute(t) |
| 1772 | |
| 1773 | The advantages :func:`_expression.text` |
| 1774 | provides over a plain string are |
| 1775 | backend-neutral support for bind parameters, per-statement |
| 1776 | execution options, as well as |
| 1777 | bind parameter and result-column typing behavior, allowing |
| 1778 | SQLAlchemy type constructs to play a role when executing |
| 1779 | a statement that is specified literally. The construct can also |
| 1780 | be provided with a ``.c`` collection of column elements, allowing |
| 1781 | it to be embedded in other SQL expression constructs as a subquery. |
| 1782 | |
| 1783 | Bind parameters are specified by name, using the format ``:name``. |
| 1784 | E.g.:: |
| 1785 | |
| 1786 | t = text("SELECT * FROM users WHERE id=:user_id") |
| 1787 | result = connection.execute(t, {"user_id": 12}) |
| 1788 | |
| 1789 | For SQL statements where a colon is required verbatim, as within |
| 1790 | an inline string, use a backslash to escape:: |
| 1791 | |
| 1792 | t = text(r"SELECT * FROM users WHERE name='\:username'") |
| 1793 | |
| 1794 | The :class:`_expression.TextClause` |
| 1795 | construct includes methods which can |
| 1796 | provide information about the bound parameters as well as the column |
| 1797 | values which would be returned from the textual statement, assuming |
| 1798 | it's an executable SELECT type of statement. The |
| 1799 | :meth:`_expression.TextClause.bindparams` |
| 1800 | method is used to provide bound |
| 1801 | parameter detail, and :meth:`_expression.TextClause.columns` |
| 1802 | method allows |
| 1803 | specification of return columns including names and types:: |
| 1804 | |
| 1805 | t = ( |
| 1806 | text("SELECT * FROM users WHERE id=:user_id") |
| 1807 | .bindparams(user_id=7) |
| 1808 | .columns(id=Integer, name=String) |
| 1809 | ) |
| 1810 | |
| 1811 | for id, name in connection.execute(t): |
| 1812 | print(id, name) |
| 1813 | |
| 1814 | The :func:`_expression.text` construct is used in cases when |
| 1815 | a literal string SQL fragment is specified as part of a larger query, |
| 1816 | such as for the WHERE clause of a SELECT statement:: |
| 1817 | |
| 1818 | s = select(users.c.id, users.c.name).where(text("id=:user_id")) |