dialtone_sqlx 0.1.0

Dialtone SQLx Back-End
Documentation
use crate::db::persistent_queue::JobDbType;
use crate::logic::persistent_queue::job_details::JobDetails;
use sqlx::types::chrono::{DateTime, Utc};
use sqlx::types::Json;
use sqlx::{Executor, Postgres, Row};

pub async fn insert_job(
    exec: impl Executor<'_, Database = Postgres>,
    job_type: &JobDbType,
    job_details: &JobDetails,
    attempts_remaining: Option<i32>,
    no_sooner_than: Option<DateTime<Utc>>,
) -> Result<i32, sqlx::Error> {
    let attempts_remaining = attempts_remaining.map_or(1, |value| value);
    let no_sooner_than = no_sooner_than.map_or("now()".to_string(), |value| value.to_string());
    let result = sqlx::query(
        r#"
        insert into job_queue
            (job_type, details, attempts_remaining, no_sooner_than)
        values
            ($1,       $2,      $3,                 $4::timestamptz)
        returning id, pg_notify($1::text, null)
        "#,
    )
    .bind(job_type)
    .bind(Json(job_details))
    .bind(attempts_remaining)
    .bind(no_sooner_than)
    .fetch_one(exec)
    .await?;
    Ok(result.try_get::<i32, usize>(0)?)
}