Return a :class:`.Extract` construct. This is typically available as :func:`.extract` as well as ``func.extract`` from the :data:`.func` namespace. :param field: The field to extract. .. warning:: This field is used as a literal SQL string. **DO NOT PASS UNTRUSTED IN
(field: str, expr: _ColumnExpressionArgument[Any])
| 1176 | |
| 1177 | |
| 1178 | def extract(field: str, expr: _ColumnExpressionArgument[Any]) -> Extract: |
| 1179 | """Return a :class:`.Extract` construct. |
| 1180 | |
| 1181 | This is typically available as :func:`.extract` |
| 1182 | as well as ``func.extract`` from the |
| 1183 | :data:`.func` namespace. |
| 1184 | |
| 1185 | :param field: The field to extract. |
| 1186 | |
| 1187 | .. warning:: This field is used as a literal SQL string. |
| 1188 | **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**. |
| 1189 | |
| 1190 | :param expr: A column or Python scalar expression serving as the |
| 1191 | right side of the ``EXTRACT`` expression. |
| 1192 | |
| 1193 | E.g.:: |
| 1194 | |
| 1195 | from sqlalchemy import extract |
| 1196 | from sqlalchemy import table, column |
| 1197 | |
| 1198 | logged_table = table( |
| 1199 | "user", |
| 1200 | column("id"), |
| 1201 | column("date_created"), |
| 1202 | ) |
| 1203 | |
| 1204 | stmt = select(logged_table.c.id).where( |
| 1205 | extract("YEAR", logged_table.c.date_created) == 2021 |
| 1206 | ) |
| 1207 | |
| 1208 | In the above example, the statement is used to select ids from the |
| 1209 | database where the ``YEAR`` component matches a specific value. |
| 1210 | |
| 1211 | Similarly, one can also select an extracted component:: |
| 1212 | |
| 1213 | stmt = select(extract("YEAR", logged_table.c.date_created)).where( |
| 1214 | logged_table.c.id == 1 |
| 1215 | ) |
| 1216 | |
| 1217 | The implementation of ``EXTRACT`` may vary across database backends. |
| 1218 | Users are reminded to consult their database documentation. |
| 1219 | """ |
| 1220 | return Extract(field, expr) |
| 1221 | |
| 1222 | |
| 1223 | def false() -> False_: |