surrealdb-types 3.2.1

A scalable, distributed, collaborative, document-graph database, for the realtime web
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
use std::convert::Infallible;
use std::fmt;
use std::time::Duration;

use crate::{Kind, SurrealValue, ToSql, Value};

// -----------------------------------------------------------------------------
// JSON-RPC 2.0 and SurrealDB-specific error codes (wire backwards compatibility)
// -----------------------------------------------------------------------------

/// Numeric error codes used on the wire for RPC. Kept for backwards compatibility.
#[allow(missing_docs)]
mod code {
	pub const PARSE_ERROR: i64 = -32700;
	pub const INVALID_REQUEST: i64 = -32600;
	pub const METHOD_NOT_FOUND: i64 = -32601;
	pub const METHOD_NOT_ALLOWED: i64 = -32602;
	pub const INVALID_PARAMS: i64 = -32603;
	pub const LIVE_QUERY_NOT_SUPPORTED: i64 = -32604;
	pub const BAD_LIVE_QUERY_CONFIG: i64 = -32605;
	pub const BAD_GRAPHQL_CONFIG: i64 = -32606;
	pub const INTERNAL_ERROR: i64 = -32000;
	pub const CLIENT_SIDE_ERROR: i64 = -32001;
	pub const INVALID_AUTH: i64 = -32002;
	pub const QUERY_NOT_EXECUTED: i64 = -32003;
	pub const QUERY_TIMEDOUT: i64 = -32004;
	pub const QUERY_CANCELLED: i64 = -32005;
	pub const QUERY_TRANSACTION_CONFLICT: i64 = -32009;
	pub const THROWN: i64 = -32006;
	pub const SERIALIZATION_ERROR: i64 = -32007;
	pub const DESERIALIZATION_ERROR: i64 = -32008;
}

/// Default wire code when none is specified (e.g. for deserialization of older wire format).
fn default_code() -> i64 {
	code::INTERNAL_ERROR
}

// -----------------------------------------------------------------------------
// Public API error type (wire-friendly, non-lossy, supports chaining)
// -----------------------------------------------------------------------------

/// Represents an error in SurrealDB
///
/// Designed to be returned from public APIs (including over the wire). It is
/// wire-friendly and non-lossy: serialization preserves `kind`, `message`,
/// and optional `details`. Use this type whenever an error crosses
/// an API boundary (e.g. server response, SDK method return).
///
/// The `details` field is flattened into the serialized object, so the wire
/// format contains `kind` (string) and optionally `details` (object) at the
/// same level as `code` and `message`. The optional `cause` field allows
/// error chaining so that SDKs can receive and display full error chains.
#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
#[surreal(crate = "crate")]
pub struct Error {
	/// Wire-only error code for RPC backwards compatibility.
	#[surreal(default = "default_code")]
	code: i64,
	/// Human-readable error message describing the error.
	message: String,
	/// The error kind and optional structured details. The kind is derived from the variant.
	/// Flattened into the parent object: contributes `kind` and optionally `details` fields.
	#[surreal(flatten)]
	details: ErrorDetails,
	/// Optional underlying cause for error chaining. Serialized as a nested error object on the
	/// wire.
	#[surreal(default)]
	cause: Option<Box<Error>>,
}

impl Error {
	/// Validation error (parse error, invalid request or params), with optional structured details.
	/// When `details` is provided, the wire code is set from the variant (e.g. `Parse` →
	/// `PARSE_ERROR`).
	pub fn validation(message: String, details: impl Into<Option<ValidationError>>) -> Self {
		let details = details.into();
		let code = details
			.as_ref()
			.map(|d| match d {
				ValidationError::Parse => code::PARSE_ERROR,
				ValidationError::InvalidRequest => code::INVALID_REQUEST,
				ValidationError::InvalidParams => code::INVALID_PARAMS,
				ValidationError::NamespaceEmpty
				| ValidationError::DatabaseEmpty
				| ValidationError::InvalidParameter {
					..
				}
				| ValidationError::InvalidContent {
					..
				}
				| ValidationError::InvalidMerge {
					..
				} => code::INVALID_REQUEST,
			})
			.unwrap_or(code::INTERNAL_ERROR);
		Self {
			message,
			code,
			details: ErrorDetails::Validation(details),
			cause: None,
		}
	}

	/// Not-allowed error (e.g. method, scripting, function, net target), with optional
	/// structured details. When `details` is provided, the wire code is set from the variant.
	pub fn not_allowed(message: String, details: impl Into<Option<NotAllowedError>>) -> Self {
		let details = details.into();
		let code = details
			.as_ref()
			.map(|d| match d {
				NotAllowedError::Auth(auth_error) => match auth_error {
					AuthError::TokenExpired => code::INVALID_AUTH,
					AuthError::SessionExpired => code::INTERNAL_ERROR,
					AuthError::InvalidAuth
					| AuthError::UnexpectedAuth
					| AuthError::MissingUserOrPass
					| AuthError::NoSigninTarget
					| AuthError::InvalidPass
					| AuthError::TokenMakingFailed
					| AuthError::InvalidRole {
						..
					}
					| AuthError::NotAllowed {
						..
					}
					| AuthError::InvalidSignup => code::INVALID_AUTH,
				},
				NotAllowedError::Method {
					..
				}
				| NotAllowedError::Scripting
				| NotAllowedError::Function {
					..
				}
				| NotAllowedError::Target {
					..
				} => code::METHOD_NOT_ALLOWED,
			})
			.unwrap_or(code::INTERNAL_ERROR);
		Self {
			message,
			code,
			details: ErrorDetails::NotAllowed(details),
			cause: None,
		}
	}

	/// Configuration error (feature or config not supported), with optional structured details.
	/// When `details` is provided, the wire code is set from the variant.
	pub fn configuration(message: String, details: impl Into<Option<ConfigurationError>>) -> Self {
		let details = details.into();
		let code = details
			.as_ref()
			.map(|d| match d {
				ConfigurationError::LiveQueryNotSupported => code::LIVE_QUERY_NOT_SUPPORTED,
				ConfigurationError::BadLiveQueryConfig => code::BAD_LIVE_QUERY_CONFIG,
				ConfigurationError::BadGraphqlConfig => code::BAD_GRAPHQL_CONFIG,
			})
			.unwrap_or(code::INTERNAL_ERROR);
		Self {
			message,
			code,
			details: ErrorDetails::Configuration(details),
			cause: None,
		}
	}

	/// User-thrown error (e.g. from THROW in SurrealQL). Sets wire code for RPC.
	pub fn thrown(message: String) -> Self {
		Self {
			message,
			code: code::THROWN,
			details: ErrorDetails::Thrown,
			cause: None,
		}
	}

	/// Query execution error (not executed, timeout, cancelled), with optional structured details.
	/// When `details` is provided, the wire code is set from the variant.
	pub fn query(message: String, details: impl Into<Option<QueryError>>) -> Self {
		let details = details.into();
		let code = details
			.as_ref()
			.map(|d| match d {
				QueryError::NotExecuted => code::QUERY_NOT_EXECUTED,
				QueryError::TimedOut {
					..
				} => code::QUERY_TIMEDOUT,
				QueryError::Cancelled => code::QUERY_CANCELLED,
				QueryError::TransactionConflict => code::QUERY_TRANSACTION_CONFLICT,
			})
			.unwrap_or(code::INTERNAL_ERROR);
		Self {
			message,
			code,
			details: ErrorDetails::Query(details),
			cause: None,
		}
	}

	/// Serialisation or deserialisation error, with optional structured details.
	/// When `details` is provided, the wire code is set from the variant.
	pub fn serialization(message: String, details: impl Into<Option<SerializationError>>) -> Self {
		let details = details.into();
		let code = details
			.as_ref()
			.map(|d| match d {
				SerializationError::Serialization => code::SERIALIZATION_ERROR,
				SerializationError::Deserialization => code::DESERIALIZATION_ERROR,
			})
			.unwrap_or(code::INTERNAL_ERROR);
		Self {
			message,
			code,
			details: ErrorDetails::Serialization(details),
			cause: None,
		}
	}

	/// Resource not found (e.g. table, record, namespace, RPC method), with optional
	/// structured details. When `details` is `NotFoundError::Method`, the wire code is set to
	/// `METHOD_NOT_FOUND` for RPC backwards compatibility.
	pub fn not_found(message: String, details: impl Into<Option<NotFoundError>>) -> Self {
		let details = details.into();
		let code = details
			.as_ref()
			.and_then(|d| match d {
				NotFoundError::Method {
					..
				} => Some(code::METHOD_NOT_FOUND),
				_ => None,
			})
			.unwrap_or(code::INTERNAL_ERROR);
		Self {
			message,
			code,
			details: ErrorDetails::NotFound(details),
			cause: None,
		}
	}

	/// Resource already exists (e.g. table, record), with optional structured details.
	pub fn already_exists(message: String, details: impl Into<Option<AlreadyExistsError>>) -> Self {
		let details = details.into();
		Self {
			message,
			code: code::INTERNAL_ERROR,
			details: ErrorDetails::AlreadyExists(details),
			cause: None,
		}
	}

	/// Connection error (e.g. uninitialised, already connected), with optional structured details.
	/// Used in the SDK for client-side connection state errors.
	pub fn connection(message: String, details: impl Into<Option<ConnectionError>>) -> Self {
		let details = details.into();
		Self {
			message,
			code: code::CLIENT_SIDE_ERROR,
			details: ErrorDetails::Connection(details),
			cause: None,
		}
	}

	/// Internal or unexpected error (server or client). Sets wire code for RPC.
	pub fn internal(message: String) -> Self {
		Self {
			message,
			code: code::INTERNAL_ERROR,
			details: ErrorDetails::Internal,
			cause: None,
		}
	}

	/// Context for error chaining.
	fn context(message: String) -> Self {
		Self {
			code: code::INTERNAL_ERROR,
			message,
			details: ErrorDetails::Context,
			cause: None,
		}
	}

	/// Build an error from a message and pre-parsed [`ErrorDetails`].
	/// Uses [`default_code`] for the wire code. Intended for deserialization paths
	/// that already have a typed `ErrorDetails` (e.g. via `ErrorDetails::from_value`).
	#[doc(hidden)]
	pub fn from_details(message: String, details: ErrorDetails) -> Self {
		Self {
			code: default_code(),
			message,
			details,
			cause: None,
		}
	}

	/// Build an error from message, details, and optional cause. For deserialization when cause is
	/// present.
	#[doc(hidden)]
	pub fn from_details_with_cause(
		message: String,
		details: ErrorDetails,
		cause: Option<Box<Error>>,
	) -> Self {
		Self {
			code: default_code(),
			message,
			details,
			cause,
		}
	}

	/// Build an error from the query-result wire shape (message, optional kind string, details).
	/// Used when deserialising query result error payloads that do not include `code`. Uses
	/// [`default_code`] and defaults kind to "Internal" when not present.
	#[doc(hidden)]
	pub fn from_parts(message: String, kind: Option<&str>, details: Option<Value>) -> Self {
		let kind_str = kind.unwrap_or("Internal");
		let typed_details = match details {
			Some(v) => ErrorDetails::from_value_with_kind_str(kind_str, v)
				.unwrap_or_else(|_| ErrorDetails::from_kind_str(kind_str)),
			None => ErrorDetails::from_kind_str(kind_str),
		};
		Self {
			code: default_code(),
			message,
			details: typed_details,
			cause: None,
		}
	}

	/// Returns the optional underlying cause for error chaining.
	pub fn cause(&self) -> Option<&Error> {
		self.cause.as_deref()
	}

	/// Returns an error with the given cause attached. Consumes `self`.
	pub fn with_cause(mut self, cause: Error) -> Self {
		self.cause = Some(Box::new(cause));
		self
	}

	/// Build an [`Error`] from an [`anyhow::Error`], surfacing only the outermost message.
	///
	/// SECURITY: do not copy the anyhow source chain to clients. Inner chain messages
	/// frequently contain raw field/computed values, storage-engine details, and other
	/// internal context that was attached by intermediate `?` / `with_context` callers
	/// without any redaction. Boundary call sites that want to attach an explicit,
	/// reviewed cause can use `with_cause` directly.
	#[doc(hidden)]
	#[allow(clippy::needless_pass_by_value)] // Public API: callers pass owned `anyhow::Error`.
	pub fn from_anyhow_with_chain(error: anyhow::Error) -> Self {
		Self::internal(error.to_string())
	}

	/// Returns the kind string for this error (e.g. "NotAllowed", "Internal").
	pub fn kind_str(&self) -> &'static str {
		self.details.kind_str()
	}

	/// Returns the human-readable error message.
	pub fn message(&self) -> &str {
		&self.message
	}

	/// Returns the error details (always present). The variant determines the error kind.
	pub fn details(&self) -> &ErrorDetails {
		&self.details
	}

	/// Returns true if this is a validation error.
	pub fn is_validation(&self) -> bool {
		self.details.is_validation()
	}

	/// Returns true if this is a configuration error.
	pub fn is_configuration(&self) -> bool {
		self.details.is_configuration()
	}

	/// Returns true if this is a query error.
	pub fn is_query(&self) -> bool {
		self.details.is_query()
	}

	/// Returns true if this is a serialization error.
	pub fn is_serialization(&self) -> bool {
		self.details.is_serialization()
	}

	/// Returns true if this is a not-allowed error.
	pub fn is_not_allowed(&self) -> bool {
		self.details.is_not_allowed()
	}

	/// Returns true if this is a not-found error.
	pub fn is_not_found(&self) -> bool {
		self.details.is_not_found()
	}

	/// Returns true if this is an already-exists error.
	pub fn is_already_exists(&self) -> bool {
		self.details.is_already_exists()
	}

	/// Returns true if this is a connection error.
	pub fn is_connection(&self) -> bool {
		self.details.is_connection()
	}

	/// Returns true if this is a user-thrown error.
	pub fn is_thrown(&self) -> bool {
		self.details.is_thrown()
	}

	/// Returns true if this is an internal error.
	pub fn is_internal(&self) -> bool {
		self.details.is_internal()
	}

	/// Returns true if this is a context error (used for error chaining).
	pub fn is_context(&self) -> bool {
		self.details.is_context()
	}

	/// Returns structured validation error details, if this is a validation error with specifics.
	pub fn validation_details(&self) -> Option<&ValidationError> {
		match &self.details {
			ErrorDetails::Validation(d) => d.as_ref(),
			_ => None,
		}
	}

	/// Returns structured not-allowed error details, if this is a not-allowed error with specifics.
	pub fn not_allowed_details(&self) -> Option<&NotAllowedError> {
		match &self.details {
			ErrorDetails::NotAllowed(d) => d.as_ref(),
			_ => None,
		}
	}

	/// Returns structured configuration error details, if this is a configuration error with
	/// specifics.
	pub fn configuration_details(&self) -> Option<&ConfigurationError> {
		match &self.details {
			ErrorDetails::Configuration(d) => d.as_ref(),
			_ => None,
		}
	}

	/// Returns structured serialization error details, if this is a serialization error with
	/// specifics.
	pub fn serialization_details(&self) -> Option<&SerializationError> {
		match &self.details {
			ErrorDetails::Serialization(d) => d.as_ref(),
			_ => None,
		}
	}

	/// Returns structured not-found error details, if this is a not-found error with specifics.
	pub fn not_found_details(&self) -> Option<&NotFoundError> {
		match &self.details {
			ErrorDetails::NotFound(d) => d.as_ref(),
			_ => None,
		}
	}

	/// Returns structured query error details, if this is a query error with specifics.
	pub fn query_details(&self) -> Option<&QueryError> {
		match &self.details {
			ErrorDetails::Query(d) => d.as_ref(),
			_ => None,
		}
	}

	/// Returns structured already-exists error details, if this is an already-exists error with
	/// specifics.
	pub fn already_exists_details(&self) -> Option<&AlreadyExistsError> {
		match &self.details {
			ErrorDetails::AlreadyExists(d) => d.as_ref(),
			_ => None,
		}
	}

	/// Returns structured connection error details, if this is a connection error with specifics.
	pub fn connection_details(&self) -> Option<&ConnectionError> {
		match &self.details {
			ErrorDetails::Connection(d) => d.as_ref(),
			_ => None,
		}
	}
}

// -----------------------------------------------------------------------------
// ErrorDetails enum (typed wrapper for all detail variants)
// -----------------------------------------------------------------------------

/// Typed error details. Each variant represents an error kind and optionally
/// wraps the detail enum for that kind. This replaces the separate `kind` field
/// on [`Error`] -- the kind is derived from the variant.
///
/// Rust users can pattern-match directly:
/// ```ignore
/// match error.details() {
///     ErrorDetails::NotAllowed(Some(NotAllowedError::Auth(AuthError::TokenExpired))) => ...,
///     ErrorDetails::NotFound(Some(NotFoundError::Table { name })) => ...,
///     ErrorDetails::Internal => ...,
///     _ => ...,
/// }
/// ```
#[derive(Clone, Debug, PartialEq, Eq, SurrealValue)]
#[non_exhaustive]
#[surreal(crate = "crate")]
#[surreal(tag = "kind", content = "details", skip_content_if = "Value::is_empty")]
pub enum ErrorDetails {
	/// Validation error (parse error, invalid request/params).
	Validation(Option<ValidationError>),
	/// Configuration error (feature/config not supported).
	Configuration(Option<ConfigurationError>),
	/// Query execution error (timeout, cancelled, not executed).
	Query(Option<QueryError>),
	/// Serialization/deserialization error.
	Serialization(Option<SerializationError>),
	/// Permission or authorization error.
	NotAllowed(Option<NotAllowedError>),
	/// Resource not found.
	NotFound(Option<NotFoundError>),
	/// Duplicate resource.
	AlreadyExists(Option<AlreadyExistsError>),
	/// Client connection error (SDK-side).
	Connection(Option<ConnectionError>),
	/// User-thrown error (THROW in SurrealQL). No detail type.
	Thrown,
	/// Internal/unexpected error. No detail type.
	/// Acts as a catch-all for unknown kinds during deserialization (forward compatibility).
	#[surreal(other)]
	Internal,
	/// Context for error chaining.
	Context,
}

impl ErrorDetails {
	/// Returns the kind string for wire serialization (e.g. "NotAllowed", "Internal").
	pub fn kind_str(&self) -> &'static str {
		match self {
			Self::Validation(_) => "Validation",
			Self::Configuration(_) => "Configuration",
			Self::Query(_) => "Query",
			Self::Serialization(_) => "Serialization",
			Self::NotAllowed(_) => "NotAllowed",
			Self::NotFound(_) => "NotFound",
			Self::AlreadyExists(_) => "AlreadyExists",
			Self::Connection(_) => "Connection",
			Self::Thrown => "Thrown",
			Self::Internal => "Internal",
			Self::Context => "Context",
		}
	}

	/// Returns true if this is a validation error.
	pub fn is_validation(&self) -> bool {
		matches!(self, Self::Validation(_))
	}
	/// Returns true if this is a configuration error.
	pub fn is_configuration(&self) -> bool {
		matches!(self, Self::Configuration(_))
	}
	/// Returns true if this is a query error.
	pub fn is_query(&self) -> bool {
		matches!(self, Self::Query(_))
	}
	/// Returns true if this is a serialization error.
	pub fn is_serialization(&self) -> bool {
		matches!(self, Self::Serialization(_))
	}
	/// Returns true if this is a not-allowed error.
	pub fn is_not_allowed(&self) -> bool {
		matches!(self, Self::NotAllowed(_))
	}
	/// Returns true if this is a not-found error.
	pub fn is_not_found(&self) -> bool {
		matches!(self, Self::NotFound(_))
	}
	/// Returns true if this is an already-exists error.
	pub fn is_already_exists(&self) -> bool {
		matches!(self, Self::AlreadyExists(_))
	}
	/// Returns true if this is a connection error.
	pub fn is_connection(&self) -> bool {
		matches!(self, Self::Connection(_))
	}
	/// Returns true if this is a user-thrown error.
	pub fn is_thrown(&self) -> bool {
		matches!(self, Self::Thrown)
	}
	/// Returns true if this is an internal error.
	pub fn is_internal(&self) -> bool {
		matches!(self, Self::Internal)
	}
	/// Returns true if this is a context error (used for error chaining).
	pub fn is_context(&self) -> bool {
		matches!(self, Self::Context)
	}

	/// Create an `ErrorDetails` from a kind string, with no inner details.
	/// Unknown kind strings fall back to `Internal` (forward compatibility).
	pub(crate) fn from_kind_str(kind: &str) -> Self {
		match kind {
			"Validation" => Self::Validation(None),
			"Configuration" => Self::Configuration(None),
			"Query" => Self::Query(None),
			"Serialization" => Self::Serialization(None),
			"NotAllowed" => Self::NotAllowed(None),
			"NotFound" => Self::NotFound(None),
			"AlreadyExists" => Self::AlreadyExists(None),
			"Connection" => Self::Connection(None),
			"Thrown" => Self::Thrown,
			"Context" => Self::Context,
			// Unknown kinds fall back to Internal (forward compat)
			_ => Self::Internal,
		}
	}

	/// Deserialize details using the kind string to select the right variant.
	/// O(1) dispatch -- no trial-and-error parsing.
	pub(crate) fn from_value_with_kind_str(kind: &str, value: Value) -> Result<Self, Error> {
		match kind {
			"Validation" => {
				ValidationError::from_value(value).map(|v| ErrorDetails::Validation(Some(v)))
			}
			"Configuration" => {
				ConfigurationError::from_value(value).map(|v| ErrorDetails::Configuration(Some(v)))
			}
			"Query" => QueryError::from_value(value).map(|v| ErrorDetails::Query(Some(v))),
			"Serialization" => {
				SerializationError::from_value(value).map(|v| ErrorDetails::Serialization(Some(v)))
			}
			"NotAllowed" => {
				NotAllowedError::from_value(value).map(|v| ErrorDetails::NotAllowed(Some(v)))
			}
			"NotFound" => NotFoundError::from_value(value).map(|v| ErrorDetails::NotFound(Some(v))),
			"AlreadyExists" => {
				AlreadyExistsError::from_value(value).map(|v| ErrorDetails::AlreadyExists(Some(v)))
			}
			"Connection" => {
				ConnectionError::from_value(value).map(|v| ErrorDetails::Connection(Some(v)))
			}
			"Thrown" => Ok(Self::Thrown),
			"Context" => Ok(Self::Context),
			_ => Ok(Self::Internal),
		}
	}

	/// Returns true if this variant has inner detail data.
	pub fn has_details(&self) -> bool {
		match self {
			Self::Validation(d) => d.is_some(),
			Self::Configuration(d) => d.is_some(),
			Self::Query(d) => d.is_some(),
			Self::Serialization(d) => d.is_some(),
			Self::NotAllowed(d) => d.is_some(),
			Self::NotFound(d) => d.is_some(),
			Self::AlreadyExists(d) => d.is_some(),
			Self::Connection(d) => d.is_some(),
			Self::Thrown | Self::Internal | Self::Context => false,
		}
	}
}

// -----------------------------------------------------------------------------
// Structured error details (wire format in Error.details)
// -----------------------------------------------------------------------------

/// Auth failure reason for [`ErrorKind::NotAllowed`] errors.
#[derive(Clone, Debug, PartialEq, Eq, SurrealValue)]
#[surreal(crate = "crate")]
#[surreal(tag = "kind", content = "details")]
#[non_exhaustive]
pub enum AuthError {
	/// The token used for authentication has expired.
	#[surreal(skip_content)]
	TokenExpired,
	/// The session has expired.
	#[surreal(skip_content)]
	SessionExpired,
	/// Authentication failed (invalid credentials or similar).
	#[surreal(skip_content)]
	InvalidAuth,
	/// Unexpected error while performing authentication.
	#[surreal(skip_content)]
	UnexpectedAuth,
	/// Username or password was not provided.
	#[surreal(skip_content)]
	MissingUserOrPass,
	/// No signin target (SC, DB, NS, or KV) specified.
	#[surreal(skip_content)]
	NoSigninTarget,
	/// The password did not verify.
	#[surreal(skip_content)]
	InvalidPass,
	/// Failed to create the authentication token.
	#[surreal(skip_content)]
	TokenMakingFailed,
	/// Signup failed.
	#[surreal(skip_content)]
	InvalidSignup,
	/// Invalid role (IAM). Carries the role name.
	InvalidRole {
		/// Name of the invalid role.
		name: String,
	},
	/// Not enough permissions to perform the action (IAM). Carries actor, action, resource.
	NotAllowed {
		/// Actor that attempted the action.
		actor: String,
		/// Action that was attempted.
		action: String,
		/// Resource the action was attempted on.
		resource: String,
	},
}

impl From<AuthError> for Option<NotAllowedError> {
	fn from(auth_error: AuthError) -> Self {
		Some(NotAllowedError::Auth(auth_error))
	}
}

/// Validation failure reason for [`ErrorKind::Validation`] errors.
#[derive(Clone, Debug, PartialEq, Eq, SurrealValue)]
#[surreal(crate = "crate")]
#[surreal(tag = "kind", content = "details")]
#[non_exhaustive]
pub enum ValidationError {
	/// Parse error (invalid message or request format).
	#[surreal(skip_content)]
	Parse,
	/// Invalid request structure.
	#[surreal(skip_content)]
	InvalidRequest,
	/// Invalid parameters.
	#[surreal(skip_content)]
	InvalidParams,
	/// Namespace is empty.
	#[surreal(skip_content)]
	NamespaceEmpty,
	/// Database is empty.
	#[surreal(skip_content)]
	DatabaseEmpty,
	/// Invalid parameter with name.
	InvalidParameter {
		/// Name of the invalid parameter.
		name: String,
	},
	/// Invalid content value.
	InvalidContent {
		/// The invalid value.
		value: String,
	},
	/// Invalid merge value.
	InvalidMerge {
		/// The invalid value.
		value: String,
	},
}

/// Not-allowed reason for [`ErrorKind::NotAllowed`] errors.
#[derive(Clone, Debug, PartialEq, Eq, SurrealValue)]
#[surreal(crate = "crate")]
#[surreal(tag = "kind", content = "details")]
#[non_exhaustive]
pub enum NotAllowedError {
	/// Scripting not allowed.
	#[surreal(skip_content)]
	Scripting,
	/// Authentication or authorisation failure.
	Auth(AuthError),
	/// RPC method not allowed.
	Method {
		/// Name of the method.
		name: String,
	},
	/// Function not allowed.
	Function {
		/// Name of the function.
		name: String,
	},
	/// Net target not allowed.
	Target {
		/// Name of the net target.
		name: String,
	},
}

/// Configuration failure reason for [`ErrorKind::Configuration`] errors.
#[derive(Clone, Debug, PartialEq, Eq, SurrealValue)]
#[surreal(crate = "crate")]
#[surreal(tag = "kind", skip_content)]
#[non_exhaustive]
pub enum ConfigurationError {
	/// Live query not supported.
	LiveQueryNotSupported,
	/// Bad live query config.
	BadLiveQueryConfig,
	/// Bad GraphQL config.
	BadGraphqlConfig,
}

/// Serialisation failure reason for [`ErrorKind::Serialization`] errors.
#[derive(Clone, Debug, PartialEq, Eq, SurrealValue)]
#[surreal(crate = "crate")]
#[surreal(tag = "kind", skip_content)]
#[non_exhaustive]
pub enum SerializationError {
	/// Serialisation error.
	Serialization,
	/// Deserialisation error.
	Deserialization,
}

/// Not-found reason for [`ErrorKind::NotFound`] errors.
#[derive(Clone, Debug, PartialEq, Eq, SurrealValue)]
#[surreal(crate = "crate")]
#[surreal(tag = "kind", content = "details")]
#[non_exhaustive]
pub enum NotFoundError {
	/// RPC method not found.
	Method {
		/// Name of the method.
		name: String,
	},
	/// Session not found.
	Session {
		/// Optional session ID that was not found.
		id: Option<String>,
	},
	/// Table not found.
	Table {
		/// Name of the table.
		name: String,
	},
	/// Record not found.
	Record {
		/// ID of the record.
		id: String,
	},
	/// Namespace not found.
	Namespace {
		/// Name of the namespace.
		name: String,
	},
	/// Database not found.
	Database {
		/// Name of the database.
		name: String,
	},
	/// Transaction not found.
	#[surreal(skip_content)]
	Transaction,
}

/// Query failure reason for [`ErrorKind::Query`] errors.
#[derive(Clone, Debug, PartialEq, Eq, SurrealValue)]
#[surreal(crate = "crate")]
#[surreal(tag = "kind", content = "details")]
#[non_exhaustive]
pub enum QueryError {
	/// Query was not executed.
	#[surreal(skip_content)]
	NotExecuted,
	/// Query timed out.
	TimedOut {
		/// Duration after which the query timed out.
		duration: Duration,
	},
	/// Query was cancelled.
	#[surreal(skip_content)]
	Cancelled,
	/// Transaction conflict; the operation can be retried.
	#[surreal(skip_content)]
	TransactionConflict,
}

/// Already-exists reason for [`ErrorKind::AlreadyExists`] errors.
#[derive(Clone, Debug, PartialEq, Eq, SurrealValue)]
#[surreal(crate = "crate")]
#[surreal(tag = "kind", content = "details")]
#[non_exhaustive]
pub enum AlreadyExistsError {
	/// Session already exists.
	Session {
		/// Optional session ID that already exists.
		id: String,
	},
	/// Table already exists.
	Table {
		/// Name of the table.
		name: String,
	},
	/// Record already exists.
	Record {
		/// ID of the record.
		id: String,
	},
	/// Namespace already exists.
	Namespace {
		/// Name of the namespace.
		name: String,
	},
	/// Database already exists.
	Database {
		/// Name of the database.
		name: String,
	},
}

/// Connection failure reason for [`ErrorKind::Connection`] errors.
/// Used in the SDK for client-side connection state errors.
#[derive(Clone, Debug, PartialEq, Eq, SurrealValue)]
#[surreal(crate = "crate")]
#[surreal(tag = "kind", skip_content)]
#[non_exhaustive]
pub enum ConnectionError {
	/// Connection was used before being initialised.
	Uninitialised,
	/// Connect was called on an instance that is already connected.
	AlreadyConnected,
	/// Connection or transport failed (e.g. network error, DNS failure, WebSocket error).
	ConnectionFailed,
}

impl fmt::Display for Error {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "{}", self.message)
	}
}

impl std::error::Error for Error {
	fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
		self.cause.as_deref().map(|e| e as &(dyn std::error::Error + 'static))
	}
}

// -----------------------------------------------------------------------------
// Error chaining trait
// -----------------------------------------------------------------------------

/// Extension trait for wrapping errors with context, producing a chained [`Error`].
///
/// # Examples
///
/// ```ignore
/// use surrealdb_types::{Error, Chain};
/// use std::io;
///
/// let result: io::Result<()> = Err(io::Error::new(io::ErrorKind::NotFound, "file missing"));
/// let err = result.chain("Failed to load config").unwrap_err();
/// assert!(err.is_internal());
/// assert!(err.cause().is_some());
/// ```
pub trait Chain<T, E> {
	/// Wrap the error with the given context message. The original error becomes the cause.
	fn chain<C>(self, context: C) -> Result<T, Error>
	where
		C: fmt::Display + Send + Sync + 'static;

	/// Wrap the error with lazily-evaluated context.
	fn chain_with<C, F>(self, f: F) -> Result<T, Error>
	where
		C: fmt::Display + Send + Sync + 'static,
		F: FnOnce() -> C;
}

impl<T, E> Chain<T, E> for Result<T, E>
where
	E: Into<Error>,
{
	fn chain<C>(self, context: C) -> Result<T, Error>
	where
		C: fmt::Display + Send + Sync + 'static,
	{
		self.map_err(|e| Error::context(context.to_string()).with_cause(e.into()))
	}

	fn chain_with<C, F>(self, f: F) -> Result<T, Error>
	where
		C: fmt::Display + Send + Sync + 'static,
		F: FnOnce() -> C,
	{
		self.map_err(|e| Error::context(f().to_string()).with_cause(e.into()))
	}
}

impl<T> Chain<T, Infallible> for Option<T> {
	fn chain<C>(self, context: C) -> Result<T, Error>
	where
		C: fmt::Display + Send + Sync + 'static,
	{
		self.ok_or_else(|| Error::context(context.to_string()))
	}

	fn chain_with<C, F>(self, f: F) -> Result<T, Error>
	where
		C: fmt::Display + Send + Sync + 'static,
		F: FnOnce() -> C,
	{
		self.ok_or_else(|| Error::context(f().to_string()))
	}
}

// -----------------------------------------------------------------------------
// From conversions (std and optional)
// -----------------------------------------------------------------------------

/// Allow conversion from [`std::io::Error`].
/// Maps [`std::io::ErrorKind`] to the most appropriate typed error where possible.
impl From<std::io::Error> for Error {
	fn from(error: std::io::Error) -> Self {
		use std::io::ErrorKind;
		let msg = error.to_string();
		match error.kind() {
			ErrorKind::NotFound => Error::not_found(msg, None),
			ErrorKind::AlreadyExists => Error::already_exists(msg, None),
			ErrorKind::PermissionDenied
			| ErrorKind::ReadOnlyFilesystem
			| ErrorKind::ResourceBusy
			| ErrorKind::ExecutableFileBusy => Error::not_allowed(msg, None),
			ErrorKind::ConnectionRefused
			| ErrorKind::ConnectionReset
			| ErrorKind::ConnectionAborted
			| ErrorKind::NotConnected
			| ErrorKind::HostUnreachable
			| ErrorKind::NetworkUnreachable
			| ErrorKind::NetworkDown
			| ErrorKind::TimedOut
			| ErrorKind::BrokenPipe
			| ErrorKind::AddrInUse
			| ErrorKind::AddrNotAvailable
			| ErrorKind::StaleNetworkFileHandle => Error::connection(msg, ConnectionError::ConnectionFailed),
			ErrorKind::InvalidData | ErrorKind::UnexpectedEof => {
				Error::serialization(msg, SerializationError::Deserialization)
			}
			ErrorKind::InvalidInput
			| ErrorKind::InvalidFilename
			| ErrorKind::NotADirectory
			| ErrorKind::IsADirectory
			| ErrorKind::DirectoryNotEmpty => Error::validation(msg, None),
			_ => Error::internal(msg),
		}
	}
}

#[cfg(feature = "convert")]
impl From<async_channel::RecvError> for Error {
	fn from(error: async_channel::RecvError) -> Self {
		Error::connection(
			format!("Channel receive error: {}", error),
			ConnectionError::ConnectionFailed,
		)
	}
}

#[cfg(feature = "convert")]
impl From<url::ParseError> for Error {
	fn from(error: url::ParseError) -> Self {
		Error::validation(error.to_string(), ValidationError::InvalidRequest)
	}
}

#[cfg(feature = "convert")]
impl From<semver::Error> for Error {
	fn from(error: semver::Error) -> Self {
		Error::validation(error.to_string(), ValidationError::InvalidParams)
	}
}

#[cfg(feature = "reqwest")]
impl From<reqwest::Error> for Error {
	fn from(error: reqwest::Error) -> Self {
		Error::connection(error.to_string(), ConnectionError::ConnectionFailed)
	}
}

// -----------------------------------------------------------------------------
// Type conversion errors (internal to the types layer)
// -----------------------------------------------------------------------------

/// Errors that can occur when working with SurrealDB types
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum TypeError {
	/// Failed to convert between types
	Conversion(ConversionError),
	/// Value is out of range for the target type
	OutOfRange(OutOfRangeError),
	/// Array or tuple length mismatch
	LengthMismatch(LengthMismatchError),
	/// Invalid format or structure
	Invalid(String),
}

/// Error when converting between types
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ConversionError {
	/// The expected kind
	pub expected: Kind,
	/// The actual kind that was received
	pub actual: Kind,
	/// Optional context about what was being converted
	pub context: Option<String>,
}

/// Error when a value is out of range for the target type
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct OutOfRangeError {
	/// The value that was out of range
	pub value: String,
	/// The target type name
	pub target_type: String,
	/// Optional additional context
	pub context: Option<String>,
}

/// Error when an array or tuple has the wrong length
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct LengthMismatchError {
	/// The expected length
	pub expected: usize,
	/// The actual length received
	pub actual: usize,
	/// The target type name
	pub target_type: String,
}

impl ConversionError {
	/// Create a new conversion error
	pub fn new(expected: Kind, actual: Kind) -> Self {
		Self {
			expected,
			actual,
			context: None,
		}
	}

	/// Create a conversion error from a value
	pub fn from_value(expected: Kind, value: &Value) -> Self {
		Self {
			expected,
			actual: value.kind(),
			context: None,
		}
	}

	/// Add context to the error
	pub fn with_context(mut self, context: impl Into<String>) -> Self {
		self.context = Some(context.into());
		self
	}
}

impl OutOfRangeError {
	/// Create a new out of range error
	pub fn new(value: impl fmt::Display, target_type: impl Into<String>) -> Self {
		Self {
			value: value.to_string(),
			target_type: target_type.into(),
			context: None,
		}
	}

	/// Add context to the error
	pub fn with_context(mut self, context: impl Into<String>) -> Self {
		self.context = Some(context.into());
		self
	}
}

impl LengthMismatchError {
	/// Create a new length mismatch error
	pub fn new(expected: usize, actual: usize, target_type: impl Into<String>) -> Self {
		Self {
			expected,
			actual,
			target_type: target_type.into(),
		}
	}
}

impl fmt::Display for TypeError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self {
			TypeError::Conversion(e) => write!(f, "{e}"),
			TypeError::OutOfRange(e) => write!(f, "{e}"),
			TypeError::LengthMismatch(e) => write!(f, "{e}"),
			TypeError::Invalid(e) => write!(f, "Invalid: {e}"),
		}
	}
}

impl fmt::Display for ConversionError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "Expected {}, got {}", self.expected.to_sql(), self.actual.to_sql())?;
		if let Some(context) = &self.context {
			write!(f, " ({})", context)?;
		}
		Ok(())
	}
}

impl fmt::Display for OutOfRangeError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "Value {} is out of range for type {}", self.value, self.target_type)?;
		if let Some(context) = &self.context {
			write!(f, " ({})", context)?;
		}
		Ok(())
	}
}

impl fmt::Display for LengthMismatchError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(
			f,
			"Length mismatch for {}: expected {}, got {}",
			self.target_type, self.expected, self.actual
		)
	}
}

impl std::error::Error for TypeError {}
impl std::error::Error for ConversionError {}
impl std::error::Error for OutOfRangeError {}
impl std::error::Error for LengthMismatchError {}

impl From<ConversionError> for Error {
	fn from(e: ConversionError) -> Self {
		Error::internal(e.to_string())
	}
}

impl From<OutOfRangeError> for Error {
	fn from(e: OutOfRangeError) -> Self {
		Error::internal(e.to_string())
	}
}

impl From<LengthMismatchError> for Error {
	fn from(e: LengthMismatchError) -> Self {
		Error::internal(e.to_string())
	}
}

impl From<TypeError> for Error {
	fn from(e: TypeError) -> Self {
		Error::internal(e.to_string())
	}
}

/// Helper function to create a conversion error
pub fn conversion_error(expected: Kind, value: impl Into<Value>) -> Error {
	let value = value.into();
	ConversionError::from_value(expected, &value).into()
}

/// Helper function to create an out of range error
pub fn out_of_range_error(value: impl fmt::Display, target_type: impl Into<String>) -> Error {
	OutOfRangeError::new(value, target_type).into()
}

/// Helper function to create a length mismatch error
pub fn length_mismatch_error(
	expected: usize,
	actual: usize,
	target_type: impl Into<String>,
) -> Error {
	LengthMismatchError::new(expected, actual, target_type).into()
}

/// Helper function to create a conversion error for union types (Either)
/// where the value doesn't match any of the possible types
pub fn union_conversion_error(expected: Kind, value: impl Into<Value>) -> Error {
	let value = value.into();
	ConversionError::from_value(expected, &value)
		.with_context("Value does not match any variant in union type")
		.into()
}