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