Skip to main content

datazen_driver_api/
traits.rs

1//! Core driver traits.
2
3use async_trait::async_trait;
4use std::collections::HashMap;
5
6use crate::query_stream::{emit_multi_query_as_stream, QueryStreamCallback};
7use crate::types::*;
8use crate::{
9    execute_command_definition, query_command_definition, CommandResult, DriverCommandDefinition,
10};
11
12#[async_trait]
13pub trait DatabaseDriver: Send + Sync {
14    fn driver_type(&self) -> DatabaseType;
15
16    fn driver_category(&self) -> DriverCategory {
17        DriverCategory::Sql
18    }
19
20    fn quote_char(&self) -> char {
21        '"'
22    }
23
24    fn quote_ident(&self, name: &str) -> String {
25        let q = self.quote_char();
26        if q == '`' {
27            format!("`{}`", name.replace('`', "``"))
28        } else {
29            format!("\"{}\"", name.replace('"', "\"\""))
30        }
31    }
32
33    fn skip_count_query(&self) -> bool {
34        false
35    }
36
37    /// Whether the driver's SQL dialect supports `OFFSET` in pagination.
38    /// Drivers that don't (e.g. Presto/Hive via Superset) should return `false`.
39    fn supports_offset(&self) -> bool {
40        true
41    }
42
43    /// Whether the driver supports EXPLAIN query plan analysis.
44    fn supports_explain(&self) -> bool {
45        true
46    }
47
48    fn format_sql_literal(&self, value: &Option<Value>) -> String {
49        match value {
50            None | Some(Value::Null) => "NULL".to_string(),
51            Some(Value::Bool(b)) => {
52                if *b {
53                    "TRUE".to_string()
54                } else {
55                    "FALSE".to_string()
56                }
57            }
58            Some(Value::Integer(i)) => i.to_string(),
59            Some(Value::Float(f)) => f.to_string(),
60            Some(Value::String(s)) => format!("'{}'", s.replace('\'', "''")),
61            Some(Value::Bytes(b)) => {
62                format!("'{}'", String::from_utf8_lossy(b).replace('\'', "''"))
63            }
64            Some(Value::Timestamp(s)) => format!("'{}'", s.replace('\'', "''")),
65            Some(Value::Json(j)) => format!("'{}'", j.to_string().replace('\'', "''")),
66        }
67    }
68
69    fn build_update_sql(
70        &self,
71        table: &str,
72        set_columns: &[(&str, Option<Value>)],
73        pk_columns: &[(&str, Option<Value>)],
74    ) -> String {
75        let set_clauses: Vec<String> = set_columns
76            .iter()
77            .map(|(col, val)| {
78                format!(
79                    "{} = {}",
80                    self.quote_ident(col),
81                    self.format_sql_literal(val)
82                )
83            })
84            .collect();
85        let where_clauses: Vec<String> = pk_columns
86            .iter()
87            .map(|(col, val)| match val {
88                None | Some(Value::Null) => format!("{} IS NULL", self.quote_ident(col)),
89                Some(v) => format!(
90                    "{} = {}",
91                    self.quote_ident(col),
92                    self.format_sql_literal(&Some(v.clone()))
93                ),
94            })
95            .collect();
96        format!(
97            "UPDATE {} SET {} WHERE {}",
98            self.quote_ident(table),
99            set_clauses.join(", "),
100            where_clauses.join(" AND ")
101        )
102    }
103
104    async fn connect(&self, config: &ConnectionConfig) -> Result<ConnectionHandle, DriverError>;
105
106    async fn test_connection(&self, config: &ConnectionConfig) -> Result<ServerInfo, DriverError>;
107
108    async fn disconnect(&self, handle: ConnectionHandle) -> Result<(), DriverError>;
109
110    async fn get_databases(&self, handle: &ConnectionHandle) -> Result<Vec<String>, DriverError>;
111
112    async fn get_tables(
113        &self,
114        handle: &ConnectionHandle,
115        database: &str,
116    ) -> Result<Vec<TableInfo>, DriverError>;
117
118    async fn get_table_schema(
119        &self,
120        handle: &ConnectionHandle,
121        table: &str,
122    ) -> Result<TableSchema, DriverError>;
123
124    async fn get_columns(
125        &self,
126        handle: &ConnectionHandle,
127        table: &str,
128    ) -> Result<(Vec<ColumnSchema>, Vec<String>), DriverError> {
129        let schema = self.get_table_schema(handle, table).await?;
130        Ok((schema.columns, schema.primary_keys))
131    }
132
133    async fn query(&self, handle: &ConnectionHandle, sql: &str)
134        -> Result<QueryResult, DriverError>;
135
136    async fn query_multi(
137        &self,
138        handle: &ConnectionHandle,
139        sql: &str,
140        limit: Option<u32>,
141    ) -> Result<MultiQueryResult, DriverError>;
142
143    /// Stream query results as row batches.
144    ///
145    /// `limit` is the SQL result cap from the host "limit SELECT results"
146    /// setting (`None` = do not rewrite/cap SQL). It is **not** the IPC batch
147    /// size. Drivers that can stream from the wire should override this;
148    /// the default materializes [`Self::query_multi`] then emits chunks.
149    async fn query_stream(
150        &self,
151        handle: &ConnectionHandle,
152        sql: &str,
153        limit: Option<u32>,
154        on_event: QueryStreamCallback,
155    ) -> Result<(), DriverError> {
156        let result = self.query_multi(handle, sql, limit).await?;
157        emit_multi_query_as_stream(result, &on_event);
158        Ok(())
159    }
160
161    async fn query_with_params(
162        &self,
163        handle: &ConnectionHandle,
164        sql: &str,
165        params: &[Value],
166    ) -> Result<QueryResult, DriverError>;
167
168    async fn execute(&self, handle: &ConnectionHandle, sql: &str) -> Result<u64, DriverError>;
169
170    /// Return commands supported by this driver.
171    ///
172    /// Existing SQL drivers get the standard `query` and `execute` commands.
173    /// A driver with additional capabilities can override this method and append
174    /// its own command definitions.
175    fn command_definitions(&self) -> Vec<DriverCommandDefinition> {
176        vec![query_command_definition(), execute_command_definition()]
177    }
178
179    /// Execute a driver command.
180    ///
181    /// The default implementation maps the existing SQL APIs to commands so
182    /// existing drivers remain source-compatible. Driver plugins can override
183    /// this method to implement driver-specific commands without adding another
184    /// application-level dispatch path.
185    async fn execute_command(
186        &self,
187        handle: &ConnectionHandle,
188        command: &str,
189        input: serde_json::Value,
190    ) -> Result<CommandResult, DriverError> {
191        execute_standard_sql_command(self, handle, command, input).await
192    }
193
194    async fn begin_transaction(
195        &self,
196        _handle: &ConnectionHandle,
197    ) -> Result<TransactionHandle, DriverError> {
198        Err(DriverError::TransactionError(
199            "Not supported for this driver type".into(),
200        ))
201    }
202
203    async fn commit(&self, _tx: TransactionHandle) -> Result<(), DriverError> {
204        Err(DriverError::TransactionError(
205            "Not supported for this driver type".into(),
206        ))
207    }
208
209    async fn rollback(&self, _tx: TransactionHandle) -> Result<(), DriverError> {
210        Err(DriverError::TransactionError(
211            "Not supported for this driver type".into(),
212        ))
213    }
214
215    async fn explain(
216        &self,
217        _handle: &ConnectionHandle,
218        _sql: &str,
219    ) -> Result<ExplainResult, DriverError> {
220        Err(DriverError::QueryFailed(
221            "Not supported for this driver type".into(),
222        ))
223    }
224
225    async fn cancel_query(&self, handle: &ConnectionHandle) -> Result<(), DriverError>;
226
227    /// Fetch server version info using an existing connection handle.
228    /// Unlike `test_connection` which creates a temporary pool, this reuses the live connection.
229    async fn get_server_info(&self, _handle: &ConnectionHandle) -> Result<ServerInfo, DriverError> {
230        Ok(ServerInfo {
231            server_version: String::new(),
232            server_type: self.driver_type(),
233        })
234    }
235
236    /// Switch the active database for subsequent queries.
237    /// Drivers that maintain per-session state (e.g. Kiwi) should override this.
238    async fn use_database(
239        &self,
240        _handle: &ConnectionHandle,
241        _database: &str,
242    ) -> Result<(), DriverError> {
243        Ok(())
244    }
245
246    /// Return driver-specific prompt overrides for AI features.
247    ///
248    /// Templates can use `{{variable}}` placeholders. Available variables per
249    /// scenario are documented in the main application's `PromptResolver`.
250    /// The default implementation returns an empty map (use global defaults).
251    fn prompt_overrides(&self) -> HashMap<PromptScenario, PromptTemplate> {
252        HashMap::new()
253    }
254
255    /// Emit `CREATE TABLE` DDL for a single table.
256    ///
257    /// Default builds DDL from [`Self::get_table_schema`].
258    async fn dump_table_ddl(
259        &self,
260        handle: &ConnectionHandle,
261        table: &str,
262    ) -> Result<String, DriverError> {
263        crate::sql_dump::dump_table_ddl_from_schema::<Self>(self, handle, table).await
264    }
265
266    /// Dump an entire database to SQL text.
267    ///
268    /// Default refuses `create_database` with [`DriverError::NotSupported`] and
269    /// otherwise delegates to [`crate::sql_dump::dump_sql_database`].
270    async fn dump_database(
271        &self,
272        handle: &ConnectionHandle,
273        database: &str,
274        opts: &BackupDumpOptions,
275    ) -> Result<String, DriverError> {
276        if opts.create_database {
277            return Err(DriverError::NotSupported(
278                "Backup option 'create' (CREATE DATABASE) is not supported for this driver".into(),
279            ));
280        }
281        crate::sql_dump::dump_sql_database::<Self>(self, handle, database, opts).await
282    }
283
284    /// Restore a SQL dump by executing statements against the live connection.
285    ///
286    /// Default uses [`crate::sql_dump::split_sql_statements`] and honors
287    /// [`BackupRestoreOptions::single_transaction`] / dump header flags.
288    async fn restore_sql(
289        &self,
290        handle: &ConnectionHandle,
291        sql: &str,
292        opts: Option<&BackupRestoreOptions>,
293    ) -> Result<(), DriverError> {
294        crate::sql_dump::restore_sql_statements::<Self>(self, handle, sql, opts).await
295    }
296
297    async fn structure_capabilities(
298        &self,
299        _handle: &ConnectionHandle,
300    ) -> Result<StructureCapabilities, DriverError> {
301        Ok(StructureCapabilities {
302            dialect_id: self.driver_type(),
303            ..Default::default()
304        })
305    }
306
307    async fn plan_structure_changes(
308        &self,
309        _handle: &ConnectionHandle,
310        _request: &StructureChangeRequest,
311    ) -> Result<StructureChangePlan, DriverError> {
312        Err(DriverError::Unsupported(
313            "table structure planning is not supported by this driver".into(),
314        ))
315    }
316}
317
318/// Default `query` / `execute` command dispatch shared by SQL drivers.
319pub async fn execute_standard_sql_command<D: DatabaseDriver + ?Sized>(
320    driver: &D,
321    handle: &ConnectionHandle,
322    command: &str,
323    input: serde_json::Value,
324) -> Result<CommandResult, DriverError> {
325    match command {
326        "query" => {
327            let sql = input.get("sql").and_then(|v| v.as_str()).ok_or_else(|| {
328                DriverError::InvalidConfig("command 'query' requires string input 'sql'".into())
329            })?;
330            let limit = input
331                .get("limit")
332                .and_then(|v| v.as_u64())
333                .map(|v| v.min(u32::MAX as u64) as u32);
334            let result = driver.query_multi(handle, sql, limit).await?;
335            let data = serde_json::to_value(result).map_err(|e| {
336                DriverError::QueryFailed(format!("failed to serialize query result: {e}"))
337            })?;
338            Ok(CommandResult::new(data))
339        }
340        "execute" => {
341            let sql = input.get("sql").and_then(|v| v.as_str()).ok_or_else(|| {
342                DriverError::InvalidConfig("command 'execute' requires string input 'sql'".into())
343            })?;
344            let rows_affected = driver.execute(handle, sql).await?;
345            Ok(CommandResult::new(serde_json::json!({
346                "rowsAffected": rows_affected
347            })))
348        }
349        other => Err(DriverError::Unsupported(format!(
350            "unsupported driver command: {other}"
351        ))),
352    }
353}
354
355#[cfg(test)]
356mod structure_defaults_tests {
357    use super::*;
358    use crate::ReuseDriver;
359    use std::sync::Arc;
360
361    struct StubDriver;
362
363    #[async_trait]
364    impl DatabaseDriver for StubDriver {
365        fn driver_type(&self) -> DatabaseType {
366            "stub".to_string()
367        }
368
369        async fn connect(
370            &self,
371            _config: &ConnectionConfig,
372        ) -> Result<ConnectionHandle, DriverError> {
373            Ok(ConnectionHandle {
374                id: "conn".into(),
375                pool_id: "pool".into(),
376            })
377        }
378
379        async fn test_connection(
380            &self,
381            _config: &ConnectionConfig,
382        ) -> Result<ServerInfo, DriverError> {
383            Ok(ServerInfo {
384                server_version: String::new(),
385                server_type: self.driver_type(),
386            })
387        }
388
389        async fn disconnect(&self, _handle: ConnectionHandle) -> Result<(), DriverError> {
390            Ok(())
391        }
392
393        async fn get_databases(
394            &self,
395            _handle: &ConnectionHandle,
396        ) -> Result<Vec<String>, DriverError> {
397            Ok(vec![])
398        }
399
400        async fn get_tables(
401            &self,
402            _handle: &ConnectionHandle,
403            _database: &str,
404        ) -> Result<Vec<TableInfo>, DriverError> {
405            Ok(vec![])
406        }
407
408        async fn get_table_schema(
409            &self,
410            _handle: &ConnectionHandle,
411            _table: &str,
412        ) -> Result<TableSchema, DriverError> {
413            Ok(TableSchema {
414                table_name: String::new(),
415                columns: vec![],
416                primary_keys: vec![],
417                indexes: vec![],
418                foreign_keys: vec![],
419            })
420        }
421
422        async fn query(
423            &self,
424            _handle: &ConnectionHandle,
425            _sql: &str,
426        ) -> Result<QueryResult, DriverError> {
427            Ok(QueryResult {
428                columns: vec![],
429                rows: vec![],
430                rows_affected: None,
431                execution_time_ms: 0,
432            })
433        }
434
435        async fn query_multi(
436            &self,
437            _handle: &ConnectionHandle,
438            _sql: &str,
439            _limit: Option<u32>,
440        ) -> Result<MultiQueryResult, DriverError> {
441            Ok(MultiQueryResult {
442                results: vec![],
443                total_time_ms: 0,
444            })
445        }
446
447        async fn query_with_params(
448            &self,
449            _handle: &ConnectionHandle,
450            _sql: &str,
451            _params: &[Value],
452        ) -> Result<QueryResult, DriverError> {
453            Ok(QueryResult {
454                columns: vec![],
455                rows: vec![],
456                rows_affected: None,
457                execution_time_ms: 0,
458            })
459        }
460
461        async fn execute(
462            &self,
463            _handle: &ConnectionHandle,
464            _sql: &str,
465        ) -> Result<u64, DriverError> {
466            Ok(0)
467        }
468
469        async fn cancel_query(&self, _handle: &ConnectionHandle) -> Result<(), DriverError> {
470            Ok(())
471        }
472    }
473
474    fn sample_request() -> StructureChangeRequest {
475        StructureChangeRequest {
476            mode: StructureChangeMode::Alter,
477            schema: Some("public".into()),
478            table: "users".into(),
479            original_columns: vec![],
480            current_columns: vec![],
481            original_indexes: vec![],
482            current_indexes: vec![],
483        }
484    }
485
486    #[tokio::test]
487    async fn default_structure_capabilities_are_disabled() {
488        let driver = StubDriver;
489        let handle = ConnectionHandle {
490            id: "conn".into(),
491            pool_id: "pool".into(),
492        };
493
494        let caps = driver.structure_capabilities(&handle).await.unwrap();
495        assert_eq!(caps.dialect_id, "stub");
496        assert_eq!(caps.alter_strategy, AlterStrategy::None);
497        assert!(!caps.create_table);
498        assert!(!caps.add_column);
499        assert!(!caps.drop_column);
500        assert!(!caps.rename_column);
501        assert!(!caps.alter_type);
502        assert!(!caps.alter_nullability);
503        assert!(!caps.alter_default);
504        assert!(!caps.alter_primary_key);
505        assert!(!caps.reorder_column);
506        assert!(!caps.comment);
507        assert!(!caps.create_index);
508        assert!(!caps.drop_index);
509        assert!(!caps.rebuild_index);
510        assert!(!caps.index_type);
511        assert!(!caps.index_include);
512        assert!(!caps.index_filter);
513        assert!(!caps.index_comment);
514        assert!(caps.index_methods.is_empty());
515    }
516
517    #[tokio::test]
518    async fn default_plan_structure_changes_is_unsupported() {
519        let driver = StubDriver;
520        let handle = ConnectionHandle {
521            id: "conn".into(),
522            pool_id: "pool".into(),
523        };
524        let request = sample_request();
525
526        let err = driver
527            .plan_structure_changes(&handle, &request)
528            .await
529            .unwrap_err();
530        assert!(
531            matches!(err, DriverError::Unsupported(msg) if msg == "table structure planning is not supported by this driver")
532        );
533    }
534
535    #[tokio::test]
536    async fn reuse_driver_forwards_structure_methods() {
537        let inner: Arc<dyn DatabaseDriver> = Arc::new(StubDriver);
538        let driver = ReuseDriver::new(inner, "reuse-stub");
539        let handle = ConnectionHandle {
540            id: "conn".into(),
541            pool_id: "pool".into(),
542        };
543
544        let caps = driver.structure_capabilities(&handle).await.unwrap();
545        assert_eq!(caps.dialect_id, "stub");
546        assert_eq!(driver.driver_type(), "reuse-stub");
547
548        let err = driver
549            .plan_structure_changes(&handle, &sample_request())
550            .await
551            .unwrap_err();
552        assert!(matches!(err, DriverError::Unsupported(_)));
553    }
554}
555
556#[async_trait]
557pub trait KeyValueDriver: Send + Sync {
558    fn driver_type(&self) -> DatabaseType;
559
560    async fn scan_keys_with_info(
561        &self,
562        handle: &ConnectionHandle,
563        db_index: u32,
564        pattern: &str,
565        cursor: u64,
566        count: u32,
567    ) -> Result<(u64, Vec<KeyEntry>, u64), DriverError>;
568
569    async fn get_key_detail(
570        &self,
571        handle: &ConnectionHandle,
572        db_index: u32,
573        key: &str,
574    ) -> Result<KeyDetail, DriverError>;
575}