nitrite 0.4.0

An embedded NoSQL document database for Rust with collections, repositories, indexing, and ACID transactions
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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
use super::core::{JournalEntry, TransactionContext, TransactionState, UndoEntry};
use super::transaction_store::TransactionStore;
use crate::collection::operation::CollectionOperations;
use crate::collection::{NitriteCollection, NitriteCollectionProvider};
use crate::common::{
    repository_name_by_type, Convertible, LockRegistry, NitriteEventBus, NitriteModule,
    NitritePlugin, PluginRegistrar,
};
use crate::errors::{ErrorKind, NitriteError, NitriteResult};
use crate::nitrite::Nitrite;
use crate::nitrite_config::NitriteConfig;
use crate::repository::{NitriteEntity, ObjectRepository, RepositoryOperations};
use crate::store::NitriteStore;
use crate::transaction::transactional_collection::TransactionalCollection;
use crate::transaction::transactional_repository::TransactionalRepository;
use parking_lot::Mutex;

/// A wrapper module that provides a pre-created store
struct TransactionStoreModule {
    store: NitriteStore,
}

impl TransactionStoreModule {
    fn new(store: NitriteStore) -> Self {
        TransactionStoreModule { store }
    }
}

impl NitriteModule for TransactionStoreModule {
    fn plugins(&self) -> NitriteResult<Vec<NitritePlugin>> {
        Ok(vec![self.store.as_plugin()])
    }

    fn load(&self, plugin_registrar: &PluginRegistrar) -> NitriteResult<()> {
        plugin_registrar.register_store_plugin(self.store.clone())
    }
}
/// Nitrite transaction implementation
///
/// Provides transaction coordination with support for:
/// - Multi-collection operations
/// - Two-phase commit
/// - Automatic rollback on failure
/// - ACID guarantees
use std::collections::HashMap;
use std::ops::DerefMut;
use std::sync::Arc;
use uuid::Uuid;

/// A Nitrite transaction coordinator.
///
/// Manages ACID transaction semantics across multiple collections and repositories with
/// two-phase commit protocol implementation.
///
/// # Purpose
/// Provides atomic, consistent, isolated, and durable operations across multiple data access
/// paths within a single transaction context. Ensures that either all operations commit
/// successfully or all rollback to maintain data consistency.
///
/// # Characteristics
/// - **Transaction ID**: Each transaction has a unique UUID identifier
/// - **State Machine**: Transitions through Active → PartiallyCommitted → Committed/Failed states
/// - **Multi-Collection**: Supports operations across multiple named collections
/// - **Two-Phase Commit**: First executes all commits, then records undos; rolls back on failure
/// - **Automatic Cleanup**: Calls `close()` on drop to release resources
/// - **Thread-Safe**: All internal state protected by Arc<Mutex<>>
/// - **Lock Coordination**: Uses LockRegistry for proper lock ordering
///
/// # Usage
/// Obtain a transaction from a Nitrite database instance:
/// ```ignore
/// let txn = db.begin_transaction()?;
/// let coll = txn.collection("my_collection")?;
/// // Perform operations...
/// txn.commit()?; // or rollback
/// ```
pub struct NitriteTransaction {
    id: String,
    state: Arc<Mutex<TransactionState>>,
    contexts: Arc<Mutex<HashMap<String, TransactionContext>>>,
    undo_registry: Arc<Mutex<HashMap<String, Vec<UndoEntry>>>>,
    collection_registry: Arc<Mutex<HashMap<String, TransactionalCollection>>>,
    repository_registry: Arc<Mutex<HashMap<String, TransactionalCollection>>>,
    db: Nitrite,
    lock_registry: LockRegistry,
    store: TransactionStore,
    tx_config: NitriteConfig,
}

impl NitriteTransaction {
    /// Creates a new transaction.
    ///
    /// # Arguments
    /// * `db` - Reference to the parent Nitrite database
    /// * `lock_registry` - Registry for coordinating locks across transaction contexts
    ///
    /// # Returns
    /// * `Ok(NitriteTransaction)` - A new transaction initialized in Active state
    /// * `Err(NitriteError)` - If configuration or store initialization fails
    ///
    /// The transaction creates an isolated transaction store that snapshots the
    /// current database state, ensuring read consistency for the transaction's lifetime.
    pub fn new(db: Nitrite, lock_registry: LockRegistry) -> NitriteResult<Self> {
        let db_store = db.store();
        let tx_store = TransactionStore::new(db_store);

        // Create a transaction-specific config that uses the transaction store
        // This ensures index operations in the transaction are isolated
        let tx_config = NitriteConfig::new();
        tx_config.load_module(TransactionStoreModule::new(NitriteStore::new(
            tx_store.clone(),
        )))?;
        tx_config.auto_configure()?;
        tx_config.initialize()?;

        Ok(NitriteTransaction {
            id: Uuid::new_v4().to_string(),
            state: Arc::new(Mutex::new(TransactionState::Active)),
            contexts: Arc::new(Mutex::new(HashMap::new())),
            undo_registry: Arc::new(Mutex::new(HashMap::new())),
            collection_registry: Arc::new(Mutex::new(HashMap::new())),
            repository_registry: Arc::new(Mutex::new(HashMap::new())),
            db,
            lock_registry,
            store: tx_store,
            tx_config,
        })
    }

    /// Gets the transaction ID.
    ///
    /// # Returns
    /// A string slice containing the UUID of this transaction
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Gets the current transaction state.
    ///
    /// # Returns
    /// Current `TransactionState` (Active, PartiallyCommitted, Committed, Closed, Failed, or Aborted)
    pub fn state(&self) -> TransactionState {
        *self.state.lock()
    }

    /// Gets or creates a transactional collection.
    ///
    /// # Arguments
    /// * `name` - The name of the collection to access
    ///
    /// # Returns
    /// * `Ok(NitriteCollection)` - A transactional view of the collection
    /// * `Err(NitriteError)` - If transaction is not active or collection access fails
    ///
    /// Multiple calls with the same name return the same transactional collection instance.
    /// Operations on the returned collection are recorded in the transaction journal.
    pub fn collection(&self, name: &str) -> NitriteResult<NitriteCollection> {
        self.check_active()?;

        let mut registry = self.collection_registry.lock();
        if let Some(tc) = registry.get(name) {
            return Ok(NitriteCollection::new(tc.clone()));
        }

        let primary = self.db.collection(name)?;
        let context = self.get_or_create_context(name.to_string())?;
        let db_store = self.db.store();
        let event_bus = NitriteEventBus::new();
        let operations = CollectionOperations::new(
            name,
            context.txn_map().clone(),
            self.tx_config.clone(), // Use transaction config for isolated index operations
            event_bus.clone(),
        )?;
        let tc = TransactionalCollection::new(primary, context, db_store, operations, event_bus);
        registry.insert(name.to_string(), tc.clone());
        Ok(NitriteCollection::new(tc))
    }

    /// Gets or creates a transactional object repository.
    ///
    /// # Type Parameters
    /// * `T` - The entity type, must implement `NitriteEntity` and `Convertible`
    ///
    /// # Returns
    /// * `Ok(ObjectRepository<T>)` - A transactional repository for the entity type
    /// * `Err(NitriteError)` - If transaction is not active or repository access fails
    ///
    /// Creates a repository with an auto-generated key. For keyed repositories, use
    /// `keyed_repository()`.
    pub fn repository<T>(&self) -> NitriteResult<ObjectRepository<T>>
    where
        T: Convertible<Output = T> + NitriteEntity + Send + Sync + 'static,
    {
        self.get_repository::<T>(None)
    }

    /// Gets or creates a keyed transactional object repository.
    ///
    /// # Type Parameters
    /// * `T` - The entity type, must implement `NitriteEntity` and `Convertible`
    ///
    /// # Arguments
    /// * `key` - The repository key to identify this particular repository
    ///
    /// # Returns
    /// * `Ok(ObjectRepository<T>)` - A transactional repository for the entity type
    /// * `Err(NitriteError)` - If transaction is not active or repository access fails
    ///
    /// Multiple repositories with different keys for the same entity type are stored
    /// separately, allowing parallel operations on the same type with different namespaces.
    pub fn keyed_repository<T>(&self, key: &str) -> NitriteResult<ObjectRepository<T>>
    where
        T: Convertible<Output = T> + NitriteEntity + Send + Sync + 'static,
    {
        self.get_repository(Some(key))
    }

    fn get_repository<T>(&self, key: Option<&str>) -> NitriteResult<ObjectRepository<T>>
    where
        T: Convertible<Output = T> + NitriteEntity + Send + Sync + 'static,
    {
        self.check_active()?;

        let mut registry = self.repository_registry.lock();
        // Use key in repository name to differentiate keyed repositories
        let name = repository_name_by_type::<T>(key)?;
        if let Some(tc) = registry.get(&name) {
            let collection = tc.clone();
            return self.create_repository_from_collection(collection, key);
        }

        let primary_repo = match key {
            Some(key) => self.db.keyed_repository::<T>(key)?,
            None => self.db.repository::<T>()?,
        };
        let context = self.get_or_create_context(name.clone())?;
        let db_store = self.db.store();
        let event_bus = NitriteEventBus::new();
        let operations = CollectionOperations::new(
            &name,
            context.txn_map().clone(),
            self.tx_config.clone(), // Use transaction config for isolated index operations
            event_bus.clone(),
        )?;
        let tc = TransactionalCollection::new(
            primary_repo.document_collection(),
            context,
            db_store,
            operations,
            event_bus,
        );
        registry.insert(name.clone(), tc.clone());
        self.create_repository_from_collection::<T>(tc, key)
    }

    fn create_repository_from_collection<T>(
        &self,
        tx_collection: TransactionalCollection,
        key: Option<&str>,
    ) -> NitriteResult<ObjectRepository<T>>
    where
        T: Convertible<Output = T> + NitriteEntity + Send + Sync + 'static,
    {
        let primary_repo = match key {
            Some(key) => self.db.keyed_repository::<T>(key)?,
            None => self.db.repository::<T>()?,
        };
        let nitrite_config = self.db.config().clone();
        let operation = RepositoryOperations::new();
        let nitrite_collection = NitriteCollection::new(tx_collection.clone());
        // Initialize the operation with the collection
        operation.initialize::<T>(nitrite_collection.clone())?;
        let tx_repo = TransactionalRepository::new(
            primary_repo,
            nitrite_collection,
            nitrite_config,
            operation,
        );
        Ok(ObjectRepository::new(tx_repo))
    }

    /// Gets or creates a transaction context for a collection
    fn get_or_create_context(&self, collection_name: String) -> NitriteResult<TransactionContext> {
        self.check_active()?;

        let mut contexts = self.contexts.lock();
        if let Some(ctx) = contexts.get(&collection_name) {
            return Ok(ctx.clone());
        }

        // Create a transactional map for this collection
        let txn_map = self.store.open_map(&collection_name)?;
        let ctx = TransactionContext::new(collection_name.clone(), txn_map);
        contexts.insert(collection_name, ctx.clone());
        Ok(ctx)
    }

    /// Adds a journal entry to a collection's context
    pub fn add_journal_entry(
        &self,
        collection_name: String,
        entry: JournalEntry,
    ) -> NitriteResult<()> {
        let ctx = self.get_or_create_context(collection_name)?;
        ctx.add_entry(entry)
    }

    /// Commits the transaction using two-phase commit protocol.
    ///
    /// # Returns
    /// * `Ok(())` - If all operations committed successfully
    /// * `Err(NitriteError)` - If transaction is not active or any commit operation fails
    ///
    /// # Two-Phase Commit Process
    /// 1. Transitions state to PartiallyCommitted
    /// 2. Executes all pending commit commands from journal
    /// 3. Records undo information for successful commits
    /// 4. If any commit fails: rolls back all completed commits and returns error
    /// 5. Transitions to Committed on success or Failed on error
    /// 6. Closes transaction and releases resources
    ///
    /// After commit (success or failure), the transaction is closed and cannot be used.
    pub fn commit(&self) -> NitriteResult<()> {
        // Acquire exclusive access during commit
        let mut state = self.state.lock();

        if *state != TransactionState::Active {
            return Err(NitriteError::new(
                "Transaction is not active",
                ErrorKind::InvalidOperation,
            ));
        }

        *state = TransactionState::PartiallyCommitted;
        drop(state); // Release lock

        // Perform two-phase commit
        match self.perform_commit() {
            Ok(_) => {
                *self.state.lock() = TransactionState::Committed;
                self.close();
                Ok(())
            }
            Err(e) => {
                *self.state.lock() = TransactionState::Failed;
                // Try to rollback on failure
                let _ = self.perform_rollback();
                self.close();
                Err(NitriteError::new(
                    &format!("Commit failed: {}", e.message()),
                    ErrorKind::InvalidOperation,
                ))
            }
        }
    }

    /// Two-phase commit implementation.
    ///
    /// All of the transaction's buffered commit commands across every touched collection
    /// are executed inside a single store-level atomic scope (see
    /// [`NitriteStore::with_atomic`]). On a backend that supports atomic, cross-map write
    /// scopes (e.g. the Fjall adapter) this makes the whole transaction crash-atomic: every
    /// data- and index-partition write lands together or not at all, closing the
    /// cross-partition consistency gap. On backends without atomic support the scope is a
    /// transparent pass-through and behaviour is unchanged.
    ///
    /// Because the atomic scope may replay the work on a serialization conflict, the commit
    /// commands are snapshotted (not drained) before execution and the journals are only
    /// finalized after the scope commits successfully.
    fn perform_commit(&self) -> NitriteResult<()> {
        // NOTE: We don't acquire the collection lock here because:
        // 1. Each commit command (insert/update/remove) will acquire its own lock
        // 2. The individual operations are already atomic
        // 3. Acquiring the lock here and then calling methods that also lock
        //    would cause a deadlock since parking_lot::RwLock is not reentrant

        // Snapshot the buffered commands without draining, so the atomic scope can replay
        // them if it has to retry on a serialization conflict. JournalEntry is cheap to
        // clone (Arc-wrapped commands).
        let plan: Vec<(String, Vec<JournalEntry>)> = {
            let contexts = self.contexts.lock();
            contexts
                .iter()
                .map(|(name, context)| {
                    let journal = context.journal.lock();
                    (name.clone(), journal.iter().cloned().collect())
                })
                .collect()
        };

        // Phase 1+2: execute all commit commands atomically, building the undo registry.
        // with_atomic runs this closure exactly once; the undo information escapes it via
        // `undo_cell` so it is still available on the failure path (where it drives the
        // logical rollback for non-atomic backends).
        let supports_atomic = self.db.store().supports_atomic();
        let undo_cell: Mutex<HashMap<String, Vec<UndoEntry>>> = Mutex::new(HashMap::new());

        let outcome = self.db.store().with_atomic(|| {
            let mut undo_registry: HashMap<String, Vec<UndoEntry>> = HashMap::new();
            for (collection_name, entries) in &plan {
                let mut undo_stack = Vec::new();
                for entry in entries {
                    if let Some(commit_cmd) = &entry.commit {
                        if let Err(e) = commit_cmd() {
                            // Preserve the partial undo for the failing collection so a
                            // non-atomic backend can still undo what was applied.
                            undo_registry.insert(collection_name.clone(), undo_stack);
                            *undo_cell.lock() = undo_registry;
                            return Err(NitriteError::new(
                                &format!("Failed to execute commit: {}", e.message()),
                                ErrorKind::InvalidOperation,
                            ));
                        }

                        // Record undo information for successful commits.
                        if let Some(rollback_cmd) = &entry.rollback {
                            undo_stack.push(UndoEntry {
                                collection_name: collection_name.clone(),
                                rollback: Arc::new(rollback_cmd.clone()),
                            });
                        }
                    }
                }
                undo_registry.insert(collection_name.clone(), undo_stack);
            }
            *undo_cell.lock() = undo_registry;
            Ok(())
        });

        match outcome {
            Ok(()) => {
                // The atomic scope committed durably. Finalize the bookkeeping that must run
                // exactly once: drain the journals, deactivate the contexts, and publish the
                // undo registry so a later explicit rollback can still undo the entries.
                let contexts = self.contexts.lock();
                for (_, context) in contexts.iter() {
                    context.journal.lock().clear();
                    context.set_inactive();
                }
                drop(contexts);
                *self.undo_registry.lock() = undo_cell.into_inner();
                Ok(())
            }
            Err(e) => {
                // On an atomic backend with_atomic has already discarded every storage write,
                // so the logical undo must NOT run again — leave the undo registry empty. On a
                // non-atomic backend publish the partial undo so perform_rollback can undo the
                // writes that were already applied.
                if !supports_atomic {
                    *self.undo_registry.lock() = undo_cell.into_inner();
                }
                Err(e)
            }
        }
    }

    /// Rolls back the transaction, undoing all pending operations.
    ///
    /// # Returns
    /// * `Ok(())` - If rollback completed successfully
    /// * `Err(NitriteError)` - If rollback operations fail
    ///
    /// Transitions the state to Aborted and executes all recorded rollback commands
    /// to restore the database to its pre-transaction state. If the transaction is
    /// already closed, returns Ok without further action.
    ///
    /// After rollback, the transaction is closed and cannot be used further.
    pub fn rollback(&self) -> NitriteResult<()> {
        let mut state = self.state.lock();

        if *state == TransactionState::Closed {
            return Ok(());
        }

        *state = TransactionState::Aborted;
        drop(state);

        self.perform_rollback()?;
        self.close();
        Ok(())
    }

    /// Rollback implementation
    fn perform_rollback(&self) -> NitriteResult<()> {
        let undo_registry = self.undo_registry.lock();

        for (_, undo_stack) in undo_registry.iter() {
            // NOTE: We don't acquire the collection lock here because:
            // 1. Each rollback command (remove/update/insert) will acquire its own lock
            // 2. The individual operations are already atomic
            // 3. Acquiring the lock here and then calling methods that also lock
            //    would cause a deadlock since parking_lot::RwLock is not reentrant

            // LIFO order - rollback in reverse
            for undo in undo_stack.iter().rev() {
                (undo.rollback)().ok();
            }
        }

        Ok(())
    }

    /// Closes the transaction and releases all resources.
    ///
    /// Closes all transaction contexts and their associated maps, and transitions
    /// the state to Closed. This is called automatically on drop.
    /// After closing, the transaction cannot be used further.
    pub fn close(&self) {
        let contexts = self.contexts.lock();
        for (_, ctx) in contexts.iter() {
            ctx.close();
        }

        *self.state.lock() = TransactionState::Closed;
        let _ = self.store.close_all();
    }

    /// Checks if transaction is active
    fn check_active(&self) -> NitriteResult<()> {
        let state = *self.state.lock();
        if state != TransactionState::Active {
            return Err(NitriteError::new(
                "Transaction is not active",
                ErrorKind::InvalidOperation,
            ));
        }
        Ok(())
    }

    /// Gets the total number of pending operations across all collections.
    ///
    /// # Returns
    /// Sum of all journal entries from all transactional contexts
    pub fn pending_operations(&self) -> usize {
        let contexts = self.contexts.lock();
        contexts.values().map(|ctx| ctx.pending_operations()).sum()
    }

    /// Lists all collection names accessed in this transaction.
    ///
    /// # Returns
    /// Vector of all unique collection names that have been accessed via
    /// `collection()` or repository operations
    pub fn collection_names(&self) -> Vec<String> {
        self.contexts.lock().keys().cloned().collect()
    }
}

impl Clone for NitriteTransaction {
    fn clone(&self) -> Self {
        NitriteTransaction {
            id: self.id.clone(),
            state: Arc::clone(&self.state),
            contexts: Arc::clone(&self.contexts),
            undo_registry: Arc::clone(&self.undo_registry),
            collection_registry: Arc::clone(&self.collection_registry),
            repository_registry: Arc::clone(&self.repository_registry),
            db: self.db.clone(),
            lock_registry: self.lock_registry.clone(),
            store: self.store.clone(),
            tx_config: self.tx_config.clone(),
        }
    }
}

impl std::fmt::Debug for NitriteTransaction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Acquire contexts lock once and extract both values to avoid deadlock
        let contexts = self.contexts.lock();
        let context_count = contexts.len();
        let pending_ops: usize = contexts.values().map(|ctx| ctx.pending_operations()).sum();
        drop(contexts);

        f.debug_struct("NitriteTransaction")
            .field("id", &self.id)
            .field("state", &self.state())
            .field("context_count", &context_count)
            .field("pending_operations", &pending_ops)
            .finish()
    }
}

impl Drop for NitriteTransaction {
    fn drop(&mut self) {
        // Ensure transaction is closed
        self.close();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::collection::Document;
    use crate::common::Convertible;
    use crate::common::LockRegistry;
    use crate::common::Value;
    use crate::errors::ErrorKind;
    use crate::repository::{EntityId, EntityIndex, NitriteEntity};
    use crate::transaction::core::ChangeType;

    fn create_test_db() -> Nitrite {
        Nitrite::builder().open_or_create(None, None).unwrap()
    }

    /// Test entity for repository tests
    #[derive(Clone, Debug, Default)]
    struct TestEntity {
        id: i64,
        name: String,
    }

    impl NitriteEntity for TestEntity {
        type Id = i64;

        fn entity_name(&self) -> String {
            "TestEntity".to_string()
        }

        fn entity_indexes(&self) -> Option<Vec<EntityIndex>> {
            None
        }

        fn entity_id(&self) -> Option<EntityId> {
            Some(EntityId::new("id", None, None))
        }
    }

    impl Convertible for TestEntity {
        type Output = TestEntity;

        fn to_value(&self) -> NitriteResult<Value> {
            let mut doc = Document::new();
            doc.put("id", Value::I64(self.id))?;
            doc.put("name", Value::String(self.name.clone()))?;
            doc.to_value()
        }

        fn from_value(value: &Value) -> NitriteResult<Self::Output> {
            if let Value::Document(doc) = value {
                let id = match doc.get("id") {
                    Ok(Value::I64(i)) => i,
                    _ => 0,
                };
                let name = match doc.get("name") {
                    Ok(Value::String(s)) => s.clone(),
                    _ => String::new(),
                };
                Ok(TestEntity { id, name })
            } else {
                Err(NitriteError::new(
                    "Invalid value type",
                    ErrorKind::ValidationError,
                ))
            }
        }
    }

    // ==================== Creation Tests ====================

    /// Tests that a transaction can be created
    #[test]
    fn test_transaction_creation() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry);

        assert!(tx.is_ok());
        let tx = tx.unwrap();
        assert!(!tx.id().is_empty());
        assert_eq!(tx.state(), TransactionState::Active);
    }

    /// Tests that each transaction gets a unique ID
    #[test]
    fn test_transaction_unique_ids() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx1 = NitriteTransaction::new(db.clone(), lock_registry.clone()).unwrap();
        let tx2 = NitriteTransaction::new(db, lock_registry).unwrap();

        assert_ne!(tx1.id(), tx2.id());
    }

    /// Tests that transaction ID has correct format (UUID)
    #[test]
    fn test_transaction_id_format() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        let id = tx.id();

        assert!(!id.is_empty());
        assert_eq!(id.len(), 36); // UUID v4 string length
    }

    /// Tests that new transaction is in Active state
    #[test]
    fn test_transaction_initial_state() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();

        assert_eq!(tx.state(), TransactionState::Active);
    }

    // ==================== Clone Tests ====================

    /// Tests Clone implementation
    #[test]
    fn test_transaction_clone() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx1 = NitriteTransaction::new(db, lock_registry).unwrap();
        let tx2 = tx1.clone();

        assert_eq!(tx1.id(), tx2.id());
        assert_eq!(tx1.state(), tx2.state());
    }

    /// Tests that cloned transactions share state
    #[test]
    fn test_transaction_clone_shares_state() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx1 = NitriteTransaction::new(db, lock_registry).unwrap();
        let tx2 = tx1.clone();

        // Access collection on tx1
        let _coll = tx1.collection("test_collection").unwrap();

        // Check that collection names are visible on tx2
        let names = tx2.collection_names();
        assert!(names.contains(&"test_collection".to_string()));
    }

    // ==================== Debug Tests ====================

    /// Tests Debug implementation
    #[test]
    fn test_transaction_debug() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        let debug_str = format!("{:?}", tx);

        assert!(debug_str.contains("NitriteTransaction"));
        assert!(debug_str.contains("id"));
        assert!(debug_str.contains("state"));
        assert!(debug_str.contains("context_count"));
        assert!(debug_str.contains("pending_operations"));
    }

    /// Tests Debug output with collection
    #[test]
    fn test_transaction_debug_with_collection() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        let _coll = tx.collection("test").unwrap();

        let debug_str = format!("{:?}", tx);
        // Context count should be at least 1
        assert!(debug_str.contains("context_count"));
    }

    // ==================== Collection Tests ====================

    /// Tests getting a collection from a transaction
    #[test]
    fn test_transaction_collection() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        let collection = tx.collection("test_collection");

        assert!(collection.is_ok());
    }

    /// Tests getting the same collection twice returns cached version
    #[test]
    fn test_transaction_collection_cached() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();

        let _coll1 = tx.collection("test_collection").unwrap();
        let _coll2 = tx.collection("test_collection").unwrap();

        // Collection names should only have one entry
        let names = tx.collection_names();
        assert_eq!(names.len(), 1);
    }

    /// Tests getting multiple different collections
    #[test]
    fn test_transaction_multiple_collections() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();

        let _coll1 = tx.collection("collection1").unwrap();
        let _coll2 = tx.collection("collection2").unwrap();
        let _coll3 = tx.collection("collection3").unwrap();

        let names = tx.collection_names();
        assert_eq!(names.len(), 3);
        assert!(names.contains(&"collection1".to_string()));
        assert!(names.contains(&"collection2".to_string()));
        assert!(names.contains(&"collection3".to_string()));
    }

    /// Tests getting collection from closed transaction fails
    #[test]
    fn test_transaction_collection_on_closed() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        tx.close();

        let result = tx.collection("test");

        assert!(result.is_err());
        if let Err(err) = result {
            assert_eq!(*err.kind(), ErrorKind::InvalidOperation);
            assert!(err.message().contains("not active"));
        }
    }

    // ==================== Repository Tests ====================

    /// Tests getting a repository from a transaction
    #[test]
    fn test_transaction_repository() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        let repository = tx.repository::<TestEntity>();

        assert!(repository.is_ok());
    }

    /// Tests getting a keyed repository from a transaction
    #[test]
    fn test_transaction_keyed_repository() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        let repository = tx.keyed_repository::<TestEntity>("my_key");

        assert!(repository.is_ok());
    }

    /// Tests getting repository from closed transaction fails
    #[test]
    fn test_transaction_repository_on_closed() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        tx.close();

        let result = tx.repository::<TestEntity>();

        assert!(result.is_err());
        if let Err(err) = result {
            assert_eq!(*err.kind(), ErrorKind::InvalidOperation);
        }
    }

    /// Tests getting keyed repository from closed transaction fails
    #[test]
    fn test_transaction_keyed_repository_on_closed() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        tx.close();

        let result = tx.keyed_repository::<TestEntity>("key");

        assert!(result.is_err());
        if let Err(err) = result {
            assert_eq!(*err.kind(), ErrorKind::InvalidOperation);
        }
    }

    // ==================== Commit Tests ====================

    /// Tests committing an empty transaction
    #[test]
    fn test_transaction_commit_empty() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        let result = tx.commit();

        assert!(result.is_ok());
        assert_eq!(tx.state(), TransactionState::Closed);
    }

    /// Tests committing a transaction with collection access
    #[test]
    fn test_transaction_commit_with_collection() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        let _coll = tx.collection("test").unwrap();

        let result = tx.commit();

        assert!(result.is_ok());
        assert_eq!(tx.state(), TransactionState::Closed);
    }

    /// Tests committing an already committed transaction fails
    #[test]
    fn test_transaction_commit_twice() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        tx.commit().unwrap();

        let result = tx.commit();

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(*err.kind(), ErrorKind::InvalidOperation);
        assert!(err.message().contains("not active"));
    }

    /// Tests committing a closed transaction fails
    #[test]
    fn test_transaction_commit_on_closed() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        tx.close();

        let result = tx.commit();

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(*err.kind(), ErrorKind::InvalidOperation);
    }

    /// Tests that state transitions through PartiallyCommitted to Committed
    #[test]
    fn test_transaction_commit_state_transition() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        assert_eq!(tx.state(), TransactionState::Active);

        tx.commit().unwrap();

        // After successful commit, state should be Closed
        assert_eq!(tx.state(), TransactionState::Closed);
    }

    // ==================== Rollback Tests ====================

    /// Tests rolling back an empty transaction
    #[test]
    fn test_transaction_rollback_empty() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        let result = tx.rollback();

        assert!(result.is_ok());
        assert_eq!(tx.state(), TransactionState::Closed);
    }

    /// Tests rolling back a transaction with collection access
    #[test]
    fn test_transaction_rollback_with_collection() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        let _coll = tx.collection("test").unwrap();

        let result = tx.rollback();

        assert!(result.is_ok());
        assert_eq!(tx.state(), TransactionState::Closed);
    }

    /// Tests that rollback on a closed transaction succeeds (idempotent)
    #[test]
    fn test_transaction_rollback_on_closed() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        tx.close();

        let result = tx.rollback();

        assert!(result.is_ok());
    }

    /// Tests that rollback after commit succeeds (already closed)
    #[test]
    fn test_transaction_rollback_after_commit() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        tx.commit().unwrap();

        // Transaction is already closed, rollback should succeed
        let result = tx.rollback();
        assert!(result.is_ok());
    }

    /// Tests rollback twice succeeds (idempotent)
    #[test]
    fn test_transaction_rollback_twice() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        tx.rollback().unwrap();

        let result = tx.rollback();

        assert!(result.is_ok());
    }

    // ==================== Close Tests ====================

    /// Tests closing a transaction
    #[test]
    fn test_transaction_close() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        tx.close();

        assert_eq!(tx.state(), TransactionState::Closed);
    }

    /// Tests closing a transaction multiple times (idempotent)
    #[test]
    fn test_transaction_close_idempotent() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        tx.close();
        tx.close();
        tx.close();

        assert_eq!(tx.state(), TransactionState::Closed);
    }

    /// Tests that Drop calls close automatically
    #[test]
    fn test_transaction_drop_calls_close() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db.clone(), lock_registry.clone()).unwrap();
        let _id = tx.id().to_string();

        // Create a collection to ensure context exists
        let _coll = tx.collection("test").unwrap();

        drop(tx);
        // After drop, transaction should be closed
        // We can't directly test this without reference, but coverage confirms drop() was called
    }

    // ==================== check_active Tests ====================

    /// Tests check_active on active transaction (implicit through collection access)
    #[test]
    fn test_check_active_on_active_transaction() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();

        // This internally calls check_active
        let result = tx.collection("test");
        assert!(result.is_ok());
    }

    /// Tests check_active fails on closed transaction
    #[test]
    fn test_check_active_on_closed_transaction() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        tx.close();

        // This internally calls check_active
        let result = tx.collection("test");
        assert!(result.is_err());
    }

    // ==================== pending_operations Tests ====================

    /// Tests pending_operations on empty transaction
    #[test]
    fn test_pending_operations_empty() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();

        assert_eq!(tx.pending_operations(), 0);
    }

    /// Tests pending_operations after accessing collection
    #[test]
    fn test_pending_operations_with_collection() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        let _coll = tx.collection("test").unwrap();

        // Just accessing collection doesn't add pending operations
        // Operations are added when actually modifying data
        let _ = tx.pending_operations();
    }

    // ==================== collection_names Tests ====================

    /// Tests collection_names on empty transaction
    #[test]
    fn test_collection_names_empty() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();

        let names = tx.collection_names();
        assert!(names.is_empty());
    }

    /// Tests collection_names with multiple collections
    #[test]
    fn test_collection_names_with_collections() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();

        let _coll1 = tx.collection("alpha").unwrap();
        let _coll2 = tx.collection("beta").unwrap();
        let _coll3 = tx.collection("gamma").unwrap();

        let names = tx.collection_names();
        assert_eq!(names.len(), 3);
        assert!(names.contains(&"alpha".to_string()));
        assert!(names.contains(&"beta".to_string()));
        assert!(names.contains(&"gamma".to_string()));
    }

    // ==================== Journal Entry Tests ====================

    /// Tests adding a journal entry
    #[test]
    fn test_add_journal_entry() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();

        // Create a simple journal entry
        let entry = JournalEntry {
            change_type: ChangeType::Insert,
            commit: Some(Arc::new(|| Ok(()))),
            rollback: Some(Arc::new(|| Ok(()))),
        };

        let result = tx.add_journal_entry("test_collection".to_string(), entry);

        assert!(result.is_ok());
    }

    /// Tests adding journal entry on closed transaction fails
    #[test]
    fn test_add_journal_entry_on_closed() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        tx.close();

        let entry = JournalEntry {
            change_type: ChangeType::Update,
            commit: Some(Arc::new(|| Ok(()))),
            rollback: Some(Arc::new(|| Ok(()))),
        };

        let result = tx.add_journal_entry("test_collection".to_string(), entry);

        assert!(result.is_err());
    }

    /// Tests adding multiple journal entries
    #[test]
    fn test_add_multiple_journal_entries() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();

        for i in 0..5 {
            let entry = JournalEntry {
                change_type: ChangeType::Insert,
                commit: Some(Arc::new(move || Ok(()))),
                rollback: Some(Arc::new(move || Ok(()))),
            };
            tx.add_journal_entry(format!("collection_{}", i), entry)
                .unwrap();
        }

        let names = tx.collection_names();
        assert_eq!(names.len(), 5);
    }

    // ==================== Concurrency Tests ====================

    /// Tests concurrent access to transaction
    #[test]
    fn test_transaction_concurrent_access() {
        use std::sync::Barrier;
        use std::thread;

        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        let tx_id = tx.id().to_string();

        let tx1 = tx.clone();
        let tx2 = tx.clone();

        // Use a barrier to ensure both threads complete their work
        // before we check the results
        let barrier = Arc::new(Barrier::new(3)); // 2 threads + main thread
        let barrier1 = barrier.clone();
        let barrier2 = barrier.clone();

        let handle1 = thread::spawn(move || {
            let result = tx1.collection("collection1");
            let id = tx1.id().to_string();
            barrier1.wait(); // Signal that we're done
            (result.is_ok(), id)
        });

        let handle2 = thread::spawn(move || {
            let result = tx2.collection("collection2");
            let id = tx2.id().to_string();
            barrier2.wait(); // Signal that we're done
            (result.is_ok(), id)
        });

        // Wait for both threads to complete their work
        barrier.wait();

        let (ok1, id1) = handle1.join().unwrap();
        let (ok2, id2) = handle2.join().unwrap();

        // Verify results
        assert!(ok1, "Thread 1 should successfully access collection");
        assert!(ok2, "Thread 2 should successfully access collection");

        // Both should have same transaction ID
        assert_eq!(id1, tx_id);
        assert_eq!(id2, tx_id);

        // Both collections should be registered
        let names = tx.collection_names();
        assert_eq!(names.len(), 2);
    }

    // ==================== get_or_create_context Tests ====================

    /// Tests that get_or_create_context creates new context for new collection
    #[test]
    fn test_get_or_create_context_new() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();

        // Accessing a collection creates context internally
        let _coll = tx.collection("new_collection").unwrap();

        assert!(tx
            .collection_names()
            .contains(&"new_collection".to_string()));
    }

    /// Tests that get_or_create_context returns existing context
    #[test]
    fn test_get_or_create_context_existing() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();

        let _coll1 = tx.collection("same_collection").unwrap();
        let _coll2 = tx.collection("same_collection").unwrap();

        // Should still only have one context
        assert_eq!(tx.collection_names().len(), 1);
    }

    // ==================== State Transition Tests ====================

    /// Tests state after successful commit
    #[test]
    fn test_state_after_commit() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        assert_eq!(tx.state(), TransactionState::Active);

        tx.commit().unwrap();
        assert_eq!(tx.state(), TransactionState::Closed);
    }

    /// Tests state after rollback
    #[test]
    fn test_state_after_rollback() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        assert_eq!(tx.state(), TransactionState::Active);

        tx.rollback().unwrap();
        assert_eq!(tx.state(), TransactionState::Closed);
    }

    /// Tests state after close
    #[test]
    fn test_state_after_close() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        assert_eq!(tx.state(), TransactionState::Active);

        tx.close();
        assert_eq!(tx.state(), TransactionState::Closed);
    }

    // ==================== Error Message Tests ====================

    /// Tests error message when committing inactive transaction
    #[test]
    fn test_commit_error_message() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        tx.close();

        let result = tx.commit();
        assert!(result.is_err());

        let err = result.unwrap_err();
        assert!(err.message().contains("not active"));
    }

    /// Tests error message when accessing collection on closed transaction
    #[test]
    fn test_collection_error_message() {
        let db = create_test_db();
        let lock_registry = LockRegistry::new();

        let tx = NitriteTransaction::new(db, lock_registry).unwrap();
        tx.close();

        let result = tx.collection("test");
        assert!(result.is_err());

        if let Err(err) = result {
            assert!(err.message().contains("not active"));
        }
    }
}