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

feat: implement select iterator utility function #1429

Merged
merged 2 commits into from
Oct 15, 2023
Merged
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
33 changes: 33 additions & 0 deletions core/src/executor/execute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,39 @@ pub enum Payload {
ShowVariable(PayloadVariable),
}

impl Payload {
/// Exports `select` payloads as an [`std::iter::Iterator`].
///
/// The items of the Iterator are `HashMap<Column, Value>`, and they are borrowed by default.
/// If ownership is required, you need to acquire them directly.
///
/// - Some: [`Payload::Select`], [`Payload::SelectMap`]
/// - None: otherwise
pub fn select(&self) -> Option<impl Iterator<Item = HashMap<&str, &Value>>> {
#[derive(iter_enum::Iterator)]
enum Iter<I1, I2> {
Schema(I1),
Schemaless(I2),
}

Some(match self {
Payload::Select { labels, rows } => Iter::Schema(rows.iter().map(move |row| {
labels
.iter()
.zip(row.iter())
.map(|(label, value)| (label.as_str(), value))
.collect::<HashMap<_, _>>()
})),
Payload::SelectMap(rows) => Iter::Schemaless(rows.iter().map(|row| {
row.iter()
.map(|(k, v)| (k.as_str(), v))
.collect::<HashMap<_, _>>()
})),
_ => return None,
})
}
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum PayloadVariable {
Tables(Vec<String>),
Expand Down
63 changes: 17 additions & 46 deletions pkg/rust/examples/hello_world.rs
Original file line number Diff line number Diff line change
@@ -1,56 +1,14 @@
#[cfg(feature = "sled-storage")]
mod hello_world {
use {
gluesql::{
prelude::{Glue, Payload},
sled_storage::SledStorage,
},
gluesql::{prelude::Glue, sled_storage::SledStorage},
std::fs,
};

struct GreetTable {
rows: Vec<GreetRow>,
}
struct GreetRow {
name: String,
}

impl TryFrom<Payload> for GreetTable {
type Error = &'static str;

fn try_from(payload: Payload) -> Result<Self, Self::Error> {
match payload {
Payload::Select { labels: _, rows } => {
let rows = rows
.into_iter()
.map(|mut row| {
let name = row.remove(0);
GreetRow {
name: String::from(name),
}
})
.collect::<Vec<_>>();

Ok(Self { rows })
}
Payload::SelectMap(rows) => {
let rows = rows
.into_iter()
.map(|row| {
let name = row.get("name").unwrap();
GreetRow {
name: String::from(name),
}
})
.collect::<Vec<_>>();

Ok(Self { rows })
}
_ => Err("unexpected payload, expected a select query result"),
}
}
}

pub async fn run() {
/*
Initiate a connection
Expand Down Expand Up @@ -92,10 +50,23 @@ mod hello_world {
*/
assert_eq!(result.len(), 1);

let table: GreetTable = result.remove(0).try_into().unwrap();
assert_eq!(table.rows.len(), 1);
let payload = result.remove(0);

let rows = payload
.select()
.unwrap()
.map(|map| {
let name = *map.get("name").unwrap();
let name = name.into();

GreetRow { name }
})
.collect::<Vec<_>>();

assert_eq!(rows.len(), 1);
assert_eq!(&rows[0].name, "World");

println!("Hello {}!", table.rows[0].name); // Will always output "Hello World!"
println!("Hello {}!", rows[0].name); // Will always output "Hello World!"
}
}

Expand Down
Loading