| Crates.io | kaccy-db |
| lib.rs | kaccy-db |
| version | 0.1.0 |
| created_at | 2026-01-18 21:54:25.053779+00 |
| updated_at | 2026-01-18 21:54:25.053779+00 |
| description | Database layer for Kaccy Protocol - PostgreSQL, Redis, and distributed caching |
| homepage | https://github.com/cool-japan/kaccy |
| repository | https://github.com/cool-japan/kaccy |
| max_upload_size | |
| id | 2053177 |
| size | 1,452,831 |
Comprehensive database layer for Kaccy Protocol with enterprise-grade features.
This crate provides a complete PostgreSQL database solution with:
pool - Connection pool with retry logic and health checksreplica - Read replica management with load balancing strategiesmulti_region - Geographic replication with proximity-based routingsharding - Database sharding with consistent hashingAll repositories provide type-safe, async database operations:
UserRepository - User accounts, profiles, KYC, reputationTokenRepository - Personal tokens with bonding curvesBalanceRepository - Token balances with locking supportOrderRepository - Buy/sell orders with BTC integrationTradeRepository - Trade execution and analyticsReputationEventRepository - Reputation scoring and historyCommitmentRepository - User commitments with deadlinesAuditRepository - Compliance reporting and audit logscache - Redis caching with rate limiting and distributed locksquery_logger - Query performance monitoring and slow query detectionindex_analyzer - Index optimization recommendationsanalytics - TimescaleDB integration with materialized views for dashboardsbackup - Automated backups with pg_dump/restore and PITRtransaction - Transaction management with isolation levels and savepointsuse kaccy_db::{create_pool_with_retry, RetryConfig, UserRepository};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let database_url = std::env::var("DATABASE_URL")?;
// Create pool with automatic retry
let retry_config = RetryConfig::default();
let pool = create_pool_with_retry(&database_url, retry_config).await?;
// Use repositories
let user_repo = UserRepository::new(pool.clone());
let user = user_repo.find_by_email("user@example.com").await?;
Ok(())
}
use kaccy_db::{RedisCache, CacheConfig};
let cache_config = CacheConfig::default();
let cache = RedisCache::connect("redis://localhost", cache_config).await?;
// Cache user sessions
cache.set_session("user123", &session_data, 3600).await?;
// Rate limiting
let allowed = cache.check_rate_limit("api:user123", 100, 60).await?;
use kaccy_db::{ReplicaPoolManager, LoadBalanceStrategy, SmartDbClientBuilder};
let manager = ReplicaPoolManager::new(
primary_pool,
vec![replica1, replica2],
LoadBalanceStrategy::LeastConnections,
).await?;
let client = SmartDbClientBuilder::new(manager).build();
// Automatically routes SELECTs to replicas, writes to primary
use kaccy_db::{ShardPoolManager, ShardingStrategy, ShardKey};
let shard_manager = ShardPoolManager::new(
vec![shard1_pool, shard2_pool, shard3_pool],
ShardingStrategy::Hash,
).await?;
// Route queries to appropriate shard
let user = shard_manager.execute_on_shard(
&ShardKey::UserId(user_id),
|pool| async move {
UserRepository::new(pool).find_by_id(user_id).await
}
).await?;
use kaccy_db::AnalyticsService;
let analytics = AnalyticsService::new(pool);
// Get dashboard metrics from materialized views
let metrics = analytics.get_dashboard_metrics().await?;
// Query time-series data (requires TimescaleDB)
let prices = analytics.get_price_history(token_id, start_time, end_time).await?;
Environment variables:
DATABASE_URL - PostgreSQL connection stringREDIS_URL - Redis connection string (optional)kaccy-db/
├── src/
│ ├── lib.rs # Public API
│ ├── pool.rs # Connection pooling
│ ├── cache.rs # Redis caching
│ ├── replica.rs # Read replicas
│ ├── sharding.rs # Database sharding
│ ├── multi_region.rs # Geographic replication
│ ├── analytics.rs # TimescaleDB & materialized views
│ ├── query_logger.rs # Performance monitoring
│ ├── index_analyzer.rs # Index optimization
│ ├── backup.rs # Backup/recovery
│ ├── transaction.rs # Transaction management
│ ├── error.rs # Error types
│ └── repositories/
│ ├── user.rs
│ ├── token.rs
│ ├── balance.rs
│ ├── order.rs
│ ├── trade.rs
│ ├── reputation_event.rs
│ ├── commitment.rs
│ └── audit.rs
├── migrations/ # SQL migrations
└── Cargo.toml
sqlx - Async SQL with compile-time checkingredis - Async Redis clienttokio - Async runtimeserde - Serializationchrono - Date/time handlinguuid - UUID supportrust_decimal - Decimal arithmeticSee migrations/ directory for the current schema. Key tables:
users - User accounts with DID, KYC status, reputationtokens - Personal tokens with bonding curve parametersbalances - User token balancesorders - Buy/sell orders with BTC payment infotrades - Executed trade recordsreputation_events - Reputation score changesoutput_commitments - User commitments with deadlines# Run with test database
DATABASE_URL=postgresql://test@localhost/kaccy_test cargo test -p kaccy-db
# Run migrations
sqlx migrate run