botserver/src/basic/keywords/on.rs

79 lines
2.5 KiB
Rust
Raw Normal View History

2025-10-11 20:02:14 -03:00
use diesel::prelude::*;
2025-10-06 10:30:17 -03:00
use log::{error, info};
use rhai::Dynamic;
use rhai::Engine;
use serde_json::{json, Value};
2025-10-06 20:49:38 -03:00
use crate::shared::models::TriggerKind;
2025-10-11 12:29:03 -03:00
use crate::shared::models::UserSession;
2025-10-11 20:02:14 -03:00
use crate::shared::state::AppState;
2025-10-06 10:30:17 -03:00
2025-10-11 20:02:14 -03:00
pub fn on_keyword(state: &AppState, _user: UserSession, engine: &mut Engine) {
2025-10-11 12:29:03 -03:00
let state_clone = state.clone();
2025-10-06 10:30:17 -03:00
engine
.register_custom_syntax(
2025-10-11 20:02:14 -03:00
&["ON", "$ident$", "OF", "$string$"],
2025-10-06 10:30:17 -03:00
true,
2025-10-11 20:02:14 -03:00
move |context, inputs| {
let trigger_type = context.eval_expression_tree(&inputs[0])?.to_string();
let table = context.eval_expression_tree(&inputs[1])?.to_string();
let name = format!("{}_{}.rhai", table, trigger_type.to_lowercase());
2025-10-06 10:30:17 -03:00
2025-10-11 20:02:14 -03:00
let kind = match trigger_type.to_uppercase().as_str() {
"UPDATE" => TriggerKind::TableUpdate,
"INSERT" => TriggerKind::TableInsert,
"DELETE" => TriggerKind::TableDelete,
_ => return Err(format!("Invalid trigger type: {}", trigger_type).into()),
};
2025-10-06 10:30:17 -03:00
2025-10-11 20:02:14 -03:00
let mut conn = state_clone.conn.lock().unwrap();
let result = execute_on_trigger(&mut *conn, kind, &table, &name)
2025-10-11 20:02:14 -03:00
.map_err(|e| format!("DB error: {}", e))?;
2025-10-06 10:30:17 -03:00
2025-10-11 20:02:14 -03:00
if let Some(rows_affected) = result.get("rows_affected") {
Ok(Dynamic::from(rows_affected.as_i64().unwrap_or(0)))
} else {
Err("No rows affected".into())
2025-10-06 10:30:17 -03:00
}
},
)
.unwrap();
}
2025-10-11 12:29:03 -03:00
pub fn execute_on_trigger(
2025-10-11 20:02:14 -03:00
conn: &mut diesel::PgConnection,
2025-10-06 10:30:17 -03:00
kind: TriggerKind,
table: &str,
param: &str,
2025-10-06 10:30:17 -03:00
) -> Result<Value, String> {
info!(
"Starting execute_on_trigger with kind: {:?}, table: {}, param: {}",
kind, table, param
2025-10-06 10:30:17 -03:00
);
2025-10-11 12:29:03 -03:00
use crate::shared::models::system_automations;
let new_automation = (
system_automations::kind.eq(kind as i32),
system_automations::target.eq(table),
system_automations::param.eq(param),
2025-10-11 12:29:03 -03:00
);
let result = diesel::insert_into(system_automations::table)
.values(&new_automation)
2025-10-11 20:02:14 -03:00
.execute(conn)
2025-10-11 12:29:03 -03:00
.map_err(|e| {
error!("SQL execution error: {}", e);
e.to_string()
})?;
2025-10-06 10:30:17 -03:00
Ok(json!({
"command": "on_trigger",
"trigger_type": format!("{:?}", kind),
"table": table,
"param": param,
2025-10-11 12:29:03 -03:00
"rows_affected": result
2025-10-06 10:30:17 -03:00
}))
}