Files
Available since: v3.0.0
Files are accessed by a path, which is prefixed with an f to differentiate it from a regular string.
Some examples of file pointers:
f"bucket:/some/key/to/a/file.txt";
f"bucket:/some/key/with\ escaped";
To work with the files that can be accessed through these pointers, use the following:
DEFINE BUCKET my_bucket BACKEND "memory";
f"my_bucket:/some_file.txt".put("Some text inside");
f"my_bucket:/some_file.txt".get();
<string>f"my_bucket:/some_file.txt".get();
Output
b"536F6D65207465787420696E73696465"
'Some text inside'
Using files for ad-hoc memory storage
A combination of files and SurrealDB’s encoding functions can be used to set up ad-hoc memory storage. This can be convenient when running an instance that saves data to disk but prefers to keep certain items in memory.
The following example shows how this pattern might be used for temporary storage such as a user’s shopping cart during a single session.
SURREAL_BUCKET_FOLDER_ALLOWLIST="/users/your_user_name" surreal start --allow-experimental files
DEFINE BUCKET my_bucket BACKEND "file:/users/your_user_name";
DEFINE FUNCTION fn::save_file($file_name: string, $input: any) {
LET $file = type::file("shopping_carts", $file_name);
$file.put(encoding::cbor::encode($input));
};
DEFINE FUNCTION fn::get_file($file_name: string) -> object {
encoding::cbor::decode(type::file("shopping_carts", $file_name).get())
};
DEFINE FUNCTION fn::delete_file($file_name: string) {
type::file("shopping_carts", $file_name).delete();
};
fn::save_file("temp_cart_user_24567", {
items: ["shirt1"],
last_updated: time::now()
});
fn::get_file("temp_cart_user_24567");
fn::save_file("temp_cart_user_24567", {
items: ["shirt1", "deck_of_cards"],
last_updated: time::now()
});
fn::get_file("temp_cart_user_24567");
fn::delete_file("temp_cart_user_24567");