dmsc/c/database.rs
1//! Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
2//!
3//! This file is part of DMSC.
4//! The DMSC project belongs to the Dunimd Team.
5//!
6//! Licensed under the Apache License, Version 2.0 (the "License");
7//! You may not use this file except in compliance with the License.
8//! You may obtain a copy of the License at
9//!
10//! http://www.apache.org/licenses/LICENSE-2.0
11//!
12//! Unless required by applicable law or agreed to in writing, software
13//! distributed under the License is distributed on an "AS IS" BASIS,
14//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15//! See the License for the specific language governing permissions and
16//! limitations under the License.
17
18//! # Database Module C API
19//!
20//! This module provides C language bindings for DMSC's database subsystem. The database
21//! module delivers unified database access patterns across multiple database backends,
22//! including PostgreSQL, MySQL, SQLite, and Redis. This C API enables C/C++ applications
23//! to leverage DMSC's sophisticated database management capabilities including connection
24//! pooling, transaction management, query building, and result set handling.
25//!
26//! ## Module Architecture
27//!
28//! The database module comprises three primary components that together provide a complete
29//! database access layer:
30//!
31//! - **DMSCDatabaseConfig**: Configuration container for database connection parameters.
32//! Manages connection strings, pool sizes, timeout settings, and backend-specific options.
33//! The configuration object is required for initializing database pools and controls
34//! resource allocation and behavior characteristics for all database operations.
35//!
36//! - **DMSCDatabasePool**: Connection pool management interface providing efficient
37//! database connection reuse across multiple concurrent requests. The pool implements
38//! dynamic scaling, health checking, and automatic reconnection for maintaining
39//! reliable database connectivity. Connection pooling significantly improves performance
40//! by avoiding the overhead of establishing new connections for each operation.
41//!
42//! - **DMSCDBRow**: Result row abstraction providing type-safe access to query results.
43//! The row object supports column-by-column access with automatic type conversion.
44//! Multiple rows are typically returned as a collection that can be iterated efficiently.
45//!
46//! ## Supported Databases
47//!
48//! The database module provides native support for:
49//!
50//! - **PostgreSQL**: Full-featured relational database with advanced data types,
51//! JSON support, and powerful query capabilities. Accessed via sqlx with
52//! async/await support and connection pooling.
53//!
54//! - **MySQL**: Popular relational database with high performance and wide adoption.
55//! Supports replication, partitioning, and stored procedures through sqlx.
56//!
57//! - **SQLite**: Embedded database requiring no separate server process. Ideal for
58//! local storage, testing, and applications with modest concurrency requirements.
59//!
60//! - **Redis**: In-memory data store used for caching, session storage, and
61//! message queuing. Accessed through the Redis protocol with pub/sub support.
62//!
63//! ## Connection Pooling
64//!
65//! The connection pool implementation provides:
66//!
67//! - **Dynamic Sizing**: Pool size adjusts based on demand up to configured maximum.
68//! Idle connections are released when not needed to conserve resources.
69//!
70//! - **Health Checking**: Connections are validated before use to detect stale or
71//! broken connections. Failed connections are automatically recreated.
72//!
73//! - **Connection Lifetime**: Connections have maximum lifetime limits to prevent
74//! resource exhaustion. Long-lived connections are periodically refreshed.
75//!
76//! - **Wait Semantics**: When pool is exhausted, requests can either wait for a
77//! connection or fail immediately based on configuration.
78//!
79//! ## Transaction Management
80//!
81//! Full transaction support includes:
82//!
83//! - **Explicit Transactions**: BEGIN, COMMIT, ROLLBACK control for fine-grained
84//! transaction boundaries.
85//!
86//! - **Savepoints**: Nested transaction support with savepoint rollback capabilities
87//! for partial transaction recovery.
88//!
89//! - **Isolation Levels**: Configurable isolation levels (Read Committed, Repeatable
90//! Read, Serializable) matching database capabilities.
91//!
92//! - **Auto-Commit Mode**: Per-statement execution with automatic commit for
93//! simple operations without transaction overhead.
94//!
95//! ## Query Operations
96//!
97//! The module provides comprehensive query capabilities:
98//!
99//! - **Prepared Statements**: Pre-compiled queries for repeated execution with
100//! parameter binding and automatic type conversion.
101//!
102//! - **Query Builder**: Fluent API for constructing queries programmatically
103//! without raw SQL string manipulation.
104//!
105//! - **Batch Operations**: Efficient bulk inserts and updates with transaction
106//! batching for high-throughput data loading.
107//!
108//! - **Streaming Results**: Large result sets can be streamed row-by-row to
109//! minimize memory footprint for big queries.
110//!
111//! ## Memory Management
112//!
113//! All C API objects use opaque pointers with manual memory management:
114//!
115//! - Constructor functions allocate new instances on the heap
116//! - Destructor functions must be called to release memory
117//! - Result sets must be properly iterated and freed
118//! - Null pointer checks are required before all operations
119//!
120//! ## Thread Safety
121//!
122//! The underlying implementations are thread-safe:
123//!
124//! - Connection pools support concurrent access from multiple threads
125//! - Individual connections are not thread-safe (use pool for concurrency)
126//! - Query execution and result processing require synchronization
127//!
128//! ## Performance Characteristics
129//!
130//! Database operations have the following performance profiles:
131//!
132//! - Connection acquisition: O(1) average case
133//! - Simple query execution: O(log n) for query planning, O(n) for results
134//! - Bulk operations: O(n) with batching optimizations
135//! - Connection reuse: Eliminates ~10ms connection establishment overhead
136//!
137//! ## Error Handling
138//!
139//! Database operations use error codes and optional error messages:
140//!
141//! - Success/failure indication through return values
142//! - Detailed error messages available for debugging
143//! - Connection failures trigger automatic retry (configurable)
144//! - Deadlock detection and transaction restart
145//!
146//! ## Usage Example
147//!
148//! ```c
149//! // Create database configuration
150//! DMSCDatabaseConfig* config = dmsc_database_config_new();
151//! dmsc_database_config_set_connection_string(config, "postgresql://localhost/mydb");
152//! dmsc_database_config_set_pool_size(config, 10);
153//!
154//! // Create connection pool
155//! DMSCDatabasePool* pool = dmsc_database_pool_new(config);
156//!
157//! // Execute query
158//! DMSCDBRow* row;
159//! int result = dmsc_database_pool_query(pool, "SELECT * FROM users WHERE id = $1", 1, &row);
160//!
161//! if (result == 0) {
162//! // Process row
163//! char* name = dmsc_db_row_get_string(row, "name");
164//! int age = dmsc_db_row_get_int(row, "age");
165//!
166//! // Cleanup row
167//! dmsc_db_row_free(row);
168//! }
169//!
170//! // Cleanup
171//! dmsc_database_pool_free(pool);
172//! dmsc_database_config_free(config);
173//! ```
174//!
175//! ## Dependencies
176//!
177//! This module depends on the following DMSC components:
178//!
179//! - `crate::database`: Rust database module implementation
180//! - `crate::prelude`: Common types and traits
181//!
182//! ## Feature Flags
183//!
184//! Database support is enabled through individual feature flags:
185//!
186//! - "postgres": PostgreSQL database support
187//! - "mysql": MySQL database support
188//! - "sqlite": SQLite database support
189//! - Disable features to reduce binary size
190
191use crate::database::{DMSCDatabaseConfig, DMSCDatabasePool, DMSCDBRow};
192
193
194c_wrapper!(CDMSCDatabaseConfig, DMSCDatabaseConfig);
195
196c_wrapper!(CDMSCDatabasePool, DMSCDatabasePool);
197
198c_wrapper!(CDMSCDBRow, DMSCDBRow);
199
200c_constructor!(dmsc_database_config_new, CDMSCDatabaseConfig, DMSCDatabaseConfig, DMSCDatabaseConfig::default());
201
202c_destructor!(dmsc_database_config_free, CDMSCDatabaseConfig);