## Overview
The DAP Global DB module provides a comprehensive distributed database infrastructure for the DAP ecosystem. This module implements high-performance data storage, replication, synchronization, and consensus mechanisms essential for maintaining consistent state across distributed blockchain networks and decentralized applications.
**Based on:** `dap-sdk/global-db/include/dap_global_db.h`, `dap-sdk/global-db/src/dap_global_db.c`
## Document Structure
- [[#Overview|Overview]]
- [[#Module Structures|Module Structures]]
- [[#dap_global_db_t|dap_global_db_t - Database Context]]
- [[#dap_db_transaction_t|dap_db_transaction_t - Transaction Management]]
- [[#dap_db_record_t|dap_db_record_t - Data Record]]
- [[#dap_db_index_t|dap_db_index_t - Database Index]]
- [[#dap_db_sync_t|dap_db_sync_t - Synchronization Context]]
- [[#Module Functions|Module Functions]]
- [[#Database Management Functions|Database System Management]]
- [[#Transaction Operations|Transaction Processing]]
- [[#Data Operations|Record Management]]
- [[#Synchronization Functions|Data Synchronization]]
- [[#Error Codes|Error Codes]]
- [[#Typical Examples|Typical Examples]]
## Module Structures
### dap_global_db_t
Core global database context managing distributed data storage.
```c
typedef struct dap_global_db {
struct {
char *db_name; // Database identifier name
dap_db_type_t type; // Database type (local, distributed)
uint32_t node_count; // Number of participating nodes
bool is_synchronized; // Synchronization status
uint64_t total_records; // Total number of records
dap_time_t last_sync_time; // Last synchronization timestamp
dap_db_consensus_t consensus_type; // Consensus mechanism used
} pub;
struct {
dap_htable_t *tables; // Database tables hash table
dap_htable_t *indexes; // Index structures hash table
dap_list_t *active_transactions; // Currently active transactions
dap_db_storage_t *storage_engine; // Storage backend engine
dap_db_cache_t *cache_manager; // Caching system
pthread_rwlock_t db_lock; // Database-wide read-write lock
dap_db_replication_t *replication; // Replication management
dap_timer_t *sync_timer; // Periodic synchronization timer
} priv;
} dap_global_db_t;
```
**Public Fields:**
- `db_name` - Unique database identifier for network operations
- `type` - Database type (local storage, distributed, hybrid)
- `node_count` - Number of nodes participating in database consensus
- `is_synchronized` - Current synchronization status across network
- `total_records` - Total number of records in database
- `consensus_type` - Consensus algorithm (Raft, PBFT, PoS, etc.)
**Private Fields:**
- `tables` - Hash table managing all database tables and collections
- `indexes` - Index structures for query optimization
- `active_transactions` - List of currently executing transactions
- `storage_engine` - Backend storage implementation
- `replication` - Data replication and distribution management
### dap_db_transaction_t
Transaction management structure for ACID-compliant operations.
```c
typedef struct dap_db_transaction {
struct {
dap_db_transaction_id_t id; // Unique transaction identifier
dap_db_transaction_state_t state; // Current transaction state
dap_time_t start_time; // Transaction start timestamp
dap_time_t timeout; // Transaction timeout
uint32_t isolation_level; // Isolation level setting
bool is_read_only; // Read-only transaction flag
uint64_t affected_records; // Number of affected records
} pub;
struct {
dap_list_t *operations; // List of transaction operations
dap_db_savepoint_t *savepoints; // Transaction savepoints
dap_htable_t *locks; // Acquired locks hash table
dap_buffer_t *log_buffer; // Transaction log buffer
dap_db_rollback_t *rollback_data; // Rollback information
pthread_mutex_t transaction_mutex; // Transaction synchronization
bool is_distributed; // Distributed transaction flag
dap_list_t *participating_nodes; // Participating nodes list
} priv;
} dap_db_transaction_t;
```
**Transaction Management:**
- `id` - Globally unique transaction identifier
- `state` - Current state (begin, active, committed, rolled back)
- `isolation_level` - ACID isolation level configuration
- `operations` - List of operations within transaction
- `locks` - Database locks acquired by transaction
### dap_db_record_t
Database record structure representing stored data.
```c
typedef struct dap_db_record {
struct {
dap_db_record_key_t key; // Primary key identifier
size_t data_size; // Size of record data
void *data; // Record data payload
dap_time_t created_time; // Record creation timestamp
dap_time_t modified_time; // Last modification timestamp
uint64_t version; // Record version number
dap_hash_fast_t checksum; // Data integrity checksum
} pub;
struct {
dap_db_record_metadata_t *metadata; // Extended metadata
dap_list_t *indexes; // Associated index entries
dap_db_lock_t *lock; // Record-level lock
bool is_deleted; // Soft deletion flag
dap_db_record_t *previous_version; // Previous version link
uint32_t reference_count; // Reference counter
dap_buffer_t *compressed_data; // Compressed data storage
} priv;
} dap_db_record_t;
```
### dap_db_index_t
Database index structure for query optimization.
```c
typedef struct dap_db_index {
struct {
char *index_name; // Index identifier name
dap_db_index_type_t type; // Index type (B-tree, hash, etc.)
char *table_name; // Associated table name
char **indexed_columns; // Indexed column names
uint32_t column_count; // Number of indexed columns
bool is_unique; // Unique constraint flag
uint64_t entry_count; // Number of index entries
} pub;
struct {
void *index_structure; // Internal index structure
dap_htable_t *index_cache; // Index entry cache
pthread_rwlock_t index_lock; // Index read-write lock
dap_db_statistics_t *stats; // Index usage statistics
bool is_dirty; // Needs persistence flag
dap_time_t last_update; // Last index update time
uint32_t maintenance_cycle; // Maintenance cycle counter
} priv;
} dap_db_index_t;
```
### dap_db_sync_t
Data synchronization context for distributed consistency.
```c
typedef struct dap_db_sync {
struct {
dap_db_sync_mode_t mode; // Synchronization mode
uint32_t participating_nodes; // Number of sync nodes
dap_time_t last_sync_time; // Last successful sync
uint64_t sync_sequence; // Synchronization sequence number
bool is_syncing; // Currently synchronizing flag
dap_db_consensus_state_t consensus_state; // Current consensus state
} pub;
struct {
dap_htable_t *node_states; // Node synchronization states
dap_list_t *pending_changes; // Changes awaiting sync
dap_db_conflict_resolution_t *resolver; // Conflict resolution engine
dap_buffer_t *sync_log; // Synchronization log
pthread_mutex_t sync_mutex; // Synchronization lock
dap_timer_t *heartbeat_timer; // Node heartbeat timer
dap_db_merkle_tree_t *state_tree; // State merkle tree
} priv;
} dap_db_sync_t;
```
## Module Functions
### Database Management Functions
#### `dap_global_db_init()`
Initializes the global database system with configuration.
```c
int dap_global_db_init(const char *a_db_name, dap_db_config_t *a_config);
```
**Parameters:**
- `a_db_name` (const char*) - Database identifier name
- `a_config` (dap_db_config_t*) - Database configuration parameters
**Returns:**
- `0` - Database system initialized successfully
- `-1` - Invalid parameters
- `-2` - Memory allocation failed
- `-3` - Storage initialization failed
**Error Conditions:**
- Returns -1 if a_db_name is NULL or a_config is invalid
- Returns -2 if memory allocation for database context fails
- Returns -3 if storage engine initialization fails
**Description:** Initializes the global database system with specified configuration including storage engine, consensus mechanism, replication settings, and network parameters.
#### `dap_global_db_deinit()`
Cleanup and shutdown the database system.
```c
void dap_global_db_deinit(void);
```
**Parameters:** None
**Returns:** None (void function)
**Description:** Performs complete cleanup of the database system including closing all connections, flushing pending transactions, and releasing allocated resources.
#### `dap_global_db_open()`
Opens or creates a global database instance.
```c
dap_global_db_t* dap_global_db_open(const char *a_db_name, dap_db_flags_t a_flags);
```
**Parameters:**
- `a_db_name` (const char*) - Database name to open
- `a_flags` (dap_db_flags_t) - Database access flags
**Returns:**
- `dap_global_db_t*` - Database context
- `NULL` - Open failed
**Error Conditions:**
- Returns NULL if a_db_name is invalid
- Returns NULL if database does not exist and creation is not allowed
- Returns NULL if insufficient permissions
#### `dap_global_db_close()`
Closes database and ensures data persistence.
```c
int dap_global_db_close(dap_global_db_t *a_db);
```
**Parameters:**
- `a_db` (dap_global_db_t*) - Database context to close
**Returns:**
- `0` - Database closed successfully
- `-1` - Close operation failed
### Transaction Operations
#### `dap_db_transaction_begin()`
Starts a new database transaction.
```c
dap_db_transaction_t* dap_db_transaction_begin(dap_global_db_t *a_db, dap_db_transaction_flags_t a_flags);
```
**Parameters:**
- `a_db` (dap_global_db_t*) - Database context
- `a_flags` (dap_db_transaction_flags_t) - Transaction flags
**Returns:**
- `dap_db_transaction_t*` - New transaction context
- `NULL` - Transaction creation failed
**Error Conditions:**
- Returns NULL if a_db is NULL
- Returns NULL if maximum concurrent transactions exceeded
- Returns NULL if distributed transaction coordination fails
**Description:** Creates a new database transaction with specified isolation level and distributed coordination settings.
#### `dap_db_transaction_commit()`
Commits transaction changes to database.
```c
int dap_db_transaction_commit(dap_db_transaction_t *a_transaction);
```
**Parameters:**
- `a_transaction` (dap_db_transaction_t*) - Transaction to commit
**Returns:**
- `0` - Transaction committed successfully
- `-1` - Commit failed
- `-2` - Consensus failure
**Error Conditions:**
- Returns -1 if transaction is in invalid state
- Returns -2 if distributed consensus cannot be reached
- Returns -1 if storage write fails
#### `dap_db_transaction_rollback()`
Rolls back transaction changes.
```c
int dap_db_transaction_rollback(dap_db_transaction_t *a_transaction);
```
**Parameters:**
- `a_transaction` (dap_db_transaction_t*) - Transaction to rollback
**Returns:**
- `0` - Transaction rolled back successfully
- `-1` - Rollback failed
### Data Operations
#### `dap_db_record_insert()`
Inserts new record into database.
```c
int dap_db_record_insert(dap_db_transaction_t *a_transaction, const char *a_table, dap_db_record_t *a_record);
```
**Parameters:**
- `a_transaction` (dap_db_transaction_t*) - Transaction context
- `a_table` (const char*) - Target table name
- `a_record` (dap_db_record_t*) - Record to insert
**Returns:**
- `0` - Record inserted successfully
- `-1` - Insert failed
- `-2` - Duplicate key error
- `-3` - Constraint violation
**Error Conditions:**
- Returns -1 if transaction is not active
- Returns -2 if record with same key already exists
- Returns -3 if record violates table constraints
#### `dap_db_record_update()`
Updates existing record in database.
```c
int dap_db_record_update(dap_db_transaction_t *a_transaction, const char *a_table, dap_db_record_key_t a_key, dap_db_record_t *a_record);
```
**Parameters:**
- `a_transaction` (dap_db_transaction_t*) - Transaction context
- `a_table` (const char*) - Target table name
- `a_key` (dap_db_record_key_t) - Record key to update
- `a_record` (dap_db_record_t*) - Updated record data
**Returns:**
- `0` - Record updated successfully
- `-1` - Update failed
- `-2` - Record not found
- `-3` - Version conflict
#### `dap_db_record_select()`
Retrieves record from database.
```c
dap_db_record_t* dap_db_record_select(dap_db_transaction_t *a_transaction, const char *a_table, dap_db_record_key_t a_key);
```
**Parameters:**
- `a_transaction` (dap_db_transaction_t*) - Transaction context
- `a_table` (const char*) - Source table name
- `a_key` (dap_db_record_key_t) - Record key to retrieve
**Returns:**
- `dap_db_record_t*` - Retrieved record
- `NULL` - Record not found
#### `dap_db_record_delete()`
Deletes record from database.
```c
int dap_db_record_delete(dap_db_transaction_t *a_transaction, const char *a_table, dap_db_record_key_t a_key);
```
**Parameters:**
- `a_transaction` (dap_db_transaction_t*) - Transaction context
- `a_table` (const char*) - Target table name
- `a_key` (dap_db_record_key_t) - Record key to delete
**Returns:**
- `0` - Record deleted successfully
- `-1` - Delete failed
- `-2` - Record not found
### Synchronization Functions
#### `dap_db_sync_start()`
Initiates database synchronization process.
```c
int dap_db_sync_start(dap_global_db_t *a_db, dap_db_sync_config_t *a_config);
```
**Parameters:**
- `a_db` (dap_global_db_t*) - Database context
- `a_config` (dap_db_sync_config_t*) - Synchronization configuration
**Returns:**
- `0` - Synchronization started successfully
- `-1` - Sync start failed
- `-2` - Already synchronizing
#### `dap_db_sync_wait()`
Waits for synchronization completion.
```c
int dap_db_sync_wait(dap_global_db_t *a_db, uint32_t a_timeout_ms);
```
**Parameters:**
- `a_db` (dap_global_db_t*) - Database context
- `a_timeout_ms` (uint32_t) - Timeout in milliseconds
**Returns:**
- `0` - Synchronization completed
- `-1` - Timeout reached
- `-2` - Synchronization failed
## Error Codes
### Database Error Codes
```c
typedef enum dap_db_error {
DAP_DB_ERROR_SUCCESS = 0, // Operation successful
DAP_DB_ERROR_INVALID_PARAM = -1, // Invalid parameter provided
DAP_DB_ERROR_NO_MEMORY = -2, // Memory allocation failed
DAP_DB_ERROR_NOT_FOUND = -3, // Record or table not found
DAP_DB_ERROR_DUPLICATE_KEY = -4, // Duplicate key constraint
DAP_DB_ERROR_CONSTRAINT_VIOLATION = -5, // Data constraint violation
DAP_DB_ERROR_TRANSACTION_FAILED = -6, // Transaction operation failed
DAP_DB_ERROR_CONSENSUS_FAILED = -7, // Distributed consensus failed
DAP_DB_ERROR_SYNC_FAILED = -8, // Synchronization failed
DAP_DB_ERROR_STORAGE_FAILED = -9, // Storage operation failed
DAP_DB_ERROR_INDEX_CORRUPTED = -10, // Index corruption detected
DAP_DB_ERROR_VERSION_CONFLICT = -11 // Version conflict detected
} dap_db_error_t;
```
## Typical Examples
### Basic Database Operations Example
```c
#include "dap_common.h"
#include "dap_global_db.h"
typedef struct user_record {
uint64_t user_id;
char username[64];
char email[128];
uint64_t balance;
dap_time_t created_at;
} user_record_t;
int basic_database_example() {
log_it(L_INFO, "=== Basic Database Operations Example ===");
// Step 1: Initialize database system
dap_db_config_t config = {
.storage_type = DAP_DB_STORAGE_LEVELDB,
.consensus_type = DAP_DB_CONSENSUS_RAFT,
.max_connections = 100,
.cache_size_mb = 256,
.sync_interval_sec = 30,
.replication_factor = 3
};
if (dap_global_db_init("user_database", &config) != 0) {
log_it(L_ERROR, "✗ Failed to initialize database system");
return -1;
}
log_it(L_DEBUG, "✓ Database system initialized");
// Step 2: Open database
dap_global_db_t *db = dap_global_db_open("user_database", DAP_DB_FLAG_CREATE_IF_NOT_EXISTS);
if (!db) {
log_it(L_ERROR, "✗ Failed to open database");
goto cleanup;
}
log_it(L_DEBUG, "✓ Database opened successfully");
// Step 3: Begin transaction
dap_db_transaction_t *transaction = dap_db_transaction_begin(db, DAP_DB_TRANSACTION_READ_WRITE);
if (!transaction) {
log_it(L_ERROR, "✗ Failed to begin transaction");
goto cleanup_db;
}
log_it(L_DEBUG, "✓ Transaction started: %llu", transaction->pub.id);
// Step 4: Create user records
user_record_t users[] = {
{1001, "alice", "
[email protected]", 1000000, dap_time_now()},
{1002, "bob", "
[email protected]", 500000, dap_time_now()},
{1003, "charlie", "
[email protected]", 750000, dap_time_now()}
};
// Step 5: Insert records
for (int i = 0; i < 3; i++) {
dap_db_record_t record = {
.pub.key = users[i].user_id,
.pub.data = &users[i],
.pub.data_size = sizeof(user_record_t),
.pub.created_time = dap_time_now(),
.pub.version = 1
};
// Calculate checksum
dap_hash_fast(&users[i], sizeof(user_record_t), &record.pub.checksum);
int result = dap_db_record_insert(transaction, "users", &record);
if (result == 0) {
log_it(L_INFO, "✓ Inserted user: %s (ID: %llu, Balance: %llu)",
users[i].username, users[i].user_id, users[i].balance);
} else {
log_it(L_ERROR, "✗ Failed to insert user %s: %d", users[i].username, result);
}
}
// Step 6: Query records
log_it(L_INFO, "Querying inserted records:");
for (int i = 0; i < 3; i++) {
dap_db_record_t *retrieved = dap_db_record_select(transaction, "users", users[i].user_id);
if (retrieved) {
user_record_t *user_data = (user_record_t*)retrieved->pub.data;
log_it(L_INFO, "✓ Found user: %s (Email: %s, Balance: %llu)",
user_data->username, user_data->email, user_data->balance);
dap_db_record_delete_ptr(retrieved);
} else {
log_it(L_ERROR, "✗ User %llu not found", users[i].user_id);
}
}
// Step 7: Update a record
dap_db_record_t *alice_record = dap_db_record_select(transaction, "users", 1001);
if (alice_record) {
user_record_t *alice_data = (user_record_t*)alice_record->pub.data;
alice_data->balance += 250000; // Add to balance
int result = dap_db_record_update(transaction, "users", 1001, alice_record);
if (result == 0) {
log_it(L_INFO, "✓ Updated Alice's balance to %llu", alice_data->balance);
} else {
log_it(L_ERROR, "✗ Failed to update Alice's record: %d", result);
}
dap_db_record_delete_ptr(alice_record);
}
// Step 8: Commit transaction
if (dap_db_transaction_commit(transaction) == 0) {
log_it(L_INFO, "✓ Transaction committed successfully");
} else {
log_it(L_ERROR, "✗ Transaction commit failed");
dap_db_transaction_rollback(transaction);
}
cleanup_db:
dap_global_db_close(db);
log_it(L_DEBUG, "✓ Database closed");
cleanup:
dap_global_db_deinit();
log_it(L_INFO, "✓ Basic database operations example completed");
return 0;
}
```
### Distributed Transaction Example
```c
#include "dap_common.h"
#include "dap_global_db.h"
int distributed_transaction_example() {
log_it(L_INFO, "=== Distributed Transaction Example ===");
// Step 1: Initialize distributed database system
dap_db_config_t config = {
.storage_type = DAP_DB_STORAGE_DISTRIBUTED,
.consensus_type = DAP_DB_CONSENSUS_PBFT,
.node_count = 5,
.replication_factor = 3,
.distributed_mode = true,
.network_timeout_ms = 5000
};
if (dap_global_db_init("distributed_ledger", &config) != 0) {
log_it(L_ERROR, "✗ Failed to initialize distributed database");
return -1;
}
// Step 2: Open distributed database
dap_global_db_t *db = dap_global_db_open("distributed_ledger",
DAP_DB_FLAG_DISTRIBUTED | DAP_DB_FLAG_CONSENSUS_REQUIRED);
if (!db) {
log_it(L_ERROR, "✗ Failed to open distributed database");
goto cleanup;
}
log_it(L_DEBUG, "✓ Distributed database opened with %u participating nodes",
db->pub.node_count);
// Step 3: Wait for network synchronization
log_it(L_INFO, "Waiting for network synchronization...");
if (dap_db_sync_wait(db, 10000) != 0) {
log_it(L_WARNING, "Network sync timeout, proceeding anyway");
} else {
log_it(L_INFO, "✓ Network synchronized");
}
// Step 4: Begin distributed transaction
dap_db_transaction_t *transaction = dap_db_transaction_begin(db,
DAP_DB_TRANSACTION_DISTRIBUTED | DAP_DB_TRANSACTION_CONSENSUS);
if (!transaction) {
log_it(L_ERROR, "✗ Failed to begin distributed transaction");
goto cleanup_db;
}
log_it(L_DEBUG, "✓ Distributed transaction started: %llu", transaction->pub.id);
// Step 5: Simulate transfer operation (atomic across multiple records)
struct {
uint64_t from_account;
uint64_t to_account;
uint64_t amount;
} transfer = {1001, 1002, 100000};
log_it(L_INFO, "Processing transfer: %llu from account %llu to account %llu",
transfer.amount, transfer.from_account, transfer.to_account);
// Step 6: Read source account
dap_db_record_t *from_record = dap_db_record_select(transaction, "accounts",
transfer.from_account);
if (!from_record) {
log_it(L_ERROR, "✗ Source account %llu not found", transfer.from_account);
goto rollback;
}
// Step 7: Read destination account
dap_db_record_t *to_record = dap_db_record_select(transaction, "accounts",
transfer.to_account);
if (!to_record) {
log_it(L_ERROR, "✗ Destination account %llu not found", transfer.to_account);
dap_db_record_delete_ptr(from_record);
goto rollback;
}
// Step 8: Verify sufficient balance
uint64_t *from_balance = (uint64_t*)from_record->pub.data;
uint64_t *to_balance = (uint64_t*)to_record->pub.data;
if (*from_balance < transfer.amount) {
log_it(L_ERROR, "✗ Insufficient balance: %llu < %llu",
*from_balance, transfer.amount);
goto cleanup_records;
}
// Step 9: Perform transfer
uint64_t original_from = *from_balance;
uint64_t original_to = *to_balance;
*from_balance -= transfer.amount;
*to_balance += transfer.amount;
// Step 10: Update both records atomically
int from_result = dap_db_record_update(transaction, "accounts",
transfer.from_account, from_record);
int to_result = dap_db_record_update(transaction, "accounts",
transfer.to_account, to_record);
if (from_result != 0 || to_result != 0) {
log_it(L_ERROR, "✗ Failed to update account records: from=%d, to=%d",
from_result, to_result);
goto cleanup_records;
}
log_it(L_INFO, "✓ Transfer prepared: %llu->%llu, %llu->%llu",
original_from, *from_balance, original_to, *to_balance);
// Step 11: Commit distributed transaction
log_it(L_INFO, "Committing distributed transaction...");
if (dap_db_transaction_commit(transaction) == 0) {
log_it(L_INFO, "✓ Distributed transaction committed successfully");
log_it(L_INFO, "✓ Transfer completed with network consensus");
} else {
log_it(L_ERROR, "✗ Distributed transaction commit failed");
goto cleanup_records;
}
dap_db_record_delete_ptr(from_record);
dap_db_record_delete_ptr(to_record);
goto cleanup_db;
cleanup_records:
dap_db_record_delete_ptr(from_record);
dap_db_record_delete_ptr(to_record);
rollback:
log_it(L_WARNING, "Rolling back distributed transaction");
dap_db_transaction_rollback(transaction);
cleanup_db:
dap_global_db_close(db);
cleanup:
dap_global_db_deinit();
log_it(L_INFO, "✓ Distributed transaction example completed");
return 0;
}
```
### Database Synchronization Example
```c
#include "dap_common.h"
#include "dap_global_db.h"
static void sync_progress_callback(dap_db_sync_t *a_sync,
dap_db_sync_progress_t *a_progress, void *a_arg) {
log_it(L_INFO, "Sync progress: %u/%u nodes, %llu records synchronized",
a_progress->completed_nodes, a_progress->total_nodes,
a_progress->synchronized_records);
}
int database_synchronization_example() {
log_it(L_INFO, "=== Database Synchronization Example ===");
// Step 1: Initialize database with sync configuration
dap_db_config_t config = {
.storage_type = DAP_DB_STORAGE_DISTRIBUTED,
.consensus_type = DAP_DB_CONSENSUS_RAFT,
.node_count = 3,
.sync_mode = DAP_DB_SYNC_REALTIME,
.sync_interval_sec = 10,
.conflict_resolution = DAP_DB_CONFLICT_LAST_WRITE_WINS
};
if (dap_global_db_init("sync_database", &config) != 0) {
log_it(L_ERROR, "✗ Failed to initialize database system");
return -1;
}
// Step 2: Open database
dap_global_db_t *db = dap_global_db_open("sync_database",
DAP_DB_FLAG_SYNC_ENABLED | DAP_DB_FLAG_AUTO_RECOVERY);
if (!db) {
log_it(L_ERROR, "✗ Failed to open database");
goto cleanup;
}
log_it(L_DEBUG, "✓ Database opened with sync enabled");
// Step 3: Configure synchronization
dap_db_sync_config_t sync_config = {
.mode = DAP_DB_SYNC_INCREMENTAL,
.timeout_ms = 30000,
.max_retries = 3,
.progress_callback = sync_progress_callback,
.callback_arg = NULL
};
// Step 4: Start initial synchronization
log_it(L_INFO, "Starting initial database synchronization...");
if (dap_db_sync_start(db, &sync_config) != 0) {
log_it(L_ERROR, "✗ Failed to start synchronization");
goto cleanup_db;
}
// Step 5: Monitor synchronization progress
int sync_timeout = 300; // 30 seconds
while (sync_timeout > 0 && db->pub.is_synchronized == false) {
usleep(100000); // 100ms
sync_timeout--;
if (sync_timeout % 50 == 0) { // Every 5 seconds
log_it(L_INFO, "Synchronization in progress... (%d seconds remaining)",
sync_timeout / 10);
}
}
if (db->pub.is_synchronized) {
log_it(L_INFO, "✓ Initial synchronization completed successfully");
log_it(L_INFO, "Database state: %llu records, last sync: %llu",
db->pub.total_records, db->pub.last_sync_time);
} else {
log_it(L_WARNING, "Synchronization timeout, continuing with partial sync");
}
// Step 6: Simulate data changes and observe sync
log_it(L_INFO, "Simulating data changes to test real-time sync...");
dap_db_transaction_t *transaction = dap_db_transaction_begin(db,
DAP_DB_TRANSACTION_AUTO_SYNC);
if (transaction) {
// Insert test records that will trigger sync
for (int i = 0; i < 5; i++) {
char key_str[32];
snprintf(key_str, sizeof(key_str), "test_record_%d", i);
dap_db_record_t record = {
.pub.key = i + 1000,
.pub.data = key_str,
.pub.data_size = strlen(key_str) + 1,
.pub.created_time = dap_time_now(),
.pub.version = 1
};
if (dap_db_record_insert(transaction, "test_data", &record) == 0) {
log_it(L_DEBUG, "✓ Inserted test record: %s", key_str);
}
// Brief delay to observe sync behavior
usleep(500000); // 500ms
}
// Commit changes
if (dap_db_transaction_commit(transaction) == 0) {
log_it(L_INFO, "✓ Test data committed, observing sync propagation");
}
}
// Step 7: Wait for sync propagation
sleep(5);
// Step 8: Verify sync status
if (dap_db_sync_wait(db, 5000) == 0) {
log_it(L_INFO, "✓ Data changes synchronized across network");
log_it(L_INFO, "Final database state: %llu records",
db->pub.total_records);
} else {
log_it(L_WARNING, "Sync verification timeout");
}
cleanup_db:
dap_global_db_close(db);
log_it(L_DEBUG, "✓ Database closed");
cleanup:
dap_global_db_deinit();
log_it(L_INFO, "✓ Database synchronization example completed");
return 0;
}
```
---
**See also:** [[Module DAP Core|Module DAP Core]], [[Module DAP Net|Module DAP Net]], [[ETC/Architecture Overview|Architecture Overview]]
---
*Based on: `dap-sdk/global-db/include/dap_global_db.h`, `dap-sdk/global-db/src/dap_global_db.c`*