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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
use crate::prelude::*;

#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[cfg_attr(feature = "ts_rs", derive(TS))]

pub struct StudentCountry {
    pub id: Uuid,
    pub user_id: Uuid,
    pub course_id: Uuid,
    pub course_instance_id: Uuid,
    pub country_code: String,
    pub created_at: DateTime<Utc>,
    pub deleted_at: Option<DateTime<Utc>>,
}

pub async fn insert(
    conn: &mut PgConnection,
    user_id: Uuid,
    course_id: Uuid,
    course_instance_id: Uuid,
    country_code: &str,
) -> ModelResult<()> {
    sqlx::query!(
        "
INSERT INTO student_countries (
  user_id,
  course_id,
  course_instance_id,
  country_code
)
VALUES($1, $2, $3, $4)
      ",
        user_id,
        course_id,
        course_instance_id,
        country_code,
    )
    .execute(conn)
    .await?;
    Ok(())
}

pub async fn delete_student_country(conn: &mut PgConnection, id: Uuid) -> ModelResult<()> {
    sqlx::query!(
        r#"
UPDATE student_countries
SET deleted_at = now()
WHERE id = $1
      "#,
        id
    )
    .execute(conn)
    .await?;
    Ok(())
}

pub async fn get_countries(
    conn: &mut PgConnection,
    course_id: Uuid,
    course_instance_id: Uuid,
) -> ModelResult<Vec<StudentCountry>> {
    let student_countries = sqlx::query_as!(
        StudentCountry,
        "
SELECT *
FROM student_countries
WHERE course_id = $1
AND course_instance_id = $2
AND deleted_at IS NULL;
",
        course_id,
        course_instance_id,
    )
    .fetch_all(conn)
    .await?;
    Ok(student_countries)
}

pub async fn get_selected_country_by_user_id(
    conn: &mut PgConnection,
    user_id: Uuid,
    course_instance_id: Uuid,
) -> ModelResult<StudentCountry> {
    let country = sqlx::query_as!(
        StudentCountry,
        "
SELECT *
FROM student_countries
WHERE user_id = $1
AND course_instance_id = $2
AND deleted_at IS NULL;
",
        user_id,
        course_instance_id,
    )
    .fetch_one(conn)
    .await?;
    Ok(country)
}