stormchaser_api/db/
event_rules.rs1use serde_json::Value;
2use sqlx::PgPool;
3use stormchaser_model::event_rules::EventRule;
4use stormchaser_model::EventId;
5use stormchaser_model::RuleId;
6use stormchaser_model::WebhookId;
7
8use stormchaser_model::event;
9
10#[allow(clippy::too_many_arguments)]
12pub async fn create_event_rule(
14 pool: &PgPool,
15 id: RuleId,
16 name: &str,
17 description: &Option<String>,
18 webhook_id: Option<WebhookId>,
19 event_type_pattern: &str,
20 condition_expr: &Option<String>,
21 workflow_name: &str,
22 repo_url: &str,
23 workflow_path: &str,
24 git_ref: &str,
25 input_mappings: Value,
26) -> Result<(), sqlx::Error> {
27 sqlx::query(
28 r#"
29 INSERT INTO event_rules (
30 id, name, description, webhook_id, event_type_pattern, condition_expr,
31 workflow_name, repo_url, workflow_path, git_ref, input_mappings
32 ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
33 "#,
34 )
35 .bind(id)
36 .bind(name)
37 .bind(description)
38 .bind(webhook_id)
39 .bind(event_type_pattern)
40 .bind(condition_expr)
41 .bind(workflow_name)
42 .bind(repo_url)
43 .bind(workflow_path)
44 .bind(git_ref)
45 .bind(input_mappings)
46 .execute(pool)
47 .await?;
48 Ok(())
49}
50
51pub async fn list_event_rules(pool: &PgPool) -> Result<Vec<EventRule>, sqlx::Error> {
54 sqlx::query_as("SELECT * FROM event_rules ORDER BY created_at DESC")
55 .fetch_all(pool)
56 .await
57}
58
59pub async fn get_active_event_rules_by_webhook(
62 pool: &PgPool,
63 webhook_id: WebhookId,
64) -> Result<Vec<EventRule>, sqlx::Error> {
65 sqlx::query_as("SELECT * FROM event_rules WHERE webhook_id = $1 AND is_active = TRUE")
66 .bind(webhook_id)
67 .fetch_all(pool)
68 .await
69}
70
71pub async fn delete_event_rule(pool: &PgPool, id: RuleId) -> Result<(), sqlx::Error> {
74 sqlx::query("DELETE FROM event_rules WHERE id = $1")
75 .bind(id)
76 .execute(pool)
77 .await?;
78 Ok(())
79}
80
81pub async fn get_event_correlation(
84 pool: &PgPool,
85 key: &str,
86 value: &str,
87) -> Result<Option<event::EventCorrelation>, sqlx::Error> {
88 sqlx::query_as(
89 "SELECT id, step_instance_id, run_id, correlation_key, correlation_value, created_at FROM event_correlations WHERE correlation_key = $1 AND correlation_value = $2"
90 )
91 .bind(key)
92 .bind(value)
93 .fetch_optional(pool)
94 .await
95}
96
97pub async fn delete_event_correlation(pool: &sqlx::PgPool, id: EventId) -> Result<(), sqlx::Error> {
99 sqlx::query("DELETE FROM event_correlations WHERE id = $1")
100 .bind(id)
101 .execute(pool)
102 .await?;
103 Ok(())
104}