algohub_server/utils/
submission.rs

1use crate::models::submission::Status;
2use crate::models::submission::Submission;
3use anyhow::Result;
4use eval_stack::compile::Language;
5use surrealdb::{engine::remote::ws::Client, sql::Thing, Surreal};
6
7pub async fn create(
8    db: &Surreal<Client>,
9    account_id: &str,
10    problem: &str,
11    code: String,
12    lang: Language,
13) -> Result<Option<Submission>> {
14    Ok(db
15        .create("submission")
16        .content(Submission {
17            id: None,
18            lang,
19            code,
20            problem: ("problem", problem).into(),
21            status: Status::InQueue,
22
23            creator: ("account", account_id).into(),
24            judge_details: vec![],
25            judge_result: None,
26
27            contest: None,
28
29            created_at: chrono::Local::now().naive_local(),
30            updated_at: chrono::Local::now().naive_local(),
31        })
32        .await?)
33}
34
35pub async fn get_by_id(db: &Surreal<Client>, id: &str) -> Result<Option<Submission>> {
36    Ok(db.select(("submission", id)).await?)
37}
38
39pub async fn list_by_user(db: &Surreal<Client>, creator: Thing) -> Result<Vec<Submission>> {
40    Ok(db
41        .query("SELECT * FROM submission WHERE creator = $creator")
42        .bind(("creator", creator))
43        .await?
44        .take(0)?)
45}
46
47pub async fn list_by_contest(db: &Surreal<Client>, contest: Thing) -> Result<Vec<Submission>> {
48    Ok(db
49        .query("SELECT * FROM submission WHERE contest = $contest")
50        .bind(("contest", contest))
51        .await?
52        .take(0)?)
53}
54
55pub async fn list_within_contest(
56    db: &Surreal<Client>,
57    contest: Thing,
58    creator: Thing,
59) -> Result<Vec<Submission>> {
60    Ok(db
61        .query("SELECT * FROM submission WHERE contest = $contest AND creator = $creator")
62        .bind(("contest", contest))
63        .bind(("creator", creator))
64        .await?
65        .take(0)?)
66}
67
68pub async fn list_by_problem(db: &Surreal<Client>, problem: Thing) -> Result<Vec<Submission>> {
69    Ok(db
70        .query("SELECT * FROM submission WHERE problem = $problem")
71        .bind(("problem", problem))
72        .await?
73        .take(0)?)
74}
75
76const LIST_BY_PROBLEM_FOR_USER_QUERY: &str = r#"
77SELECT * FROM submission WHERE record::id(problem) = $id AND record::id(creator) = $account_id ORDER BY created_at DESC
78"#;
79pub async fn list_by_problem_for_account(
80    db: &Surreal<Client>,
81    id: &str,
82    account_id: &str,
83) -> Result<Vec<Submission>> {
84    Ok(db
85        .query(LIST_BY_PROBLEM_FOR_USER_QUERY)
86        .bind(("id", id.to_string()))
87        .bind(("account_id", account_id.to_string()))
88        .await?
89        .take(0)?)
90}