surrealdb_core/err/
mod.rs

1use crate::api::err::ApiError;
2use crate::iam::Error as IamError;
3use crate::idx::ft::MatchRef;
4use crate::idx::trees::vector::SharedVector;
5use crate::sql::idiom::Idiom;
6use crate::sql::index::Distance;
7use crate::sql::thing::Thing;
8use crate::sql::value::Value;
9use crate::syn::error::RenderedError as RenderedParserError;
10use crate::vs::VersionStampError;
11use base64::DecodeError as Base64Error;
12use bincode::Error as BincodeError;
13#[cfg(storage)]
14use ext_sort::SortError;
15use fst::Error as FstError;
16use http::header::{InvalidHeaderName, InvalidHeaderValue, ToStrError};
17use jsonwebtoken::errors::Error as JWTError;
18use object_store::Error as ObjectStoreError;
19use revision::Error as RevisionError;
20use serde::Serialize;
21use std::io::Error as IoError;
22use std::string::FromUtf8Error;
23use storekey::decode::Error as DecodeError;
24use storekey::encode::Error as EncodeError;
25use thiserror::Error;
26
27/// An error originating from an embedded SurrealDB database.
28#[derive(Error, Debug)]
29#[non_exhaustive]
30pub enum Error {
31	/// This error is used for ignoring a document when processing a query
32	#[doc(hidden)]
33	#[error("Conditional clause is not truthy")]
34	Ignore,
35
36	/// This error is used for breaking a loop in a foreach statement
37	#[doc(hidden)]
38	#[error("Break statement has been reached")]
39	Break,
40
41	/// This error is used for skipping a loop in a foreach statement
42	#[doc(hidden)]
43	#[error("Continue statement has been reached")]
44	Continue,
45
46	/// This error is used for retrying document processing with a new id
47	#[doc(hidden)]
48	#[error("This document should be retried with a new ID")]
49	RetryWithId(Thing),
50
51	/// The database encountered unreachable logic
52	#[error("The database encountered unreachable logic: {0}")]
53	Unreachable(String),
54
55	/// Statement has been deprecated
56	#[error("{0}")]
57	Deprecated(String),
58
59	/// A custom error has been thrown
60	#[error("An error occurred: {0}")]
61	Thrown(String),
62
63	/// There was a problem with the underlying datastore
64	#[error("There was a problem with the underlying datastore: {0}")]
65	Ds(String),
66
67	/// There was a problem with a datastore transaction
68	#[error("There was a problem with a datastore transaction: {0}")]
69	Tx(String),
70
71	/// There was an error when starting a new datastore transaction
72	#[error("There was an error when starting a new datastore transaction")]
73	TxFailure,
74
75	/// The transaction was already cancelled or committed
76	#[error("Couldn't update a finished transaction")]
77	TxFinished,
78
79	/// The current transaction was created as read-only
80	#[error("Couldn't write to a read only transaction")]
81	TxReadonly,
82
83	/// The conditional value in the request was not equal
84	#[error("Value being checked was not correct")]
85	TxConditionNotMet,
86
87	/// The key being inserted in the transaction already exists
88	#[error("The key being inserted already exists")]
89	TxKeyAlreadyExists,
90
91	/// The key exceeds a limit set by the KV store
92	#[error("Record id or key is too large")]
93	TxKeyTooLarge,
94
95	/// The value exceeds a limit set by the KV store
96	#[error("Record or value is too large")]
97	TxValueTooLarge,
98
99	/// There was a transaction error that can be retried
100	#[error("Failed to commit transaction due to a read or write conflict. This transaction can be retried")]
101	TxRetryable,
102
103	/// The transaction writes too much data for the KV store
104	#[error("Transaction is too large")]
105	TxTooLarge,
106
107	/// No namespace has been selected
108	#[error("Specify a namespace to use")]
109	NsEmpty,
110
111	/// No database has been selected
112	#[error("Specify a database to use")]
113	DbEmpty,
114
115	/// No SQL query has been specified
116	#[error("Specify some SQL code to execute")]
117	QueryEmpty,
118
119	/// There was an error with the SQL query
120	#[error("The SQL query was not parsed fully")]
121	QueryRemaining,
122
123	/// There was an error with the SQL query
124	#[error("Parse error: {0}")]
125	InvalidQuery(RenderedParserError),
126
127	/// There was an error with the SQL query
128	#[error("Can not use {value} in a CONTENT clause")]
129	InvalidContent {
130		value: Value,
131	},
132
133	/// There was an error with the SQL query
134	#[error("Can not use {value} in a MERGE clause")]
135	InvalidMerge {
136		value: Value,
137	},
138
139	/// There was an error with the provided JSON Patch
140	#[error("The JSON Patch contains invalid operations. {message}")]
141	InvalidPatch {
142		message: String,
143	},
144
145	/// Given test operation failed for JSON Patch
146	#[error("Given test operation failed for JSON Patch. Expected `{expected}`, but got `{got}` instead.")]
147	PatchTest {
148		expected: String,
149		got: String,
150	},
151
152	/// Remote HTTP request functions are not enabled
153	#[error("Remote HTTP request functions are not enabled")]
154	HttpDisabled,
155
156	/// it is not possible to set a variable with the specified name
157	#[error("'{name}' is a protected variable and cannot be set")]
158	InvalidParam {
159		name: String,
160	},
161
162	#[error("Found '{field}' in SELECT clause on line {line}, but field is not an aggregate function, and is not present in GROUP BY expression")]
163	InvalidField {
164		line: usize,
165		field: String,
166	},
167
168	/// The FETCH clause accepts idioms, strings and fields.
169	#[error("Found {value} on FETCH CLAUSE, but FETCH expects an idiom, a string or fields")]
170	InvalidFetch {
171		value: Value,
172	},
173
174	#[error("Found '{field}' in SPLIT ON clause on line {line}, but field is not present in SELECT expression")]
175	InvalidSplit {
176		line: usize,
177		field: String,
178	},
179
180	#[error("Found '{field}' in ORDER BY clause on line {line}, but field is not present in SELECT expression")]
181	InvalidOrder {
182		line: usize,
183		field: String,
184	},
185
186	#[error("Found '{field}' in GROUP BY clause on line {line}, but field is not present in SELECT expression")]
187	InvalidGroup {
188		line: usize,
189		field: String,
190	},
191
192	/// The LIMIT clause must evaluate to a positive integer
193	#[error("Found {value} but the LIMIT clause must evaluate to a positive integer")]
194	InvalidLimit {
195		value: String,
196	},
197
198	/// The START clause must evaluate to a positive integer
199	#[error("Found {value} but the START clause must evaluate to a positive integer")]
200	InvalidStart {
201		value: String,
202	},
203
204	/// There was an error with the provided JavaScript code
205	#[error("Problem with embedded script function. {message}")]
206	InvalidScript {
207		message: String,
208	},
209
210	/// There was an error with the provided machine learning model
211	#[error("Problem with machine learning computation. {message}")]
212	InvalidModel {
213		message: String,
214	},
215
216	/// There was a problem running the specified function
217	#[error("There was a problem running the {name}() function. {message}")]
218	InvalidFunction {
219		name: String,
220		message: String,
221	},
222
223	/// The wrong quantity or magnitude of arguments was given for the specified function
224	#[error("Incorrect arguments for function {name}(). {message}")]
225	InvalidArguments {
226		name: String,
227		message: String,
228	},
229
230	/// The wrong quantity or magnitude of arguments was given for the specified function
231	#[error("Incorrect arguments for aggregate function {name}() on table '{table}'. {message}")]
232	InvalidAggregation {
233		name: String,
234		table: String,
235		message: String,
236	},
237
238	/// The wrong quantity or magnitude of arguments was given for the specified function
239	#[error("There was a problem running the {name} function. Expected this function to return a value of type {check}, but found {value}")]
240	FunctionCheck {
241		name: String,
242		value: String,
243		check: String,
244	},
245
246	/// The URL is invalid
247	#[error("The URL `{0}` is invalid")]
248	InvalidUrl(String),
249
250	/// The size of the vector is incorrect
251	#[error("Incorrect vector dimension ({current}). Expected a vector of {expected} dimension.")]
252	InvalidVectorDimension {
253		current: usize,
254		expected: usize,
255	},
256
257	/// The size of the vector is incorrect
258	#[error("Unable to compute distance.The calculated result is not a valid number: {dist}. Vectors: {left:?} - {right:?}")]
259	InvalidVectorDistance {
260		left: SharedVector,
261		right: SharedVector,
262		dist: f64,
263	},
264
265	/// The size of the vector is incorrect
266	#[error("The vector element ({current}) is not a number.")]
267	InvalidVectorType {
268		current: String,
269		expected: &'static str,
270	},
271
272	/// The size of the vector is incorrect
273	#[error("The value cannot be converted to a vector: {0}")]
274	InvalidVectorValue(String),
275
276	/// Invalid regular expression
277	#[error("Invalid regular expression: {0:?}")]
278	InvalidRegex(String),
279
280	/// Invalid timeout
281	#[error("Invalid timeout: {0:?} seconds")]
282	InvalidTimeout(u64),
283
284	/// The query timedout
285	#[error("The query was not executed because it exceeded the timeout")]
286	QueryTimedout,
287
288	/// The query did not execute, because the transaction was cancelled
289	#[error("The query was not executed due to a cancelled transaction")]
290	QueryCancelled,
291
292	/// The query did not execute, because the transaction has failed
293	#[error("The query was not executed due to a failed transaction")]
294	QueryNotExecuted,
295
296	/// The query did not execute, because the transaction has failed (with a message)
297	#[error("The query was not executed due to a failed transaction. {message}")]
298	QueryNotExecutedDetail {
299		message: String,
300	},
301
302	/// The permissions do not allow for changing to the specified namespace
303	#[error("You don't have permission to change to the {ns} namespace")]
304	NsNotAllowed {
305		ns: String,
306	},
307
308	/// The permissions do not allow for changing to the specified database
309	#[error("You don't have permission to change to the {db} database")]
310	DbNotAllowed {
311		db: String,
312	},
313
314	/// The requested namespace does not exist
315	#[error("The namespace '{name}' does not exist")]
316	NsNotFound {
317		name: String,
318	},
319
320	/// The requested namespace login does not exist
321	#[error("The namespace login '{name}' does not exist")]
322	NlNotFound {
323		name: String,
324	},
325
326	/// The requested database does not exist
327	#[error("The database '{name}' does not exist")]
328	DbNotFound {
329		name: String,
330	},
331
332	/// The requested database login does not exist
333	#[error("The database login '{name}' does not exist")]
334	DlNotFound {
335		name: String,
336	},
337
338	/// The requested event does not exist
339	#[error("The event '{name}' does not exist")]
340	EvNotFound {
341		name: String,
342	},
343
344	/// The requested function does not exist
345	#[error("The function 'fn::{name}' does not exist")]
346	FcNotFound {
347		name: String,
348	},
349
350	/// The requested field does not exist
351	#[error("The field '{name}' does not exist")]
352	FdNotFound {
353		name: String,
354	},
355
356	/// The requested model does not exist
357	#[error("The model 'ml::{name}' does not exist")]
358	MlNotFound {
359		name: String,
360	},
361
362	/// The cluster node does not exist
363	#[error("The node '{uuid}' does not exist")]
364	NdNotFound {
365		uuid: String,
366	},
367
368	/// The requested param does not exist
369	#[error("The param '${name}' does not exist")]
370	PaNotFound {
371		name: String,
372	},
373
374	/// The requested config does not exist
375	#[error("The config for {name} does not exist")]
376	CgNotFound {
377		name: String,
378	},
379
380	/// The requested table does not exist
381	#[error("The table '{name}' does not exist")]
382	TbNotFound {
383		name: String,
384	},
385
386	/// The requested live query does not exist
387	#[error("The live query '{name}' does not exist")]
388	LvNotFound {
389		name: String,
390	},
391
392	/// The requested cluster live query does not exist
393	#[error("The cluster live query '{name}' does not exist")]
394	LqNotFound {
395		name: String,
396	},
397
398	/// The requested api does not exist
399	#[error("The api '/{value}' does not exist")]
400	ApNotFound {
401		value: String,
402	},
403
404	/// The requested analyzer does not exist
405	#[error("The analyzer '{name}' does not exist")]
406	AzNotFound {
407		name: String,
408	},
409
410	/// The requested analyzer does not exist
411	#[error("The index '{name}' does not exist")]
412	IxNotFound {
413		name: String,
414	},
415
416	/// The requested record does not exist
417	#[error("The record '{rid}' does not exist")]
418	IdNotFound {
419		rid: String,
420	},
421
422	#[error("Unsupported distance: {0}")]
423	UnsupportedDistance(Distance),
424
425	/// The requested root user does not exist
426	#[error("The root user '{name}' does not exist")]
427	UserRootNotFound {
428		name: String,
429	},
430
431	/// The requested namespace user does not exist
432	#[error("The user '{name}' does not exist in the namespace '{ns}'")]
433	UserNsNotFound {
434		name: String,
435		ns: String,
436	},
437
438	/// The requested database user does not exist
439	#[error("The user '{name}' does not exist in the database '{db}'")]
440	UserDbNotFound {
441		name: String,
442		ns: String,
443		db: String,
444	},
445
446	/// Unable to perform the realtime query
447	#[error("Unable to perform the realtime query")]
448	RealtimeDisabled,
449
450	/// Reached excessive computation depth due to functions, subqueries, or futures
451	#[error("Reached excessive computation depth due to functions, subqueries, or futures")]
452	ComputationDepthExceeded,
453
454	/// Can not execute statement using the specified value
455	#[error("Can not execute statement using value: {value}")]
456	InvalidStatementTarget {
457		value: String,
458	},
459
460	/// Can not execute CREATE statement using the specified value
461	#[error("Can not execute CREATE statement using value: {value}")]
462	CreateStatement {
463		value: String,
464	},
465
466	/// Can not execute UPSERT statement using the specified value
467	#[error("Can not execute UPSERT statement using value: {value}")]
468	UpsertStatement {
469		value: String,
470	},
471
472	/// Can not execute UPDATE statement using the specified value
473	#[error("Can not execute UPDATE statement using value: {value}")]
474	UpdateStatement {
475		value: String,
476	},
477
478	/// Can not execute RELATE statement using the specified value
479	#[error("Can not execute RELATE statement using value: {value}")]
480	RelateStatement {
481		value: String,
482	},
483
484	/// Can not execute RELATE statement using the specified value
485	#[error("Can not execute RELATE statement where property 'in' is: {value}")]
486	RelateStatementIn {
487		value: String,
488	},
489
490	/// Can not execute RELATE statement using the specified value
491	#[error("Can not execute RELATE statement where property 'id' is: {value}")]
492	RelateStatementId {
493		value: String,
494	},
495
496	/// Can not execute RELATE statement using the specified value
497	#[error("Can not execute RELATE statement where property 'out' is: {value}")]
498	RelateStatementOut {
499		value: String,
500	},
501
502	/// Can not execute DELETE statement using the specified value
503	#[error("Can not execute DELETE statement using value: {value}")]
504	DeleteStatement {
505		value: String,
506	},
507
508	/// Can not execute INSERT statement using the specified value
509	#[error("Can not execute INSERT statement using value: {value}")]
510	InsertStatement {
511		value: String,
512	},
513
514	/// Can not execute INSERT statement using the specified value
515	#[error("Can not execute INSERT statement where property 'in' is: {value}")]
516	InsertStatementIn {
517		value: String,
518	},
519
520	/// Can not execute INSERT statement using the specified value
521	#[error("Can not execute INSERT statement where property 'id' is: {value}")]
522	InsertStatementId {
523		value: String,
524	},
525
526	/// Can not execute INSERT statement using the specified value
527	#[error("Can not execute INSERT statement where property 'out' is: {value}")]
528	InsertStatementOut {
529		value: String,
530	},
531
532	/// Can not execute LIVE statement using the specified value
533	#[error("Can not execute LIVE statement using value: {value}")]
534	LiveStatement {
535		value: String,
536	},
537
538	/// Can not execute KILL statement using the specified id
539	#[error("Can not execute KILL statement using id: {value}")]
540	KillStatement {
541		value: String,
542	},
543
544	/// Can not execute CREATE statement using the specified value
545	#[error("Expected a single result output when using the ONLY keyword")]
546	SingleOnlyOutput,
547
548	/// The permissions do not allow this query to be run on this table
549	#[error("You don't have permission to run this query on the `{table}` table")]
550	TablePermissions {
551		table: String,
552	},
553
554	/// The permissions do not allow this query to be run on this table
555	#[error("You don't have permission to view the ${name} parameter")]
556	ParamPermissions {
557		name: String,
558	},
559
560	/// The permissions do not allow this query to be run on this table
561	#[error("You don't have permission to run the fn::{name} function")]
562	FunctionPermissions {
563		name: String,
564	},
565
566	/// The specified table can not be written as it is setup as a foreign table view
567	#[error("Unable to write to the `{table}` table while setup as a view")]
568	TableIsView {
569		table: String,
570	},
571
572	/// A database entry for the specified record already exists
573	#[error("Database record `{thing}` already exists")]
574	RecordExists {
575		thing: Thing,
576	},
577
578	/// A database index entry for the specified record already exists
579	#[error("Database index `{index}` already contains {value}, with record `{thing}`")]
580	IndexExists {
581		thing: Thing,
582		index: String,
583		value: String,
584	},
585
586	/// The specified table is not configured for the type of record being added
587	#[error("Found record: `{thing}` which is {}a relation, but expected a {target_type}", if *relation { "not " } else { "" })]
588	TableCheck {
589		thing: String,
590		relation: bool,
591		target_type: String,
592	},
593
594	/// The specified field did not conform to the field type check
595	#[error("Found {value} for field `{field}`, with record `{thing}`, but expected a {check}")]
596	FieldCheck {
597		thing: String,
598		value: String,
599		field: Idiom,
600		check: String,
601	},
602
603	/// The specified field did not conform to the field ASSERT clause
604	#[error("Found {value} for field `{field}`, with record `{thing}`, but field must conform to: {check}")]
605	FieldValue {
606		thing: String,
607		value: String,
608		field: Idiom,
609		check: String,
610	},
611
612	/// The specified value did not conform to the LET type check
613	#[error("Found {value} for param ${name}, but expected a {check}")]
614	SetCheck {
615		value: String,
616		name: String,
617		check: String,
618	},
619
620	/// The specified field did not conform to the field ASSERT clause
621	#[error(
622		"Found changed value for field `{field}`, with record `{thing}`, but field is readonly"
623	)]
624	FieldReadonly {
625		thing: String,
626		field: Idiom,
627	},
628
629	/// The specified field on a SCHEMAFUL table was not defined
630	#[error("Found field '{field}', but no such field exists for table '{table}'")]
631	FieldUndefined {
632		table: String,
633		field: Idiom,
634	},
635
636	/// Found a record id for the record but this is not a valid id
637	#[error("Found {value} for the Record ID but this is not a valid id")]
638	IdInvalid {
639		value: String,
640	},
641
642	/// Found a record id for the record but we are creating a specific record
643	#[error("Found {value} for the `id` field, but a specific record has been specified")]
644	IdMismatch {
645		value: String,
646	},
647
648	/// Found a record id for the record but this is not a valid id
649	#[error("Found {value} for the incoming relation, but this is not a valid Record ID")]
650	InInvalid {
651		value: String,
652	},
653
654	/// Found a record id for the record but we are creating a specific record
655	#[error("Found {value} for the `in` field, but the value does not match the `in` record id")]
656	InMismatch {
657		value: String,
658	},
659
660	/// Found a record id for the record but we are creating a specific record
661	#[error("Found {value} for the `in` field, which does not match the existing field value")]
662	InOverride {
663		value: String,
664	},
665
666	/// Found a record id for the record but this is not a valid id
667	#[error("Found {value} for the outgoing relation, but this is not a valid Record ID")]
668	OutInvalid {
669		value: String,
670	},
671
672	/// Found a record id for the record but we are creating a specific record
673	#[error("Found {value} for the `out` field, but the value does not match the `out` record id")]
674	OutMismatch {
675		value: String,
676	},
677
678	/// Found a record id for the record but we are creating a specific record
679	#[error("Found {value} for the `out` field, which does not match the existing field value")]
680	OutOverride {
681		value: String,
682	},
683
684	/// Unable to coerce to a value to another value
685	#[error("Expected a {into} but found {from}")]
686	CoerceTo {
687		from: Value,
688		into: String,
689	},
690
691	/// Unable to convert a value to another value
692	#[error("Expected a {into} but cannot convert {from} into a {into}")]
693	ConvertTo {
694		from: Value,
695		into: String,
696	},
697
698	/// Unable to coerce to a value to another value
699	#[error("Expected a {kind} but the array had {size} items")]
700	LengthInvalid {
701		kind: String,
702		size: usize,
703	},
704
705	/// Cannot perform addition
706	#[error("Cannot perform addition with '{0}' and '{1}'")]
707	TryAdd(String, String),
708
709	/// Cannot perform subtraction
710	#[error("Cannot perform subtraction with '{0}' and '{1}'")]
711	TrySub(String, String),
712
713	/// Cannot perform multiplication
714	#[error("Cannot perform multiplication with '{0}' and '{1}'")]
715	TryMul(String, String),
716
717	/// Cannot perform division
718	#[error("Cannot perform division with '{0}' and '{1}'")]
719	TryDiv(String, String),
720
721	/// Cannot perform remainder
722	#[error("Cannot perform remainder with '{0}' and '{1}'")]
723	TryRem(String, String),
724
725	/// Cannot perform power
726	#[error("Cannot raise the value '{0}' with '{1}'")]
727	TryPow(String, String),
728
729	/// Cannot perform negation
730	#[error("Cannot negate the value '{0}'")]
731	TryNeg(String),
732
733	/// It's is not possible to convert between the two types
734	#[error("Cannot convert from '{0}' to '{1}'")]
735	TryFrom(String, &'static str),
736
737	/// There was an error processing a remote HTTP request
738	#[error("There was an error processing a remote HTTP request: {0}")]
739	Http(String),
740
741	/// There was an error processing a value in parallel
742	#[error("There was an error processing a value in parallel: {0}")]
743	Channel(String),
744
745	/// Represents an underlying error with IO encoding / decoding
746	#[error("I/O error: {0}")]
747	Io(#[from] IoError),
748
749	/// Represents an error when encoding a key-value entry
750	#[error("Key encoding error: {0}")]
751	Encode(#[from] EncodeError),
752
753	/// Represents an error when decoding a key-value entry
754	#[error("Key decoding error: {0}")]
755	Decode(#[from] DecodeError),
756
757	/// Represents an underlying error with versioned data encoding / decoding
758	#[error("Versioned error: {0}")]
759	Revision(#[from] RevisionError),
760
761	/// The index has been found to be inconsistent
762	#[error("Index is corrupted: {0}")]
763	CorruptedIndex(&'static str),
764
765	/// The query planner did not find an index able to support the given expression
766	#[error("There was no suitable index supporting the expression: {exp}")]
767	NoIndexFoundForMatch {
768		exp: String,
769	},
770
771	/// Represents an error when analyzing a value
772	#[error("A value can't be analyzed: {0}")]
773	AnalyzerError(String),
774
775	/// Represents an error when trying to highlight a value
776	#[error("A value can't be highlighted: {0}")]
777	HighlightError(String),
778
779	/// Represents an underlying error with Bincode serializing / deserializing
780	#[error("Bincode error: {0}")]
781	Bincode(#[from] BincodeError),
782
783	/// Represents an underlying error with FST
784	#[error("FstError error: {0}")]
785	FstError(#[from] FstError),
786
787	/// Represents an underlying error while reading UTF8 characters
788	#[error("Utf8 error: {0}")]
789	Utf8Error(#[from] FromUtf8Error),
790
791	/// Represents an underlying error with the Object Store
792	#[error("Object Store error: {0}")]
793	ObsError(#[from] ObjectStoreError),
794
795	/// There was an error with model computation
796	#[error("There was an error with model computation: {0}")]
797	ModelComputation(String),
798
799	/// The feature has not yet being implemented
800	#[error("Feature not yet implemented: {feature}")]
801	FeatureNotYetImplemented {
802		feature: String,
803	},
804
805	/// Duplicated match references are not allowed
806	#[error("Duplicated Match reference: {mr}")]
807	DuplicatedMatchRef {
808		mr: MatchRef,
809	},
810
811	/// Represents a failure in timestamp arithmetic related to database internals
812	#[error("Timestamp arithmetic error: {0}")]
813	TimestampOverflow(String),
814
815	/// Internal server error
816	/// This should be used extremely sporadically, since we lose the type of error as a consequence
817	/// There will be times when it is useful, such as with unusual type conversion errors
818	#[error("Internal database error: {0}")]
819	Internal(String),
820
821	/// Unimplemented functionality
822	#[error("Unimplemented functionality: {0}")]
823	Unimplemented(String),
824
825	#[error("Versionstamp in key is corrupted: {0}")]
826	CorruptedVersionstampInKey(#[from] VersionStampError),
827
828	/// Invalid level
829	#[error("Invalid level '{0}'")]
830	InvalidLevel(String),
831
832	/// Represents an underlying IAM error
833	#[error("IAM error: {0}")]
834	IamError(#[from] IamError),
835
836	//
837	// Capabilities
838	//
839	/// Scripting is not allowed
840	#[error("Scripting functions are not allowed")]
841	ScriptingNotAllowed,
842
843	/// Function is not allowed
844	#[error("Function '{0}' is not allowed to be executed")]
845	FunctionNotAllowed(String),
846
847	/// Network target is not allowed
848	#[error("Access to network target '{0}' is not allowed")]
849	NetTargetNotAllowed(String),
850
851	//
852	// Authentication / Signup
853	//
854	#[error("There was an error creating the token")]
855	TokenMakingFailed,
856
857	#[error("No record was returned")]
858	NoRecordFound,
859
860	#[error("The signup query failed")]
861	SignupQueryFailed,
862
863	#[error("The signin query failed")]
864	SigninQueryFailed,
865
866	#[error("Username or Password was not provided")]
867	MissingUserOrPass,
868
869	#[error("No signin target to either SC or DB or NS or KV")]
870	NoSigninTarget,
871
872	#[error("The password did not verify")]
873	InvalidPass,
874
875	/// There was an error with authentication
876	///
877	/// This error hides different kinds of errors directly related to authentication
878	#[error("There was a problem with authentication")]
879	InvalidAuth,
880
881	/// There was an unexpected error while performing authentication
882	///
883	/// This error hides different kinds of unexpected errors that may affect authentication
884	#[error("There was an unexpected error while performing authentication")]
885	UnexpectedAuth,
886
887	/// There was an error with signing up
888	#[error("There was a problem with signing up")]
889	InvalidSignup,
890
891	/// Auth was expected to be set but was unknown
892	#[error("Auth was expected to be set but was unknown")]
893	UnknownAuth,
894
895	/// Auth requires a token header which is missing
896	#[error("Auth token is missing the '{0}' header")]
897	MissingTokenHeader(String),
898
899	/// Auth requires a token claim which is missing
900	#[error("Auth token is missing the '{0}' claim")]
901	MissingTokenClaim(String),
902
903	/// The db is running without an available storage engine
904	#[error("The db is running without an available storage engine")]
905	MissingStorageEngine,
906
907	// The cluster node already exists
908	#[error("The node '{id}' already exists")]
909	ClAlreadyExists {
910		id: String,
911	},
912
913	/// The requested api already exists
914	#[error("The api '/{value}' already exists")]
915	ApAlreadyExists {
916		value: String,
917	},
918
919	/// The requested analyzer already exists
920	#[error("The analyzer '{name}' already exists")]
921	AzAlreadyExists {
922		name: String,
923	},
924
925	/// The requested database already exists
926	#[error("The database '{name}' already exists")]
927	DbAlreadyExists {
928		name: String,
929	},
930
931	/// The requested event already exists
932	#[error("The event '{name}' already exists")]
933	EvAlreadyExists {
934		name: String,
935	},
936
937	/// The requested field already exists
938	#[error("The field '{name}' already exists")]
939	FdAlreadyExists {
940		name: String,
941	},
942
943	/// The requested function already exists
944	#[error("The function 'fn::{name}' already exists")]
945	FcAlreadyExists {
946		name: String,
947	},
948
949	/// The requested index already exists
950	#[error("The index '{name}' already exists")]
951	IxAlreadyExists {
952		name: String,
953	},
954
955	/// The requested model already exists
956	#[error("The model '{name}' already exists")]
957	MlAlreadyExists {
958		name: String,
959	},
960
961	/// The requested namespace already exists
962	#[error("The namespace '{name}' already exists")]
963	NsAlreadyExists {
964		name: String,
965	},
966
967	/// The requested param already exists
968	#[error("The param '${name}' already exists")]
969	PaAlreadyExists {
970		name: String,
971	},
972
973	/// The requested config already exists
974	#[error("The config for {name} already exists")]
975	CgAlreadyExists {
976		name: String,
977	},
978
979	/// The requested table already exists
980	#[error("The table '{name}' already exists")]
981	TbAlreadyExists {
982		name: String,
983	},
984
985	/// The requested namespace token already exists
986	#[error("The namespace token '{name}' already exists")]
987	NtAlreadyExists {
988		name: String,
989	},
990
991	/// The requested database token already exists
992	#[error("The database token '{name}' already exists")]
993	DtAlreadyExists {
994		name: String,
995	},
996
997	/// The requested user already exists
998	#[error("The root user '{name}' already exists")]
999	UserRootAlreadyExists {
1000		name: String,
1001	},
1002
1003	/// The requested namespace user already exists
1004	#[error("The user '{name}' already exists in the namespace '{ns}'")]
1005	UserNsAlreadyExists {
1006		name: String,
1007		ns: String,
1008	},
1009
1010	/// The requested database user already exists
1011	#[error("The user '{name}' already exists in the database '{db}'")]
1012	UserDbAlreadyExists {
1013		name: String,
1014		ns: String,
1015		db: String,
1016	},
1017
1018	/// A database index entry for the specified table is already building
1019	#[error("Database index `{name}` is currently building")]
1020	IndexAlreadyBuilding {
1021		name: String,
1022	},
1023
1024	/// The token has expired
1025	#[error("The token has expired")]
1026	ExpiredToken,
1027
1028	/// The session has expired
1029	#[error("The session has expired")]
1030	ExpiredSession,
1031
1032	/// A node task has failed
1033	#[error("A node task has failed: {0}")]
1034	NodeAgent(&'static str),
1035
1036	/// The supplied type could not be serialiazed into `sql::Value`
1037	#[error("Serialization error: {0}")]
1038	Serialization(String),
1039
1040	/// The requested root access method already exists
1041	#[error("The root access method '{ac}' already exists")]
1042	AccessRootAlreadyExists {
1043		ac: String,
1044	},
1045
1046	/// The requested namespace access method already exists
1047	#[error("The access method '{ac}' already exists in the namespace '{ns}'")]
1048	AccessNsAlreadyExists {
1049		ac: String,
1050		ns: String,
1051	},
1052
1053	/// The requested database access method already exists
1054	#[error("The access method '{ac}' already exists in the database '{db}'")]
1055	AccessDbAlreadyExists {
1056		ac: String,
1057		ns: String,
1058		db: String,
1059	},
1060
1061	/// The requested root access method does not exist
1062	#[error("The root access method '{ac}' does not exist")]
1063	AccessRootNotFound {
1064		ac: String,
1065	},
1066
1067	/// The requested root access grant does not exist
1068	#[error("The root access grant '{gr}' does not exist for '{ac}'")]
1069	AccessGrantRootNotFound {
1070		ac: String,
1071		gr: String,
1072	},
1073
1074	/// The requested namespace access method does not exist
1075	#[error("The access method '{ac}' does not exist in the namespace '{ns}'")]
1076	AccessNsNotFound {
1077		ac: String,
1078		ns: String,
1079	},
1080
1081	/// The requested namespace access grant does not exist
1082	#[error("The access grant '{gr}' does not exist for '{ac}' in the namespace '{ns}'")]
1083	AccessGrantNsNotFound {
1084		ac: String,
1085		gr: String,
1086		ns: String,
1087	},
1088
1089	/// The requested database access method does not exist
1090	#[error("The access method '{ac}' does not exist in the database '{db}'")]
1091	AccessDbNotFound {
1092		ac: String,
1093		ns: String,
1094		db: String,
1095	},
1096
1097	/// The requested database access grant does not exist
1098	#[error("The access grant '{gr}' does not exist for '{ac}' in the database '{db}'")]
1099	AccessGrantDbNotFound {
1100		ac: String,
1101		gr: String,
1102		ns: String,
1103		db: String,
1104	},
1105
1106	/// The access method cannot be defined on the requested level
1107	#[error("The access method cannot be defined on the requested level")]
1108	AccessLevelMismatch,
1109
1110	#[error("The access method cannot be used in the requested operation")]
1111	AccessMethodMismatch,
1112
1113	#[error("The access method does not exist")]
1114	AccessNotFound,
1115
1116	#[error("This access method has an invalid duration")]
1117	AccessInvalidDuration,
1118
1119	#[error("This access method results in an invalid expiration")]
1120	AccessInvalidExpiration,
1121
1122	#[error("The record access signup query failed")]
1123	AccessRecordSignupQueryFailed,
1124
1125	#[error("The record access signin query failed")]
1126	AccessRecordSigninQueryFailed,
1127
1128	#[error("This record access method does not allow signup")]
1129	AccessRecordNoSignup,
1130
1131	#[error("This record access method does not allow signin")]
1132	AccessRecordNoSignin,
1133
1134	#[error("This bearer access method requires a key to be provided")]
1135	AccessBearerMissingKey,
1136
1137	#[error("This bearer access grant has an invalid format")]
1138	AccessGrantBearerInvalid,
1139
1140	#[error("This access grant has an invalid subject")]
1141	AccessGrantInvalidSubject,
1142
1143	#[error("This access grant has been revoked")]
1144	AccessGrantRevoked,
1145
1146	/// Found a table name for the record but this is not a valid table
1147	#[error("Found {value} for the Record ID but this is not a valid table name")]
1148	TbInvalid {
1149		value: String,
1150	},
1151
1152	/// This error is used for breaking execution when a value is returned
1153	#[doc(hidden)]
1154	#[error("Return statement has been reached")]
1155	Return {
1156		value: Value,
1157	},
1158
1159	/// A destructuring variant was used in a context where it is not supported
1160	#[error("{variant} destructuring method is not supported here")]
1161	UnsupportedDestructure {
1162		variant: String,
1163	},
1164
1165	#[doc(hidden)]
1166	#[error("The underlying datastore does not support versioned queries")]
1167	UnsupportedVersionedQueries,
1168
1169	/// Found an unexpected value in a range
1170	#[error("Expected a range value of '{expected}', but found '{found}'")]
1171	InvalidRangeValue {
1172		expected: String,
1173		found: String,
1174	},
1175
1176	/// Found an unexpected value in a range
1177	#[error("The range cannot exceed a size of {max} for this operation")]
1178	RangeTooBig {
1179		max: usize,
1180	},
1181
1182	/// There was an invalid storage version stored in the database
1183	#[error("There was an invalid storage version stored in the database")]
1184	InvalidStorageVersion,
1185
1186	/// There was an outdated storage version stored in the database
1187	#[error("The data stored on disk is out-of-date with this version. Please follow the upgrade guides in the documentation")]
1188	OutdatedStorageVersion,
1189
1190	#[error("Found a non-computed value where they are not allowed")]
1191	NonComputed,
1192
1193	#[error("Size of query script exceeded maximum supported size of 4,294,967,295 bytes.")]
1194	QueryTooLarge,
1195
1196	/// Represents a failure in timestamp arithmetic related to database internals
1197	#[error("Failed to compute: \"{0}\", as the operation results in an arithmetic overflow.")]
1198	ArithmeticOverflow(String),
1199
1200	/// Represents a negative value for a type that must be zero or positive
1201	#[error("Failed to compute: \"{0}\", as the operation results in a negative value.")]
1202	ArithmeticNegativeOverflow(String),
1203
1204	#[error("Failed to allocate space for \"{0}\"")]
1205	InsufficientReserve(String),
1206
1207	#[error("Received error while streaming query: {0}.")]
1208	QueryStream(String),
1209
1210	#[error("Error while ordering a result: {0}.")]
1211	OrderingError(String),
1212
1213	#[error("Encountered an issue while processed export config: found {0}, but expected {1}.")]
1214	InvalidExportConfig(Value, String),
1215
1216	/// Found an unexpected value in a range
1217	#[error("Found {found} for bound but expected {expected}.")]
1218	InvalidBound {
1219		found: String,
1220		expected: String,
1221	},
1222
1223	/// Found an unexpected value in a range
1224	#[error("Exceeded the idiom recursion limit of {limit}.")]
1225	IdiomRecursionLimitExceeded {
1226		limit: u32,
1227	},
1228
1229	/// Found an unexpected value in a range
1230	#[error("Tried to use a `@` repeat recurse symbol, while not recursing.")]
1231	RepeatRecurseNotRecursing,
1232
1233	/// Found an unexpected value in a range
1234	#[error("Tried to use a `{symbol}` recursion symbol, while already recursing.")]
1235	IdiomRecursionAlreadyRecursing {
1236		symbol: String,
1237	},
1238
1239	/// Tried to use an idiom RepeatRecurse symbol in a position where it is not supported
1240	#[error("Tried to use a `@` repeat recurse symbol in a position where it is not supported")]
1241	UnsupportedRepeatRecurse,
1242
1243	#[error("Error while computing version: expected a datetime, but found {found}")]
1244	InvalidVersion {
1245		found: Value,
1246	},
1247
1248	/// Tried to use an idiom RepeatRecurse symbol in a position where it is not supported
1249	#[error("Can not construct a recursion plan when an instruction is provided")]
1250	RecursionInstructionPlanConflict,
1251
1252	/// The record cannot be deleted as it's still referenced elsewhere
1253	#[error("Cannot delete `{0}` as it is referenced by `{1}` with an ON DELETE REJECT clause")]
1254	DeleteRejectedByReference(String, String),
1255
1256	/// The `REFERENCE` keyword can only be used in combination with a type referencing a record
1257	#[error(
1258		"Cannot use the `REFERENCE` keyword with `TYPE {0}`. Specify a `record` type, or a type containing only records, instead."
1259	)]
1260	ReferenceTypeConflict(String),
1261
1262	/// The `references` type cannot be used with other clauses altering or working with the value
1263	#[error("Cannot use the `{0}` keyword with `TYPE {0}`.")]
1264	RefsTypeConflict(String, String),
1265
1266	/// The `references` type cannot be used with other clauses altering or working with the value
1267	#[error("When specifying a `TYPE` clause with `references`, all variants must be of type `references`.")]
1268	RefsMismatchingVariants,
1269
1270	/// Something went wrong while updating references
1271	#[error("An error occured while updating references for `{0}`: {1}")]
1272	RefsUpdateFailure(String, String),
1273
1274	/// Cannot process `Value::Refs` as there is no Record ID in the context for the operation
1275	#[error("Cannot obtain a list of references as there is no Record ID in the context for the operation")]
1276	InvalidRefsContext,
1277
1278	#[error("Cannot set field `{name}` with type `{kind}` as it mismatched with field `{existing_name}` with type `{existing_kind}`")]
1279	MismatchedFieldTypes {
1280		name: String,
1281		kind: String,
1282		existing_name: String,
1283		existing_kind: String,
1284	},
1285
1286	#[error("An API error occurred: {0}")]
1287	ApiError(ApiError),
1288
1289	#[error("The string could not be parsed into a bytesize")]
1290	InvalidBytesize,
1291
1292	#[error("The string could not be parsed into a path: {0}")]
1293	InvalidPath(String),
1294}
1295
1296impl From<Error> for String {
1297	fn from(e: Error) -> String {
1298		e.to_string()
1299	}
1300}
1301
1302impl From<ApiError> for Error {
1303	fn from(value: ApiError) -> Self {
1304		Error::ApiError(value)
1305	}
1306}
1307
1308impl From<Base64Error> for Error {
1309	fn from(_: Base64Error) -> Error {
1310		Error::InvalidAuth
1311	}
1312}
1313
1314impl From<JWTError> for Error {
1315	fn from(_: JWTError) -> Error {
1316		Error::InvalidAuth
1317	}
1318}
1319
1320impl From<regex::Error> for Error {
1321	fn from(error: regex::Error) -> Self {
1322		Error::InvalidRegex(error.to_string())
1323	}
1324}
1325
1326impl From<InvalidHeaderName> for Error {
1327	fn from(error: InvalidHeaderName) -> Self {
1328		Error::Unreachable(error.to_string())
1329	}
1330}
1331
1332impl From<InvalidHeaderValue> for Error {
1333	fn from(error: InvalidHeaderValue) -> Self {
1334		Error::Unreachable(error.to_string())
1335	}
1336}
1337
1338impl From<ToStrError> for Error {
1339	fn from(error: ToStrError) -> Self {
1340		Error::Unreachable(error.to_string())
1341	}
1342}
1343
1344#[cfg(any(feature = "kv-mem", feature = "kv-surrealkv"))]
1345impl From<surrealkv::Error> for Error {
1346	fn from(e: surrealkv::Error) -> Error {
1347		match e {
1348			surrealkv::Error::TransactionReadConflict => Error::TxRetryable,
1349			surrealkv::Error::TransactionWriteConflict => Error::TxRetryable,
1350			_ => Error::Tx(e.to_string()),
1351		}
1352	}
1353}
1354
1355#[cfg(feature = "kv-rocksdb")]
1356impl From<rocksdb::Error> for Error {
1357	fn from(e: rocksdb::Error) -> Error {
1358		match e.kind() {
1359			rocksdb::ErrorKind::Busy => Error::TxRetryable,
1360			rocksdb::ErrorKind::TryAgain => Error::TxRetryable,
1361			_ => Error::Tx(e.to_string()),
1362		}
1363	}
1364}
1365
1366#[cfg(feature = "kv-indxdb")]
1367impl From<indxdb::err::Error> for Error {
1368	fn from(e: indxdb::err::Error) -> Error {
1369		match e {
1370			indxdb::err::Error::KeyAlreadyExists => Error::TxKeyAlreadyExists,
1371			indxdb::err::Error::ValNotExpectedValue => Error::TxConditionNotMet,
1372			_ => Error::Tx(e.to_string()),
1373		}
1374	}
1375}
1376
1377#[cfg(feature = "kv-tikv")]
1378impl From<tikv::Error> for Error {
1379	fn from(e: tikv::Error) -> Error {
1380		match e {
1381			tikv::Error::DuplicateKeyInsertion => Error::TxKeyAlreadyExists,
1382			tikv::Error::KeyError(ke) if ke.conflict.is_some() => Error::TxRetryable,
1383			tikv::Error::KeyError(ke) if ke.abort.contains("KeyTooLarge") => Error::TxKeyTooLarge,
1384			tikv::Error::RegionError(re) if re.raft_entry_too_large.is_some() => Error::TxTooLarge,
1385			_ => Error::Tx(e.to_string()),
1386		}
1387	}
1388}
1389
1390#[cfg(feature = "kv-fdb")]
1391impl From<foundationdb::FdbError> for Error {
1392	fn from(e: foundationdb::FdbError) -> Error {
1393		if e.is_retryable() {
1394			return Error::TxRetryable;
1395		}
1396		if e.is_retryable_not_committed() {
1397			return Error::TxRetryable;
1398		}
1399		Error::Ds(e.to_string())
1400	}
1401}
1402
1403#[cfg(feature = "kv-fdb")]
1404impl From<foundationdb::TransactionCommitError> for Error {
1405	fn from(e: foundationdb::TransactionCommitError) -> Error {
1406		if e.is_retryable() {
1407			return Error::TxRetryable;
1408		}
1409		if e.is_retryable_not_committed() {
1410			return Error::TxRetryable;
1411		}
1412		Error::Tx(e.to_string())
1413	}
1414}
1415
1416impl From<async_channel::RecvError> for Error {
1417	fn from(e: async_channel::RecvError) -> Error {
1418		Error::Channel(e.to_string())
1419	}
1420}
1421
1422impl<T> From<async_channel::SendError<T>> for Error {
1423	fn from(e: async_channel::SendError<T>) -> Error {
1424		Error::Channel(e.to_string())
1425	}
1426}
1427
1428#[cfg(any(feature = "http", feature = "jwks"))]
1429impl From<reqwest::Error> for Error {
1430	fn from(e: reqwest::Error) -> Error {
1431		Error::Http(e.to_string())
1432	}
1433}
1434
1435#[cfg(storage)]
1436impl<S, D, I> From<SortError<S, D, I>> for Error
1437where
1438	S: std::error::Error,
1439	D: std::error::Error,
1440	I: std::error::Error,
1441{
1442	fn from(e: SortError<S, D, I>) -> Error {
1443		Error::Internal(e.to_string())
1444	}
1445}
1446
1447impl Serialize for Error {
1448	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1449	where
1450		S: serde::Serializer,
1451	{
1452		serializer.serialize_str(self.to_string().as_str())
1453	}
1454}
1455impl Error {
1456	/// Check if this error is related to schema checks
1457	pub fn is_schema_related(&self) -> bool {
1458		matches!(
1459			self,
1460			Error::FieldCheck { .. }
1461				| Error::FieldValue { .. }
1462				| Error::FieldReadonly { .. }
1463				| Error::FieldUndefined { .. }
1464		)
1465	}
1466
1467	/// Convert CoerceTo errors in LET statements
1468	pub fn set_check_from_coerce(self, name: String) -> Error {
1469		match self {
1470			Error::CoerceTo {
1471				from,
1472				into,
1473			} => Error::SetCheck {
1474				name,
1475				value: from.to_string(),
1476				check: into,
1477			},
1478			e => e,
1479		}
1480	}
1481
1482	/// Convert CoerceTo errors in functions and closures
1483	pub fn function_check_from_coerce(self, name: impl Into<String>) -> Error {
1484		match self {
1485			Error::CoerceTo {
1486				from,
1487				into,
1488			} => Error::FunctionCheck {
1489				name: name.into(),
1490				value: from.to_string(),
1491				check: into,
1492			},
1493			e => e,
1494		}
1495	}
1496}