Implement SQL Query as a newtype tuple struct

This commit is contained in:
Tobie Morgan Hitchcock 2022-05-04 22:34:28 +01:00
parent 643592d750
commit bd6f01971f
3 changed files with 17 additions and 14 deletions

View file

@ -126,7 +126,7 @@ impl<'a> Executor<'a> {
// Initialise array of responses // Initialise array of responses
let mut out: Vec<Response> = vec![]; let mut out: Vec<Response> = vec![];
// Process all statements in query // Process all statements in query
for stm in qry.statements().iter() { for stm in qry.iter() {
// Log the statement // Log the statement
debug!("Executing: {}", stm); debug!("Executing: {}", stm);
// Reset errors // Reset errors

View file

@ -3,33 +3,28 @@ use crate::sql::statement::{statements, Statement, Statements};
use nom::combinator::all_consuming; use nom::combinator::all_consuming;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::fmt; use std::fmt;
use std::ops::Deref;
use std::str; use std::str;
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] #[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct Query { pub struct Query(pub Statements);
pub statements: Statements,
}
impl Query { impl Deref for Query {
pub fn statements(&self) -> &Vec<Statement> { type Target = Vec<Statement>;
&self.statements.0 fn deref(&self) -> &Self::Target {
&self.0 .0
} }
} }
impl fmt::Display for Query { impl fmt::Display for Query {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.statements) write!(f, "{}", self.0)
} }
} }
pub fn query(i: &str) -> IResult<&str, Query> { pub fn query(i: &str) -> IResult<&str, Query> {
let (i, v) = all_consuming(statements)(i)?; let (i, v) = all_consuming(statements)(i)?;
Ok(( Ok((i, Query(v)))
i,
Query {
statements: v,
},
))
} }
#[cfg(test)] #[cfg(test)]

View file

@ -32,12 +32,20 @@ use nom::multi::separated_list1;
use nom::sequence::delimited; use nom::sequence::delimited;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::fmt; use std::fmt;
use std::ops::Deref;
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] #[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct Statements(pub Vec<Statement>); pub struct Statements(pub Vec<Statement>);
impl Deref for Statements {
type Target = Vec<Statement>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl fmt::Display for Statements { impl fmt::Display for Statements {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0.iter().map(|ref v| format!("{};", v)).collect::<Vec<_>>().join("\n")) write!(f, "{}", self.0.iter().map(|ref v| format!("{};", v)).collect::<Vec<_>>().join("\n"))