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

Implement subqueries #136

Merged
merged 1 commit into from
Oct 6, 2024
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
40 changes: 32 additions & 8 deletions njord/src/sqlite/select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,24 @@ use rusqlite::types::Value;

use crate::table::Table;

/// Define the enum to represent a column as either a String or SelectQueryBuilder
/// TODO: Implement clone
pub enum Column<'a, T: Table + Default> {
Text(String),
SubQuery(SelectQueryBuilder<'a, T>),
}

// Implement the build method to convert the enum to a string
impl<'a, T: Table + Default> Column<'a, T> {
/// Helper function to convert the columns to a string
pub fn build(&self) -> String {
match self {
Column::Text(text) => text.clone(),
Column::SubQuery(sub_query) => "(".to_string() + &sub_query.build_query() + ")",
}
}
}

/// Constructs a new SELECT query builder.
///
/// # Arguments
Expand All @@ -53,18 +71,18 @@ use crate::table::Table;
/// # Returns
///
/// A `SelectQueryBuilder` instance.
pub fn select<T: Table + Default>(
conn: &Connection,
columns: Vec<String>,
) -> SelectQueryBuilder<T> {
pub fn select<'a, T: Table + Default>(
conn: &'a Connection,
columns: Vec<Column<'a, T>>,
) -> SelectQueryBuilder<'a, T> {
SelectQueryBuilder::new(conn, columns)
}

/// A builder for constructing SELECT queries.
pub struct SelectQueryBuilder<'a, T: Table + Default> {
conn: &'a Connection,
table: Option<T>,
columns: Vec<String>,
columns: Vec<Column<'a, T>>,
where_condition: Option<Condition>,
distinct: bool,
group_by: Option<Vec<String>>,
Expand All @@ -83,7 +101,7 @@ impl<'a, T: Table + Default> SelectQueryBuilder<'a, T> {
///
/// * `conn` - A `rusqlite::Connection` to the SQLite database.
/// * `columns` - A vector of strings representing the columns to be selected.
pub fn new(conn: &'a Connection, columns: Vec<String>) -> Self {
pub fn new(conn: &'a Connection, columns: Vec<Column<'a, T>>) -> Self {
SelectQueryBuilder {
conn,
table: None,
Expand All @@ -105,7 +123,7 @@ impl<'a, T: Table + Default> SelectQueryBuilder<'a, T> {
/// # Arguments
///
/// * `columns` - A vector of strings representing the columns to be selected.
pub fn select(mut self, columns: Vec<String>) -> Self {
pub fn select(mut self, columns: Vec<Column<'a, T>>) -> Self {
self.columns = columns;
self
}
Expand Down Expand Up @@ -234,7 +252,13 @@ impl<'a, T: Table + Default> SelectQueryBuilder<'a, T> {

/// Builds the query string, this function should be used internally.
fn build_query(&self) -> String {
let columns_str = self.columns.join(", ");
let columns_str = self
.columns
.iter()
.map(|c| c.build())
.collect::<Vec<String>>()
.join(", ");

let table_name = self
.table
.as_ref()
Expand Down
144 changes: 104 additions & 40 deletions njord/tests/sqlite_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

use njord::condition::Condition;
use njord::keys::{AutoIncrementPrimaryKey, PrimaryKey};
use njord::sqlite::select::Column;
use njord::sqlite::{self};
use njord::table::Table;
use njord_derive::Table;
Expand All @@ -17,6 +18,16 @@ pub struct User {
address: String,
}

#[derive(Table)]
#[table_name = "users"]
pub struct UserWithSubQuery {
id: AutoIncrementPrimaryKey<usize>,
username: String,
email: String,
address: String,
additional_address: String,
}

#[derive(Table)]
#[table_name = "categories"]
pub struct Category {
Expand Down Expand Up @@ -152,10 +163,10 @@ fn select() {
let conn = sqlite::open(db_path);

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

Expand All @@ -182,10 +193,10 @@ fn select_distinct() {
let conn = sqlite::open(db_path);

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

Expand Down Expand Up @@ -217,10 +228,10 @@ fn select_group_by() {
let conn = sqlite::open(db_path);

let columns = vec![
"id".to_string(),
"username".to_string(),
"email".to_string(),
"address".to_string(),
Column::Text("id".to_string()),
Column::Text("username".to_string()),
Column::Text("email".to_string()),
Column::Text("address".to_string()),
];
let condition = Condition::Eq("username".to_string(), "mjovanc".to_string());
let group_by = vec!["username".to_string(), "email".to_string()];
Expand Down Expand Up @@ -249,10 +260,10 @@ fn select_order_by() {
let conn = sqlite::open(db_path);

let columns = vec![
"id".to_string(),
"username".to_string(),
"email".to_string(),
"address".to_string(),
Column::Text("id".to_string()),
Column::Text("username".to_string()),
Column::Text("email".to_string()),
Column::Text("address".to_string()),
];
let condition = Condition::Eq("username".to_string(), "mjovanc".to_string());
let group_by = vec!["username".to_string(), "email".to_string()];
Expand Down Expand Up @@ -285,10 +296,10 @@ fn select_limit_offset() {
let conn = sqlite::open(db_path);

let columns = vec![
"id".to_string(),
"username".to_string(),
"email".to_string(),
"address".to_string(),
Column::Text("id".to_string()),
Column::Text("username".to_string()),
Column::Text("email".to_string()),
Column::Text("address".to_string()),
];
let condition = Condition::Eq("username".to_string(), "mjovanc".to_string());
let group_by = vec!["username".to_string(), "email".to_string()];
Expand Down Expand Up @@ -323,10 +334,10 @@ fn select_having() {
let conn = sqlite::open(db_path);

let columns = vec![
"id".to_string(),
"username".to_string(),
"email".to_string(),
"address".to_string(),
Column::Text("id".to_string()),
Column::Text("username".to_string()),
Column::Text("email".to_string()),
Column::Text("address".to_string()),
];
let condition = Condition::Eq("username".to_string(), "mjovanc".to_string());
let group_by = vec!["username".to_string(), "email".to_string()];
Expand Down Expand Up @@ -362,10 +373,24 @@ fn select_except() {
let conn = sqlite::open(db_path);

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

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

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

let condition1 = Condition::Eq("username".to_string(), "mjovanc".to_string());
Expand All @@ -375,15 +400,15 @@ fn select_except() {
match conn {
Ok(c) => {
// Create a new connection for each query builder
let query1 = sqlite::select(&c, columns.clone())
let query1 = sqlite::select(&c, columns)
.from(User::default())
.where_clause(condition1);

let query2 = sqlite::select(&c, columns.clone())
let query2 = sqlite::select(&c, columns2)
.from(User::default())
.where_clause(condition2);

let query3 = sqlite::select(&c, columns.clone())
let query3 = sqlite::select(&c, columns3)
.from(User::default())
.where_clause(condition3);

Expand All @@ -408,10 +433,16 @@ fn select_union() {
let conn = sqlite::open(db_path);

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

let condition1 = Condition::Eq("id".to_string(), 42.to_string());
Expand All @@ -420,18 +451,16 @@ fn select_union() {
match conn {
Ok(c) => {
// Create a new connection for each query builder
let query1 = sqlite::select(&c, columns.clone())
let query1 = sqlite::select(&c, columns)
.from(User::default())
.where_clause(condition1);

let query2 = sqlite::select(&c, columns.clone())
let query2 = sqlite::select(&c, columns2)
.from(User::default())
.where_clause(condition2);

// Test a chain of UNION queries (query1 UNION query2)
let result = query1
.union(query2)
.build();
let result = query1.union(query2).build();

match result {
Ok(r) => {
Expand All @@ -454,3 +483,38 @@ fn select_union() {
Err(e) => panic!("Failed to SELECT: {:?}", e),
}
}

#[test]
fn select_sub_queries() {
let db_relative_path = "./db/select.db";
let db_path = Path::new(&db_relative_path);
let conn = sqlite::open(db_path);

match conn {
Ok(c) => {
let sub_query = sqlite::select(&c, vec![Column::Text("username".to_string())])
.from(UserWithSubQuery::default());

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

let result = sqlite::select(&c, columns)
.from(UserWithSubQuery::default())
.build();

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