dameng_rust_sdk 0.1.3

A Rust SDK for Dameng Database (DM8) with ODBC support
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
//! Connection management for Dameng Rust SDK

use std::fmt;
use odbc_api::{Connection as OdbcConnection, Environment, Cursor, ResultSetMetadata, ConnectionOptions as OdbcConnectionOptions, handles::StatementImpl};
use log::{debug, warn};

use crate::error::{Error, Result as SdkResult};
use crate::types::{DamengValue};
use crate::query::QueryBuilder;

/// Convert GBK bytes to UTF-8 string
fn gbk_to_utf8(bytes: &[u8]) -> SdkResult<String> {
    use encoding_rs::GBK;
    
    // Try UTF-8 first (fallback for data that's already UTF-8)
    if let Ok(s) = std::str::from_utf8(bytes) {
        return Ok(s.to_string());
    }
    
    // Use GBK decoder from encoding_rs
    let (decoded, _, _) = GBK.decode(bytes);
    
    Ok(decoded.to_string())
}

/// Connection options for Dameng database
#[derive(Debug, Clone)]
pub struct ConnectionOptions {
    /// Database server address
    pub server: String,
    /// Database port
    pub port: u16,
    /// Database username
    pub username: String,
    /// Database password
    pub password: String,
    /// Database schema
    pub schema: String,
    /// Connection timeout in seconds
    pub timeout: u32,
    /// Whether to use TLS
    pub use_tls: bool,
    /// Additional connection parameters
    pub additional_params: Vec<(String, String)>,
    ///DRIVER
    pub driver:String,
}

impl Default for ConnectionOptions {
    fn default() -> Self {
        Self {
            server: "localhost".to_string(),
            port: 5236,
            username: "SYSDBA".to_string(),
            driver:"{DM8 ODBC DRIVER}".to_string(),
            password: "".to_string(),
            schema: "DMHR".to_string(),
            timeout: 30,
            use_tls: false,
            additional_params: Vec::new(),
        }
    }
}

impl fmt::Display for ConnectionOptions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "ConnectionOptions {{ server: {}, port: {}, username: {}, schema: {}, timeout: {}s, use_tls: {} }}",
            self.server, self.port, self.username, self.schema, self.timeout, self.use_tls
        )
    }
}

/// Transaction handle
pub struct Transaction {
    _inner: (),
}

/// Connection to Dameng database
pub struct Connection {
    _environment: Environment,
    _inner: Option<OdbcConnection<'static>>,
    options: ConnectionOptions,
}
use odbc_api::IntoParameter;
impl Connection {
    /// Create a new connection (returns a placeholder for now)
    pub fn connect() -> SdkResult<Self> {
        Self::with_options(ConnectionOptions::default())
    }
    
    /// Create a new connection with options
    pub fn with_options(options: ConnectionOptions) -> SdkResult<Self> {
        debug!("Creating connection with options: {}", options);
        
        // Build connection string
        let connection_string = build_connection_string(&options);
        debug!("Connection string: {}", mask_password(&connection_string));
        
        // Create a static environment for the connection
        let environment = Environment::new()
            .map_err(|e| Error::connection(format!("Failed to create ODBC environment: {}", e)))?;
        
        // Leak the environment to give it a 'static lifetime
        // This is necessary because ODBC connections must outlive their environment
        let env_ref: &'static Environment = Box::leak(Box::new(environment));
        
        // Establish connection
        let connection = env_ref.connect_with_connection_string(&connection_string, OdbcConnectionOptions::default())
            .map_err(|e| Error::connection(format!("Failed to connect to database: {}", e)))?;
        
        debug!("Successfully connected to database");
        
        // Store a reference to the leaked environment
        // Note: This will leak memory, but it's acceptable for the lifetime of the application
        Ok(Self {
            _environment: Environment::new().unwrap(), // Placeholder
            _inner: Some(connection),
            options,
        })
    }
    
    /// Get connection options
    pub fn options(&self) -> &ConnectionOptions {
        &self.options
    }
    
        /// Execute a SQL query with parameters
    /// 
    /// # Arguments
    /// * `sql` - The SQL query string
    /// * `params` - Parameters implementing the `odbc_api::Parameter` trait (e.g., tuples)
    /// 
    /// # Example
    /// ```ignore
    /// // Using a tuple for parameters
    /// let result = conn.query_with_param("SELECT * FROM city WHERE name = ?", (&"Beijing",))?;
    /// ```
    pub fn query_with_param<P>(&mut self, sql: &str, params: P) -> SdkResult<QueryResult>
    where
    P:  odbc_api::ParameterCollectionRef,
    {
        debug!("Executing parametrized query: {}", sql);
        
        // Execute query with parameters and get cursor
        let cursor = self._inner.as_mut()
            .ok_or_else(|| Error::connection("Connection not established".to_string()))?
            .execute(sql, params)
            .map_err(|e| Error::query(format!("Failed to execute query with params: {}", e)))?
            .ok_or_else(|| Error::query("Query did not return a result set".to_string()))?;
        
        // Create query result and fetch all data immediately
        QueryResult::from_cursor(cursor, sql)
    }
    
    /// Execute a SQL statement with parameters (INSERT, UPDATE, DELETE)
    /// 
    /// # Arguments
    /// * `sql` - The SQL statement string
    /// * `params` - Parameters implementing the `odbc_api::Parameter` trait
    /// 
    /// # Example
    /// ```ignore
    /// conn.execute_with_param("INSERT INTO t1 VALUES (?, ?)", (1, "test"))?;
    /// ```
    pub fn execute_with_param<P>(&mut self, sql: &str, params: P) -> SdkResult<bool>
    where
        P: odbc_api::ParameterCollectionRef,
    {
        debug!("Executing parametrized statement: {}", sql);
        
        let conn = self._inner.as_mut()
            .ok_or_else(|| Error::connection("Connection not established".to_string()))?;
        
        // Execute the statement with parameters
        let result = conn.execute(sql, params);
        
        match result {
            Ok(_) => Ok(true),
            Err(e) => Err(Error::query(format!("Failed to execute statement with params: {}", e))),
        }
    }


    /// Execute a SQL query
    pub fn query(&mut self, sql: &str) -> SdkResult<QueryResult> {
        debug!("Executing query: {}", sql);
        
        // Execute query and get cursor
        let cursor = self._inner.as_mut()
            .ok_or_else(|| Error::connection("Connection not established".to_string()))?
            .execute(sql, ())
            .map_err(|e| Error::query(format!("Failed to execute query: {}", e)))?
            .ok_or_else(|| Error::query("Query did not return a result set".to_string()))?;
        
        // Create query result and fetch all data immediately
        QueryResult::from_cursor(cursor, sql)
    }
    
    /// Execute a SQL statement (INSERT, UPDATE, DELETE)
    pub fn execute(&mut self, sql: &str) -> SdkResult<bool> {
        debug!("Executing statement: {}", sql);
        
        let conn = self._inner.as_mut()
            .ok_or_else(|| Error::connection("Connection not established".to_string()))?;
        
        // Execute the statement
        let cursor = self._inner.as_mut()
        .ok_or_else(|| Error::connection("Connection not established".to_string()))?
        .execute(sql, ());
        Ok(cursor.is_ok())
    }
    
    /// Begin a transaction
    pub fn begin_transaction(&mut self) -> SdkResult<Transaction> {
        debug!("Beginning transaction");
        
        let conn = self._inner.as_mut()
            .ok_or_else(|| Error::connection("Connection not established".to_string()))?;
        
        // Set autocommit to false to begin a transaction
        conn.set_autocommit(false)
            .map_err(|e| Error::transaction(format!("Failed to begin transaction: {}", e)))?;
        
        Ok(Transaction { _inner: () })
    }
    
    /// Commit current transaction
    pub fn commit(&mut self) -> SdkResult<()> {
        debug!("Committing transaction");
        
        let conn = self._inner.as_mut()
            .ok_or_else(|| Error::connection("Connection not established".to_string()))?;
        
        conn.commit()
            .map_err(|e| Error::transaction(format!("Failed to commit transaction: {}", e)))?;
        
        // Set autocommit back to true
        conn.set_autocommit(true)
            .map_err(|e| Error::transaction(format!("Failed to set autocommit after commit: {}", e)))?;
        
        Ok(())
    }
    
    /// Rollback current transaction
    pub fn rollback(&mut self) -> SdkResult<()> {
        debug!("Rolling back transaction");
        
        let conn = self._inner.as_mut()
            .ok_or_else(|| Error::connection("Connection not established".to_string()))?;
        
        conn.rollback()
            .map_err(|e| Error::transaction(format!("Failed to rollback transaction: {}", e)))?;
        
        // Set autocommit back to true
        conn.set_autocommit(true)
            .map_err(|e| Error::transaction(format!("Failed to set autocommit after rollback: {}", e)))?;
        
        Ok(())
    }
    
    /// Create a query builder
    pub fn query_builder(&self) -> QueryBuilder {
        QueryBuilder::new()
    }
    
    /// Get database information
    pub fn database_info(&self) -> SdkResult<DatabaseInfo> {
        // Return database info based on connection options
        Ok(DatabaseInfo {
            dbms_name: "Dameng DB".to_string(),
            db_name: self.options.schema.clone(),
            driver_name: "DM8 ODBC DRIVER".to_string(),
            driver_version: "8.1.4".to_string(),
        })
    }
}

/// Database information
#[derive(Debug, Clone)]
pub struct DatabaseInfo {
    /// Database management system name
    pub dbms_name: String,
    /// Database name
    pub db_name: String,
    /// Driver name
    pub driver_name: String,
    /// Driver version
    pub driver_version: String,
}

impl fmt::Display for DatabaseInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "DatabaseInfo {{ dbms: {}, name: {}, driver: {} {} }}",
            self.dbms_name, self.db_name, self.driver_name, self.driver_version
        )
    }
}

/// Query result
#[derive(Debug, Clone)]
pub struct QueryResult {
    sql: String,
    columns: Vec<String>,
    rows: Vec<Vec<DamengValue>>,
}

impl QueryResult {
    /// Create a new query result from cursor (simplified for now)
    fn from_cursor<C>(mut cursor: odbc_api::CursorImpl<C>, sql: &str) -> SdkResult<Self>
    where
        C: odbc_api::handles::AsStatementRef,
    {
        use odbc_api::buffers::TextRowSet;
        
        // Get column count
        let num_cols = cursor.num_result_cols()
            .map_err(|e| Error::query(format!("Failed to get column count: {}", e)))? as usize;
        
        // Get column names
        let mut columns = Vec::with_capacity(num_cols);
        for col_index in 1..=num_cols as u16 {
            let name = cursor.col_name(col_index)
                .map_err(|e| Error::query(format!("Failed to get column name: {}", e)))?;
            columns.push(name);
        }
        
        // If no columns or no data, return empty result
        if num_cols == 0 {
            return Ok(Self {
                sql: sql.to_string(),
                columns,
                rows: Vec::new(),
            });
        }
        
        // Create buffer for text access with reasonable batch size
        let batch_size = 250;
        let max_str_len = 4000;
        let mut buffer = TextRowSet::for_cursor(batch_size, &mut cursor, Some(max_str_len))
            .map_err(|e| Error::query(format!("Failed to create text buffer: {}", e)))?;
        
        // Bind buffer and fetch
        let mut block_cursor = cursor.bind_buffer(&mut buffer)
            .map_err(|e| Error::query(format!("Failed to bind buffer: {}", e)))?;
        
        let mut rows = Vec::new();
        
        // Fetch data in batches
        while let Some(batch) = block_cursor.fetch()
            .map_err(|e| Error::query(format!("Failed to fetch batch: {}", e)))?
        {
            let num_rows = batch.num_rows();
            
            for row_idx in 0..num_rows {
                let mut row = Vec::with_capacity(num_cols);
                
                for col_idx in 0..num_cols {
                    let text = batch.at(col_idx, row_idx);
                    if let Some(text_bytes) = text {
                        // Use GBK to UTF-8 conversion
                        let string_value = gbk_to_utf8(text_bytes)?;
                        row.push(DamengValue::String(string_value));
                    } else {
                        row.push(DamengValue::Null);
                    }
                }
                
                rows.push(row);
            }
        }
        
        Ok(Self {
            sql: sql.to_string(),
            columns,
            rows,
        })
    }
    
    /// Create a new query result
    pub fn new() -> Self {
        Self {
            sql: String::new(),
            columns: Vec::new(),
            rows: Vec::new(),
        }
    }
    
    /// Get the number of columns
    pub fn num_columns(&self) -> SdkResult<usize> {
        Ok(self.columns.len())
    }
    
    /// Get column names
    pub fn column_names(&self) -> SdkResult<Vec<String>> {
        Ok(self.columns.clone())
    }
    
    /// Get the number of rows
    pub fn num_rows(&self) -> usize {
        self.rows.len()
    }
    
    /// Fetch all rows
    pub fn fetch_all(&mut self) -> SdkResult<Vec<Vec<DamengValue>>> {
        Ok(self.rows.clone())
    }
    
    /// Get a specific row by index
    pub fn get_row(&self, index: usize) -> Option<&Vec<DamengValue>> {
        self.rows.get(index)
    }
    
    /// Get a specific value by row and column index
    pub fn get_value(&self, row: usize, col: usize) -> Option<&DamengValue> {
        self.rows.get(row)?.get(col)
    }
}

/// Build ODBC connection string from options
fn build_connection_string(options: &ConnectionOptions) -> String {
    let mut parts = vec![
        format!("DRIVER={}",options.driver),
        format!("SERVER={}", options.server),
        format!("PORT={}", options.port),
        format!("UID={}", options.username),
        format!("PWD={}", options.password),
        format!("DATABASE={}", options.schema),
    ];
    
    // Add TLS parameter if enabled
    if options.use_tls {
        parts.push("ENCRYPT=yes".to_string());
    }
    
    // Add additional parameters
    for (key, value) in &options.additional_params {
        parts.push(format!("{}={}", key, value));
    }
    
    parts.join(";")
}

/// Mask password in connection string for logging
fn mask_password(connection_string: &str) -> String {
    // Simple password masking for logging
    let parts: Vec<&str> = connection_string.split(';').collect();
    let masked_parts: Vec<String> = parts
        .iter()
        .map(|part| {
            if part.starts_with("PWD=") || part.starts_with("PASSWORD=") {
                // Mask the password value
                if let Some((key, _)) = part.split_once('=') {
                    format!("{}=*****", key)
                } else {
                    part.to_string()
                }
            } else {
                part.to_string()
            }
        })
        .collect();
    
    masked_parts.join(";")
}

impl Transaction {
    /// Commit the transaction (requires calling commit() on the connection instead)
    #[deprecated(note = "Use Connection::commit() instead")]
    pub fn commit(&mut self) -> SdkResult<()> {
        Ok(())
    }
    
    /// Rollback the transaction (requires calling rollback() on the connection instead)
    #[deprecated(note = "Use Connection::rollback() instead")]
    pub fn rollback(&mut self) -> SdkResult<()> {
        Ok(())
    }
}