Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add Client method returning a stream of rows #40

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ lazy_static = "1.4"
regex = "1.5"
# network dependencies
reqwest = { version = "0.11", default-features = false, features = ["rustls-tls", "json"]}
futures = "0.3"
futures = "0.3.30"
http = "0.2"
tokio = { version = "1.16", features = ["full"]}
urlencoding = "2.1"
Expand Down
117 changes: 117 additions & 0 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,88 @@ fn need_retry(e: &Error) -> bool {
}
}

struct MyStream<'a, T: Presto + 'static> {
inner: QueryInternal<'a, T>,
phantom: std::marker::PhantomData<T>,
}

enum QueryInternal<'a, T: Presto + 'static> {
Query {
sql: String,
client: &'a Client,
},
Next {
already: Vec<T>,
next: Option<String>,
client: &'a Client,
},
}
Comment on lines +394 to +409
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we merge MyStream and QueryInternal into something like QueryStream.
I can't see why a wrapper is necessary.


impl<'a, T: Presto + 'static> MyStream<'a, T> {
async fn next_and_self(self) -> Result<Option<(T, Self)>> {
match self.inner {
QueryInternal::Query { sql, client } => {
let res = client.get_retry::<T>(sql).await?;
let next = res.next_uri.clone();
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

clone seems unnecessary

let mut already = res.data_set.map(|d| d.into_vec()).unwrap_or_default();
already.reverse();
Ok(already.pop().map(|v| {
(
v,
MyStream {
inner: QueryInternal::Next {
already,
next,
client,
},
phantom: std::marker::PhantomData,
},
)
}))
}
QueryInternal::Next {
mut already,
next,
client,
} => {
if let Some(v) = already.pop() {
Ok(Some((
v,
MyStream {
inner: QueryInternal::Next {
already,
next,
client,
},
phantom: std::marker::PhantomData,
},
)))
} else if let Some(url) = next {
let res = client.get_next_retry::<T>(&url).await?;
let next = res.next_uri.clone();
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

clone seems unnecessary

let mut already = res.data_set.map(|d| d.into_vec()).unwrap_or_default();
already.reverse();
Ok(already.pop().map(|v| {
(
v,
MyStream {
inner: QueryInternal::Next {
already,
next,
client,
},
phantom: std::marker::PhantomData,
},
)
}))
} else {
Ok(None)
}
}
}
}
}

impl Client {
pub async fn get_all<T: Presto + 'static>(&self, sql: String) -> Result<DataSet<T>> {
let res = self.get_retry(sql).await?;
Expand All @@ -415,6 +497,41 @@ impl Client {
}
}

/// Return a `futures::TryStream` of results from a query.
///
/// # Example
///
/// You can iterate over the rows from a query using a `while` loop:
/// ```no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use prusto::{ Presto,Client };
/// use futures::stream::TryStreamExt;
///
/// #[derive(Presto)]
/// struct MyRow {
/// a: i32,
/// b: String,
/// }
///
/// let client: Client = unimplemented!();
///
/// let results = client.stream::<MyRow>("SELECT * FROM my_table".to_string());
/// while let Some(MyRow { a, b }) = results.try_next().await? {
/// println!("This row has {a} and {b}");
/// }
/// # Ok(())
/// # }
pub fn stream<T: Presto + 'static>(
&self,
sql: String,
) -> impl futures::stream::Stream<Item = Result<T>> + std::marker::Unpin + '_ {
let stream = MyStream {
inner: QueryInternal::Query { sql, client: self },
phantom: std::marker::PhantomData,
};
Box::pin(futures::stream::try_unfold(stream, MyStream::next_and_self))
}
Comment on lines +527 to +533
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should remove std::marker::Unpin on the return type and let user decide which pin strategy to use, e.g. pin! macro,Box::pin.


pub async fn execute(&self, sql: String) -> Result<ExecuteResult> {
let res = self.get_retry::<Row>(sql).await?;

Expand Down
Loading