reifydb-transaction 0.4.11

Transaction management and concurrency control for ReifyDB
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2025 ReifyDB

use OperationType::Delete;
use reifydb_core::{
	encoded::row::EncodedRow,
	interface::catalog::{
		authentication::{Authentication, AuthenticationId},
		binding::Binding,
		config::{Config, ConfigKey},
		dictionary::Dictionary,
		flow::{Flow, FlowId},
		handler::Handler,
		id::{
			BindingId, HandlerId, MigrationEventId, MigrationId, NamespaceId, ProcedureId, RingBufferId,
			SeriesId, SinkId, SourceId, TableId, TestId, ViewId,
		},
		identity::{GrantedRole, Identity, Role, RoleId},
		migration::{Migration, MigrationEvent},
		namespace::Namespace,
		policy::{Policy, PolicyId},
		procedure::Procedure,
		ringbuffer::RingBuffer,
		series::Series,
		shape::ShapeId,
		sink::Sink,
		source::Source,
		sumtype::SumType,
		table::Table,
		test::Test,
		view::View,
	},
	row::RowTtl,
};
use reifydb_type::value::{dictionary::DictionaryId, identity::IdentityId, row_number::RowNumber, sumtype::SumTypeId};

use crate::TransactionId;

pub trait TransactionalChanges:
	TransactionalBindingChanges
	+ TransactionalDictionaryChanges
	+ TransactionalFlowChanges
	+ TransactionalHandlerChanges
	+ TransactionalMigrationChanges
	+ TransactionalNamespaceChanges
	+ TransactionalProcedureChanges
	+ TransactionalRingBufferChanges
	+ TransactionalRoleChanges
	+ TransactionalPolicyChanges
	+ TransactionalSeriesChanges
	+ TransactionalSinkChanges
	+ TransactionalSourceChanges
	+ TransactionalSumTypeChanges
	+ TransactionalTableChanges
	+ TransactionalTestChanges
	+ TransactionalAuthenticationChanges
	+ TransactionalIdentityChanges
	+ TransactionalGrantedRoleChanges
	+ TransactionalViewChanges
	+ TransactionalConfigChanges
	+ TransactionalRowTtlChanges
{
}

pub trait TransactionalBindingChanges {
	fn find_binding(&self, id: BindingId) -> Option<&Binding>;

	fn find_binding_by_name(&self, namespace: NamespaceId, name: &str) -> Option<&Binding>;

	fn is_binding_deleted(&self, id: BindingId) -> bool;

	fn is_binding_deleted_by_name(&self, namespace: NamespaceId, name: &str) -> bool;
}

pub trait TransactionalRowTtlChanges {
	fn find_row_ttl(&self, shape: ShapeId) -> Option<&RowTtl>;

	fn is_row_ttl_deleted(&self, shape: ShapeId) -> bool;
}

pub trait TransactionalConfigChanges {
	fn find_config(&self, key: ConfigKey) -> Option<&Config>;
}

pub trait TransactionalDictionaryChanges {
	fn find_dictionary(&self, id: DictionaryId) -> Option<&Dictionary>;

	fn find_dictionary_by_name(&self, namespace: NamespaceId, name: &str) -> Option<&Dictionary>;

	fn is_dictionary_deleted(&self, id: DictionaryId) -> bool;

	fn is_dictionary_deleted_by_name(&self, namespace: NamespaceId, name: &str) -> bool;
}

pub trait TransactionalNamespaceChanges {
	fn find_namespace(&self, id: NamespaceId) -> Option<&Namespace>;

	fn find_namespace_by_name(&self, name: &str) -> Option<&Namespace>;

	fn is_namespace_deleted(&self, id: NamespaceId) -> bool;

	fn is_namespace_deleted_by_name(&self, name: &str) -> bool;
}

pub trait TransactionalFlowChanges {
	fn find_flow(&self, id: FlowId) -> Option<&Flow>;

	fn find_flow_by_name(&self, namespace: NamespaceId, name: &str) -> Option<&Flow>;

	fn is_flow_deleted(&self, id: FlowId) -> bool;

	fn is_flow_deleted_by_name(&self, namespace: NamespaceId, name: &str) -> bool;
}

pub trait TransactionalTableChanges {
	fn find_table(&self, id: TableId) -> Option<&Table>;

	fn find_table_by_name(&self, namespace: NamespaceId, name: &str) -> Option<&Table>;

	fn is_table_deleted(&self, id: TableId) -> bool;

	fn is_table_deleted_by_name(&self, namespace: NamespaceId, name: &str) -> bool;
}

pub trait TransactionalProcedureChanges {
	fn find_procedure(&self, id: ProcedureId) -> Option<&Procedure>;

	fn find_procedure_by_name(&self, namespace: NamespaceId, name: &str) -> Option<&Procedure>;

	fn is_procedure_deleted(&self, id: ProcedureId) -> bool;

	fn is_procedure_deleted_by_name(&self, namespace: NamespaceId, name: &str) -> bool;
}

pub trait TransactionalTestChanges {
	fn find_test(&self, id: TestId) -> Option<&Test>;

	fn find_test_by_name(&self, namespace: NamespaceId, name: &str) -> Option<&Test>;

	fn is_test_deleted(&self, id: TestId) -> bool;

	fn is_test_deleted_by_name(&self, namespace: NamespaceId, name: &str) -> bool;
}

pub trait TransactionalRingBufferChanges {
	fn find_ringbuffer(&self, id: RingBufferId) -> Option<&RingBuffer>;

	fn find_ringbuffer_by_name(&self, namespace: NamespaceId, name: &str) -> Option<&RingBuffer>;

	fn is_ringbuffer_deleted(&self, id: RingBufferId) -> bool;

	fn is_ringbuffer_deleted_by_name(&self, namespace: NamespaceId, name: &str) -> bool;
}

pub trait TransactionalSeriesChanges {
	fn find_series(&self, id: SeriesId) -> Option<&Series>;

	fn find_series_by_name(&self, namespace: NamespaceId, name: &str) -> Option<&Series>;

	fn is_series_deleted(&self, id: SeriesId) -> bool;

	fn is_series_deleted_by_name(&self, namespace: NamespaceId, name: &str) -> bool;
}

pub trait TransactionalViewChanges {
	fn find_view(&self, id: ViewId) -> Option<&View>;

	fn find_view_by_name(&self, namespace: NamespaceId, name: &str) -> Option<&View>;

	fn is_view_deleted(&self, id: ViewId) -> bool;

	fn is_view_deleted_by_name(&self, namespace: NamespaceId, name: &str) -> bool;
}

pub trait TransactionalSumTypeChanges {
	fn find_sumtype(&self, id: SumTypeId) -> Option<&SumType>;

	fn find_sumtype_by_name(&self, namespace: NamespaceId, name: &str) -> Option<&SumType>;

	fn is_sumtype_deleted(&self, id: SumTypeId) -> bool;

	fn is_sumtype_deleted_by_name(&self, namespace: NamespaceId, name: &str) -> bool;
}

pub trait TransactionalHandlerChanges {
	fn find_handler_by_id(&self, id: HandlerId) -> Option<&Handler>;

	fn find_handler_by_name(&self, namespace: NamespaceId, name: &str) -> Option<&Handler>;

	fn is_handler_deleted(&self, id: HandlerId) -> bool;

	fn is_handler_deleted_by_name(&self, namespace: NamespaceId, name: &str) -> bool;
}

pub trait TransactionalIdentityChanges {
	fn find_identity(&self, id: IdentityId) -> Option<&Identity>;

	fn find_identity_by_name(&self, name: &str) -> Option<&Identity>;

	fn is_identity_deleted(&self, id: IdentityId) -> bool;

	fn is_identity_deleted_by_name(&self, name: &str) -> bool;
}

pub trait TransactionalRoleChanges {
	fn find_role(&self, id: RoleId) -> Option<&Role>;

	fn find_role_by_name(&self, name: &str) -> Option<&Role>;

	fn is_role_deleted(&self, id: RoleId) -> bool;

	fn is_role_deleted_by_name(&self, name: &str) -> bool;
}

pub trait TransactionalAuthenticationChanges {
	fn find_authentication(&self, id: AuthenticationId) -> Option<&Authentication>;

	fn find_authentication_by_identity_and_method(
		&self,
		identity: IdentityId,
		method: &str,
	) -> Option<&Authentication>;

	fn is_authentication_deleted(&self, id: AuthenticationId) -> bool;

	fn is_authentication_deleted_by_identity_and_method(&self, identity: IdentityId, method: &str) -> bool;
}

pub trait TransactionalGrantedRoleChanges {
	fn find_granted_role(&self, identity: IdentityId, role: RoleId) -> Option<&GrantedRole>;

	fn find_granted_roles_for_identity(&self, identity: IdentityId) -> Vec<&GrantedRole>;

	fn is_granted_role_deleted(&self, identity: IdentityId, role: RoleId) -> bool;
}

pub trait TransactionalPolicyChanges {
	fn find_policy(&self, id: PolicyId) -> Option<&Policy>;

	fn find_policy_by_name(&self, name: &str) -> Option<&Policy>;

	fn is_policy_deleted(&self, id: PolicyId) -> bool;

	fn is_policy_deleted_by_name(&self, name: &str) -> bool;
}

pub trait TransactionalSourceChanges {
	fn find_source(&self, id: SourceId) -> Option<&Source>;

	fn find_source_by_name(&self, namespace: NamespaceId, name: &str) -> Option<&Source>;

	fn is_source_deleted(&self, id: SourceId) -> bool;

	fn is_source_deleted_by_name(&self, namespace: NamespaceId, name: &str) -> bool;
}

pub trait TransactionalSinkChanges {
	fn find_sink(&self, id: SinkId) -> Option<&Sink>;

	fn find_sink_by_name(&self, namespace: NamespaceId, name: &str) -> Option<&Sink>;

	fn is_sink_deleted(&self, id: SinkId) -> bool;

	fn is_sink_deleted_by_name(&self, namespace: NamespaceId, name: &str) -> bool;
}

pub trait TransactionalMigrationChanges {
	fn find_migration(&self, id: MigrationId) -> Option<&Migration>;

	fn find_migration_by_name(&self, name: &str) -> Option<&Migration>;

	fn is_migration_deleted(&self, id: MigrationId) -> bool;

	fn is_migration_deleted_by_name(&self, name: &str) -> bool;
}

#[derive(Default, Debug, Clone)]
pub struct TransactionalCatalogChanges {
	/// Transaction ID this change set belongs to
	pub txn_id: TransactionId,
	/// Configuration changes in order
	pub config: Vec<Change<Config>>,
	/// All binding definition changes in order (no coalescing)
	pub binding: Vec<Change<Binding>>,
	/// All dictionary definition changes in order (no coalescing)
	pub dictionary: Vec<Change<Dictionary>>,
	/// All flow definition changes in order (no coalescing)
	pub flow: Vec<Change<Flow>>,
	/// All handler definition changes in order (no coalescing)
	pub handler: Vec<Change<Handler>>,
	/// All migration definition changes in order (no coalescing)
	pub migration: Vec<Change<Migration>>,
	/// All migration event changes in order (no coalescing)
	pub migration_event: Vec<Change<MigrationEvent>>,
	/// All namespace definition changes in order (no coalescing)
	pub namespace: Vec<Change<Namespace>>,
	/// All procedure definition changes in order (no coalescing)
	pub procedure: Vec<Change<Procedure>>,
	/// All ring buffer definition changes in order (no coalescing)
	pub ringbuffer: Vec<Change<RingBuffer>>,
	/// All series definition changes in order (no coalescing)
	pub series: Vec<Change<Series>>,
	/// All sink definition changes in order (no coalescing)
	pub sink: Vec<Change<Sink>>,
	/// All source definition changes in order (no coalescing)
	pub source: Vec<Change<Source>>,
	pub sumtype: Vec<Change<SumType>>,
	/// All test definition changes in order (no coalescing)
	pub test: Vec<Change<Test>>,
	/// All table definition changes in order (no coalescing)
	pub table: Vec<Change<Table>>,
	/// All identity definition changes in order (no coalescing)
	pub identity: Vec<Change<Identity>>,
	/// All authentication definition changes in order (no coalescing)
	pub authentication: Vec<Change<Authentication>>,
	/// All role definition changes in order (no coalescing)
	pub role: Vec<Change<Role>>,
	/// All granted-role changes in order (no coalescing)
	pub granted_role: Vec<Change<GrantedRole>>,
	/// All policy definition changes in order (no coalescing)
	pub policy: Vec<Change<Policy>>,
	/// All view definition changes in order (no coalescing)
	pub view: Vec<Change<View>>,
	/// All row TTL changes in order (no coalescing)
	pub row_ttl: Vec<Change<(ShapeId, RowTtl)>>,
	/// Order of operations for replay/rollback
	pub log: Vec<Operation>,
}

pub struct CatalogChangesSavepoint {
	binding_len: usize,
	config_len: usize,
	dictionary_len: usize,
	flow_len: usize,
	handler_len: usize,
	migration_len: usize,
	migration_event_len: usize,
	namespace_len: usize,
	procedure_len: usize,
	ringbuffer_len: usize,
	series_len: usize,
	sink_len: usize,
	source_len: usize,
	sumtype_len: usize,
	test_len: usize,
	table_len: usize,
	identity_len: usize,
	authentication_len: usize,
	role_len: usize,
	granted_role_len: usize,
	policy_len: usize,
	view_len: usize,
	row_ttl_len: usize,
	log_len: usize,
}

impl TransactionalCatalogChanges {
	pub fn savepoint(&self) -> CatalogChangesSavepoint {
		CatalogChangesSavepoint {
			binding_len: self.binding.len(),
			config_len: self.config.len(),
			dictionary_len: self.dictionary.len(),
			flow_len: self.flow.len(),
			handler_len: self.handler.len(),
			migration_len: self.migration.len(),
			migration_event_len: self.migration_event.len(),
			namespace_len: self.namespace.len(),
			procedure_len: self.procedure.len(),
			ringbuffer_len: self.ringbuffer.len(),
			series_len: self.series.len(),
			sink_len: self.sink.len(),
			source_len: self.source.len(),
			sumtype_len: self.sumtype.len(),
			test_len: self.test.len(),
			table_len: self.table.len(),
			identity_len: self.identity.len(),
			authentication_len: self.authentication.len(),
			role_len: self.role.len(),
			granted_role_len: self.granted_role.len(),
			policy_len: self.policy.len(),
			view_len: self.view.len(),
			row_ttl_len: self.row_ttl.len(),
			log_len: self.log.len(),
		}
	}

	pub fn restore_savepoint(&mut self, sp: CatalogChangesSavepoint) {
		self.binding.truncate(sp.binding_len);
		self.config.truncate(sp.config_len);
		self.dictionary.truncate(sp.dictionary_len);
		self.flow.truncate(sp.flow_len);
		self.handler.truncate(sp.handler_len);
		self.migration.truncate(sp.migration_len);
		self.migration_event.truncate(sp.migration_event_len);
		self.namespace.truncate(sp.namespace_len);
		self.procedure.truncate(sp.procedure_len);
		self.ringbuffer.truncate(sp.ringbuffer_len);
		self.series.truncate(sp.series_len);
		self.sink.truncate(sp.sink_len);
		self.source.truncate(sp.source_len);
		self.sumtype.truncate(sp.sumtype_len);
		self.test.truncate(sp.test_len);
		self.table.truncate(sp.table_len);
		self.identity.truncate(sp.identity_len);
		self.authentication.truncate(sp.authentication_len);
		self.role.truncate(sp.role_len);
		self.granted_role.truncate(sp.granted_role_len);
		self.policy.truncate(sp.policy_len);
		self.view.truncate(sp.view_len);
		self.row_ttl.truncate(sp.row_ttl_len);
		self.log.truncate(sp.log_len);
	}

	pub fn add_binding_change(&mut self, change: Change<Binding>) {
		let id = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|b| b.id)
			.expect("Change must have either pre or post state");
		let op = change.op;
		self.binding.push(change);
		self.log.push(Operation::Binding {
			id,
			op,
		});
	}

	pub fn add_config_change(&mut self, change: Change<Config>) {
		let key = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|c| c.key)
			.expect("Change must have either pre or post state");
		let op = change.op;
		self.config.push(change);
		self.log.push(Operation::Config {
			key,
			op,
		});
	}

	pub fn add_dictionary_change(&mut self, change: Change<Dictionary>) {
		let id = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|d| d.id)
			.expect("Change must have either pre or post state");
		let op = change.op;
		self.dictionary.push(change);
		self.log.push(Operation::Dictionary {
			id,
			op,
		});
	}

	pub fn add_flow_change(&mut self, change: Change<Flow>) {
		let id = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|f| f.id)
			.expect("Change must have either pre or post state");
		let op = change.op;
		self.flow.push(change);
		self.log.push(Operation::Flow {
			id,
			op,
		});
	}

	pub fn add_namespace_change(&mut self, change: Change<Namespace>) {
		let id = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|s| s.id())
			.expect("Change must have either pre or post state");
		let op = change.op;
		self.namespace.push(change);
		self.log.push(Operation::Namespace {
			id,
			op,
		});
	}

	pub fn add_handler_change(&mut self, change: Change<Handler>) {
		let id = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|h| h.id)
			.expect("Change must have either pre or post state");
		let op = change.op;
		self.handler.push(change);
		self.log.push(Operation::Handler {
			id,
			op,
		});
	}

	pub fn add_migration_change(&mut self, change: Change<Migration>) {
		let id = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|m| m.id)
			.expect("Change must have either pre or post state");
		let op = change.op;
		self.migration.push(change);
		self.log.push(Operation::Migration {
			id,
			op,
		});
	}

	pub fn add_migration_event_change(&mut self, change: Change<MigrationEvent>) {
		let id = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|e| e.id)
			.expect("Change must have either pre or post state");
		let op = change.op;
		self.migration_event.push(change);
		self.log.push(Operation::MigrationEvent {
			id,
			op,
		});
	}

	pub fn add_procedure_change(&mut self, change: Change<Procedure>) {
		let id = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|p| p.id())
			.expect("Change must have either pre or post state");
		let op = change.op;
		self.procedure.push(change);
		self.log.push(Operation::Procedure {
			id,
			op,
		});
	}

	pub fn add_test_change(&mut self, change: Change<Test>) {
		let id = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|t| t.id)
			.expect("Change must have either pre or post state");
		let op = change.op;
		self.test.push(change);
		self.log.push(Operation::Test {
			id,
			op,
		});
	}

	pub fn add_ringbuffer_change(&mut self, change: Change<RingBuffer>) {
		let id = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|rb| rb.id)
			.expect("Change must have either pre or post state");
		let op = change.op;
		self.ringbuffer.push(change);
		self.log.push(Operation::RingBuffer {
			id,
			op,
		});
	}

	pub fn add_series_change(&mut self, change: Change<Series>) {
		let id = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|s| s.id)
			.expect("Change must have either pre or post state");
		let op = change.op;
		self.series.push(change);
		self.log.push(Operation::Series {
			id,
			op,
		});
	}

	pub fn add_sink_change(&mut self, change: Change<Sink>) {
		let id = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|s| s.id)
			.expect("Change must have either pre or post state");
		let op = change.op;
		self.sink.push(change);
		self.log.push(Operation::Sink {
			id,
			op,
		});
	}

	pub fn add_source_change(&mut self, change: Change<Source>) {
		let id = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|s| s.id)
			.expect("Change must have either pre or post state");
		let op = change.op;
		self.source.push(change);
		self.log.push(Operation::Source {
			id,
			op,
		});
	}

	pub fn add_table_change(&mut self, change: Change<Table>) {
		let id = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|t| t.id)
			.expect("Change must have either pre or post state");
		let op = change.op;
		self.table.push(change);
		self.log.push(Operation::Table {
			id,
			op,
		});
	}

	pub fn add_view_change(&mut self, change: Change<View>) {
		let id = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|v| v.id())
			.expect("Change must have either pre or post state");
		let op = change.op;
		self.view.push(change);
		self.log.push(Operation::View {
			id,
			op,
		});
	}

	pub fn add_sumtype_change(&mut self, change: Change<SumType>) {
		let id = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|s| s.id)
			.expect("Change must have either pre or post state");
		let op = change.op;
		self.sumtype.push(change);
		self.log.push(Operation::SumType {
			id,
			op,
		});
	}

	pub fn add_identity_change(&mut self, change: Change<Identity>) {
		let id = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|u| u.id)
			.expect("Change must have either pre or post state");
		let op = change.op;
		self.identity.push(change);
		self.log.push(Operation::Identity {
			id,
			op,
		});
	}

	pub fn add_role_change(&mut self, change: Change<Role>) {
		let id = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|r| r.id)
			.expect("Change must have either pre or post state");
		let op = change.op;
		self.role.push(change);
		self.log.push(Operation::Role {
			id,
			op,
		});
	}

	pub fn add_granted_role_change(&mut self, change: Change<GrantedRole>) {
		let identity = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|ur| ur.identity)
			.expect("Change must have either pre or post state");
		let role = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|ur| ur.role_id)
			.expect("Change must have either pre or post state");
		let op = change.op;
		self.granted_role.push(change);
		self.log.push(Operation::GrantedRole {
			identity,
			role,
			op,
		});
	}

	pub fn add_authentication_change(&mut self, change: Change<Authentication>) {
		let id = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|a| a.id)
			.expect("Change must have either pre or post state");
		let op = change.op;
		self.authentication.push(change);
		self.log.push(Operation::Authentication {
			id,
			op,
		});
	}

	pub fn add_policy_change(&mut self, change: Change<Policy>) {
		let id = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|p| p.id)
			.expect("Change must have either pre or post state");
		let op = change.op;
		self.policy.push(change);
		self.log.push(Operation::Policy {
			id,
			op,
		});
	}

	pub fn add_row_ttl_change(&mut self, change: Change<(ShapeId, RowTtl)>) {
		let shape = change
			.post
			.as_ref()
			.or(change.pre.as_ref())
			.map(|(s, _)| *s)
			.expect("Change must have either pre or post state");
		let op = change.op;
		self.row_ttl.push(change);
		self.log.push(Operation::RowTtl {
			shape,
			op,
		});
	}
}

/// Represents a single change
#[derive(Debug, Clone)]
pub struct Change<T> {
	/// State before the change (None for CREATE)
	pub pre: Option<T>,

	/// State after the change (None for DELETE)
	pub post: Option<T>,

	/// Type of operation
	pub op: OperationType,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum OperationType {
	Create,
	Update,
	Delete,
}

/// Log entry for operation ordering
#[derive(Debug, Clone)]
pub enum Operation {
	Binding {
		id: BindingId,
		op: OperationType,
	},
	Config {
		key: ConfigKey,
		op: OperationType,
	},
	Dictionary {
		id: DictionaryId,
		op: OperationType,
	},
	Flow {
		id: FlowId,
		op: OperationType,
	},
	Handler {
		id: HandlerId,
		op: OperationType,
	},
	Migration {
		id: MigrationId,
		op: OperationType,
	},
	MigrationEvent {
		id: MigrationEventId,
		op: OperationType,
	},
	Namespace {
		id: NamespaceId,
		op: OperationType,
	},
	Procedure {
		id: ProcedureId,
		op: OperationType,
	},
	RingBuffer {
		id: RingBufferId,
		op: OperationType,
	},
	Series {
		id: SeriesId,
		op: OperationType,
	},
	Sink {
		id: SinkId,
		op: OperationType,
	},
	Source {
		id: SourceId,
		op: OperationType,
	},
	SumType {
		id: SumTypeId,
		op: OperationType,
	},
	Test {
		id: TestId,
		op: OperationType,
	},
	Table {
		id: TableId,
		op: OperationType,
	},
	Identity {
		id: IdentityId,
		op: OperationType,
	},
	Authentication {
		id: AuthenticationId,
		op: OperationType,
	},
	Role {
		id: RoleId,
		op: OperationType,
	},
	GrantedRole {
		identity: IdentityId,
		role: RoleId,
		op: OperationType,
	},
	Policy {
		id: PolicyId,
		op: OperationType,
	},
	View {
		id: ViewId,
		op: OperationType,
	},
	RowTtl {
		shape: ShapeId,
		op: OperationType,
	},
}

impl TransactionalCatalogChanges {
	pub fn new(txn_id: TransactionId) -> Self {
		Self {
			txn_id,
			binding: Vec::new(),
			config: Vec::new(),
			dictionary: Vec::new(),
			flow: Vec::new(),
			handler: Vec::new(),
			migration: Vec::new(),
			migration_event: Vec::new(),
			namespace: Vec::new(),
			procedure: Vec::new(),
			ringbuffer: Vec::new(),
			series: Vec::new(),
			sink: Vec::new(),
			source: Vec::new(),
			sumtype: Vec::new(),
			test: Vec::new(),
			table: Vec::new(),
			identity: Vec::new(),
			authentication: Vec::new(),
			role: Vec::new(),
			granted_role: Vec::new(),
			policy: Vec::new(),
			view: Vec::new(),
			row_ttl: Vec::new(),
			log: Vec::new(),
		}
	}

	/// Check if a table exists in this transaction's view
	pub fn table_exists(&self, id: TableId) -> bool {
		self.get_table(id).is_some()
	}

	/// Get current state of a table within this transaction
	pub fn get_table(&self, id: TableId) -> Option<&Table> {
		// Find the last change for this table ID
		for change in self.table.iter().rev() {
			if let Some(table) = &change.post {
				if table.id == id {
					return Some(table);
				}
			} else if let Some(table) = &change.pre
				&& table.id == id && change.op == Delete
			{
				// Table was deleted
				return None;
			}
		}
		None
	}

	/// Check if a view exists in this transaction's view
	pub fn view_exists(&self, id: ViewId) -> bool {
		self.get_view(id).is_some()
	}

	/// Get current state of a view within this transaction
	pub fn get_view(&self, id: ViewId) -> Option<&View> {
		// Find the last change for this view ID
		for change in self.view.iter().rev() {
			if let Some(view) = &change.post {
				if view.id() == id {
					return Some(view);
				}
			} else if let Some(view) = &change.pre
				&& view.id() == id && change.op == Delete
			{
				// View was deleted
				return None;
			}
		}
		None
	}

	/// Get current state of a row TTL within this transaction
	pub fn get_row_ttl(&self, shape: ShapeId) -> Option<&RowTtl> {
		// Find the last change for this shape ID
		for change in self.row_ttl.iter().rev() {
			if let Some((s, ttl)) = &change.post {
				if *s == shape {
					return Some(ttl);
				}
			} else if let Some((s, _)) = &change.pre
				&& *s == shape && change.op == Delete
			{
				// TTL was deleted
				return None;
			}
		}
		None
	}

	/// Get all pending changes for commit
	pub fn get_pending_changes(&self) -> &[Operation] {
		&self.log
	}

	/// Get the transaction ID
	pub fn txn_id(&self) -> TransactionId {
		self.txn_id
	}

	/// Get namespace definition changes
	pub fn namespace(&self) -> &[Change<Namespace>] {
		&self.namespace
	}

	/// Get table definition changes
	pub fn table(&self) -> &[Change<Table>] {
		&self.table
	}

	/// Get view definition changes
	pub fn view(&self) -> &[Change<View>] {
		&self.view
	}

	/// Clear all changes (for rollback)
	pub fn clear(&mut self) {
		self.binding.clear();
		self.config.clear();
		self.dictionary.clear();
		self.flow.clear();
		self.handler.clear();
		self.migration.clear();
		self.migration_event.clear();
		self.namespace.clear();
		self.procedure.clear();
		self.ringbuffer.clear();
		self.series.clear();
		self.sink.clear();
		self.source.clear();
		self.sumtype.clear();
		self.test.clear();
		self.table.clear();
		self.identity.clear();
		self.authentication.clear();
		self.role.clear();
		self.granted_role.clear();
		self.policy.clear();
		self.view.clear();
		self.log.clear();
	}
}

/// Tracks a table row insertion for post-commit event emission
#[derive(Debug, Clone)]
pub struct TableRowInsertion {
	pub table_id: TableId,
	pub row_number: RowNumber,
	pub encoded: EncodedRow,
}

/// Tracks row changes across different entity types for post-commit event emission
#[derive(Debug, Clone)]
pub enum RowChange {
	/// A row was inserted into a table
	TableInsert(TableRowInsertion),
	// Future variants:
	// ViewInsert(ViewRowInsertion),
	// RingBufferInsert(RingBufferRowInsertion),
	// TableUpdate(TableRowUpdate),
	// TableDelete(TableRowDelete),
}