reinhardt-db 0.1.2

Django-style database layer for Reinhardt framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
/// Lambda Statement - Cached query compilation
/// Based on SQLAlchemy's lambda_stmt
use std::collections::HashMap;
use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};

/// Lambda statement for query caching
pub struct LambdaStmt {
	/// The cache key.
	pub cache_key: String,
	lambda_fn: Box<dyn Fn() -> String + Send + Sync>,
}

impl LambdaStmt {
	/// Create a new cached lambda statement
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::lambda_stmt::LambdaStmt;
	///
	/// let stmt = LambdaStmt::new("get_active_users", || {
	///     "SELECT * FROM users WHERE active = true".to_string()
	/// });
	///
	/// let result = stmt.execute().unwrap();
	/// assert_eq!(result, "SELECT * FROM users WHERE active = true");
	/// ```
	pub fn new<F>(cache_key: impl Into<String>, lambda_fn: F) -> Self
	where
		F: Fn() -> String + Send + Sync + 'static,
	{
		Self {
			cache_key: cache_key.into(),
			lambda_fn: Box::new(lambda_fn),
		}
	}
	/// Execute the lambda function and cache the compiled query
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::lambda_stmt::LambdaStmt;
	///
	/// let stmt = LambdaStmt::new("user_query", || {
	///     "SELECT id, name FROM users".to_string()
	/// });
	///
	/// let result = stmt.execute();
	/// assert!(result.is_ok());
	/// assert_eq!(result.unwrap(), "SELECT id, name FROM users");
	/// ```
	pub fn execute(&self) -> Result<String, String> {
		// Check cache first
		if let Some(cached) = QUERY_CACHE.get(&self.cache_key) {
			acquire_stats_write_lock().hits += 1;
			return Ok(cached);
		}

		// Execute the lambda function to generate the query
		let query = (self.lambda_fn)();

		// Cache the compiled query
		QUERY_CACHE.set(self.cache_key.clone(), query.clone());
		acquire_stats_write_lock().misses += 1;

		Ok(query)
	}
	/// Check if this query has been cached
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::lambda_stmt::LambdaStmt;
	///
	/// let stmt = LambdaStmt::new("check_cache", || {
	///     "SELECT * FROM products".to_string()
	/// });
	///
	/// assert!(!stmt.is_cached());
	/// stmt.execute().unwrap();
	/// assert!(stmt.is_cached());
	/// ```
	pub fn is_cached(&self) -> bool {
		QUERY_CACHE.get(&self.cache_key).is_some()
	}
}

/// Cache for compiled queries
pub struct QueryCache {
	cache: Arc<RwLock<HashMap<String, String>>>,
}

impl QueryCache {
	/// Create a new empty query cache
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::lambda_stmt::QueryCache;
	///
	/// let cache = QueryCache::new();
	/// assert_eq!(cache.size(), 0);
	/// ```
	pub fn new() -> Self {
		Self {
			cache: Arc::new(RwLock::new(HashMap::new())),
		}
	}
	/// Get a cached query by key
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::lambda_stmt::QueryCache;
	///
	/// let cache = QueryCache::new();
	/// cache.set("key1".to_string(), "SELECT * FROM users".to_string());
	/// assert_eq!(cache.get("key1"), Some("SELECT * FROM users".to_string()));
	/// ```
	pub fn get(&self, key: &str) -> Option<String> {
		self.acquire_read_lock().get(key).cloned()
	}
	/// Store a compiled query in the cache
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::lambda_stmt::QueryCache;
	///
	/// let cache = QueryCache::new();
	/// cache.set("users".to_string(), "SELECT id, name FROM users".to_string());
	/// assert!(cache.contains("users"));
	/// ```
	pub fn set(&self, key: String, value: String) {
		self.acquire_write_lock().insert(key, value);
	}
	/// Clear all cached queries
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::lambda_stmt::QueryCache;
	///
	/// let cache = QueryCache::new();
	/// cache.set("key1".to_string(), "value1".to_string());
	/// assert_eq!(cache.size(), 1);
	/// cache.clear();
	/// assert_eq!(cache.size(), 0);
	/// ```
	pub fn clear(&self) {
		self.acquire_write_lock().clear();
	}
	/// Get the number of cached queries
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::lambda_stmt::QueryCache;
	///
	/// let cache = QueryCache::new();
	/// cache.set("a".to_string(), "query1".to_string());
	/// cache.set("b".to_string(), "query2".to_string());
	/// assert_eq!(cache.size(), 2);
	/// ```
	pub fn size(&self) -> usize {
		self.acquire_read_lock().len()
	}
	/// Remove a specific query from the cache
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::lambda_stmt::QueryCache;
	///
	/// let cache = QueryCache::new();
	/// cache.set("key1".to_string(), "value1".to_string());
	/// let removed = cache.remove("key1");
	/// assert_eq!(removed, Some("value1".to_string()));
	/// assert_eq!(cache.size(), 0);
	/// ```
	pub fn remove(&self, key: &str) -> Option<String> {
		self.acquire_write_lock().remove(key)
	}
	/// Check if a query key exists in the cache
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::lambda_stmt::QueryCache;
	///
	/// let cache = QueryCache::new();
	/// cache.set("key1".to_string(), "value1".to_string());
	/// assert!(cache.contains("key1"));
	/// assert!(!cache.contains("key2"));
	/// ```
	pub fn contains(&self, key: &str) -> bool {
		self.acquire_read_lock().contains_key(key)
	}

	/// Acquire a read lock, clearing the cache on poison to prevent corrupted data
	fn acquire_read_lock(&self) -> RwLockReadGuard<'_, HashMap<String, String>> {
		match self.cache.read() {
			Ok(guard) => guard,
			Err(poisoned) => {
				tracing::warn!(
					"Query cache RwLock was poisoned on read, clearing cache to prevent corrupted data"
				);
				// We need a write lock to clear, so drop the poisoned read guard
				drop(poisoned);
				// Clear via write lock, then re-acquire read
				match self.cache.write() {
					Ok(mut guard) => {
						guard.clear();
						drop(guard);
					}
					Err(poisoned) => {
						let mut guard = poisoned.into_inner();
						guard.clear();
						drop(guard);
					}
				}
				// After clearing, acquire the read lock (now unpoisoned after clear)
				self.cache.read().unwrap_or_else(|e| e.into_inner())
			}
		}
	}

	/// Acquire a write lock, clearing the cache on poison to prevent corrupted data
	fn acquire_write_lock(&self) -> RwLockWriteGuard<'_, HashMap<String, String>> {
		match self.cache.write() {
			Ok(guard) => guard,
			Err(poisoned) => {
				tracing::warn!(
					"Query cache RwLock was poisoned on write, clearing cache to prevent corrupted data"
				);
				let mut guard = poisoned.into_inner();
				guard.clear();
				guard
			}
		}
	}
}

impl Default for QueryCache {
	fn default() -> Self {
		Self::new()
	}
}

use once_cell::sync::Lazy;

/// Global query cache.
pub static QUERY_CACHE: Lazy<QueryCache> = Lazy::new(QueryCache::new);
/// Global cache stats.
pub static CACHE_STATS: Lazy<Arc<RwLock<CacheStatistics>>> =
	Lazy::new(|| Arc::new(RwLock::new(CacheStatistics::new())));

/// Acquire write lock on CACHE_STATS, clearing on poison
fn acquire_stats_write_lock() -> RwLockWriteGuard<'static, CacheStatistics> {
	match CACHE_STATS.write() {
		Ok(guard) => guard,
		Err(poisoned) => {
			tracing::warn!("Cache statistics RwLock was poisoned, resetting statistics");
			let mut guard = poisoned.into_inner();
			guard.reset();
			guard
		}
	}
}

// Type alias for lambda function
type LambdaFunction = Box<dyn Fn() -> String + Send + Sync>;
type LambdaFunctionMap = Arc<RwLock<HashMap<String, LambdaFunction>>>;

// Lambda function registry
/// Represents a lambda registry.
pub struct LambdaRegistry {
	// Allow dead_code: function registry stored for future lambda statement execution
	#[allow(dead_code)]
	functions: LambdaFunctionMap,
}

impl Default for LambdaRegistry {
	fn default() -> Self {
		Self::new()
	}
}

impl LambdaRegistry {
	/// Create a new lambda function registry
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::lambda_stmt::LambdaRegistry;
	///
	/// let registry = LambdaRegistry::new();
	/// ```
	pub fn new() -> Self {
		Self {
			functions: Arc::new(RwLock::new(HashMap::new())),
		}
	}
}

// Cache statistics
#[derive(Debug, Clone)]
/// Represents a cache statistics.
pub struct CacheStatistics {
	/// The hits.
	pub hits: usize,
	/// The misses.
	pub misses: usize,
	/// The total size.
	pub total_size: usize,
}

impl CacheStatistics {
	/// Create new cache statistics with zero counts
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::lambda_stmt::CacheStatistics;
	///
	/// let stats = CacheStatistics::new();
	/// assert_eq!(stats.hits, 0);
	/// assert_eq!(stats.misses, 0);
	/// ```
	pub fn new() -> Self {
		Self {
			hits: 0,
			misses: 0,
			total_size: 0,
		}
	}
	/// Calculate the cache hit rate as a percentage
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::lambda_stmt::CacheStatistics;
	///
	/// let mut stats = CacheStatistics::new();
	/// stats.hits = 7;
	/// stats.misses = 3;
	/// assert_eq!(stats.hit_rate(), 0.7);
	/// ```
	pub fn hit_rate(&self) -> f64 {
		if self.hits + self.misses == 0 {
			0.0
		} else {
			self.hits as f64 / (self.hits + self.misses) as f64
		}
	}
	/// Reset all statistics to zero
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::lambda_stmt::CacheStatistics;
	///
	/// let mut stats = CacheStatistics::new();
	/// stats.hits = 10;
	/// stats.misses = 5;
	/// stats.reset();
	/// assert_eq!(stats.hits, 0);
	/// assert_eq!(stats.misses, 0);
	/// ```
	pub fn reset(&mut self) {
		self.hits = 0;
		self.misses = 0;
		self.total_size = 0;
	}
}

impl Default for CacheStatistics {
	fn default() -> Self {
		Self::new()
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_lambda_stmt_cache_operations() {
		let cache = QueryCache::new();
		cache.set("key1".to_string(), "value1".to_string());
		assert_eq!(cache.get("key1"), Some("value1".to_string()));
		cache.clear();
		assert_eq!(cache.get("key1"), None);
	}

	#[test]
	fn test_lambda_execution() {
		let stmt = LambdaStmt::new("test_query", || {
			"SELECT * FROM users WHERE active = true".to_string()
		});

		let result = stmt.execute().unwrap();
		assert_eq!(result, "SELECT * FROM users WHERE active = true");

		// Second execution should hit cache
		let result2 = stmt.execute().unwrap();
		assert_eq!(result2, result);
		assert!(stmt.is_cached());
	}

	#[test]
	fn test_cache_statistics() {
		let stats = CacheStatistics::new();
		assert_eq!(stats.hits, 0);
		assert_eq!(stats.misses, 0);
		assert_eq!(stats.hit_rate(), 0.0);
	}
}