Skip to content

Commit

Permalink
Implement IN and NOT IN (#139)
Browse files Browse the repository at this point in the history
  • Loading branch information
mjovanc authored Oct 7, 2024
2 parents a95c91d + 960115f commit 4869e4b
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 0 deletions.
Binary file modified njord/db/insert.db
Binary file not shown.
Empty file added njord/db/update.db
Empty file.
20 changes: 20 additions & 0 deletions njord/src/condition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ pub enum Condition {
And(Box<Condition>, Box<Condition>),
/// Logical OR condition.
Or(Box<Condition>, Box<Condition>),
/// In condition: column IN (value1, value2, ...).
In(String, Vec<String>),
/// Not in condition: column NOT IN (value1, value2, ...).
NotIn(String, Vec<String>),
}

impl Condition {
Expand Down Expand Up @@ -113,6 +117,22 @@ impl Condition {
}
Condition::And(left, right) => format!("({}) AND ({})", left.build(), right.build()),
Condition::Or(left, right) => format!("({}) OR ({})", left.build(), right.build()),
Condition::In(column, values) => {
let values = values
.iter()
.map(|v| format!("'{}'", v))
.collect::<Vec<String>>()
.join(", ");
format!("{} IN ({})", column, values)
}
Condition::NotIn(column, values) => {
let values = values
.iter()
.map(|v| format!("'{}'", v))
.collect::<Vec<String>>()
.join(", ");
format!("{} NOT IN ({})", column, values)
}
}
}
}
39 changes: 39 additions & 0 deletions njord/tests/sqlite_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -539,3 +539,42 @@ fn update_with_sub_queries() {
Err(e) => panic!("Failed to UPDATE: {:?}", e),
};
}

fn select_in() {
let db_relative_path = "./db/select.db";
let db_path = Path::new(&db_relative_path);
let conn = sqlite::open(db_path);

let columns = vec![
Column::Text("id".to_string()),
Column::Text("username".to_string()),
Column::Text("email".to_string()),
Column::Text("address".to_string()),
];

let condition = Condition::And(
Box::new(Condition::In(
"username".to_string(),
vec!["mjovanc".to_string(), "otheruser".to_string()],
)),
Box::new(Condition::NotIn(
"username".to_string(),
vec!["chasewillden".to_string()],
)),
);

match conn {
Ok(c) => {
let result = sqlite::select(&c, columns)
.from(User::default())
.where_clause(condition)
.build();

match result {
Ok(r) => assert_eq!(r.len(), 2),
Err(e) => panic!("Failed to SELECT: {:?}", e),
};
}
Err(e) => panic!("Failed to SELECT: {:?}", e),
};
}

0 comments on commit 4869e4b

Please sign in to comment.