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
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
# Dameng Rust SDK


A comprehensive Rust SDK for Dameng Database (DM8) with ODBC support.

![Crates.io](https://img.shields.io/crates/v/dameng_rust_sdk)
![License](https://img.shields.io/crates/l/dameng_rust_sdk)
![Rust](https://img.shields.io/badge/rust-1.70+-orange.svg)

## Features


- **Connection Management** - Robust connection handling with connection pooling support
-**CRUD Operations** - Complete support for Create, Read, Update, Delete operations
-**Transaction Support** - Full ACID transaction support with commit and rollback
-**Type-Safe Queries** - Type-safe query building with compile-time safety
-**Parameterized Queries** - Safe parameterized queries to prevent SQL injection
-**Error Handling** - Comprehensive error types with proper error propagation
-**Logging** - Built-in logging support using the `log` crate
-**Character Encoding** - Automatic GBK to UTF-8 conversion for Chinese character support
-**JSON Serialization** - Optional JSON serialization/deserialization support
-**TLS Support** - Secure database connections with TLS encryption

## Installation


Add this to your `Cargo.toml`:

```toml
[dependencies]
dameng_rust_sdk = "0.1.0"
```

Or install via cargo:

```bash
cargo add dameng_rust_sdk
```

## Quick Start


```rust
use dameng_rust_sdk::prelude::*;
use dameng_rust_sdk::ConnectionOptions;

fn main() -> Result<()> {
    // Create connection options
    let options = ConnectionOptions {
        server: "localhost".to_string(),
        port: 5236,
        username: "SYSDBA".to_string(),
        password: "your_password".to_string(),
        schema: "DMHR".to_string(),
        ..Default::default()
    };
    
    // Connect to database
    let mut conn = Connection::with_options(options)?;
    
    // Execute a simple query
    let mut result = conn.query("SELECT * FROM EMPLOYEES LIMIT 10")?;
    let rows = result.fetch_all()?;
    
    // Process results
    for row in rows {
        println!("{:?}", row);
    }
    
    // Use parameterized queries for safety
    use dameng_rust_sdk::prelude::parameter::InputParameter;
    
    let odbc_params: Vec<Box<dyn InputParameter>> = vec![
        Box::new("Alice".into_parameter()),
    ];
    
    let mut result = conn.query_with_param(
        "SELECT * FROM EMPLOYEES WHERE NAME = ?",
        odbc_params.as_slice()
    )?;
    
    let rows = result.fetch_all()?;
    for row in rows {
        println!("{:?}", row);
    }
    
    Ok(())
}
```

## Usage


### Basic Connection


```rust
use dameng_rust_sdk::{Connection, ConnectionOptions};

// Default connection
let mut conn = Connection::connect()?;

// Connection with custom options
let options = ConnectionOptions {
    server: "localhost".to_string(),
    port: 5236,
    username: "SYSDBA".to_string(),
    password: "password".to_string(),
    schema: "DMHR".to_string(),
    timeout: 30,
    use_tls: false,
    ..Default::default()
};

let mut conn = Connection::with_options(options)?;
```

### Query Operations


#### Simple SELECT Query


```rust
// Execute SELECT query
let mut result = conn.query("SELECT * FROM EMPLOYEES WHERE DEPARTMENT_ID = 1")?;

// Get column names
let columns = result.column_names()?;
println!("Columns: {:?}", columns);

// Fetch all rows
let rows = result.fetch_all()?;

// Access specific row
if let Some(row) = result.get_row(0) {
    println!("First row: {:?}", row);
}

// Access specific value
if let Some(value) = result.get_value(0, 0) {
    println!("First value: {:?}", value);
}
```

#### Parameterized SELECT Query


Use parameterized queries to prevent SQL injection and handle special characters safely:

```rust
use dameng_rust_sdk::prelude::parameter::InputParameter;

// Create parameters
let odbc_params: Vec<Box<dyn InputParameter>> = vec![
    Box::new("红楼梦".into_parameter()),  // String parameter
];

// Execute parameterized query with placeholders
let mut result = conn.query_with_param(
    "SELECT * FROM PRODUCTION.PRODUCT WHERE NAME = ?",
    odbc_params.as_slice()
)?;

let rows = result.fetch_all()?;
for row in rows {
    // Process each row
    for col in row {
        match col {
                    DamengValue::Null =>print!("Null\t"),
                    DamengValue::Int(r) => print!("{r}\t"),
                    DamengValue::BigInt(r) => print!("{r}\t"),
                    DamengValue::Float(r) => print!("{r}\t"),
                    DamengValue::String(r) => print!("{r}\t"),
                    DamengValue::Bool(r) => print!("{r}\t"),
                    DamengValue::Decimal(a, b, c) => print!("{a}.{b}.{c}\t"),
                    DamengValue::Date(naive_date) => print!("{}\t",naive_date.to_string()),
                    DamengValue::DateTime(naive_date_time) => print!("{}\t",naive_date_time.to_string()),
                    DamengValue::Binary(items) => print!("{:?}\t",items),
        }
    }
    println!();
}
```

#### Simple INSERT/UPDATE/DELETE


```rust
// INSERT
let sql = "INSERT INTO EMPLOYEES (NAME, DEPARTMENT_ID, SALARY) VALUES ('John Doe', 1, 50000)";
let result = conn.execute(sql)?;
println!("Insert successful: {}", result);

// UPDATE
let sql = "UPDATE EMPLOYEES SET SALARY = 55000 WHERE EMPLOYEE_ID = 1";
let result = conn.execute(sql)?;
println!("Update successful: {}", result);

// DELETE
let sql = "DELETE FROM EMPLOYEES WHERE EMPLOYEE_ID = 100";
let result = conn.execute(sql)?;
println!("Delete successful: {}", result);
```

#### Parameterized INSERT/UPDATE/DELETE


Use parameterized queries for dynamic values to prevent SQL injection:

```rust
use dameng_rust_sdk::prelude::parameter::InputParameter;

// Single parameter
let odbc_params: Vec<Box<dyn InputParameter>> = vec![
    Box::new(500.into_parameter()),  // Integer parameter
];

let result = conn.execute_with_param(
    "UPDATE PRODUCTION.PRODUCT_VENDOR SET STANDARDPRICE = ? WHERE PRODUCTID = 7",
    odbc_params.as_slice()
)?;
println!("Update successful: {}", result);

// Multiple parameters
let odbc_params: Vec<Box<dyn InputParameter>> = vec![
    Box::new(500.into_parameter()),   // First parameter
    Box::new(5.into_parameter()),     // Second parameter
];

let result = conn.execute_with_param(
    "UPDATE PRODUCTION.PRODUCT_VENDOR SET STANDARDPRICE = ? WHERE PRODUCTID = 7 AND VENDORID = ?",
    odbc_params.as_slice()
)?;
println!("Update successful: {}", result);
```

### Transaction Support


```rust
// Begin a transaction
conn.begin_transaction()?;

try {
    // Execute multiple operations
    conn.execute("INSERT INTO EMPLOYEES (NAME) VALUES ('Alice')")?;
    conn.execute("INSERT INTO EMPLOYEES (NAME) VALUES ('Bob')")?;
    
    // Commit if all operations succeed
    conn.commit()?;
} catch {
    // Rollback if any operation fails
    conn.rollback()?;
}
```

### Working with Different Data Types


The SDK supports various Dameng data types:

```rust
match value {
    DamengValue::Null => println!("NULL value"),
    DamengValue::Int(i) => println!("Integer: {}", i),
    DamengValue::BigInt(b) => println!("Big Integer: {}", b),
    DamengValue::Float(f) => println!("Float: {}", f),
    DamengValue::String(s) => println!("String: {}", s),
    DamengValue::Bool(b) => println!("Boolean: {}", b),
    DamengValue::Date(d) => println!("Date: {}", d),
    DamengValue::DateTime(dt) => println!("DateTime: {}", dt),
    DamengValue::Binary(bytes) => println!("Binary: {:?}", bytes),
    _ => println!("Other value"),
}
```

### Database Information


```rust
let db_info = conn.database_info()?;
println!("DBMS: {}", db_info.dbms_name);
println!("Database: {}", db_info.db_name);
println!("Driver: {}", db_info.driver_name);
println!("Driver Version: {}", db_info.driver_version);
```

### Using DamengClient


For advanced usage, use the `DamengClient` which provides additional functionality:

```rust
use dameng_rust_sdk::prelude::*;
use dameng_rust_sdk::ConnectionOptions;
use log::info;
use env_logger::Env;

fn main() -> dameng_rust_sdk::Result<()> {
    // Initialize logging
    env_logger::Builder::from_env(Env::default().default_filter_or("info")).init();
    
    // Create connection options
    let options = ConnectionOptions {
        server: "localhost".to_string(),
        port: 5236,
        username: "SYSDBA".to_string(),
        password: "your_password".to_string(),
        schema: "PRODUCTION".to_string(),
        ..Default::default()
    };
    
    // Create client
    let client = DamengClient::new(options)?;
    
    // Test connection
    client.test_connection()?;
    info!("✓ Connection test successful");
    
    // Get database information
    let db_info = client.database_info()?;
    info!("✓ Database Information:");
    info!("  DBMS: {}", db_info.dbms_name);
    info!("  Database: {}", db_info.db_name);
    info!("  Driver: {} {}", db_info.driver_name, db_info.driver_version);
    
    // Connect to database
    let mut conn = client.connect()?;
    info!("✓ Connected to database");
    
    // Now you can use the connection for queries
    use dameng_rust_sdk::prelude::parameter::InputParameter;
    
    let odbc_params: Vec<Box<dyn InputParameter>> = vec![
        Box::new("红楼梦".into_parameter()),
    ];
    
    let mut result = conn.query_with_param(
        "SELECT * FROM PRODUCTION.PRODUCT WHERE NAME = ?",
        odbc_params.as_slice()
    )?;
    
    let rows = result.fetch_all()?;
    info!("✓ Query executed successfully");
    
    Ok(())
}
```

### Using Query Builder


```rust
let builder = conn.query_builder();
// Query builder functionality (implementation depends on version)
```

### Logging


Enable logging by setting the `RUST_LOG` environment variable:

```bash
RUST_LOG=info cargo run
```

```rust
use env_logger::Env;

fn main() -> Result<()> {
    env_logger::Builder::from_env(Env::default().default_filter_or("info")).init();
    // Your code here
}
```

## Configuration


### Connection Options


| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `server` | `String` | `"localhost"` | Database server address |
| `port` | `u16` | `5236` | Database port |
| `username` | `String` | `"SYSDBA"` | Database username |
| `password` | `String` | `""` | Database password |
| `schema` | `String` | `"DMHR"` | Database schema |
| `timeout` | `u32` | `30` | Connection timeout in seconds |
| `use_tls` | `bool` | `false` | Enable TLS encryption |
| `additional_params` | `Vec<(String, String)>` | `[]` | Additional connection parameters |

### Features


- `default` - Includes TLS and JSON support
- `full` - Includes all features (TLS, JSON, serde, env_logger)
- `tls` - TLS encryption support
- `json` - JSON serialization support

```toml
# Use specific features

[dependencies]
dameng_rust_sdk = { version = "0.1.0", features = ["full"] }
```

## Examples


### Run Demo


The SDK includes a demo application:

```bash
cargo run --bin dameng_demo --features full
```

### Example Projects


See the `examples/` directory for more usage examples.

## Error Handling


The SDK uses the `Result<T>` type for error handling:

```rust
use dameng_rust_sdk::Error;

match result {
    Ok(data) => println!("Success: {:?}", data),
    Err(Error::Connection(msg)) => eprintln!("Connection error: {}", msg),
    Err(Error::Query(msg)) => eprintln!("Query error: {}", msg),
    Err(Error::Transaction(msg)) => eprintln!("Transaction error: {}", msg),
    Err(e) => eprintln!("Other error: {}", e),
}
```

## Character Encoding


The SDK automatically handles GBK to UTF-8 conversion for Chinese character support. This is particularly useful when working with Dameng databases containing Chinese data.

## Prerequisites


1. **Rust** - Install Rust 1.70 or later from [rustup.rs]https://rustup.rs/
2. **Dameng Database** - Install and configure Dameng Database (DM8)
3. **ODBC Driver** - Install DM8 ODBC DRIVER

### Installing ODBC Driver


1. Download DM8 ODBC Driver from the Dameng official website
2. Follow the installation instructions for your operating system
3. Configure the ODBC Data Source (DSN) if needed

## Troubleshooting


### Connection Issues


If you encounter connection errors:

1. Verify the Dameng database is running
2. Check the server address and port
3. Ensure the username and password are correct
4. Verify the schema exists
5. Check ODBC driver installation

### Character Encoding Issues


If you see garbled Chinese characters:

- The SDK automatically handles GBK to UTF-8 conversion
- Ensure your database character set is properly configured

### Performance Tips


- Use connection pooling for production applications
- Use transactions for multiple related operations
- Optimize your SQL queries with proper indexing
- Use LIMIT clauses to reduce data transfer

## API Documentation


Full API documentation is available on [docs.rs](https://docs.rs/dameng_rust_sdk)

## Contributing


Contributions are welcome! Please follow these guidelines:

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

### Development


```bash
# Clone the repository

git clone https://github.com/your-username/dameng_rust_sdk.git
cd dameng_rust_sdk

# Run tests

cargo test

# Run examples

cargo run --example example_name

# Build documentation

cargo doc --open
```

## License


This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Support


- 📧 Email: andrew@out.com
- 📖 Documentation: [docs.rs]https://docs.rs/dameng_rust_sdk
- 🐛 Issue Tracker: [GitHub Issues]https://github.com/your-username/dameng_rust_sdk/issues
- 💬 Discussions: [GitHub Discussions]https://github.com/your-username/dameng_rust_sdk/discussions

## Acknowledgments


- Built with [odbc-api]https://github.com/pkrempa/odbc-api
- Character encoding support via [encoding_rs]https://github.com/hsivonen/encoding_rs
- Error handling with [thiserror]https://github.com/dtolnay/thiserror

## Roadmap


- [ ] Connection pooling
- [ ] Async support
- [ ] Stored procedure support
- [ ] Batch operations
- [ ] Query builder enhancements
- [ ] ORM-like features
- [ ] Migration tools

## Changelog


See [CHANGELOG.md](CHANGELOG.md) for a list of changes in each version.

---

**Made with ❤️ in Rust**