|
| 1 | +use crate::diesel::query_dsl::methods::DistinctDsl; |
| 2 | +use crate::error::Result; |
| 3 | +use crate::models::List; |
| 4 | +use crate::models::NoParams; |
| 5 | +use crate::modelsv2::{Retrieve, Row}; |
| 6 | +use crate::tables::timetable_v2::dsl; |
| 7 | +use crate::views::pagination::Paginate; |
| 8 | +use crate::views::pagination::PaginatedResponse; |
| 9 | +use async_trait::async_trait; |
| 10 | +use diesel::sql_query; |
| 11 | +use diesel::sql_types::{Array, BigInt, Nullable}; |
| 12 | +use diesel_async::AsyncPgConnection as PgConnection; |
| 13 | +use editoast_derive::ModelV2; |
| 14 | + |
| 15 | +#[derive(Debug, Default, Clone, ModelV2)] |
| 16 | +#[model(table = crate::tables::timetable_v2)] |
| 17 | +#[model(changeset(public))] |
| 18 | +pub struct Timetable { |
| 19 | + pub id: i64, |
| 20 | + pub electrical_profile_set_id: Option<i64>, |
| 21 | +} |
| 22 | + |
| 23 | +#[async_trait] |
| 24 | +impl List<NoParams> for Timetable { |
| 25 | + async fn list_conn( |
| 26 | + conn: &mut PgConnection, |
| 27 | + page: i64, |
| 28 | + page_size: i64, |
| 29 | + _: NoParams, |
| 30 | + ) -> Result<PaginatedResponse<Self>> { |
| 31 | + let timetable_rows = dsl::timetable_v2 |
| 32 | + .distinct() |
| 33 | + .paginate(page, page_size) |
| 34 | + .load_and_count::<Row<Timetable>>(conn) |
| 35 | + .await?; |
| 36 | + |
| 37 | + Ok(timetable_rows.into()) |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +/// Should be used to retrieve a timetable with its trains |
| 42 | +#[derive(Debug, Clone, QueryableByName)] |
| 43 | +pub struct TimetableWithTrains { |
| 44 | + #[diesel(sql_type = BigInt)] |
| 45 | + pub id: i64, |
| 46 | + #[diesel(sql_type = Nullable<BigInt>)] |
| 47 | + pub electrical_profile_set_id: Option<i64>, |
| 48 | + #[diesel(sql_type = Array<BigInt>)] |
| 49 | + pub train_ids: Vec<i64>, |
| 50 | +} |
| 51 | + |
| 52 | +#[async_trait::async_trait] |
| 53 | +impl Retrieve<i64> for TimetableWithTrains { |
| 54 | + async fn retrieve( |
| 55 | + conn: &mut diesel_async::AsyncPgConnection, |
| 56 | + timetable_id: i64, |
| 57 | + ) -> Result<Option<Self>> { |
| 58 | + use diesel_async::RunQueryDsl; |
| 59 | + let result = sql_query( |
| 60 | + "SELECT timetable_v2.*, |
| 61 | + array_remove(array_agg(train_schedule_v2.id), NULL) as train_ids |
| 62 | + FROM timetable_v2 |
| 63 | + LEFT JOIN train_schedule_v2 ON timetable_v2.id = train_schedule_v2.timetable_id |
| 64 | + WHERE timetable_v2.id = $1 |
| 65 | + GROUP BY timetable_v2.id", |
| 66 | + ) |
| 67 | + .bind::<BigInt, _>(timetable_id) |
| 68 | + .get_result::<TimetableWithTrains>(conn) |
| 69 | + .await; |
| 70 | + match result { |
| 71 | + Ok(result) => Ok(Some(result)), |
| 72 | + Err(diesel::result::Error::NotFound) => Ok(None), |
| 73 | + Err(err) => Err(err.into()), |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments