Last active
September 16, 2015 05:41
-
-
Save film42/b477b213bb5244fa0a99 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait Queryable { | |
fn pluralized_table_name(&self) -> String; | |
fn predicates(&self) -> &Vec<String>; | |
fn has_limit(&self) -> bool { | |
return self.limit_value() >= 0; | |
} | |
fn limit_value(&self) -> i64; | |
fn to_sql(&self) -> String { | |
let mut query_string = "SELECT * FROM ".to_string(); | |
query_string = query_string + &self.pluralized_table_name(); | |
let mut and_predicate = false; | |
for predicate in self.predicates() { | |
if and_predicate { | |
query_string = query_string + " AND" | |
} | |
query_string = query_string + " " + &predicate.to_string(); | |
and_predicate = true; | |
} | |
if self.has_limit() { | |
query_string = query_string + " LIMIT " + &self.limit_value().to_string(); | |
} | |
query_string = query_string + ";"; | |
return query_string; | |
} | |
} | |
#[derive(Clone)] | |
struct Query { | |
table: &'static str, | |
predicates: Vec<String>, | |
limit: i64 | |
} | |
impl Query { | |
pub fn new(table: &'static str) -> Query { | |
return Query{table: table, predicates: Vec::new(), limit: -1}; | |
} | |
pub fn from(table: &'static str) -> Query { | |
return Query::new(table); | |
} | |
pub fn limit(&mut self, n: i64) -> Query { | |
self.limit = n; | |
return self.clone() | |
} | |
pub fn where_eq(&mut self, attribute: &'static str, value: &'static str) -> Query { | |
let predicate = "WHERE '".to_string() + &attribute.to_string() + "' = '" + &value.to_string() + "'"; | |
self.predicates.push(predicate); | |
return self.clone(); | |
} | |
} | |
impl Queryable for Query { | |
fn pluralized_table_name(&self) -> String { | |
return self.table.to_string(); | |
} | |
fn predicates(&self) -> &Vec<String> { | |
return &self.predicates; | |
} | |
fn limit_value(&self) -> i64 { | |
return self.limit; | |
} | |
} | |
fn main() { | |
let query = Query::from("transactions").where_eq("name", "roger").where_eq("gender", "m").limit(10); | |
println!("{}", query.to_sql()); | |
} | |
//=> SELECT * FROM transactions WHERE 'name' = 'roger' AND WHERE 'gender' = 'm' LIMIT 10; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment