datazen-driver-api 0.0.8

Public API (traits and types) for DataZen database driver plugins
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
//! Shared types for database drivers.

use serde::{Deserialize, Serialize};
use thiserror::Error;

/// Database type identifier — a plain string (e.g. "postgresql", "mysql", "superset").
/// Plugins define their own identifiers without modifying this crate.
pub type DatabaseType = String;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DriverCategory {
    Sql,
    KeyValue,
    Document,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub enum SslMode {
    #[default]
    Disable,
    Prefer,
    Require,
    VerifyCa,
    VerifyFull,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SshTunnelConfig {
    #[serde(default = "default_ssh_enabled")]
    pub enabled: bool,
    pub host: String,
    pub port: u16,
    pub username: String,
    #[serde(default = "default_auth_method")]
    pub auth_method: String,
    pub password: Option<String>,
    pub private_key_path: Option<String>,
    pub passphrase: Option<String>,
    /// Optional first hop (ProxyJump). Nested `jump` is allowed.
    #[serde(default)]
    pub jump: Option<Box<SshTunnelConfig>>,
}

fn default_ssh_enabled() -> bool {
    true
}
fn default_auth_method() -> String {
    "password".to_string()
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConnectionConfig {
    pub id: String,
    pub name: String,
    pub database_type: DatabaseType,
    pub host: Option<String>,
    pub port: Option<u16>,
    pub database: Option<String>,
    pub schema: Option<String>,
    pub username: Option<String>,
    pub password: Option<String>,
    #[serde(default)]
    pub ssl_mode: SslMode,
    #[serde(default = "default_connection_timeout")]
    pub connection_timeout: u32,
    /// Max connections in the driver's sqlx pool (host injects from AppSettings on connect).
    #[serde(default = "default_max_pool_size")]
    pub max_pool_size: u32,
    pub ssh_tunnel: Option<SshTunnelConfig>,
    pub color_tag: Option<String>,
    pub group: Option<String>,
    pub last_connected_at: Option<String>,
    pub server_version: Option<String>,
    /// Opaque per-driver connection options (e.g. Redis topology/TLS).
    #[serde(default)]
    pub options: Option<serde_json::Map<String, serde_json::Value>>,
    /// When true, mutating SQL and row edits are rejected by the host.
    #[serde(default)]
    pub read_only: bool,
}

fn default_connection_timeout() -> u32 {
    30
}

fn default_max_pool_size() -> u32 {
    10
}

impl ConnectionConfig {
    /// Pool size for sqlx drivers: at least 1, capped at 100.
    pub fn effective_max_pool_size(&self) -> u32 {
        self.max_pool_size.clamp(1, 100)
    }
}

#[cfg(test)]
mod connection_config_tests {
    use super::*;
    use serde_json::json;

    fn dummy_connection_config() -> ConnectionConfig {
        ConnectionConfig {
            id: "test-id".into(),
            name: "Test".into(),
            database_type: "redis".into(),
            host: Some("127.0.0.1".into()),
            port: Some(6379),
            database: Some("0".into()),
            schema: None,
            username: None,
            password: None,
            ssl_mode: SslMode::Disable,
            connection_timeout: 30,
            max_pool_size: 10,
            ssh_tunnel: None,
            color_tag: None,
            group: None,
            last_connected_at: None,
            server_version: None,
            options: None,
            read_only: false,
        }
    }

    #[test]
    fn max_pool_size_defaults_when_missing() {
        let json = json!({
            "id": "x",
            "name": "n",
            "databaseType": "postgresql",
        });
        let c: ConnectionConfig = serde_json::from_value(json).unwrap();
        assert_eq!(c.max_pool_size, 10);
        assert_eq!(c.effective_max_pool_size(), 10);
        assert!(!c.read_only);
    }

    #[test]
    fn connection_options_roundtrip() {
        let mut opts = serde_json::Map::new();
        opts.insert("topology".into(), json!("cluster"));
        let c = ConnectionConfig {
            options: Some(opts),
            ..dummy_connection_config()
        };
        let v = serde_json::to_value(&c).unwrap();
        assert_eq!(v["options"]["topology"], "cluster");

        let restored: ConnectionConfig = serde_json::from_value(v).unwrap();
        assert_eq!(
            restored.options.as_ref().unwrap()["topology"],
            json!("cluster")
        );
    }

    #[test]
    fn connection_options_default_missing() {
        let json = json!({
            "id": "x",
            "name": "n",
            "databaseType": "redis",
        });
        let c: ConnectionConfig = serde_json::from_value(json).unwrap();
        assert!(c.options.is_none());
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Value {
    Null,
    Bool(bool),
    Integer(i64),
    Float(f64),
    String(String),
    Bytes(Vec<u8>),
    Timestamp(String),
    Json(serde_json::Value),
}

impl Default for Value {
    fn default() -> Self {
        Value::Null
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ColumnInfo {
    pub name: String,
    pub data_type: String,
    pub nullable: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct QueryResult {
    pub columns: Vec<ColumnInfo>,
    pub rows: Vec<Vec<Option<Value>>>,
    pub rows_affected: Option<u64>,
    pub execution_time_ms: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MultiQueryResult {
    pub results: Vec<StatementResult>,
    pub total_time_ms: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StatementResult {
    pub sql: String,
    pub columns: Vec<ColumnInfo>,
    pub rows: Vec<Vec<Option<Value>>>,
    pub rows_affected: Option<u64>,
    pub execution_time_ms: u64,
    #[serde(default)]
    pub truncated: bool,
}

#[derive(Debug, Clone)]
pub struct ConnectionHandle {
    pub id: String,
    pub pool_id: String,
}

#[derive(Debug)]
pub struct TransactionHandle {
    pub id: String,
    pub connection_id: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ServerInfo {
    pub server_version: String,
    pub server_type: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum TableType {
    Table,
    View,
    MaterializedView,
    SystemTable,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TableInfo {
    pub name: String,
    pub schema: Option<String>,
    pub table_type: TableType,
    pub row_count: Option<i64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TableSchema {
    pub table_name: String,
    pub columns: Vec<ColumnSchema>,
    pub primary_keys: Vec<String>,
    pub indexes: Vec<IndexInfo>,
    pub foreign_keys: Vec<ForeignKeyInfo>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ColumnSchema {
    pub name: String,
    pub data_type: String,
    pub nullable: bool,
    pub default_value: Option<String>,
    pub comment: Option<String>,
    pub is_primary_key: bool,
    pub is_auto_increment: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IndexInfo {
    pub name: String,
    pub columns: Vec<String>,
    pub is_unique: bool,
    pub is_primary: bool,
    pub index_type: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ForeignKeyInfo {
    pub name: String,
    pub columns: Vec<String>,
    pub referenced_table: String,
    pub referenced_columns: Vec<String>,
    pub on_update: String,
    pub on_delete: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExplainResult {
    pub plan_text: String,
    pub plan_json: Option<serde_json::Value>,
    pub total_cost: Option<f64>,
    pub estimated_rows: Option<i64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TableDataResult {
    pub columns: Vec<ColumnSchema>,
    pub rows: Vec<Vec<Option<Value>>>,
    pub total_rows: Option<i64>,
    pub page: u32,
    pub page_size: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct KeyEntry {
    pub key: String,
    pub key_type: String,
    pub ttl: i64,
    pub size: u64,
    pub preview: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct KeyDetail {
    pub key: String,
    pub key_type: String,
    pub ttl: i64,
    pub value: serde_json::Value,
}

/// Identifies an AI prompt scenario.
///
/// Each scenario has a default system prompt template built into the main app.
/// Drivers can override per-scenario prompts via [`DatabaseDriver::prompt_overrides`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PromptScenario {
    #[serde(rename = "nl2sql")]
    Nl2Sql,
    Diagnose,
    #[serde(rename = "nl_filter")]
    NlFilter,
    #[serde(rename = "schema_doc_select_tables")]
    SchemaDocSelectTables,
    #[serde(rename = "schema_doc")]
    SchemaDoc,
    #[serde(rename = "connection_diagnose")]
    ConnectionDiagnose,
    #[serde(rename = "query_summary")]
    QuerySummary,
    #[serde(rename = "explain_analysis")]
    ExplainAnalysis,
    Chat,
    #[serde(rename = "workflow_generate")]
    WorkflowGenerate,
}

impl PromptScenario {
    pub fn all() -> &'static [PromptScenario] {
        &[
            Self::Nl2Sql,
            Self::Diagnose,
            Self::NlFilter,
            Self::SchemaDocSelectTables,
            Self::SchemaDoc,
            Self::ConnectionDiagnose,
            Self::QuerySummary,
            Self::ExplainAnalysis,
            Self::Chat,
            Self::WorkflowGenerate,
        ]
    }

    pub fn label(&self) -> &'static str {
        match self {
            Self::Nl2Sql => "NL → SQL",
            Self::Diagnose => "SQL Error Diagnosis",
            Self::NlFilter => "NL Filter",
            Self::SchemaDocSelectTables => "Schema Doc (Table Selection)",
            Self::SchemaDoc => "Schema Documentation",
            Self::ConnectionDiagnose => "Connection Diagnosis",
            Self::QuerySummary => "Query Summary",
            Self::ExplainAnalysis => "EXPLAIN Analysis",
            Self::Chat => "AI Chat",
            Self::WorkflowGenerate => "Workflow Generate",
        }
    }
}

impl std::fmt::Display for PromptScenario {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = serde_json::to_value(self)
            .ok()
            .and_then(|v| v.as_str().map(String::from))
            .unwrap_or_else(|| format!("{:?}", self));
        f.write_str(&s)
    }
}

/// A bilingual prompt template for a specific scenario.
///
/// Templates can contain `{{variable}}` placeholders that get substituted at
/// runtime. Available variables depend on the scenario.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PromptTemplate {
    pub system_zh: String,
    pub system_en: String,
}

/// Options for driver-native SQL database dumps.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BackupDumpOptions {
    pub schema_only: bool,
    pub data_only: bool,
    /// Emit `DROP TABLE IF EXISTS` before each table.
    pub clean: bool,
    /// Emit a driver-specific `CREATE DATABASE` preamble.
    pub create_database: bool,
    /// Omit `OWNER` clauses (PostgreSQL); documented no-op when not emitted.
    pub no_owner: bool,
    /// Hint to wrap restore in a transaction (MySQL `--single-transaction` parity).
    pub single_transaction: bool,
    /// Include stored procedures and functions (MySQL).
    pub routines: bool,
    /// Include triggers (MySQL).
    pub triggers: bool,
}

/// Options for SQL restore operations.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BackupRestoreOptions {
    /// Execute the restore inside `BEGIN`/`COMMIT` (rolls back on failure).
    pub single_transaction: bool,
}

#[derive(Debug, Error)]
pub enum DriverError {
    #[error("Connection failed: {0}")]
    ConnectionFailed(String),

    #[error("Query failed: {0}")]
    QueryFailed(String),

    #[error("Connection timeout")]
    ConnectionTimeout,

    #[error("Authentication failed: {0}")]
    AuthenticationFailed(String),

    #[error("SSL error: {0}")]
    SslError(String),

    #[error("SSH tunnel error: {0}")]
    SshTunnelError(String),

    #[error("Invalid configuration: {0}")]
    InvalidConfig(String),

    #[error("Driver not found for type: {0}")]
    DriverNotFound(DatabaseType),

    #[error("Connection pool exhausted")]
    PoolExhausted,

    #[error("Transaction error: {0}")]
    TransactionError(String),

    #[error("Not supported: {0}")]
    NotSupported(String),

    #[error("Unsupported: {0}")]
    Unsupported(String),
}

/// Table structure editor capability flags returned by drivers.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct StructureCapabilities {
    pub create_table: bool,
    pub add_column: bool,
    pub drop_column: bool,
    pub rename_column: bool,
    pub alter_type: bool,
    pub alter_nullability: bool,
    pub alter_default: bool,
    pub alter_primary_key: bool,
    pub reorder_column: bool,
    pub comment: bool,
    pub create_index: bool,
    pub drop_index: bool,
    pub rebuild_index: bool,
    pub index_type: bool,
    pub index_include: bool,
    pub index_filter: bool,
    pub index_comment: bool,
    pub alter_strategy: AlterStrategy,
    pub dialect_id: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub index_methods: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "camelCase")]
pub enum AlterStrategy {
    #[default]
    None,
    Direct,
    SqliteRebuild,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum StructureChangeMode {
    Create,
    Alter,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct StructureColumnDraft {
    pub id: String,
    pub name: String,
    pub data_type: String,
    pub nullable: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_value: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub comment: Option<String>,
    #[serde(default)]
    pub is_primary_key: bool,
    #[serde(default)]
    pub is_auto_increment: bool,
    #[serde(default)]
    pub is_unique: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct StructureIndexDraft {
    pub id: String,
    pub name: String,
    pub columns: Vec<String>,
    pub is_unique: bool,
    #[serde(default)]
    pub is_primary: bool,
    #[serde(default)]
    pub index_type: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub include_columns: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub filter: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub comment: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct StructureChangeRequest {
    pub mode: StructureChangeMode,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema: Option<String>,
    pub table: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub original_columns: Vec<StructureColumnDraft>,
    pub current_columns: Vec<StructureColumnDraft>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub original_indexes: Vec<StructureIndexDraft>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub current_indexes: Vec<StructureIndexDraft>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum StatementRisk {
    Additive,
    Destructive,
    Rewrite,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct PlanStatement {
    pub sql: String,
    pub summary: String,
    pub risk: StatementRisk,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "camelCase")]
pub struct StructureChangePlan {
    pub statements: Vec<PlanStatement>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<String>,
}

#[cfg(test)]
mod backup_dump_options_tests {
    use super::*;

    #[test]
    fn backup_dump_options_default_is_all_false() {
        let opts = BackupDumpOptions::default();
        assert!(!opts.schema_only);
        assert!(!opts.data_only);
        assert!(!opts.clean);
        assert!(!opts.create_database);
        assert!(!opts.no_owner);
        assert!(!opts.single_transaction);
        assert!(!opts.routines);
        assert!(!opts.triggers);
    }

    #[test]
    fn backup_restore_options_default_is_all_false() {
        let opts = BackupRestoreOptions::default();
        assert!(!opts.single_transaction);
    }

    #[test]
    fn not_supported_display() {
        let err = DriverError::NotSupported("create_database".into());
        assert!(err.to_string().contains("Not supported"));
        assert!(err.to_string().contains("create_database"));
    }
}