From 2b71285af067e56d0f2814c356a238da03c455b8 Mon Sep 17 00:00:00 2001 From: Tom Date: Sun, 28 Aug 2022 13:01:45 +0200 Subject: [PATCH] Reformat coms to use mysql --- src/commands/coms.rs | 56 +++++++++++++++++++++----------------------- 1 file changed, 27 insertions(+), 29 deletions(-) diff --git a/src/commands/coms.rs b/src/commands/coms.rs index afa16db..69a81d4 100644 --- a/src/commands/coms.rs +++ b/src/commands/coms.rs @@ -1,34 +1,32 @@ use crate::{Context, Error}; -use cached::proc_macro::cached; +use mysql_async::{from_row, params, prelude::Queryable, Conn}; use rand::seq::IteratorRandom; -use serde_json::{ - Map, - Value::{self, Object}, -}; -use std::fs; -async fn autocomplete_command<'a>( - _ctx: Context<'_>, - partial: &'a str, -) -> impl Iterator + 'a { - let res: Vec = get_coms() - .keys() - .filter(move |e| e.contains(&partial)) - .map(|e| e.to_string()) - .collect(); - res.into_iter() +async fn autocomplete_command<'a>(ctx: Context<'_>, partial: &'a str) -> Vec { + let mut conn = match ctx.data().database.get_conn().await { + Ok(c) => c, + Err(_) => return vec![], + }; + + let stmt = conn.prep("SELECT sign FROM commands WHERE sign LIKE CONCAT('%', :partial, '%') AND enabled ORDER BY priority DESC, sign ASC LIMIT 25").await.unwrap(); + // let ding = con.exec(&stmt, params! {partial}).await?; + // let iter = ding.into_iter().map(|a| a.to_string()); + let result = match conn.exec_iter(stmt, params! {partial}).await { + Ok(blah) => blah + .map_and_drop(|row| from_row::(row)) + .await + .unwrap_or_default(), + Err(e) => { + println!("Error autocomplete coms {}", e); + vec!["Error getting commands".to_owned()] + } + }; + result } -#[cached(time = 600)] -fn get_coms() -> Map { - let path = "./data/commands.json"; - let data = fs::read_to_string(path).expect("Unable to read file"); - let res: serde_json::Value = serde_json::from_str(&data).expect("Unable to parse"); - if let Object(things) = res { - return things; - } else { - return Map::::new(); - } +pub async fn get_command(sign: &str, con: &mut Conn) -> Result, mysql_async::Error> { + let a: Option = con.exec_first(r"SELECT response FROM commands WHERE sign = :sign and enabled order by priority desc limit 1", (sign,)).await?; + Ok(a) } // F1TV links throughout the seasons @@ -39,15 +37,15 @@ pub async fn coms( #[autocomplete = "autocomplete_command"] command: String, ) -> Result<(), Error> { - match get_coms().get(&command) { + let conn: &mut Conn = &mut ctx.data().database.get_conn().await?; + match get_command(&command, conn).await? { None => { ctx.say(format!("Command `{}` not found", command)).await?; } Some(com) => { - ctx.say(sky(com.as_str().unwrap())).await?; + ctx.say(sky(&com)).await?; } } - Ok(()) }