Merge pull request #3 from izik1/impl-get_result

Implement get_result(s)
This commit is contained in:
Ryan Leckey 2019-07-22 09:32:06 -07:00 committed by GitHub
commit 2d9442d439
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 93 additions and 3 deletions

View File

@ -1,5 +1,5 @@
use super::Connection;
use sqlx_postgres_protocol::{self as proto, Execute, Message, Parse, Sync};
use sqlx_postgres_protocol::{self as proto, DataRow, Execute, Message, Parse, Sync};
use std::io;
pub struct Prepare<'a> {
@ -81,4 +81,91 @@ impl<'a> Prepare<'a> {
// FIXME: This is an end-of-file error. How we should bubble this up here?
unreachable!()
}
#[inline]
pub async fn get_result(self) -> io::Result<Option<DataRow>> {
proto::bind::trailer(
&mut self.connection.wbuf,
self.bind_state,
self.bind_values,
&[],
);
self.connection.send(Execute::new("", 0));
self.connection.send(Sync);
self.connection.flush().await?;
let mut row: Option<DataRow> = None;
while let Some(message) = self.connection.receive().await? {
match message {
Message::BindComplete | Message::ParseComplete => {
// Indicates successful completion of a phase
}
Message::DataRow(data_row) => {
// we only care about the first result.
if row.is_none() {
row = Some(data_row);
}
}
Message::CommandComplete(_) => {}
Message::ReadyForQuery(_) => {
// Successful completion of the whole cycle
return Ok(row);
}
message => {
unimplemented!("received {:?} unimplemented message", message);
}
}
}
// FIXME: This is an end-of-file error. How we should bubble this up here?
unreachable!()
}
#[inline]
pub async fn get_results(self) -> io::Result<Vec<DataRow>> {
proto::bind::trailer(
&mut self.connection.wbuf,
self.bind_state,
self.bind_values,
&[],
);
self.connection.send(Execute::new("", 0));
self.connection.send(Sync);
self.connection.flush().await?;
let mut rows = vec![];
while let Some(message) = self.connection.receive().await? {
match message {
Message::BindComplete | Message::ParseComplete => {
// Indicates successful completion of a phase
}
Message::DataRow(row) => {
rows.push(row);
}
Message::CommandComplete(_) => {}
Message::ReadyForQuery(_) => {
// Successful completion of the whole cycle
return Ok(rows);
}
message => {
unimplemented!("received {:?} unimplemented message", message);
}
}
}
// FIXME: This is an end-of-file error. How we should bubble this up here?
unreachable!()
}
}

View File

@ -31,11 +31,14 @@ CREATE TABLE IF NOT EXISTS users (
.execute()
.await?;
conn.prepare("INSERT INTO users (name) VALUES ($1)")
let row_id = conn
.prepare("INSERT INTO users (name) VALUES ($1) RETURNING id")
.bind(b"Joe")
.execute()
.get_result()
.await?;
println!("row_id: {:?}", row_id);
let count = conn.prepare("SELECT name FROM users").execute().await?;
println!("users: {}", count);