reinhardt-db 0.3.14

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
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
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

const SQL_NULL_ARRAY_ELEMENT_KEY: &str = "__reinhardt_sql_null_array_element";
const JSON_ARRAY_ELEMENT_KEY: &str = "__reinhardt_json_array_element";

#[doc(hidden)]
pub type DatabaseValue = serde_json::Value;

#[doc(hidden)]
pub type DatabaseSerializationError = serde_json::Error;

#[doc(hidden)]
pub fn serialize_model_database_value<T: Serialize>(
	value: &T,
) -> Result<DatabaseValue, DatabaseSerializationError> {
	serde_json::to_value(value)
}

/// Encode a nullable JSON array while retaining SQL-NULL element semantics.
#[doc(hidden)]
pub fn serialize_nullable_json_array(values: &[Option<serde_json::Value>]) -> serde_json::Value {
	serde_json::Value::Array(
		values
			.iter()
			.map(|value| {
				value.as_ref().map_or_else(
					|| {
						let mut marker = serde_json::Map::new();
						marker.insert(
							SQL_NULL_ARRAY_ELEMENT_KEY.to_owned(),
							serde_json::Value::Bool(true),
						);
						serde_json::Value::Object(marker)
					},
					|value| {
						let mut element = serde_json::Map::new();
						element.insert(JSON_ARRAY_ELEMENT_KEY.to_owned(), value.clone());
						serde_json::Value::Object(element)
					},
				)
			})
			.collect(),
	)
}

/// Encode an optional nullable JSON array while retaining SQL-NULL elements.
#[doc(hidden)]
pub fn serialize_nullable_json_array_option(
	values: &Option<Vec<Option<serde_json::Value>>>,
) -> serde_json::Value {
	values.as_ref().map_or(serde_json::Value::Null, |values| {
		serialize_nullable_json_array(values)
	})
}

pub(crate) fn is_sql_null_array_element(value: &serde_json::Value) -> bool {
	value.as_object().is_some_and(|object| {
		object.len() == 1
			&& object
				.get(SQL_NULL_ARRAY_ELEMENT_KEY)
				.is_some_and(|value| value == &serde_json::Value::Bool(true))
	})
}

pub(crate) fn unwrap_json_array_element(value: &serde_json::Value) -> Option<&serde_json::Value> {
	value.as_object().and_then(|object| {
		(object.len() == 1)
			.then(|| object.get(JSON_ARRAY_ELEMENT_KEY))
			.flatten()
	})
}

/// Trait for type-safe field selectors
///
/// This trait is automatically implemented for field selector structs generated
/// by the `#[model(...)]` macro (e.g., `UserFields`).
pub trait FieldSelector: Clone {
	/// Set table alias for all fields
	///
	/// This is used for self-joins where the same table appears multiple times
	/// with different aliases.
	fn with_alias(self, alias: &str) -> Self;
}

/// Deserializes one route segment into a model primary-key type.
///
/// The route segment is first deserialized as a JSON string so string keys,
/// including numeric-looking values such as `"00123"`, retain their exact
/// representation. If that fails, the raw segment is deserialized as JSON to
/// support numeric primary keys.
#[doc(hidden)]
pub fn deserialize_primary_key_from_str<T>(value: &str) -> Result<T, serde_json::Error>
where
	T: serde::de::DeserializeOwned,
{
	serde_json::from_value(serde_json::Value::String(value.to_owned()))
		.or_else(|_| serde_json::from_str(value))
}

fn is_timezone_aware_datetime_type(type_name: &str) -> bool {
	type_name.starts_with("chrono::DateTime<")
		|| type_name.starts_with("chrono::datetime::DateTime<")
}

fn is_decimal_type(type_name: &str) -> bool {
	matches!(
		type_name,
		"rust_decimal::Decimal" | "rust_decimal::decimal::Decimal"
	)
}

/// Converts route values for primary-key types with dedicated filter variants.
///
/// This keeps UUID and UTC timestamp primary keys in their typed filter
/// variants after [`deserialize_primary_key_from_str`] applies its
/// string-first and raw-JSON fallback parsing.
#[doc(hidden)]
pub fn deserialize_primary_key_filter_value_from_str<T>(
	value: &str,
) -> Result<Option<super::query::FilterValue>, serde_json::Error>
where
	T: serde::de::DeserializeOwned,
{
	if std::any::type_name::<T>() == std::any::type_name::<uuid::Uuid>() {
		return deserialize_primary_key_from_str::<uuid::Uuid>(value)
			.map(super::query::FilterValue::Uuid)
			.map(Some);
	}

	if is_timezone_aware_datetime_type(std::any::type_name::<T>()) {
		return serde_json::from_value::<chrono::DateTime<chrono::Utc>>(serde_json::Value::String(
			value.to_owned(),
		))
		.map(super::query::FilterValue::Timestamp)
		.map(Some);
	}

	if is_decimal_type(std::any::type_name::<T>()) {
		return deserialize_primary_key_from_str::<rust_decimal::Decimal>(value)
			.map(super::query::FilterValue::Decimal)
			.map(Some);
	}

	if std::any::type_name::<T>() == std::any::type_name::<chrono::NaiveDate>() {
		return deserialize_primary_key_from_str::<chrono::NaiveDate>(value)
			.map(super::query::FilterValue::Date)
			.map(Some);
	}

	if std::any::type_name::<T>() == std::any::type_name::<chrono::NaiveTime>() {
		return deserialize_primary_key_from_str::<chrono::NaiveTime>(value)
			.map(super::query::FilterValue::Time)
			.map(Some);
	}

	Ok(None)
}

/// Converts a field metadata type and route segment into a typed filter value.
#[doc(hidden)]
pub fn filter_value_from_field_type(
	field_type: &str,
	value: &str,
) -> reinhardt_core::exception::Result<super::query::FilterValue> {
	use reinhardt_core::exception::Error;

	let invalid = || Error::Validation(format!("invalid {field_type} value: {value}"));
	match field_type.rsplit('.').next() {
		Some("BooleanField") => value
			.parse()
			.map(super::query::FilterValue::Boolean)
			.map_err(|_| invalid()),
		Some("IntegerField") | Some("AutoField") => value
			.parse::<i32>()
			.map(|value| super::query::FilterValue::Integer(i64::from(value)))
			.map_err(|_| invalid()),
		Some("BigIntegerField") | Some("BigAutoField") => value
			.parse::<i64>()
			.map(super::query::FilterValue::Integer)
			.map_err(|_| invalid()),
		Some("FloatField") => value
			.parse::<f64>()
			.map(super::query::FilterValue::Float)
			.map_err(|_| invalid()),
		Some("UuidField") | Some("UUIDField") => value
			.parse()
			.map(super::query::FilterValue::Uuid)
			.map_err(|_| invalid()),
		Some("DateTimeField") => chrono::DateTime::parse_from_rfc3339(value)
			.map(|value| super::query::FilterValue::Timestamp(value.with_timezone(&chrono::Utc)))
			.map_err(|_| invalid()),
		Some("DateField") => value
			.parse()
			.map(super::query::FilterValue::Date)
			.map_err(|_| invalid()),
		Some("TimeField") => value
			.parse()
			.map(super::query::FilterValue::Time)
			.map_err(|_| invalid()),
		Some("DecimalField") => value
			.parse()
			.map(super::query::FilterValue::Decimal)
			.map_err(|_| invalid()),
		_ => Ok(super::query::FilterValue::String(value.to_owned())),
	}
}

/// Core trait for database models
/// Uses composition instead of inheritance - models can implement multiple traits
///
/// # Breaking Change (Phase 4)
///
/// A new associated type `Fields` has been added. It provides a type-safe field selector.
/// When using the `#[model(...)]` macro, this implementation is automatically generated.
pub trait Model: Serialize + for<'de> Deserialize<'de> + Send + Sync + Clone {
	/// The primary key type
	type PrimaryKey: Send + Sync + Clone + std::fmt::Display;

	/// Type-safe field selector
	///
	/// This type is automatically generated by the `#[model(...)]` macro as `{Model}Fields`.
	/// It provides compile-time type safety for field references in queries.
	type Fields: FieldSelector;

	/// The manager type returned by `objects()`.
	///
	/// Defaults to [`Manager<Self>`](super::Manager) when no custom manager is
	/// configured. When `#[model(manager = MyManager)]` is specified, the macro
	/// sets this to the custom manager type, so `objects()` returns the custom
	/// manager directly.
	type Objects: super::custom_manager::CustomManager<Model = Self> + Default;

	/// Get the table name
	fn table_name() -> &'static str;

	/// Create a new field selector instance
	///
	/// This method is automatically implemented by the `#[model(...)]` macro.
	/// It returns a new instance of the type-safe field selector.
	fn new_fields() -> Self::Fields;

	/// Get the app label for this model
	///
	/// This is used by the migration system to organize models by application.
	/// Defaults to "default" if not specified.
	fn app_label() -> &'static str {
		"default"
	}

	/// Get the primary key field name
	fn primary_key_field() -> &'static str {
		"id"
	}

	/// Converts a primary key into a query filter value.
	///
	/// Primitive integer primary keys retain numeric bindings, while standard
	/// string primary keys retain exact string bindings. Other hand-written key
	/// types retain the historical numeric-or-string fallback for compatibility;
	/// custom string-like newtypes should override this method for exact binding.
	/// Derived models override this conversion for declared primary-key types with
	/// a dedicated database binding, such as strings, UUIDs, and timestamps.
	fn primary_key_filter_value(pk: Self::PrimaryKey) -> super::query::FilterValue {
		let value = pk.to_string();
		let type_name = std::any::type_name::<Self::PrimaryKey>();

		if [
			std::any::type_name::<i8>(),
			std::any::type_name::<i16>(),
			std::any::type_name::<i32>(),
			std::any::type_name::<i64>(),
			std::any::type_name::<isize>(),
			std::any::type_name::<i128>(),
		]
		.contains(&type_name)
		{
			return value
				.parse::<i128>()
				.map(super::query::FilterValue::from)
				.unwrap_or(super::query::FilterValue::String(value));
		}

		if [
			std::any::type_name::<u8>(),
			std::any::type_name::<u16>(),
			std::any::type_name::<u32>(),
			std::any::type_name::<u64>(),
			std::any::type_name::<usize>(),
			std::any::type_name::<u128>(),
		]
		.contains(&type_name)
		{
			return value
				.parse::<u128>()
				.map(super::query::FilterValue::from)
				.unwrap_or(super::query::FilterValue::String(value));
		}

		if type_name == std::any::type_name::<bool>() {
			return value
				.parse::<bool>()
				.map(super::query::FilterValue::Boolean)
				.unwrap_or(super::query::FilterValue::String(value));
		}

		if type_name == std::any::type_name::<f32>() {
			return value
				.parse::<f32>()
				.map(|value| super::query::FilterValue::Float(f64::from(value)))
				.unwrap_or(super::query::FilterValue::String(value));
		}

		if type_name == std::any::type_name::<f64>() {
			return value
				.parse::<f64>()
				.map(super::query::FilterValue::Float)
				.unwrap_or(super::query::FilterValue::String(value));
		}

		if matches!(
			type_name,
			name if name == std::any::type_name::<String>()
				|| name == std::any::type_name::<&str>()
				|| name == std::any::type_name::<std::borrow::Cow<'static, str>>()
		) {
			return super::query::FilterValue::String(value);
		}

		if type_name == std::any::type_name::<uuid::Uuid>() {
			return value
				.parse()
				.map(super::query::FilterValue::Uuid)
				.unwrap_or(super::query::FilterValue::String(value));
		}

		if is_timezone_aware_datetime_type(type_name) {
			return chrono::DateTime::parse_from_rfc3339(&value)
				.map(|value| {
					super::query::FilterValue::Timestamp(value.with_timezone(&chrono::Utc))
				})
				.unwrap_or(super::query::FilterValue::String(value));
		}

		if is_decimal_type(type_name) {
			return value
				.parse()
				.map(super::query::FilterValue::Decimal)
				.unwrap_or(super::query::FilterValue::String(value));
		}

		if type_name == std::any::type_name::<chrono::NaiveDate>() {
			return value
				.parse()
				.map(super::query::FilterValue::Date)
				.unwrap_or(super::query::FilterValue::String(value));
		}

		if type_name == std::any::type_name::<chrono::NaiveTime>() {
			return value
				.parse()
				.map(super::query::FilterValue::Time)
				.unwrap_or(super::query::FilterValue::String(value));
		}

		value
			.parse::<i64>()
			.map(super::query::FilterValue::Integer)
			.unwrap_or(super::query::FilterValue::String(value))
	}

	/// Converts a route primary key into a query filter value.
	///
	/// Models generated by `#[model]` strictly deserialize the declared primary
	/// key type, so malformed or out-of-range route values are rejected instead
	/// of being coerced. Manual `Model` implementations can override this method
	/// when a custom primary-key type needs an exact database binding. The method
	/// intentionally adds no new bound to [`Model::PrimaryKey`]; generated models
	/// provide the typed conversion without requiring all hand-written models to
	/// implement serde deserialization.
	fn primary_key_filter_value_from_str(
		value: &str,
	) -> reinhardt_core::exception::Result<super::query::FilterValue> {
		use reinhardt_core::exception::Error;

		let type_name = std::any::type_name::<Self::PrimaryKey>();
		macro_rules! parse_standard_integer {
			($integer:ty, $category:literal) => {
				if type_name == std::any::type_name::<$integer>() {
					return value
						.parse::<$integer>()
						.map(super::query::FilterValue::from)
						.map_err(|_| {
							Error::Validation(format!(
								concat!("invalid ", $category, " primary key: {}"),
								value
							))
						});
				}
			};
		}

		parse_standard_integer!(i8, "integer");
		parse_standard_integer!(i16, "integer");
		parse_standard_integer!(i32, "integer");
		parse_standard_integer!(i64, "integer");
		parse_standard_integer!(isize, "integer");
		parse_standard_integer!(i128, "integer");
		parse_standard_integer!(u8, "unsigned integer");
		parse_standard_integer!(u16, "unsigned integer");
		parse_standard_integer!(u32, "unsigned integer");
		parse_standard_integer!(u64, "unsigned integer");
		parse_standard_integer!(usize, "unsigned integer");
		parse_standard_integer!(u128, "unsigned integer");

		if type_name == std::any::type_name::<bool>() {
			return value
				.parse::<bool>()
				.map(super::query::FilterValue::Boolean)
				.map_err(|_| Error::Validation(format!("invalid boolean primary key: {value}")));
		}

		if type_name == std::any::type_name::<f32>() {
			return value
				.parse::<f32>()
				.map(|value| super::query::FilterValue::Float(f64::from(value)))
				.map_err(|_| Error::Validation(format!("invalid float primary key: {value}")));
		}

		if type_name == std::any::type_name::<f64>() {
			return value
				.parse::<f64>()
				.map(super::query::FilterValue::Float)
				.map_err(|_| Error::Validation(format!("invalid float primary key: {value}")));
		}

		if type_name == std::any::type_name::<uuid::Uuid>() {
			return value
				.parse()
				.map(super::query::FilterValue::Uuid)
				.map_err(|_| Error::Validation(format!("invalid UUID primary key: {value}")));
		}

		if is_timezone_aware_datetime_type(type_name) {
			return chrono::DateTime::parse_from_rfc3339(value)
				.map(|value| {
					super::query::FilterValue::Timestamp(value.with_timezone(&chrono::Utc))
				})
				.map_err(|_| Error::Validation(format!("invalid timestamp primary key: {value}")));
		}

		if is_decimal_type(type_name) {
			return value
				.parse()
				.map(super::query::FilterValue::Decimal)
				.map_err(|_| Error::Validation(format!("invalid decimal primary key: {value}")));
		}

		if type_name == std::any::type_name::<chrono::NaiveDate>() {
			return value
				.parse()
				.map(super::query::FilterValue::Date)
				.map_err(|_| Error::Validation(format!("invalid date primary key: {value}")));
		}

		if type_name == std::any::type_name::<chrono::NaiveTime>() {
			return value
				.parse()
				.map(super::query::FilterValue::Time)
				.map_err(|_| Error::Validation(format!("invalid time primary key: {value}")));
		}

		if is_decimal_type(type_name) {
			return value
				.parse()
				.map(super::query::FilterValue::Decimal)
				.map_err(|_| Error::Validation(format!("invalid decimal primary key: {value}")));
		}

		Ok(super::query::FilterValue::String(value.to_owned()))
	}

	/// Get the primary key value
	///
	/// Returns an owned copy of the primary key. For composite primary keys,
	/// this constructs a new PK value from the component fields.
	fn primary_key(&self) -> Option<Self::PrimaryKey>;

	/// Set the primary key value
	fn set_primary_key(&mut self, value: Self::PrimaryKey);

	/// Get composite primary key definition if this model uses composite PK
	///
	/// Returns None for single primary key models, Some(CompositePrimaryKey) for composite PK models.
	fn composite_primary_key() -> Option<super::composite_pk::CompositePrimaryKey> {
		None
	}

	/// Get composite primary key values for this instance
	///
	/// Only meaningful for models with composite primary keys.
	/// Returns empty HashMap for single primary key models.
	fn get_composite_pk_values(&self) -> HashMap<String, super::composite_pk::PkValue> {
		HashMap::new()
	}

	/// Get field metadata for inspection
	///
	/// This method should be implemented to provide introspection capabilities.
	/// By default, returns an empty vector. Override this in derive macros or
	/// manual implementations to provide actual field metadata.
	///
	/// # Examples
	///
	/// ```ignore
	/// use reinhardt_db::orm::Model;
	///
	/// struct User {
	///     id: i32,
	///     name: String,
	/// }
	///
	/// impl Model for User {
	///     // ... other required methods ...
	///
	///     fn field_metadata() -> Vec<super::inspection::FieldInfo> {
	///         vec![
	///             // Field metadata would be generated here
	///         ]
	///     }
	/// }
	/// ```
	fn field_metadata() -> Vec<super::inspection::FieldInfo> {
		Vec::new()
	}

	/// Serialize model fields for database writes.
	fn serialize_database_value(&self) -> Result<DatabaseValue, DatabaseSerializationError> {
		serialize_model_database_value(self)
	}

	/// Get relationship metadata for inspection
	///
	/// This method should be implemented to provide relationship introspection.
	/// By default, returns an empty vector. Override this in derive macros or
	/// manual implementations to provide actual relationship metadata.
	fn relationship_metadata() -> Vec<super::inspection::RelationInfo> {
		Vec::new()
	}

	/// Get index metadata for inspection
	///
	/// This method should be implemented to provide index introspection.
	/// By default, returns an empty vector. Override this in derive macros or
	/// manual implementations to provide actual index metadata.
	fn index_metadata() -> Vec<super::inspection::IndexInfo> {
		Vec::new()
	}

	/// Get constraint metadata for inspection
	///
	/// This method should be implemented to provide constraint introspection.
	/// By default, returns an empty vector. Override this in derive macros or
	/// manual implementations to provide actual constraint metadata.
	fn constraint_metadata() -> Vec<super::inspection::ConstraintInfo> {
		Vec::new()
	}

	/// Django-style objects manager accessor
	///
	/// Returns the configured manager for this model type. When a custom manager
	/// is specified via `#[model(manager = MyManager)]`, this returns the custom
	/// manager; otherwise it returns the default [`Manager<Self>`](super::Manager).
	///
	/// # Examples
	///
	/// ```rust,no_run
	/// use reinhardt_db::orm::Model;
	/// use serde::{Serialize, Deserialize};
	/// # #[derive(Debug, Clone, Serialize, Deserialize)]
	/// # struct MyModel { id: Option<i64> }
	/// # #[derive(Clone)]
	/// # struct MyModelFields;
	/// # impl reinhardt_db::orm::model::FieldSelector for MyModelFields {
	/// #     fn with_alias(self, _alias: &str) -> Self { self }
	/// # }
	/// # impl Model for MyModel {
	/// #     type PrimaryKey = i64;
	/// #     type Fields = MyModelFields;
	/// #     type Objects = reinhardt_db::orm::Manager<Self>;
	/// #     fn app_label() -> &'static str { "app" }
	/// #     fn table_name() -> &'static str { "table" }
	/// #     fn new_fields() -> Self::Fields { MyModelFields }
	/// #     fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id.clone() }
	/// #     fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
	/// #     fn primary_key_field() -> &'static str { "id" }
	/// # }
	///
	/// # #[tokio::main]
	/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
	/// let manager = MyModel::objects();
	/// let all_records = manager.all().all().await?;
	/// # Ok(())
	/// # }
	/// ```
	fn objects() -> Self::Objects
	where
		Self: Sized,
	{
		Self::Objects::default()
	}

	/// Save the model instance to the database with event dispatching
	///
	/// If the primary key is None, performs an INSERT and dispatches before_insert/after_insert events.
	/// If the primary key is Some, performs an UPDATE and dispatches before_update/after_update events.
	///
	/// Event listeners can veto the operation by returning `EventResult::Veto`.
	///
	/// # Examples
	///
	/// ```rust,no_run
	/// use reinhardt_db::orm::Model;
	/// use serde::{Serialize, Deserialize};
	/// # #[derive(Debug, Clone, Serialize, Deserialize)]
	/// # struct User { id: Option<i64>, name: String }
	/// # #[derive(Clone)]
	/// # struct UserFields;
	/// # impl reinhardt_db::orm::model::FieldSelector for UserFields {
	/// #     fn with_alias(self, _alias: &str) -> Self { self }
	/// # }
	/// # impl Model for User {
	/// #     type PrimaryKey = i64;
	/// #     type Fields = UserFields;
	/// #     type Objects = reinhardt_db::orm::Manager<Self>;
	/// #     fn app_label() -> &'static str { "app" }
	/// #     fn table_name() -> &'static str { "users" }
	/// #     fn new_fields() -> Self::Fields { UserFields }
	/// #     fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id.clone() }
	/// #     fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
	/// #     fn primary_key_field() -> &'static str { "id" }
	/// # }
	///
	/// # #[tokio::main]
	/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
	/// let mut user = User { id: None, name: "John".to_string() };
	///
	/// // INSERT - triggers before_insert/after_insert events
	/// user.save().await?;
	///
	/// // UPDATE - triggers before_update/after_update events
	/// user.name = "Jane".to_string();
	/// user.save().await?;
	/// # Ok(())
	/// # }
	/// ```
	fn save(
		&mut self,
	) -> impl std::future::Future<Output = reinhardt_core::exception::Result<()>> + Send
	where
		Self: Sized,
	{
		async move {
			use super::events::{EventResult, get_active_registry};
			use super::manager::get_connection;

			let registry = get_active_registry();
			let conn = get_connection().await?;
			let manager = super::Manager::<Self>::new();

			let json = serde_json::to_value(&*self)
				.map_err(|e| reinhardt_core::exception::Error::Database(e.to_string()))?;

			if self.primary_key().is_none() {
				// INSERT: new record
				let instance_id = format!("{}-new-{}", Self::table_name(), uuid::Uuid::now_v7());

				// Dispatch before_insert event if registry is active
				if let Some(ref reg) = registry {
					let result = reg
						.dispatch_before_insert(Self::table_name(), &instance_id, &json)
						.await;
					if result == EventResult::Veto {
						return Err(reinhardt_core::exception::Error::Database(
							"Insert operation vetoed by event listener".to_string(),
						));
					}
				}

				// Perform the INSERT
				let created = manager.create_with_conn(&conn, self).await?;
				*self = created;

				// Dispatch after_insert event if registry is active
				if let Some(ref reg) = registry {
					let final_id = format!(
						"{}-{}",
						Self::table_name(),
						self.primary_key()
							.map(|pk| pk.to_string())
							.unwrap_or_default()
					);
					reg.dispatch_after_insert(Self::table_name(), &final_id)
						.await;
				}
			} else {
				// UPDATE: existing record
				let instance_id = format!(
					"{}-{}",
					Self::table_name(),
					self.primary_key()
						.map(|pk| pk.to_string())
						.unwrap_or_default()
				);

				// Dispatch before_update event if registry is active
				if let Some(ref reg) = registry {
					let result = reg
						.dispatch_before_update(Self::table_name(), &instance_id, &json)
						.await;
					if result == EventResult::Veto {
						return Err(reinhardt_core::exception::Error::Database(
							"Update operation vetoed by event listener".to_string(),
						));
					}
				}

				// Perform the UPDATE
				let updated = manager.update_with_conn(&conn, self).await?;
				*self = updated;

				// Dispatch after_update event if registry is active
				if let Some(ref reg) = registry {
					reg.dispatch_after_update(Self::table_name(), &instance_id)
						.await;
				}
			}

			Ok(())
		}
	}

	/// Delete the model instance from the database with event dispatching
	///
	/// Dispatches before_delete/after_delete events. Event listeners can veto
	/// the operation by returning `EventResult::Veto`.
	///
	/// # Examples
	///
	/// ```rust,no_run
	/// use reinhardt_db::orm::Model;
	/// use serde::{Serialize, Deserialize};
	/// # #[derive(Debug, Clone, Serialize, Deserialize)]
	/// # struct User { id: Option<i64>, name: String }
	/// # #[derive(Clone)]
	/// # struct UserFields;
	/// # impl reinhardt_db::orm::model::FieldSelector for UserFields {
	/// #     fn with_alias(self, _alias: &str) -> Self { self }
	/// # }
	/// # impl Model for User {
	/// #     type PrimaryKey = i64;
	/// #     type Fields = UserFields;
	/// #     type Objects = reinhardt_db::orm::Manager<Self>;
	/// #     fn app_label() -> &'static str { "app" }
	/// #     fn table_name() -> &'static str { "users" }
	/// #     fn new_fields() -> Self::Fields { UserFields }
	/// #     fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id.clone() }
	/// #     fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
	/// #     fn primary_key_field() -> &'static str { "id" }
	/// # }
	///
	/// # #[tokio::main]
	/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
	/// let mut user = User { id: Some(1), name: "John".to_string() };
	///
	/// // Triggers before_delete/after_delete events
	/// user.delete().await?;
	/// # Ok(())
	/// # }
	/// ```
	fn delete(
		&self,
	) -> impl std::future::Future<Output = reinhardt_core::exception::Result<()>> + Send
	where
		Self: Sized,
	{
		async move {
			use super::events::{EventResult, get_active_registry};
			use super::manager::get_connection;

			let pk = self.primary_key().ok_or_else(|| {
				reinhardt_core::exception::Error::Database(
					"Cannot delete model without primary key".to_string(),
				)
			})?;

			let conn = get_connection().await?;
			let manager = super::Manager::<Self>::new();

			let instance_id = format!("{}-{}", Self::table_name(), pk);

			// Dispatch before_delete event if registry is available
			if let Some(registry) = get_active_registry() {
				let result = registry
					.dispatch_before_delete(Self::table_name(), &instance_id)
					.await;
				if result == EventResult::Veto {
					return Err(reinhardt_core::exception::Error::Database(
						"Delete operation vetoed by event listener".to_string(),
					));
				}
			}

			// Perform the DELETE
			manager.delete_with_conn(&conn, pk.clone()).await?;

			// Dispatch after_delete event if registry is available
			if let Some(registry) = get_active_registry() {
				registry
					.dispatch_after_delete(Self::table_name(), &instance_id)
					.await;
			}

			Ok(())
		}
	}
}

/// Trait for models with timestamps - compose this with Model
/// This follows Rust's composition pattern rather than Django's inheritance
pub trait Timestamped {
	/// Returns the creation timestamp.
	fn created_at(&self) -> chrono::DateTime<chrono::Utc>;
	/// Returns the last update timestamp.
	fn updated_at(&self) -> chrono::DateTime<chrono::Utc>;
	/// Sets the last update timestamp.
	fn set_updated_at(&mut self, time: chrono::DateTime<chrono::Utc>);
}

/// Trait for soft-deletable models
/// Another composition trait instead of inheritance
pub trait SoftDeletable {
	/// Returns the deletion timestamp, or `None` if not deleted.
	fn deleted_at(&self) -> Option<chrono::DateTime<chrono::Utc>>;
	/// Sets the deletion timestamp, or `None` to restore.
	fn set_deleted_at(&mut self, time: Option<chrono::DateTime<chrono::Utc>>);
	/// Returns whether the model has been soft-deleted.
	fn is_deleted(&self) -> bool {
		self.deleted_at().is_some()
	}
}

/// Common timestamp fields that can be composed into structs
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Timestamps {
	/// The created at.
	pub created_at: chrono::DateTime<chrono::Utc>,
	/// The updated at.
	pub updated_at: chrono::DateTime<chrono::Utc>,
}

impl Timestamps {
	/// Creates a new Timestamps instance with current time
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::model::Timestamps;
	///
	/// let timestamps = Timestamps::now();
	/// assert!(timestamps.created_at <= chrono::Utc::now());
	/// assert!(timestamps.updated_at <= chrono::Utc::now());
	/// ```
	pub fn now() -> Self {
		let now = chrono::Utc::now();
		Self {
			created_at: now,
			updated_at: now,
		}
	}
	/// Updates the updated_at timestamp to current time
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::model::Timestamps;
	/// use chrono::Utc;
	///
	/// let mut timestamps = Timestamps::now();
	/// let old_updated = timestamps.updated_at;
	///
	/// // Wait a small amount to ensure time difference
	/// std::thread::sleep(std::time::Duration::from_millis(1));
	/// timestamps.touch();
	///
	/// assert!(timestamps.updated_at > old_updated);
	/// ```
	pub fn touch(&mut self) {
		self.updated_at = chrono::Utc::now();
	}
}

/// Soft delete field that can be composed into structs
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SoftDelete {
	/// The deleted at.
	pub deleted_at: Option<chrono::DateTime<chrono::Utc>>,
}

impl SoftDelete {
	/// Creates a new SoftDelete instance with no deletion timestamp
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::model::SoftDelete;
	///
	/// let soft_delete = SoftDelete::new();
	/// assert!(soft_delete.deleted_at.is_none());
	/// ```
	pub fn new() -> Self {
		Self { deleted_at: None }
	}
	/// Marks the record as deleted by setting the deletion timestamp
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::model::SoftDelete;
	///
	/// let mut soft_delete = SoftDelete::new();
	/// assert!(!soft_delete.is_deleted());
	///
	/// soft_delete.delete();
	/// assert!(soft_delete.is_deleted());
	/// assert!(soft_delete.deleted_at.is_some());
	/// ```
	pub fn delete(&mut self) {
		self.deleted_at = Some(chrono::Utc::now());
	}
	/// Restores a soft-deleted record by clearing the deletion timestamp
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::model::SoftDelete;
	///
	/// let mut soft_delete = SoftDelete::new();
	/// soft_delete.delete();
	/// assert!(soft_delete.is_deleted());
	///
	/// soft_delete.restore();
	/// assert!(!soft_delete.is_deleted());
	/// assert!(soft_delete.deleted_at.is_none());
	/// ```
	pub fn restore(&mut self) {
		self.deleted_at = None;
	}

	/// Check if the record is soft-deleted
	pub fn is_deleted(&self) -> bool {
		self.deleted_at.is_some()
	}
}

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

#[cfg(test)]
mod tests {
	use super::{FieldSelector, Model};
	use crate::orm::{Manager, query::FilterValue};
	use serde::{Deserialize, Serialize};

	#[test]
	fn serialize_nullable_json_array_preserves_sql_null_elements() {
		let values = vec![
			Some(serde_json::json!({"status": "ready"})),
			None,
			Some(serde_json::Value::Null),
		];

		let serialized = super::serialize_nullable_json_array(&values);

		assert_eq!(
			serialized[0],
			serde_json::json!({"__reinhardt_json_array_element": {"status": "ready"}})
		);
		assert!(super::is_sql_null_array_element(&serialized[1]));
		assert_eq!(
			serialized[2],
			serde_json::json!({"__reinhardt_json_array_element": null})
		);
	}

	#[test]
	fn serialize_nullable_json_array_escapes_sql_null_marker_values() {
		let marker = serde_json::json!({"__reinhardt_sql_null_array_element": true});
		let serialized = super::serialize_nullable_json_array(&[Some(marker.clone())]);

		assert!(!super::is_sql_null_array_element(&serialized[0]));
		assert_eq!(
			super::unwrap_json_array_element(&serialized[0]),
			Some(&marker)
		);
	}

	#[derive(Clone, Serialize, Deserialize)]
	struct StringPrimaryKeyModel {
		id: String,
	}

	#[derive(Clone, Serialize, Deserialize)]
	struct IntegerPrimaryKeyModel {
		id: i64,
	}

	#[derive(Clone, Serialize, Deserialize)]
	struct SmallIntegerPrimaryKeyModel {
		id: i8,
	}

	#[derive(Clone, Serialize, Deserialize)]
	struct DecimalPrimaryKeyModel {
		id: rust_decimal::Decimal,
	}

	type UuidPrimaryKey = uuid::Uuid;
	type TimestampPrimaryKey = chrono::DateTime<chrono::Utc>;
	type FixedOffsetTimestampPrimaryKey = chrono::DateTime<chrono::FixedOffset>;
	type LocalTimestampPrimaryKey = chrono::DateTime<chrono::Local>;
	type DatePrimaryKey = chrono::NaiveDate;
	type TimePrimaryKey = chrono::NaiveTime;

	#[derive(Clone, Serialize, Deserialize)]
	struct UuidPrimaryKeyModel {
		id: UuidPrimaryKey,
	}

	#[derive(Clone, Serialize, Deserialize)]
	struct TimestampPrimaryKeyModel {
		id: TimestampPrimaryKey,
	}

	#[derive(Clone, Serialize, Deserialize)]
	struct FixedOffsetTimestampPrimaryKeyModel {
		id: FixedOffsetTimestampPrimaryKey,
	}

	#[derive(Clone, Serialize, Deserialize)]
	struct LocalTimestampPrimaryKeyModel {
		id: LocalTimestampPrimaryKey,
	}

	#[derive(Clone, Serialize, Deserialize)]
	struct DatePrimaryKeyModel {
		id: DatePrimaryKey,
	}

	#[derive(Clone, Serialize, Deserialize)]
	struct TimePrimaryKeyModel {
		id: TimePrimaryKey,
	}

	#[derive(Clone)]
	struct PrimaryKeyTestFields;

	impl FieldSelector for PrimaryKeyTestFields {
		fn with_alias(self, _alias: &str) -> Self {
			self
		}
	}

	macro_rules! impl_primary_key_test_model {
		($model:ty, $pk:ty) => {
			impl Model for $model {
				type PrimaryKey = $pk;
				type Fields = PrimaryKeyTestFields;
				type Objects = Manager<Self>;

				fn table_name() -> &'static str {
					"primary_key_test"
				}

				fn new_fields() -> Self::Fields {
					PrimaryKeyTestFields
				}

				fn primary_key(&self) -> Option<Self::PrimaryKey> {
					Some(self.id.clone())
				}

				fn set_primary_key(&mut self, value: Self::PrimaryKey) {
					self.id = value;
				}
			}
		};
	}

	impl_primary_key_test_model!(StringPrimaryKeyModel, String);
	impl_primary_key_test_model!(IntegerPrimaryKeyModel, i64);
	impl_primary_key_test_model!(SmallIntegerPrimaryKeyModel, i8);
	impl_primary_key_test_model!(DecimalPrimaryKeyModel, rust_decimal::Decimal);

	macro_rules! impl_alias_primary_key_test_model {
		($model:ty, $pk:ty) => {
			impl Model for $model {
				type PrimaryKey = $pk;
				type Fields = PrimaryKeyTestFields;
				type Objects = Manager<Self>;

				fn table_name() -> &'static str {
					"primary_key_test"
				}

				fn new_fields() -> Self::Fields {
					PrimaryKeyTestFields
				}

				fn primary_key(&self) -> Option<Self::PrimaryKey> {
					Some(self.id)
				}

				fn set_primary_key(&mut self, value: Self::PrimaryKey) {
					self.id = value;
				}

				fn primary_key_filter_value_from_str(
					value: &str,
				) -> reinhardt_core::exception::Result<FilterValue> {
					let filter_value = super::deserialize_primary_key_filter_value_from_str::<
						Self::PrimaryKey,
					>(value)
					.map_err(|_| {
						reinhardt_core::exception::Error::Validation(format!(
							"invalid primary key: {value}"
						))
					})?;
					if let Some(filter_value) = filter_value {
						return Ok(filter_value);
					}
					let primary_key =
						super::deserialize_primary_key_from_str::<Self::PrimaryKey>(value)
							.map_err(|_| {
								reinhardt_core::exception::Error::Validation(format!(
									"invalid primary key: {value}"
								))
							})?;
					Ok(Self::primary_key_filter_value(primary_key))
				}
			}
		};
	}

	impl_alias_primary_key_test_model!(UuidPrimaryKeyModel, UuidPrimaryKey);
	impl_alias_primary_key_test_model!(TimestampPrimaryKeyModel, TimestampPrimaryKey);
	impl_alias_primary_key_test_model!(
		FixedOffsetTimestampPrimaryKeyModel,
		FixedOffsetTimestampPrimaryKey
	);
	impl_alias_primary_key_test_model!(LocalTimestampPrimaryKeyModel, LocalTimestampPrimaryKey);
	impl_alias_primary_key_test_model!(DatePrimaryKeyModel, DatePrimaryKey);
	impl_alias_primary_key_test_model!(TimePrimaryKeyModel, TimePrimaryKey);

	#[rstest::rstest]
	fn primary_key_filter_value_from_str_parses_date_and_time_keys() {
		let date = DatePrimaryKeyModel::primary_key_filter_value_from_str("2026-08-20").unwrap();
		let time = TimePrimaryKeyModel::primary_key_filter_value_from_str("12:34:56").unwrap();
		let direct_date = DatePrimaryKeyModel::primary_key_filter_value(
			chrono::NaiveDate::from_ymd_opt(2026, 8, 20).expect("date should be valid"),
		);
		let direct_time = TimePrimaryKeyModel::primary_key_filter_value(
			chrono::NaiveTime::from_hms_opt(12, 34, 56).expect("time should be valid"),
		);

		let FilterValue::Date(date) = date else {
			panic!("date primary key should use the date filter variant");
		};
		let FilterValue::Time(time) = time else {
			panic!("time primary key should use the time filter variant");
		};
		let FilterValue::Date(direct_date) = direct_date else {
			panic!("direct date primary key should use the date filter variant");
		};
		let FilterValue::Time(direct_time) = direct_time else {
			panic!("direct time primary key should use the time filter variant");
		};
		assert_eq!(
			date,
			chrono::NaiveDate::from_ymd_opt(2026, 8, 20).expect("date should be valid")
		);
		assert_eq!(
			direct_date,
			chrono::NaiveDate::from_ymd_opt(2026, 8, 20).expect("date should be valid")
		);
		assert_eq!(
			time,
			chrono::NaiveTime::from_hms_opt(12, 34, 56).expect("time should be valid")
		);
		assert_eq!(
			direct_time,
			chrono::NaiveTime::from_hms_opt(12, 34, 56).expect("time should be valid")
		);
	}

	#[test]
	fn primary_key_filter_value_from_str_preserves_numeric_strings() {
		let value = StringPrimaryKeyModel::primary_key_filter_value_from_str("00123").unwrap();
		assert!(matches!(value, FilterValue::String(ref value) if value == "00123"));
	}

	#[test]
	fn primary_key_filter_value_from_str_parses_integer_keys() {
		let value = IntegerPrimaryKeyModel::primary_key_filter_value_from_str("42").unwrap();
		assert!(matches!(value, FilterValue::Integer(42)));
	}

	#[test]
	fn primary_key_filter_value_from_str_rejects_invalid_integer_keys() {
		let error = IntegerPrimaryKeyModel::primary_key_filter_value_from_str("not-an-integer")
			.unwrap_err();
		assert!(matches!(
			error,
			reinhardt_core::exception::Error::Validation(_)
		));
	}

	#[test]
	fn primary_key_filter_value_from_str_rejects_out_of_range_integer_keys() {
		let error =
			SmallIntegerPrimaryKeyModel::primary_key_filter_value_from_str("128").unwrap_err();
		assert!(matches!(
			error,
			reinhardt_core::exception::Error::Validation(_)
		));
	}

	#[test]
	fn primary_key_filter_value_from_str_parses_decimal_keys() {
		let value = DecimalPrimaryKeyModel::primary_key_filter_value_from_str("1.25").unwrap();
		assert!(matches!(
			value,
			FilterValue::Decimal(value) if value == rust_decimal::Decimal::new(125, 2)
		));
	}

	#[test]
	fn primary_key_filter_value_from_str_uses_uuid_filter_for_aliases() {
		let value = UuidPrimaryKeyModel::primary_key_filter_value_from_str(
			"018e9c80-0b25-7d44-9c68-3a88f6797553",
		)
		.unwrap();
		assert!(matches!(value, FilterValue::Uuid(_)));
	}

	#[test]
	fn primary_key_filter_value_from_str_uses_timestamp_filter_for_aliases() {
		for value in [
			TimestampPrimaryKeyModel::primary_key_filter_value_from_str("2026-08-19T00:00:00Z")
				.unwrap(),
			FixedOffsetTimestampPrimaryKeyModel::primary_key_filter_value_from_str(
				"2026-08-19T00:00:00+09:00",
			)
			.unwrap(),
			LocalTimestampPrimaryKeyModel::primary_key_filter_value_from_str(
				"2026-08-19T00:00:00Z",
			)
			.unwrap(),
		] {
			assert!(matches!(value, FilterValue::Timestamp(_)));
		}
	}
}