reinhardt-db 0.1.0

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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
//! MongoDB connection and backend implementation
//!
//! This module provides the MongoDB database backend that implements
//! the `DocumentBackend` and `NoSQLBackend` traits.
//!
//! # Example
//!
//! ```rust,no_run
//! use reinhardt_db::nosql::backends::mongodb::MongoDBBackend;
//! use reinhardt_db::nosql::traits::DocumentBackend;
//! use bson::doc;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Connect to MongoDB
//! let backend = MongoDBBackend::connect("mongodb://localhost:27017").await?;
//!
//! // Use a specific database
//! let backend_with_db = backend.with_database("myapp");
//!
//! // Insert a document
//! let id = backend_with_db.insert_one("users", doc! {
//!     "name": "Alice",
//!     "email": "alice@example.com"
//! }).await?;
//! # Ok(())
//! # }
//! ```

use async_trait::async_trait;
use bson::{Bson, Document};
use mongodb::{Client, ClientSession, Database};
use std::sync::Arc;

use crate::nosql::error::{NoSQLError, Result};
use crate::nosql::traits::{DocumentBackend, NoSQLBackend};
use crate::nosql::types::{FindOptions, NoSQLBackendType, UpdateResult};

/// MongoDB backend implementation
///
/// Supports connection pooling, replica sets, and sharded clusters.
///
/// # Example
///
/// ```rust,no_run
/// use reinhardt_db::nosql::backends::mongodb::MongoDBBackend;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// // Basic connection
/// let backend = MongoDBBackend::connect("mongodb://localhost:27017").await?;
/// let backend = backend.with_database("mydb");
///
/// // Connection with options
/// let backend = MongoDBBackend::builder()
///     .url("mongodb://localhost:27017")
///     .database("mydb")
///     .max_pool_size(100)
///     .min_pool_size(10)
///     .build()
///     .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct MongoDBBackend {
	client: Arc<Client>,
	database_name: String,
}

/// MongoDB transaction executor
///
/// This struct wraps a MongoDB `ClientSession` to ensure all operations
/// within a transaction run within the same session context.
///
/// # Note
///
/// MongoDB transactions require a replica set or sharded cluster.
/// Standalone MongoDB instances do not support transactions.
pub struct MongoDBTransactionExecutor {
	/// The MongoDB session (Option for consume-on-commit/rollback pattern)
	session: Option<ClientSession>,
	/// Reference to the client for accessing database/collections
	// Allow dead_code: client stored for collection access during transactional operations
	#[allow(dead_code)]
	client: Arc<Client>,
	/// Database name for operations
	// Allow dead_code: database name stored for scoping collection lookups within transactions
	#[allow(dead_code)]
	database_name: String,
}

impl MongoDBTransactionExecutor {
	/// Create a new MongoDB transaction executor
	pub fn new(session: ClientSession, client: Arc<Client>, database_name: String) -> Self {
		Self {
			session: Some(session),
			client,
			database_name,
		}
	}

	/// Commit the transaction
	pub async fn commit(mut self) -> Result<()> {
		let mut session = self
			.session
			.take()
			.ok_or_else(|| NoSQLError::DatabaseError("Transaction already consumed".to_string()))?;

		session.commit_transaction().await.map_err(|e| {
			NoSQLError::DatabaseError(format!("Failed to commit MongoDB transaction: {}", e))
		})
	}

	/// Rollback the transaction
	pub async fn rollback(mut self) -> Result<()> {
		let mut session = self
			.session
			.take()
			.ok_or_else(|| NoSQLError::DatabaseError("Transaction already consumed".to_string()))?;

		session.abort_transaction().await.map_err(|e| {
			NoSQLError::DatabaseError(format!("Failed to rollback MongoDB transaction: {}", e))
		})
	}
}

/// Builder for configuring MongoDB connections
///
/// # Example
///
/// ```rust,no_run
/// use reinhardt_db::nosql::backends::mongodb::MongoDBBackendBuilder;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let backend = MongoDBBackendBuilder::new()
///     .url("mongodb://localhost:27017")
///     .database("mydb")
///     .max_pool_size(100)
///     .min_pool_size(10)
///     .max_idle_time_secs(300)
///     .build()
///     .await?;
/// # Ok(())
/// # }
/// ```
pub struct MongoDBBackendBuilder {
	url: String,
	database: String,
	max_pool_size: Option<u32>,
	min_pool_size: Option<u32>,
	max_idle_time_secs: Option<u64>,
}

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

impl MongoDBBackendBuilder {
	/// Create a new builder with default settings
	///
	/// # Example
	///
	/// ```rust
	/// # use reinhardt_db::nosql::backends::mongodb::MongoDBBackendBuilder;
	/// let builder = MongoDBBackendBuilder::new();
	/// // Builder successfully created with default settings
	/// ```
	pub fn new() -> Self {
		Self {
			url: "mongodb://localhost:27017".to_string(),
			database: "test".to_string(),
			max_pool_size: None,
			min_pool_size: None,
			max_idle_time_secs: None,
		}
	}

	/// Set the MongoDB connection URL
	///
	/// # Example
	///
	/// ```rust
	/// # use reinhardt_db::nosql::backends::mongodb::MongoDBBackendBuilder;
	/// let builder = MongoDBBackendBuilder::new()
	///     .url("mongodb://localhost:27017");
	/// // URL successfully set
	/// ```
	pub fn url(mut self, url: impl Into<String>) -> Self {
		self.url = url.into();
		self
	}

	/// Set the database name
	///
	/// # Example
	///
	/// ```rust
	/// # use reinhardt_db::nosql::backends::mongodb::MongoDBBackendBuilder;
	/// let builder = MongoDBBackendBuilder::new()
	///     .database("mydb");
	/// // Database name successfully set
	/// ```
	pub fn database(mut self, database: impl Into<String>) -> Self {
		self.database = database.into();
		self
	}

	/// Set the maximum connection pool size
	///
	/// # Example
	///
	/// ```rust
	/// # use reinhardt_db::nosql::backends::mongodb::MongoDBBackendBuilder;
	/// let builder = MongoDBBackendBuilder::new()
	///     .max_pool_size(100);
	/// // Max pool size successfully set
	/// ```
	pub fn max_pool_size(mut self, size: u32) -> Self {
		self.max_pool_size = Some(size);
		self
	}

	/// Set the minimum connection pool size
	///
	/// # Example
	///
	/// ```rust
	/// # use reinhardt_db::nosql::backends::mongodb::MongoDBBackendBuilder;
	/// let builder = MongoDBBackendBuilder::new()
	///     .min_pool_size(10);
	/// // Min pool size successfully set
	/// ```
	pub fn min_pool_size(mut self, size: u32) -> Self {
		self.min_pool_size = Some(size);
		self
	}

	/// Set the maximum idle time for connections in seconds
	///
	/// # Example
	///
	/// ```rust
	/// # use reinhardt_db::nosql::backends::mongodb::MongoDBBackendBuilder;
	/// let builder = MongoDBBackendBuilder::new()
	///     .max_idle_time_secs(300);
	/// // Max idle time successfully set
	/// ```
	pub fn max_idle_time_secs(mut self, secs: u64) -> Self {
		self.max_idle_time_secs = Some(secs);
		self
	}

	/// Build the MongoDB backend
	///
	/// # Example
	///
	/// ```rust,no_run
	/// use reinhardt_db::nosql::backends::mongodb::MongoDBBackendBuilder;
	///
	/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
	/// let backend = MongoDBBackendBuilder::new()
	///     .url("mongodb://localhost:27017")
	///     .database("mydb")
	///     .build()
	///     .await?;
	/// # Ok(())
	/// # }
	/// ```
	pub async fn build(self) -> Result<MongoDBBackend> {
		use mongodb::options::ClientOptions;
		use std::time::Duration;

		let mut options = ClientOptions::parse(&self.url)
			.await
			.map_err(|e| NoSQLError::ConnectionError(e.to_string()))?;

		// Configure connection pool
		if let Some(max_size) = self.max_pool_size {
			options.max_pool_size = Some(max_size);
		}

		if let Some(min_size) = self.min_pool_size {
			options.min_pool_size = Some(min_size);
		}

		if let Some(idle_time) = self.max_idle_time_secs {
			options.max_idle_time = Some(Duration::from_secs(idle_time));
		}

		let client = Client::with_options(options)
			.map_err(|e| NoSQLError::ConnectionError(e.to_string()))?;

		Ok(MongoDBBackend {
			client: Arc::new(client),
			database_name: self.database,
		})
	}
}

impl MongoDBBackend {
	/// Connect to MongoDB using a connection string
	///
	/// # Arguments
	///
	/// * `url` - MongoDB connection string (e.g., "mongodb://localhost:27017")
	///
	/// # Example
	///
	/// ```rust,no_run
	/// use reinhardt_db::nosql::backends::mongodb::MongoDBBackend;
	///
	/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
	/// let backend = MongoDBBackend::connect("mongodb://localhost:27017").await?;
	/// # Ok(())
	/// # }
	/// ```
	pub async fn connect(url: &str) -> Result<Self> {
		let client = Client::with_uri_str(url)
			.await
			.map_err(|e| NoSQLError::ConnectionError(e.to_string()))?;

		Ok(Self {
			client: Arc::new(client),
			database_name: "test".to_string(), // Default database
		})
	}

	/// Create a builder for configuring the MongoDB connection
	///
	/// # Example
	///
	/// ```rust,no_run
	/// use reinhardt_db::nosql::backends::mongodb::MongoDBBackend;
	///
	/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
	/// let backend = MongoDBBackend::builder()
	///     .url("mongodb://localhost:27017")
	///     .database("mydb")
	///     .max_pool_size(100)
	///     .build()
	///     .await?;
	/// # Ok(())
	/// # }
	/// ```
	pub fn builder() -> MongoDBBackendBuilder {
		MongoDBBackendBuilder::new()
	}

	/// Set the database name to use
	///
	/// # Example
	///
	/// ```rust,no_run
	/// use reinhardt_db::nosql::backends::mongodb::MongoDBBackend;
	///
	/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
	/// let backend = MongoDBBackend::connect("mongodb://localhost:27017").await?;
	/// let backend = backend.with_database("myapp");
	/// # Ok(())
	/// # }
	/// ```
	pub fn with_database(mut self, database_name: &str) -> Self {
		self.database_name = database_name.to_string();
		self
	}

	/// Get the MongoDB database instance
	///
	/// # Example
	///
	/// ```rust,no_run
	/// use reinhardt_db::nosql::backends::mongodb::MongoDBBackend;
	///
	/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
	/// let backend = MongoDBBackend::connect("mongodb://localhost:27017").await?;
	/// let db = backend.database();
	/// # Ok(())
	/// # }
	/// ```
	pub fn database(&self) -> Database {
		self.client.database(&self.database_name)
	}

	/// Begin a transaction
	///
	/// # Note
	///
	/// MongoDB transactions require a replica set or sharded cluster.
	///
	/// # Example
	///
	/// ```rust,no_run
	/// use reinhardt_db::nosql::backends::mongodb::MongoDBBackend;
	/// use bson::doc;
	///
	/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
	/// let backend = MongoDBBackend::connect("mongodb://localhost:27017").await?
	///     .with_database("mydb");
	///
	/// // Begin transaction
	/// let mut tx = backend.begin_transaction().await?;
	///
	/// // Perform operations...
	///
	/// // Commit or rollback
	/// tx.commit().await?;
	/// # Ok(())
	/// # }
	/// ```
	pub async fn begin_transaction(&self) -> Result<MongoDBTransactionExecutor> {
		// Start a new session from the client
		let mut session = self.client.start_session().await.map_err(|e| {
			NoSQLError::ConnectionError(format!("Failed to start MongoDB session: {}", e))
		})?;

		// Begin the transaction on the session
		session.start_transaction().await.map_err(|e| {
			NoSQLError::DatabaseError(format!("Failed to start MongoDB transaction: {}", e))
		})?;

		Ok(MongoDBTransactionExecutor::new(
			session,
			Arc::clone(&self.client),
			self.database_name.clone(),
		))
	}
}

#[async_trait]
impl NoSQLBackend for MongoDBBackend {
	fn backend_type(&self) -> NoSQLBackendType {
		NoSQLBackendType::MongoDB
	}

	async fn health_check(&self) -> Result<()> {
		// Perform a simple ping to check database connectivity
		let db = self.database();
		db.run_command(bson::doc! { "ping": 1 })
			.await
			.map_err(|e| NoSQLError::ConnectionError(format!("Health check failed: {}", e)))?;
		Ok(())
	}

	fn as_any(&self) -> &dyn std::any::Any {
		self
	}
}

#[async_trait]
impl DocumentBackend for MongoDBBackend {
	async fn find_one(&self, collection: &str, filter: Document) -> Result<Option<Document>> {
		let db = self.database();
		let coll = db.collection::<Document>(collection);

		coll.find_one(filter)
			.await
			.map_err(|e| NoSQLError::ExecutionError(e.to_string()))
	}

	async fn find_many(
		&self,
		collection: &str,
		filter: Document,
		options: FindOptions,
	) -> Result<Vec<Document>> {
		use futures::stream::TryStreamExt;

		let db = self.database();
		let coll = db.collection::<Document>(collection);

		// Convert FindOptions to MongoDB's FindOptions
		let mut mongo_options = mongodb::options::FindOptions::default();
		mongo_options.limit = options.limit;
		mongo_options.skip = options.skip;
		mongo_options.sort = options.sort;
		mongo_options.projection = options.projection;
		mongo_options.batch_size = options.batch_size;

		let cursor = coll
			.find(filter)
			.with_options(mongo_options)
			.await
			.map_err(|e| NoSQLError::ExecutionError(e.to_string()))?;

		cursor
			.try_collect()
			.await
			.map_err(|e| NoSQLError::ExecutionError(e.to_string()))
	}

	async fn insert_one(&self, collection: &str, document: Document) -> Result<String> {
		let db = self.database();
		let coll = db.collection::<Document>(collection);

		let result = coll
			.insert_one(document)
			.await
			.map_err(|e| NoSQLError::ExecutionError(e.to_string()))?;

		// Convert Bson to String
		match result.inserted_id {
			Bson::ObjectId(oid) => Ok(oid.to_hex()),
			Bson::String(s) => Ok(s),
			other => Ok(other.to_string()),
		}
	}

	async fn insert_many(&self, collection: &str, documents: Vec<Document>) -> Result<Vec<String>> {
		let db = self.database();
		let coll = db.collection::<Document>(collection);

		let result = coll
			.insert_many(documents)
			.await
			.map_err(|e| NoSQLError::ExecutionError(e.to_string()))?;

		// Convert Bson IDs to Strings
		let ids = result
			.inserted_ids
			.into_values()
			.map(|bson| match bson {
				Bson::ObjectId(oid) => oid.to_hex(),
				Bson::String(s) => s,
				other => other.to_string(),
			})
			.collect();

		Ok(ids)
	}

	async fn update_one(
		&self,
		collection: &str,
		filter: Document,
		update: Document,
	) -> Result<UpdateResult> {
		let db = self.database();
		let coll = db.collection::<Document>(collection);

		let result = coll
			.update_one(filter, update)
			.await
			.map_err(|e| NoSQLError::ExecutionError(e.to_string()))?;

		let upserted_id = result.upserted_id.map(|bson| match bson {
			Bson::ObjectId(oid) => oid.to_hex(),
			Bson::String(s) => s,
			other => other.to_string(),
		});

		Ok(UpdateResult::new(
			result.matched_count,
			result.modified_count,
			if upserted_id.is_some() { 1 } else { 0 },
			upserted_id,
		))
	}

	async fn update_many(
		&self,
		collection: &str,
		filter: Document,
		update: Document,
	) -> Result<UpdateResult> {
		let db = self.database();
		let coll = db.collection::<Document>(collection);

		let result = coll
			.update_many(filter, update)
			.await
			.map_err(|e| NoSQLError::ExecutionError(e.to_string()))?;

		let upserted_id = result.upserted_id.map(|bson| match bson {
			Bson::ObjectId(oid) => oid.to_hex(),
			Bson::String(s) => s,
			other => other.to_string(),
		});

		Ok(UpdateResult::new(
			result.matched_count,
			result.modified_count,
			if upserted_id.is_some() { 1 } else { 0 },
			upserted_id,
		))
	}

	async fn delete_one(&self, collection: &str, filter: Document) -> Result<u64> {
		let db = self.database();
		let coll = db.collection::<Document>(collection);

		let result = coll
			.delete_one(filter)
			.await
			.map_err(|e| NoSQLError::ExecutionError(e.to_string()))?;

		Ok(result.deleted_count)
	}

	async fn delete_many(&self, collection: &str, filter: Document) -> Result<u64> {
		let db = self.database();
		let coll = db.collection::<Document>(collection);

		let result = coll
			.delete_many(filter)
			.await
			.map_err(|e| NoSQLError::ExecutionError(e.to_string()))?;

		Ok(result.deleted_count)
	}

	async fn aggregate(&self, collection: &str, pipeline: Vec<Document>) -> Result<Vec<Document>> {
		use futures::stream::TryStreamExt;

		let db = self.database();
		let coll = db.collection::<Document>(collection);

		let cursor = coll
			.aggregate(pipeline)
			.await
			.map_err(|e| NoSQLError::ExecutionError(e.to_string()))?;

		cursor
			.try_collect()
			.await
			.map_err(|e| NoSQLError::ExecutionError(e.to_string()))
	}
}

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

	#[test]
	fn test_builder_default() {
		let builder = MongoDBBackendBuilder::new();
		assert_eq!(builder.url, "mongodb://localhost:27017");
		assert_eq!(builder.database, "test");
		assert_eq!(builder.max_pool_size, None);
		assert_eq!(builder.min_pool_size, None);
	}

	#[test]
	fn test_builder_configuration() {
		let builder = MongoDBBackendBuilder::new()
			.url("mongodb://example.com:27017")
			.database("mydb")
			.max_pool_size(100)
			.min_pool_size(10)
			.max_idle_time_secs(300);

		assert_eq!(builder.url, "mongodb://example.com:27017");
		assert_eq!(builder.database, "mydb");
		assert_eq!(builder.max_pool_size, Some(100));
		assert_eq!(builder.min_pool_size, Some(10));
		assert_eq!(builder.max_idle_time_secs, Some(300));
	}

	#[test]
	fn test_backend_builder_method() {
		let builder = MongoDBBackend::builder();
		assert_eq!(builder.url, "mongodb://localhost:27017");
	}
}