Add Filters to SQL

This commit is contained in:
Chaoscaot
2023-03-09 14:52:04 +01:00
parent 5c12ce1202
commit a2a750f20e
3 changed files with 72 additions and 6 deletions

View File

@ -0,0 +1,35 @@
#[derive(Default, Debug, Clone)]
pub struct SchematicFilter {
pub user_id: Option<Vec<u32>>,
pub name: Option<Vec<String>>,
}
impl SchematicFilter {
pub fn new() -> SchematicFilter {
SchematicFilter {
user_id: None,
name: None,
}
}
pub fn user_id(mut self, user_id: Vec<&u32>) -> SchematicFilter {
self.user_id = Some(user_id.into_iter().map(|id| *id).collect());
self
}
pub fn name(mut self, name: Vec<&String>) -> SchematicFilter {
self.name = Some(name.into_iter().map(|name| name.to_string()).collect());
self
}
pub fn build(self) -> String {
let mut query = Vec::new();
if let Some(user_id) = self.user_id {
query.push(user_id.into_iter().map(|id| format!("ND.NodeOwner = {}", id)).collect::<Vec<String>>().join(" OR "));
}
if let Some(name) = self.name {
query.push(name.into_iter().map(|name| format!("SN.NodeName LIKE '%{}%'", name)).collect::<Vec<String>>().join(" OR "));
}
format!("AND ({})", query.join(") AND ("))
}
}

View File

@ -18,8 +18,10 @@
use std::sync::Mutex;
use sqlx::{Executor, MySql, MySqlPool, Pool, Row};
use sqlx::mysql::MySqlConnectOptions;
use crate::filter::SchematicFilter;
mod properties;
pub mod filter;
static mut CONN: Mutex<Option<Pool<MySql>>> = Mutex::new(None);
@ -44,10 +46,10 @@ pub async unsafe fn get_connection() {
}
}
pub async fn load_all_schematics() -> Vec<SchematicNode> {
pub async fn load_all_schematics(filter: SchematicFilter) -> Vec<SchematicNode> {
unsafe { get_connection().await; }
let mut schematics = Vec::new();
let rows = unsafe { &CONN }.lock().unwrap().as_mut().unwrap().fetch_all("SELECT SN.NodeId, SN.NodeName FROM NodeData ND INNER JOIN SchematicNode SN ON SN.NodeId = ND.NodeId WHERE NodeFormat = true").await.expect("Failed to fetch schematics");
let rows = unsafe { &CONN }.lock().unwrap().as_mut().unwrap().fetch_all(format!("SELECT SN.NodeId, SN.NodeName FROM NodeData ND INNER JOIN SchematicNode SN ON SN.NodeId = ND.NodeId WHERE NodeFormat = true {}", filter.build()).as_str()).await.expect("Failed to fetch schematics");
for row in rows {
schematics.push(SchematicNode {
id: row.get(0),