Documentation
use edm_core::Uuid;
use std::time::Instant;

/// 与查询上下文相关的结构体
#[derive(Debug, Clone)]
pub struct QueryContext {
    /// 开始时间
    start_time: Instant,
    /// 查询唯一标识 Uuid
    query_id: Uuid,
    /// 查询
    query: String,
    /// 参数
    arguments: Vec<String>,
    /// 最后插入的ID
    last_insert_id: Option<i64>,
    /// 受影响的行数
    rows_affected: Option<u64>,
    /// 查询是否成功
    success: bool,
}

impl QueryContext {
    /// 创建一个实例
    #[inline]
    pub fn new() -> Self {
        Self {
            start_time: Instant::now(),
            query_id: Uuid::new_v4(),
            query: String::new(),
            arguments: Vec::new(),
            last_insert_id: None,
            rows_affected: None,
            success: false,
        }
    }

    /// 设置 `query`参数
    #[inline]
    pub fn set_query(&mut self, query: impl ToString) {
        self.query = query.to_string();
    }

    /// 添加参数到 arguments`Vec<String>`
    #[inline]
    pub fn add_argument(&mut self, arg: impl ToString) {
        self.arguments.push(arg.to_string());
    }
    /// 追加查询参数
    #[inline]
    pub fn append_arguments(&mut self, arguments: &mut Vec<String>) {
        self.arguments.append(arguments);
    }

    /// 设置最后的插入ID
    #[inline]
    pub fn set_last_insert_id(&mut self, id: i64) {
        self.last_insert_id = Some(id);
    }

    /// 设置查询结果
    #[inline]
    pub fn set_query_result(&mut self, rows_affected: Option<u64>, success: bool) {
        self.rows_affected = rows_affected;
        self.success = success;
    }

    /// 返回开始时间
    #[inline]
    pub fn get_start_time(&self) -> Instant {
        self.start_time
    }

    /// 返回查询ID
    #[inline]
    pub fn get_query_id(&self) -> Uuid {
        self.query_id
    }

    pub fn get_query(&self) -> &str {
        &self.query
    }

    pub fn get_arguments(&self) -> &[String] {
        &self.arguments
    }

    pub fn get_last_insert_id(&self) -> Option<i64> {
        self.last_insert_id
    }

    pub fn get_rows_affected(&self) -> Option<u64> {
        self.rows_affected
    }

    pub fn is_success(&self) -> bool {
        self.success
    }

    /// 格式化参数. 将所有的参数通过 `, ` 组合成字符串
    #[inline]
    pub fn format_arguments(&self) -> String {
        self.arguments.join(", ")
    }
}

impl Default for QueryContext {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}