How to stream a query from sqlx using axum #400
-
Hi Id like to start a discussion about streaming from sqlx using hyper/axum, to show problems and solutions. The first code is the working non streaming code to show how to generate ndjson.
Working solution (without error handling)
Is this the most efficient solution? Option 1: Loop can be changed to handle some errors, and handle end of the data, ie close json (not needed in this case as ndjson is line terminated)
Option 2: loop changed to handle some errors, slightly more ergonomic but does not handle end of data.
Previous attempts left to document what does not work. If you have any suggestions as to how to make them work (if possible) or if you have another approach then please leave a comment. Streaming Attempt 1
This gives an error as the fetch requires a reference and that does not live long enough.
Streaming Attempt 2
Streaming Attempt 3
This looks like a compiler bug.
Streaming Attempt 4
This looks like it might work but there is a problem with the types and errors.
It would be great if someone could help out and edit the code to get a working example. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
If sqlx's streams borrow the connection (or connection pool) then its not compatible with axum's You're also trying to stream sql rows which you cannot stream as raw HTTP bodies (unless sqlx's streams are already of I'm not familiar enough with sqlx to know how to make it work (or if its even possible). I think you'll get better help asking them. |
Beta Was this translation helpful? Give feedback.
-
I find the solution.
|
Beta Was this translation helpful? Give feedback.
If sqlx's streams borrow the connection (or connection pool) then its not compatible with axum's
StreamBody
since it requires a'static
stream, meaning it must be fully owned and not contain borrows.You're also trying to stream sql rows which you cannot stream as raw HTTP bodies (unless sqlx's streams are already of
Vec<u8>
s). You can only stream something that can be converted intoBytes
. This is also shown in the trait bounds ofStreamBody::new
.I'm not familiar enough with sqlx to know how to make it work (or if its even possible). I think you'll get better help asking them.