next_web_dev/interceptor/
default_database_interceptor.rs

1use rbatis::async_trait;
2use rbatis::{
3    executor::Executor,
4    intercept::{Intercept, ResultType},
5    rbdc::db::ExecResult,
6    Error,
7};
8use rbs::Value;
9use tracing::warn;
10
11#[derive(Debug, Default)]
12pub struct DefaultDatabaseInterceptor;
13
14#[async_trait]
15impl Intercept for DefaultDatabaseInterceptor {
16    /// if return Some(false) will be break
17    async fn before(
18        &self,
19        _task_id: i64,
20        _rb: &dyn Executor,
21        _sql: &mut String,
22        _args: &mut Vec<Value>,
23        _result: ResultType<&mut Result<ExecResult, Error>, &mut Result<Vec<Value>, Error>>,
24    ) -> Result<Option<bool>, Error> {
25        // Check whether the full table is updated. If yes, exit without executing
26        if (_sql.starts_with("UPDATE") || _sql.starts_with("update"))
27            && (!_sql.contains("WHERE") && !_sql.contains("where"))
28        {
29            warn!("Full table update detected, exit without executing");
30            return Ok(Some(false));
31        }
32
33        // Check whether the full table is deleted. If yes, exit without executing
34        if (_sql.starts_with("DELETE") || _sql.starts_with("delete"))
35            && (!_sql.contains("WHERE") && !_sql.contains("where"))
36        {
37            warn!("Full table delete detected, exit without executing");
38            return Ok(Some(false));
39        }
40        Ok(Some(true))
41    }
42
43    /// task_id maybe is conn_id or tx_id,
44    /// is_prepared_sql = !args.is_empty(),
45    /// if return Ok(false) will be return data. return Ok(true) will run next
46    async fn after(
47        &self,
48        _task_id: i64,
49        _rb: &dyn Executor,
50        _sql: &mut String,
51        _args: &mut Vec<Value>,
52        _result: ResultType<&mut Result<ExecResult, Error>, &mut Result<Vec<Value>, Error>>,
53    ) -> Result<Option<bool>, Error> {
54        Ok(Some(true))
55    }
56}