pub enum ForeignKey<V, K> {
Loaded(V),
Key(K),
Unloaded,
}
Expand description
Represents foreign data, from a foreign node that may need to be fetched during the query or else it won’t be loaded or it will simply be the ID to a foreign node.
A ForeignKey field may have one of the following values:
- Loaded data,
- An ID,
- None of the above (
null
)
When a field is set as a ForeignKey<V, K>
or a Foreign<V>
, the field will
always be serialized into an ID so you can be sure you won’t get raw data
inserted into your nodes by mistake.
Pairs well with objects that store IDs in the surreal DB, that you can also
load using the FETCH
keyword of SurrealQL.
Imagining the following structure:
create User:John set name = "John";
create File set name = "John file", author = User:John;
which could be represented like so in Rust:
struct User {
name: String
}
struct File {
name: String,
author: ForeignKey<User, String>
}
This will cause the serde_json library to attempt to parse the File::author
as a User
, and if it fails will then attempt to parse it as a String
type
(a string in our case since this is how SurrealDB stores IDs). And if the
attempt to parse the ID fails as well it will default to the Unloaded
variant
of a ForeignKey
You are then free to use the ForeignKey’s methods to safely access the foreign data
let file: File; // = query("SELECT * from File FETCH author");
if let Some(user) = file.author.value() {
// the file had an author and it was loaded
dbg!(&user);
}
if let Some(user_id) = file.author.key() {
// the file had an author ID, but it wasn't loaded
dbg!(&user_id);
}
Note that if you plan to use ForeignKey<T, String>
(where the second generic
type is a string), you can use the Foreign<T>
type in the same module to
shorten the declaration.
Variants
Loaded(V)
Key(K)
Unloaded
Implementations
sourceimpl<V, K> ForeignKey<V, K>where
V: Debug,
V: IntoKey<K>,
impl<V, K> ForeignKey<V, K>where
V: Debug,
V: IntoKey<K>,
sourcepub fn value(&self) -> Option<&V>
pub fn value(&self) -> Option<&V>
Access the inner value by checking if it is loaded or not, thus returning
an Option<&T>
that is Some
if it is loaded and None
if it isn’t.
sourcepub fn key(&self) -> Option<&K>
pub fn key(&self) -> Option<&K>
Access the inner key by checking if the foreign key is currently
holding the key, thus returning a Some<&I>
if it is one and None
if it isn’t.
sourcepub fn is_unloaded(&self) -> bool
pub fn is_unloaded(&self) -> bool
Return whether the current ForeignKey is unloaded. Returns false
if self
is either a key or a loaded value.
sourcepub fn set_value(&mut self, value: V)
pub fn set_value(&mut self, value: V)
Drop any data self
may currently hold and set it to the Loaded
variant
with the given value.