Created
November 8, 2021 00:08
-
-
Save jayhuang75/504daecd0051443edc17a41e643a9a8d to your computer and use it in GitHub Desktop.
go train delay rust api raw json to sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| pub async fn to_sql_query(&self, namespace: &str) -> Result<SearchSQLQuery, AppError> { | |
| let mut sql_query: String; | |
| match namespace { | |
| SEARCH_NAMESPACE_DATE_RANGE => { | |
| sql_query = "select date, departure, depart_scheduled, destination, arrival_scheduled, delay, created_at, count(*) OVER() AS total_count from delays".to_string(); | |
| } | |
| _ => { | |
| return Err(AppError { | |
| message: None, | |
| cause: Some("to_sql_query with mismatch namespace".to_string()), | |
| error_type: AppErrorType::SearchError, | |
| }); | |
| } | |
| } | |
| let mut must_where: Vec<String> = Vec::new(); | |
| // get all the must where condition | |
| if let Some(must) = &self.query.must { | |
| // process must range | |
| let ranges_where = convert_ranges_to_sql(&must.ranges).await?; | |
| if !ranges_where.is_empty() { | |
| must_where.push(ranges_where); | |
| } | |
| } | |
| // construct finaly where and should | |
| if must_where.is_empty() { | |
| return Ok(SearchSQLQuery { sql: sql_query }); | |
| } | |
| // the WHERE keyword | |
| sql_query = format!("{} WHERE", sql_query); | |
| // must condition | |
| if !must_where.is_empty() { | |
| sql_query = format!("{} {}", sql_query, must_where.join(" AND ")); | |
| } | |
| // set the order by | |
| if namespace == SEARCH_NAMESPACE_DATE_RANGE { | |
| if let Some(sort_tx_time) = &self.sort_time { | |
| match sort_tx_time.as_str() { | |
| SORT_DESC_BY_TIME => sql_query = format!("{} ORDER BY date DESC", sql_query), | |
| SORT_ASC_BY_TIME => sql_query = format!("{} ORDER BY date", sql_query), | |
| _ => { | |
| return Err(AppError { | |
| message: Some(format!( | |
| "only {:?}, {:?} available.", | |
| SORT_DESC_BY_TIME, SORT_ASC_BY_TIME | |
| )), | |
| cause: Some("sort time error".to_string()), | |
| error_type: AppErrorType::SearchError, | |
| }); | |
| } | |
| } | |
| } | |
| } | |
| // set the limit | |
| if let Some(limit) = &self.limit { | |
| if limit > &(0_u64) { | |
| sql_query = format!("{} LIMIT {}", sql_query, limit.to_string()); | |
| } | |
| } | |
| // set the offset | |
| if let Some(offset) = &self.offset { | |
| if offset > &(0_u64) { | |
| sql_query = format!("{} OFFSET {}", sql_query, offset.to_string()); | |
| } | |
| } | |
| Ok(SearchSQLQuery { sql: sql_query }) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment