dialtone_sqlx 0.1.0

Dialtone SQLx Back-End
Documentation
use crate::db::return_optional;
use crate::db::site_info::SITE_INFO_JSON_OBJECT;
use const_format::concatcp;
use dialtone_common::rest::sites::site_data::SiteInfo;
use sqlx::types::chrono::{DateTime, Utc};
use sqlx::{Executor, Postgres};

pub async fn page_sites(
    exec: impl Executor<'_, Database = Postgres>,
    prev_date: Option<&DateTime<Utc>>,
    next_date: Option<&DateTime<Utc>>,
    limit: i32,
) -> Result<Option<Vec<SiteInfo>>, sqlx::Error> {
    let select = concatcp!(
        "select json_agg(",
        SITE_INFO_JSON_OBJECT,
        r#"
        ) as "site_info: Json<SiteInfo>" from (select * from site_info
        "#
    );
    let sql;
    let query = if prev_date.is_some() && next_date.is_some() {
        sql = format!(
            "{} where created_at < $1 and created_at > $2 order by created_at asc limit $3) as site_info",
            select,
        );
        sqlx::query(sql.as_str())
            .bind(prev_date.unwrap())
            .bind(next_date.unwrap())
            .bind(limit)
    } else if prev_date.is_some() && next_date.is_none() {
        sql = format!(
            "{} where created_at < $1 order by created_at asc limit $2) as site_info",
            select,
        );
        sqlx::query(sql.as_str())
            .bind(prev_date.unwrap())
            .bind(limit)
    } else if prev_date.is_none() && next_date.is_some() {
        sql = format!(
            "{} where created_at > $1 order by created_at asc limit $2) as site_info",
            select,
        );
        sqlx::query(sql.as_str())
            .bind(next_date.unwrap())
            .bind(limit)
    } else {
        sql = format!("{} order by created_at asc limit $1) as site_info", select,);
        sqlx::query(sql.as_str()).bind(limit)
    };
    let result = query.fetch_optional(exec).await?;
    return_optional(&result)
}