Module database

Module database 

Source
Expand description

Database abstraction layer with multiple backend support Copyright © 2025-2026 Wenze Wei. All Rights Reserved.

This file is part of DMSC. The DMSC project belongs to the Dunimd Team.

Licensed under the Apache License, Version 2.0 (the “License”); You may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

§Database Module

This module provides a comprehensive database abstraction layer for DMSC, supporting multiple database backends with a unified interface.

§Key Components

  • DMSCDatabase: Trait defining the database interface for all supported databases
  • DMSCDatabasePool: Connection pool management with automatic reuse and health checks
  • DMSCDatabaseConfig: Builder-style configuration for database connections
  • DMSCDatabaseMigrator: Database schema migration management
  • DMSCDBRow: Row representation with type-safe column access
  • DMSCDBResult: Query result set with iterator support
  • DMSCDatabaseTransaction: ACID transaction support for data integrity

§Supported Databases

  • PostgreSQL - Enterprise-grade relational database with full feature support
  • MySQL - Popular open-source database with high performance
  • SQLite - Embedded database for lightweight scenarios

§Features

  • Connection Pooling: Efficient connection reuse with configurable pool size
  • Async/Await: Full asynchronous API using Tokio runtime
  • Parameter Binding: Safe SQL parameter binding to prevent injection attacks
  • Batch Operations: Efficient bulk insert/update operations
  • Transactions: ACID-compliant transaction support
  • Migrations: Version-controlled schema migrations
  • Type Conversion: Automatic conversion between database and JSON types

§Usage Example

use dmsc::database::{DMSCDatabase, DMSCDatabaseConfig, PooledDatabase};

#[tokio::main]
async fn main() -> DMSCResult<()> {
    let config = DMSCDatabaseConfig::postgres()
        .host("localhost")
        .port(5432)
        .database("mydb")
        .user("user")
        .password("pass")
        .max_connections(10)
        .min_idle_connections(2)
        .connection_timeout_secs(30)
        .build();

    let pool = DMSCDatabasePool::new(config).await?;
    let db = pool.get().await?;

    // Execute a query with parameter binding
    use serde_json::json;
    let rows = db.query("SELECT * FROM users WHERE id = $1", &[&json!(1)]).await?;
    for row in rows {
        let id: i64 = row.get("id");
        let name: String = row.get("name");
        println!("User: {} - {}", id, name);
    }

    Ok(())
}

§Batch Operations Example

use dmsc::database::{DMSCDatabasePool, DMSCDatabaseConfig};

#[tokio::main]
async fn main() -> DMSCResult<()> {
    let config = DMSCDatabaseConfig::postgres()
        .host("localhost")
        .database("mydb")
        .build();

    let pool = DMSCDatabasePool::new(config).await?;
    let db = pool.get().await?;

    // Batch insert users
    let users = vec![
        vec![serde_json::json!("alice"), serde_json::json!("alice@example.com")],
        vec![serde_json::json!("bob"), serde_json::json!("bob@example.com")],
        vec![serde_json::json!("charlie"), serde_json::json!("charlie@example.com")],
    ];

    let results = db.batch_execute(
        "INSERT INTO users (name, email) VALUES ($1, $2)",
        &users
    ).await?;

    println!("Inserted {} rows", results.len());
    Ok(())
}

§Transaction Example

use dmsc::database::{DMSCDatabasePool, DMSCDatabaseConfig};

#[tokio::main]
async fn main() -> DMSCResult<()> {
    let config = DMSCDatabaseConfig::postgres()
        .host("localhost")
        .database("mydb")
        .build();

    let pool = DMSCDatabasePool::new(config).await?;
    let db = pool.get().await?;

    // Start transaction
    let mut tx = db.transaction().await?;

    // Execute operations within transaction
    tx.execute("UPDATE accounts SET balance = balance - 100 WHERE id = $1", &[&1]).await?;
    tx.execute("UPDATE accounts SET balance = balance + 100 WHERE id = $1", &[&2]).await?;

    // Commit transaction
    tx.commit().await?;

    Ok(())
}

Re-exports§

pub use orm::QueryBuilder;
pub use orm::Criteria;
pub use orm::SortOrder;
pub use orm::Pagination;
pub use orm::ComparisonOperator;
pub use orm::TableDefinition;
pub use orm::ColumnDefinition;
pub use orm::IndexDefinition;
pub use orm::ForeignKeyDefinition;
pub use orm::DMSCORMSimpleRepository;
pub use orm::DMSCORMCrudRepository;
pub use orm::DMSCORMRepository;

Modules§

mysql
Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
orm
Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
postgres
Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
sqlite
Copyright © 2025-2026 Wenze Wei. All Rights Reserved.

Structs§

DMSCDBResult
DMSCDBRow
DMSCDatabaseConfig
Configuration for database connections in DMSC.
DMSCDatabaseMigration
DMSCDatabaseMigrator
DMSCDatabasePool
DMSCMigrationHistory
DatabaseMetrics
PooledDatabase

Enums§

DMSCDatabaseTransactionError
DatabaseType
Enumeration of supported database engine types.

Traits§

DMSCDatabase
Trait defining the database interface for all supported databases.
DMSCDatabaseTransaction
Trait representing a database transaction.