Skip to main content

ocpp_service/db/
events.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Kevin Vavelin, Codetics (https://codetics.fr)
3
4//! Station event log.
5
6use serde::Serialize;
7
8use super::{Db, Ts};
9
10#[derive(Debug, Serialize, sqlx::FromRow)]
11pub struct Event {
12    pub id: i64,
13    pub action: String,
14    pub payload: serde_json::Value,
15    pub created_at: Ts,
16}
17
18pub async fn insert(
19    db: &Db,
20    station_id: i64,
21    action: &str,
22    payload: &serde_json::Value,
23) -> sqlx::Result<()> {
24    sqlx::query("INSERT INTO station_events (station_id, action, payload) VALUES ($1, $2, $3)")
25        .bind(station_id)
26        .bind(action)
27        .bind(sqlx::types::Json(payload))
28        .execute(db)
29        .await?;
30    Ok(())
31}
32
33pub async fn list(
34    db: &Db,
35    station_id: i64,
36    action: Option<&str>,
37    limit: i64,
38) -> sqlx::Result<Vec<Event>> {
39    sqlx::query_as(
40        "SELECT id, action, payload, created_at FROM station_events WHERE station_id = $1 AND ($2::text IS NULL OR action = $2) \
41         ORDER BY created_at DESC, id DESC LIMIT $3",
42    )
43    .bind(station_id)
44    .bind(action)
45    .bind(limit)
46    .fetch_all(db)
47    .await
48}