dameng_rust_sdk 0.1.0

A Rust SDK for Dameng Database (DM8) with ODBC support
Documentation
# 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
-**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 query
    let mut result = conn.query("SELECT * FROM EMPLOYEES LIMIT 10")?;
    let rows = result.fetch_all()?;
    
    // Process results
    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


#### 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);
}
```

#### INSERT Operation


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

#### UPDATE Operation


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

#### DELETE Operation


```rust
let sql = "DELETE FROM EMPLOYEES WHERE EMPLOYEE_ID = 100";
let result = conn.execute(sql)?;
println!("Delete 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 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**