Execute a query (INSERT, UPDATE, DELETE). :param query: SQLAlchemy query expression :return: For INSERT, the inserted primary key or ``None`` if the backend cannot return one (e.g. Oracle MySQL inserting into a non-AUTO_INCREMENT pk with a server def
(self, query: Executable)
| 57 | return result.scalar() |
| 58 | |
| 59 | async def execute(self, query: Executable) -> Any: |
| 60 | """ |
| 61 | Execute a query (INSERT, UPDATE, DELETE). |
| 62 | |
| 63 | :param query: SQLAlchemy query expression |
| 64 | :return: For INSERT, the inserted primary key or ``None`` if the backend |
| 65 | cannot return one (e.g. Oracle MySQL inserting into a |
| 66 | non-AUTO_INCREMENT pk with a server default — no RETURNING support). |
| 67 | For UPDATE/DELETE, the row count. |
| 68 | """ |
| 69 | result: CursorResult[Any] = await self._connection.execute(query) |
| 70 | |
| 71 | # For INSERT queries, try to get the inserted primary key via the |
| 72 | # dialect's best-available mechanism (RETURNING on PostgreSQL / SQLite |
| 73 | # 3.35+ / MariaDB 10.5+, LAST_INSERT_ID() on MySQL AUTO_INCREMENT). |
| 74 | # Do NOT fall back to rowcount here: rowcount is not a pk, and |
| 75 | # returning it would silently corrupt `Model.pk` in `save()`. |
| 76 | if result.context and result.context.isinsert: |
| 77 | if result.inserted_primary_key: |
| 78 | pk_value = result.inserted_primary_key[0] |
| 79 | if pk_value is not None: |
| 80 | return pk_value |
| 81 | |
| 82 | if hasattr(result, "lastrowid") and result.lastrowid: # pragma: no cover |
| 83 | return result.lastrowid |
| 84 | |
| 85 | return None # pragma: no cover |
| 86 | |
| 87 | return result.rowcount if result.rowcount is not None else 0 |
| 88 | |
| 89 | async def execute_many( |
| 90 | self, query: Union[Executable, str], values: Sequence[Mapping[str, Any]] |
no outgoing calls