algohub_server/utils/
contest.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use anyhow::Result;
use surrealdb::{engine::remote::ws::Client, opt::PatchOp, sql::Thing, Surreal};

use crate::models::contest::{Contest, ContestData};

pub async fn create(
    db: &Surreal<Client>,
    creator_id: &str,
    contest: ContestData,
) -> Result<Option<Contest>> {
    Ok(db
        .create("contest")
        .content(Contest {
            id: None,
            name: contest.name.to_string(),
            mode: contest.mode,
            visibility: contest.visibility,
            description: contest.description,
            announcement: None,
            start_time: contest.start_time,
            end_time: contest.end_time,
            problems: vec![],
            owner: contest.owner.clone().into(),
            creator: ("account", creator_id).into(),
            updaters: vec![("account", creator_id).into()],
            participants: vec![],
            created_at: chrono::Utc::now().naive_utc(),
            updated_at: chrono::Utc::now().naive_utc(),
        })
        .await?)
}

pub async fn get(db: &Surreal<Client>, id: &str) -> Result<Option<Contest>> {
    Ok(db.select(("contest", id)).await?)
}

pub async fn list(db: &Surreal<Client>, id: Thing) -> Result<Vec<Contest>> {
    Ok(db
        .query("SELECT * FROM contest WHERE owner = $id")
        .bind(("id", id))
        .await?
        .take(0)?)
}

pub async fn add_problems(
    db: &Surreal<Client>,
    id: &str,
    problems: &[Thing],
) -> Result<Option<Contest>> {
    Ok(db
        .update(("contest", id))
        .patch(PatchOp::add("/problems", problems))
        .await?)
}

const REMOVE_PROBLEM: &str =
    "UPDATE contest SET problems -= type::thing(\"problem\", $problem) WHERE record::id(id) = $id";
pub async fn remove_problem(
    db: &Surreal<Client>,
    id: String,
    problem: Thing,
) -> Result<Option<Contest>> {
    Ok(db
        .query(REMOVE_PROBLEM)
        .bind(("id", id))
        .bind(("problem", problem))
        .await?
        .take(0)?)
}