mirror of
https://github.com/element-hq/synapse.git
synced 2026-12-01 01:10:07 +00:00
Next step in adding Rust postgres driver. Follows on from #19996. This adds a query lifecycle state machine that is used to implement the Python transaction interface (e.g. `txn.fetchall()`, `txn.rowcount`, etc). The state machine is an enum over `Idle`/`Active`/`Closed`. The `fetch` APIs are only allowed during the `Active` phase, while `rowcount` is allowed during `Active` or `Closed`. So for each query on a connection, the state starts of at `Idle` and transitions to `Active` when `execute` completes. Rows can then be read until there are no more rows, at which point we transition to `Closed`. The state transitions back to `Idle` on the next query. If at any point a error is returned, e.g. a postgres error or failing to parse a row, the error is returned and the state immediately transitions back to `Idle`. Note that calling `txn.rowcount` will implicitly close the query state (and discard any unread rows), unlike for `sqlite3` and `psycopg2`. This is because Postgres only sends the affected row count *after* all the rows have been sent down the connection. `psycopg2` avoids this by buffering all the rows in-memory. We could do the same, but a) that's a waste, and b) we generally never need to know the affected row count up front (and even if we did we can manually buffer). The query state enum won't be exposed directly to Python, instead it will be wrapped by a transaction class. Also adds a `fetch_next_batch`, which waits for at least the next row but then returns any already buffered rows. This is to allow efficient implementation of iterating in Python over the rows, where we want to avoid doing FFI for each row. Reviewable commit-by-commit. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>