1use serde::{Deserialize, Serialize};
4use thiserror::Error;
5
6pub type DatabaseType = String;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
11#[serde(rename_all = "lowercase")]
12pub enum DriverCategory {
13 Sql,
14 KeyValue,
15 Document,
16}
17
18#[derive(Debug, Clone, Serialize, Deserialize, Default)]
19#[serde(rename_all = "camelCase")]
20pub enum SslMode {
21 #[default]
22 Disable,
23 Prefer,
24 Require,
25 VerifyCa,
26 VerifyFull,
27}
28
29#[derive(Debug, Clone, Serialize, Deserialize)]
30#[serde(rename_all = "camelCase")]
31pub struct SshTunnelConfig {
32 #[serde(default = "default_ssh_enabled")]
33 pub enabled: bool,
34 pub host: String,
35 pub port: u16,
36 pub username: String,
37 #[serde(default = "default_auth_method")]
38 pub auth_method: String,
39 pub password: Option<String>,
40 pub private_key_path: Option<String>,
41 pub passphrase: Option<String>,
42 #[serde(default)]
44 pub jump: Option<Box<SshTunnelConfig>>,
45}
46
47fn default_ssh_enabled() -> bool {
48 true
49}
50fn default_auth_method() -> String {
51 "password".to_string()
52}
53
54#[derive(Debug, Clone, Serialize, Deserialize)]
55#[serde(rename_all = "camelCase")]
56pub struct ConnectionConfig {
57 pub id: String,
58 pub name: String,
59 pub database_type: DatabaseType,
60 pub host: Option<String>,
61 pub port: Option<u16>,
62 pub database: Option<String>,
63 pub schema: Option<String>,
64 pub username: Option<String>,
65 pub password: Option<String>,
66 #[serde(default)]
67 pub ssl_mode: SslMode,
68 #[serde(default = "default_connection_timeout")]
69 pub connection_timeout: u32,
70 #[serde(default = "default_max_pool_size")]
72 pub max_pool_size: u32,
73 pub ssh_tunnel: Option<SshTunnelConfig>,
74 pub color_tag: Option<String>,
75 pub group: Option<String>,
76 pub last_connected_at: Option<String>,
77 pub server_version: Option<String>,
78 #[serde(default)]
80 pub options: Option<serde_json::Map<String, serde_json::Value>>,
81 #[serde(default)]
83 pub read_only: bool,
84}
85
86fn default_connection_timeout() -> u32 {
87 30
88}
89
90fn default_max_pool_size() -> u32 {
91 10
92}
93
94impl ConnectionConfig {
95 pub fn effective_max_pool_size(&self) -> u32 {
97 self.max_pool_size.clamp(1, 100)
98 }
99}
100
101#[cfg(test)]
102mod connection_config_tests {
103 use super::*;
104 use serde_json::json;
105
106 fn dummy_connection_config() -> ConnectionConfig {
107 ConnectionConfig {
108 id: "test-id".into(),
109 name: "Test".into(),
110 database_type: "redis".into(),
111 host: Some("127.0.0.1".into()),
112 port: Some(6379),
113 database: Some("0".into()),
114 schema: None,
115 username: None,
116 password: None,
117 ssl_mode: SslMode::Disable,
118 connection_timeout: 30,
119 max_pool_size: 10,
120 ssh_tunnel: None,
121 color_tag: None,
122 group: None,
123 last_connected_at: None,
124 server_version: None,
125 options: None,
126 read_only: false,
127 }
128 }
129
130 #[test]
131 fn max_pool_size_defaults_when_missing() {
132 let json = json!({
133 "id": "x",
134 "name": "n",
135 "databaseType": "postgresql",
136 });
137 let c: ConnectionConfig = serde_json::from_value(json).unwrap();
138 assert_eq!(c.max_pool_size, 10);
139 assert_eq!(c.effective_max_pool_size(), 10);
140 assert!(!c.read_only);
141 }
142
143 #[test]
144 fn connection_options_roundtrip() {
145 let mut opts = serde_json::Map::new();
146 opts.insert("topology".into(), json!("cluster"));
147 let c = ConnectionConfig {
148 options: Some(opts),
149 ..dummy_connection_config()
150 };
151 let v = serde_json::to_value(&c).unwrap();
152 assert_eq!(v["options"]["topology"], "cluster");
153
154 let restored: ConnectionConfig = serde_json::from_value(v).unwrap();
155 assert_eq!(
156 restored.options.as_ref().unwrap()["topology"],
157 json!("cluster")
158 );
159 }
160
161 #[test]
162 fn connection_options_default_missing() {
163 let json = json!({
164 "id": "x",
165 "name": "n",
166 "databaseType": "redis",
167 });
168 let c: ConnectionConfig = serde_json::from_value(json).unwrap();
169 assert!(c.options.is_none());
170 }
171}
172
173#[derive(Debug, Clone, Serialize, Deserialize)]
174#[serde(untagged)]
175pub enum Value {
176 Null,
177 Bool(bool),
178 Integer(i64),
179 Float(f64),
180 String(String),
181 Bytes(Vec<u8>),
182 Timestamp(String),
183 Json(serde_json::Value),
184}
185
186impl Default for Value {
187 fn default() -> Self {
188 Value::Null
189 }
190}
191
192#[derive(Debug, Clone, Serialize, Deserialize)]
193#[serde(rename_all = "camelCase")]
194pub struct ColumnInfo {
195 pub name: String,
196 pub data_type: String,
197 pub nullable: bool,
198}
199
200#[derive(Debug, Clone, Serialize, Deserialize)]
201#[serde(rename_all = "camelCase")]
202pub struct QueryResult {
203 pub columns: Vec<ColumnInfo>,
204 pub rows: Vec<Vec<Option<Value>>>,
205 pub rows_affected: Option<u64>,
206 pub execution_time_ms: u64,
207}
208
209#[derive(Debug, Clone, Serialize, Deserialize)]
210#[serde(rename_all = "camelCase")]
211pub struct MultiQueryResult {
212 pub results: Vec<StatementResult>,
213 pub total_time_ms: u64,
214}
215
216#[derive(Debug, Clone, Serialize, Deserialize)]
217#[serde(rename_all = "camelCase")]
218pub struct StatementResult {
219 pub sql: String,
220 pub columns: Vec<ColumnInfo>,
221 pub rows: Vec<Vec<Option<Value>>>,
222 pub rows_affected: Option<u64>,
223 pub execution_time_ms: u64,
224 #[serde(default)]
225 pub truncated: bool,
226}
227
228#[derive(Debug, Clone)]
229pub struct ConnectionHandle {
230 pub id: String,
231 pub pool_id: String,
232}
233
234#[derive(Debug)]
235pub struct TransactionHandle {
236 pub id: String,
237 pub connection_id: String,
238}
239
240#[derive(Debug, Clone, Serialize, Deserialize)]
241#[serde(rename_all = "camelCase")]
242pub struct ServerInfo {
243 pub server_version: String,
244 pub server_type: String,
245}
246
247#[derive(Debug, Clone, Serialize, Deserialize)]
248#[serde(rename_all = "camelCase")]
249pub enum TableType {
250 Table,
251 View,
252 MaterializedView,
253 SystemTable,
254}
255
256#[derive(Debug, Clone, Serialize, Deserialize)]
257#[serde(rename_all = "camelCase")]
258pub struct TableInfo {
259 pub name: String,
260 pub schema: Option<String>,
261 pub table_type: TableType,
262 pub row_count: Option<i64>,
263}
264
265#[derive(Debug, Clone, Serialize, Deserialize)]
266#[serde(rename_all = "camelCase")]
267pub struct TableSchema {
268 pub table_name: String,
269 pub columns: Vec<ColumnSchema>,
270 pub primary_keys: Vec<String>,
271 pub indexes: Vec<IndexInfo>,
272 pub foreign_keys: Vec<ForeignKeyInfo>,
273}
274
275#[derive(Debug, Clone, Serialize, Deserialize)]
276#[serde(rename_all = "camelCase")]
277pub struct ColumnSchema {
278 pub name: String,
279 pub data_type: String,
280 pub nullable: bool,
281 pub default_value: Option<String>,
282 pub comment: Option<String>,
283 pub is_primary_key: bool,
284 pub is_auto_increment: bool,
285}
286
287#[derive(Debug, Clone, Serialize, Deserialize)]
288#[serde(rename_all = "camelCase")]
289pub struct IndexInfo {
290 pub name: String,
291 pub columns: Vec<String>,
292 pub is_unique: bool,
293 pub is_primary: bool,
294 pub index_type: String,
295}
296
297#[derive(Debug, Clone, Serialize, Deserialize)]
298#[serde(rename_all = "camelCase")]
299pub struct ForeignKeyInfo {
300 pub name: String,
301 pub columns: Vec<String>,
302 pub referenced_table: String,
303 pub referenced_columns: Vec<String>,
304 pub on_update: String,
305 pub on_delete: String,
306}
307
308#[derive(Debug, Clone, Serialize, Deserialize)]
309#[serde(rename_all = "camelCase")]
310pub struct ExplainResult {
311 pub plan_text: String,
312 pub plan_json: Option<serde_json::Value>,
313 pub total_cost: Option<f64>,
314 pub estimated_rows: Option<i64>,
315}
316
317#[derive(Debug, Clone, Serialize, Deserialize)]
318#[serde(rename_all = "camelCase")]
319pub struct TableDataResult {
320 pub columns: Vec<ColumnSchema>,
321 pub rows: Vec<Vec<Option<Value>>>,
322 pub total_rows: Option<i64>,
323 pub page: u32,
324 pub page_size: u32,
325}
326
327#[derive(Debug, Clone, Serialize, Deserialize)]
328#[serde(rename_all = "camelCase")]
329pub struct KeyEntry {
330 pub key: String,
331 pub key_type: String,
332 pub ttl: i64,
333 pub size: u64,
334 pub preview: String,
335}
336
337#[derive(Debug, Clone, Serialize, Deserialize)]
338#[serde(rename_all = "camelCase")]
339pub struct KeyDetail {
340 pub key: String,
341 pub key_type: String,
342 pub ttl: i64,
343 pub value: serde_json::Value,
344}
345
346#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
351#[serde(rename_all = "snake_case")]
352pub enum PromptScenario {
353 #[serde(rename = "nl2sql")]
354 Nl2Sql,
355 Diagnose,
356 #[serde(rename = "nl_filter")]
357 NlFilter,
358 #[serde(rename = "schema_doc_select_tables")]
359 SchemaDocSelectTables,
360 #[serde(rename = "schema_doc")]
361 SchemaDoc,
362 #[serde(rename = "connection_diagnose")]
363 ConnectionDiagnose,
364 #[serde(rename = "query_summary")]
365 QuerySummary,
366 #[serde(rename = "explain_analysis")]
367 ExplainAnalysis,
368 Chat,
369 #[serde(rename = "workflow_generate")]
370 WorkflowGenerate,
371}
372
373impl PromptScenario {
374 pub fn all() -> &'static [PromptScenario] {
375 &[
376 Self::Nl2Sql,
377 Self::Diagnose,
378 Self::NlFilter,
379 Self::SchemaDocSelectTables,
380 Self::SchemaDoc,
381 Self::ConnectionDiagnose,
382 Self::QuerySummary,
383 Self::ExplainAnalysis,
384 Self::Chat,
385 Self::WorkflowGenerate,
386 ]
387 }
388
389 pub fn label(&self) -> &'static str {
390 match self {
391 Self::Nl2Sql => "NL → SQL",
392 Self::Diagnose => "SQL Error Diagnosis",
393 Self::NlFilter => "NL Filter",
394 Self::SchemaDocSelectTables => "Schema Doc (Table Selection)",
395 Self::SchemaDoc => "Schema Documentation",
396 Self::ConnectionDiagnose => "Connection Diagnosis",
397 Self::QuerySummary => "Query Summary",
398 Self::ExplainAnalysis => "EXPLAIN Analysis",
399 Self::Chat => "AI Chat",
400 Self::WorkflowGenerate => "Workflow Generate",
401 }
402 }
403}
404
405impl std::fmt::Display for PromptScenario {
406 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
407 let s = serde_json::to_value(self)
408 .ok()
409 .and_then(|v| v.as_str().map(String::from))
410 .unwrap_or_else(|| format!("{:?}", self));
411 f.write_str(&s)
412 }
413}
414
415#[derive(Debug, Clone, Serialize, Deserialize)]
420#[serde(rename_all = "camelCase")]
421pub struct PromptTemplate {
422 pub system_zh: String,
423 pub system_en: String,
424}
425
426#[derive(Debug, Clone, Default, PartialEq, Eq)]
428pub struct BackupDumpOptions {
429 pub schema_only: bool,
430 pub data_only: bool,
431 pub clean: bool,
433 pub create_database: bool,
435 pub no_owner: bool,
437 pub single_transaction: bool,
439 pub routines: bool,
441 pub triggers: bool,
443}
444
445#[derive(Debug, Clone, Default, PartialEq, Eq)]
447pub struct BackupRestoreOptions {
448 pub single_transaction: bool,
450}
451
452#[derive(Debug, Error)]
453pub enum DriverError {
454 #[error("Connection failed: {0}")]
455 ConnectionFailed(String),
456
457 #[error("Query failed: {0}")]
458 QueryFailed(String),
459
460 #[error("Connection timeout")]
461 ConnectionTimeout,
462
463 #[error("Authentication failed: {0}")]
464 AuthenticationFailed(String),
465
466 #[error("SSL error: {0}")]
467 SslError(String),
468
469 #[error("SSH tunnel error: {0}")]
470 SshTunnelError(String),
471
472 #[error("Invalid configuration: {0}")]
473 InvalidConfig(String),
474
475 #[error("Driver not found for type: {0}")]
476 DriverNotFound(DatabaseType),
477
478 #[error("Connection pool exhausted")]
479 PoolExhausted,
480
481 #[error("Transaction error: {0}")]
482 TransactionError(String),
483
484 #[error("Not supported: {0}")]
485 NotSupported(String),
486
487 #[error("Unsupported: {0}")]
488 Unsupported(String),
489}
490
491#[derive(Debug, Clone, Serialize, Deserialize, Default)]
493#[serde(rename_all = "camelCase")]
494pub struct StructureCapabilities {
495 pub create_table: bool,
496 pub add_column: bool,
497 pub drop_column: bool,
498 pub rename_column: bool,
499 pub alter_type: bool,
500 pub alter_nullability: bool,
501 pub alter_default: bool,
502 pub alter_primary_key: bool,
503 pub reorder_column: bool,
504 pub comment: bool,
505 pub create_index: bool,
506 pub drop_index: bool,
507 pub rebuild_index: bool,
508 pub index_type: bool,
509 pub index_include: bool,
510 pub index_filter: bool,
511 pub index_comment: bool,
512 pub alter_strategy: AlterStrategy,
513 pub dialect_id: String,
514 #[serde(default, skip_serializing_if = "Vec::is_empty")]
515 pub index_methods: Vec<String>,
516}
517
518#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
519#[serde(rename_all = "camelCase")]
520pub enum AlterStrategy {
521 #[default]
522 None,
523 Direct,
524 SqliteRebuild,
525}
526
527#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
528#[serde(rename_all = "lowercase")]
529pub enum StructureChangeMode {
530 Create,
531 Alter,
532}
533
534#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
535#[serde(rename_all = "camelCase")]
536pub struct StructureColumnDraft {
537 pub id: String,
538 pub name: String,
539 pub data_type: String,
540 pub nullable: bool,
541 #[serde(default, skip_serializing_if = "Option::is_none")]
542 pub default_value: Option<String>,
543 #[serde(default, skip_serializing_if = "Option::is_none")]
544 pub comment: Option<String>,
545 #[serde(default)]
546 pub is_primary_key: bool,
547 #[serde(default)]
548 pub is_auto_increment: bool,
549 #[serde(default)]
550 pub is_unique: bool,
551}
552
553#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
554#[serde(rename_all = "camelCase")]
555pub struct StructureIndexDraft {
556 pub id: String,
557 pub name: String,
558 pub columns: Vec<String>,
559 pub is_unique: bool,
560 #[serde(default)]
561 pub is_primary: bool,
562 #[serde(default)]
563 pub index_type: String,
564 #[serde(default, skip_serializing_if = "Vec::is_empty")]
565 pub include_columns: Vec<String>,
566 #[serde(default, skip_serializing_if = "Option::is_none")]
567 pub filter: Option<String>,
568 #[serde(default, skip_serializing_if = "Option::is_none")]
569 pub comment: Option<String>,
570}
571
572#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
573#[serde(rename_all = "camelCase")]
574pub struct StructureChangeRequest {
575 pub mode: StructureChangeMode,
576 #[serde(default, skip_serializing_if = "Option::is_none")]
577 pub schema: Option<String>,
578 pub table: String,
579 #[serde(default, skip_serializing_if = "Vec::is_empty")]
580 pub original_columns: Vec<StructureColumnDraft>,
581 pub current_columns: Vec<StructureColumnDraft>,
582 #[serde(default, skip_serializing_if = "Vec::is_empty")]
583 pub original_indexes: Vec<StructureIndexDraft>,
584 #[serde(default, skip_serializing_if = "Vec::is_empty")]
585 pub current_indexes: Vec<StructureIndexDraft>,
586}
587
588#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
589#[serde(rename_all = "snake_case")]
590pub enum StatementRisk {
591 Additive,
592 Destructive,
593 Rewrite,
594}
595
596#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
597#[serde(rename_all = "camelCase")]
598pub struct PlanStatement {
599 pub sql: String,
600 pub summary: String,
601 pub risk: StatementRisk,
602}
603
604#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
605#[serde(rename_all = "camelCase")]
606pub struct StructureChangePlan {
607 pub statements: Vec<PlanStatement>,
608 #[serde(default, skip_serializing_if = "Vec::is_empty")]
609 pub warnings: Vec<String>,
610}
611
612#[cfg(test)]
613mod backup_dump_options_tests {
614 use super::*;
615
616 #[test]
617 fn backup_dump_options_default_is_all_false() {
618 let opts = BackupDumpOptions::default();
619 assert!(!opts.schema_only);
620 assert!(!opts.data_only);
621 assert!(!opts.clean);
622 assert!(!opts.create_database);
623 assert!(!opts.no_owner);
624 assert!(!opts.single_transaction);
625 assert!(!opts.routines);
626 assert!(!opts.triggers);
627 }
628
629 #[test]
630 fn backup_restore_options_default_is_all_false() {
631 let opts = BackupRestoreOptions::default();
632 assert!(!opts.single_transaction);
633 }
634
635 #[test]
636 fn not_supported_display() {
637 let err = DriverError::NotSupported("create_database".into());
638 assert!(err.to_string().contains("Not supported"));
639 assert!(err.to_string().contains("create_database"));
640 }
641}