r"""Construct a new :class:`_expression.TString` clause, representing a SQL template string using Python 3.14+ t-strings. .. versionadded:: 2.1 E.g.:: from sqlalchemy import tstring a = 5 b = 10 stmt = tstring(t"select {a}, {b}") result = conne
(template: Template)
| 1838 | |
| 1839 | |
| 1840 | def tstring(template: Template) -> TString: |
| 1841 | r"""Construct a new :class:`_expression.TString` clause, |
| 1842 | representing a SQL template string using Python 3.14+ t-strings. |
| 1843 | |
| 1844 | .. versionadded:: 2.1 |
| 1845 | |
| 1846 | E.g.:: |
| 1847 | |
| 1848 | from sqlalchemy import tstring |
| 1849 | |
| 1850 | a = 5 |
| 1851 | b = 10 |
| 1852 | stmt = tstring(t"select {a}, {b}") |
| 1853 | result = connection.execute(stmt) |
| 1854 | |
| 1855 | The :func:`_expression.tstring` function accepts a Python 3.14+ |
| 1856 | template string (t-string) and processes it to create a SQL statement. |
| 1857 | Unlike :func:`_expression.text`, which requires manual bind parameter |
| 1858 | specification, :func:`_expression.tstring` automatically handles |
| 1859 | interpolation of Python values and SQLAlchemy expressions. |
| 1860 | |
| 1861 | **Interpolation Behavior**: |
| 1862 | |
| 1863 | - **SQL content** expressed in the plain string portions of the template |
| 1864 | are rendered directly as SQL |
| 1865 | - **SQLAlchemy expressions** (columns, functions, etc.) are embedded |
| 1866 | as clause elements |
| 1867 | - **Plain Python values** are automatically wrapped in |
| 1868 | :func:`_expression.literal` |
| 1869 | |
| 1870 | For example:: |
| 1871 | |
| 1872 | from sqlalchemy import tstring, select, literal, JSON, table, column |
| 1873 | |
| 1874 | # Python values become bound parameters |
| 1875 | user_id = 42 |
| 1876 | stmt = tstring(t"SELECT * FROM users WHERE id = {user_id}") |
| 1877 | # renders: SELECT * FROM users WHERE id = :param_1 |
| 1878 | |
| 1879 | # SQLAlchemy expressions are embedded |
| 1880 | stmt = tstring(t"SELECT {column('q')} FROM {table('t')}") |
| 1881 | # renders: SELECT q FROM t |
| 1882 | |
| 1883 | # Apply explicit SQL types to bound values using literal() |
| 1884 | some_json = {"foo": "bar"} |
| 1885 | stmt = tstring(t"SELECT {literal(some_json, JSON)}") |
| 1886 | |
| 1887 | **Column Specification**: |
| 1888 | |
| 1889 | Like :func:`_expression.text`, the :func:`_expression.tstring` construct |
| 1890 | supports the :meth:`_expression.TString.columns` method to specify |
| 1891 | return columns and their types:: |
| 1892 | |
| 1893 | from sqlalchemy import tstring, column, Integer, String |
| 1894 | |
| 1895 | stmt = tstring(t"SELECT id, name FROM users").columns( |
| 1896 | column("id", Integer), column("name", String) |
| 1897 | ) |