Skip to main content

Stream

Trait Stream 

Source
pub trait Stream<R: Resource<Self>>: Storage<R> {
    // Required method
    fn stream(
        self,
        query: Query,
        ctx: Context,
    ) -> impl Stream<Item = Result<R, Self::Error>> + Send + Unpin + 'static;
}
Available on crate features http and streaming and validation only.
Expand description

GET /resource with Accept: application/jsonl — rows, streamed.

Implement it only if you route STREAM. It is the streaming counterpart of List: where list returns a page that is fully in memory before anything is sent, this yields rows as storage produces them, and each is serialized and written before the next is asked for.

That is the whole point. A Vec<R> of a million rows is a million rows in memory; a stream of them is one. The same query that would exhaust the heap as a List runs in constant space here.

ⓘ
impl Stream<Todo> for App {
    fn stream(
        self,
        query: Query,
        ctx: Context,
    ) -> impl futures_core::Stream<Item = Result<Todo, Self::Error>> + Send + Unpin {
        // A real implementation hands back its driver's row stream —
        // `sqlx::query_as(…).fetch(&self.pool)` is already one.
        futures_util::stream::iter(self.rows().into_iter().map(Ok))
    }
}

§Paging

The Query is passed for its sort keys and any limit the client set, but a stream is not paged: the client asked for the whole collection and gets it. Honour page[limit] as a cap if you want one — nothing in the crate imposes it, because the point of streaming is to exceed what a page can hold.

§Failing partway

Once the first row is written the status is 200, so a later error cannot change it. Yield Err and the stream ends with an error line — see ERROR_LINE for why a client must check the last line rather than the status.

Required Methods§

Source

fn stream( self, query: Query, ctx: Context, ) -> impl Stream<Item = Result<R, Self::Error>> + Send + Unpin + 'static

Yield the collection’s rows, in order.

Takes self and the query by value: the returned stream outlives this call — it is polled while the response body is written — so it cannot borrow either. Your state is Clone already (a cheap handle to a pool, in practice), which is what makes that free.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§