easy-sqlx-core 0.1.7

The Rust Toolkit to easy use sqlx
Documentation
use crate::sql::{
    dialects::{
        condition::{Condition, Where, WhereAppend},
        schema::{self, schema::Schema},
    },
    schema::table::TableSchema,
    utils::pair::Pair,
};

use super::builder::ExecuteBuilder;
use sqlx::Database;

#[derive(Debug)]
pub struct UpdateBuilder<'a> {
    table: TableSchema,
    default_schema: &'a str,
    columns: Vec<Pair>,
    wh: Option<Where>,
}

impl<'a> UpdateBuilder<'a> {
    pub fn new(table: TableSchema) -> Self {
        Self {
            table,
            default_schema: "",
            columns: vec![],
            wh: None,
        }
    }

    pub fn with_default_schema(mut self, schema: &'a str) -> Self {
        self.default_schema = schema;
        self
    }

    pub fn set(mut self, pair: Pair) -> Self {
        self.columns.push(pair);
        // self.r#where()
        self
    }
}
impl<'a> WhereAppend<Condition> for UpdateBuilder<'a> {
    fn and(mut self, cond: Condition) -> Self {
        if let Some(w) = self.wh {
            self.wh = Some(w.and(cond));
        } else {
            self.wh = Some(Where::new(cond));
        }
        self
    }

    fn or(mut self, cond: Condition) -> Self {
        if let Some(w) = self.wh {
            self.wh = Some(w.or(cond));
        } else {
            self.wh = Some(Where::new(cond));
        }
        self
    }
}

impl<'a> WhereAppend<Where> for UpdateBuilder<'a> {
    fn and(mut self, wh: Where) -> Self {
        if let Some(w) = self.wh {
            self.wh = Some(w.and(wh));
        } else {
            self.wh = Some(wh);
        }
        self
    }

    fn or(mut self, wh: Where) -> Self {
        if let Some(w) = self.wh {
            self.wh = Some(w.or(wh));
        } else {
            self.wh = Some(wh);
        }
        self
    }
}

#[cfg(feature = "postgres")]
use sqlx::Postgres;

impl<'a> ExecuteBuilder for UpdateBuilder<'a> {
    #[cfg(feature = "postgres")]
    type DB = Postgres;

    async fn execute<C>(
        &self,
        conn: &mut C,
    ) -> Result<<Self::DB as sqlx::Database>::QueryResult, sqlx::Error>
    where
        for<'e> &'e mut C: sqlx::Executor<'e, Database = Self::DB>,
    {
        let schema = schema::new(self.default_schema.to_string());

        let cols: Vec<String> = self.columns.iter().map(|c| c.name.to_string()).collect();
        let sql = schema.sql_update_columns(&self.table, &cols, self.wh.clone(), false);

        let mut query: sqlx::query::Query<'_, Self::DB, <Self::DB as Database>::Arguments<'_>> =
            sqlx::query::<Self::DB>(&sql);

        for col in &self.columns {
            query = col.value.bind_to_query(query);
        }

        if let Some(w) = &self.wh {
            query = w.bind_to_query(query);
        }

        let result = query.execute(conn).await.map_err(|err| {
            let sets = &self
                .columns
                .iter()
                .map(|c| c.value.as_string())
                .collect::<Vec<String>>()
                .join(",");
            let wh = if let Some(w) = &self.wh {
                w.list_params()
            } else {
                "".to_string()
            };
            tracing::error!(
                "easy-sqlx: {} set [{}] where [{}]; \n{:?}",
                sql,
                sets,
                wh,
                err
            );
            err
        })?;

        #[cfg(feature = "logsql")]
        {
            let sets = &self
                .columns
                .iter()
                .map(|c| c.value.as_string())
                .collect::<Vec<String>>()
                .join(",");
            let wh = if let Some(w) = &self.wh {
                w.list_params()
            } else {
                "".to_string()
            };
            tracing::info!(
                "easy-sqlx: {sql} set [{sets}] where [{wh}]; \nrows_affected: {}",
                result.rows_affected()
            );
        }
        Ok(result)
    }

    #[cfg(feature = "postgres")]
    async fn execute_return<'e, 'c: 'e, C, O>(&self, executor: C) -> sqlx::Result<Vec<O>>
    where
        C: 'e + sqlx::Executor<'c, Database = Self::DB>,
        O: 'e,
        for<'r> O: sqlx::FromRow<'r, <Self::DB as Database>::Row>,
        O: std::marker::Send,
        O: Unpin,
    {
        let schema = schema::new(self.default_schema.to_string());

        let cols: Vec<String> = self.columns.iter().map(|c| c.name.to_string()).collect();
        let sql = schema.sql_update_columns(&self.table, &cols, self.wh.clone(), true);

        let mut query = sqlx::query_as::<Self::DB, O>(&sql);

        for col in &self.columns {
            query = col.value.bind_to_query_as(query);
        }

        if let Some(w) = &self.wh {
            query = w.bind_to_query_as(query);
        }

        let result = query.fetch_all(executor).await.map_err(|err| {
            let sets = &self
                .columns
                .iter()
                .map(|c| c.value.as_string())
                .collect::<Vec<String>>()
                .join(",");
            let wh = if let Some(w) = &self.wh {
                w.list_params()
            } else {
                "".to_string()
            };
            tracing::error!(
                "easy-sqlx: {} set [{}] where [{}]; \n{:?}",
                sql,
                sets,
                wh,
                err
            );
            err
        });

        #[cfg(feature = "logsql")]
        {
            let sets = &self
                .columns
                .iter()
                .map(|c| c.value.as_string())
                .collect::<Vec<String>>()
                .join(",");
            let wh = if let Some(w) = &self.wh {
                w.list_params()
            } else {
                "".to_string()
            };
            tracing::info!("easy-sqlx: {sql} set [{sets}] where [{wh}];");
        }
        result
    }
}