Statements - SurrealTools/Documentation GitHub Wiki
IF Statement
IF user:test.id THEN
true
ELSE
false
END;
let $user_id = 124123;
let $form = "WOW";
let $sex= 124123;
let $looking_for = 124123;
IF (SELECT id FROM type::thing('user', $user_id) LIMIT 1) THEN
(CREATE type::thing('user', $user_id) SET form = $form, sex = $sex, looking_for = $looking_for)
ELSE
(UPDATE type::thing('user', $user_id) SET form = $form, sex = $sex, looking_for = $looking_for)
END;
IF (SELECT * FROM environment:cloudflare_images_api_token) == NULL THEN
CREATE environment:cloudflare_images_api_token SET value = "BLANK", public = false;
END;
IF (SELECT * FROM environment:cloudflare_images_api_token) == NULL THEN
CREATE environment:cloudflare_images_api_token SET value = "BLANK", public = false;
END;
IF not(environment:cloudflare_images_api_token.id) THEN
CREATE environment:cloudflare_images_api_token SET value = "BLANK", public = false;
END;
IF person:tobie.id THEN
RETURN "person:tobie exists!";
ELSE
CREATE person:tobie.id SET name = "Tobie";
RETURN "person:tobie was created!";
END;
You can do multiple statements within { and } characters (now known as a block)...
IF person:tobie.id THEN {
RETURN "person:tobie exists!";
} ELSE {
CREATE person:tobie SET name = "Tobie";
RETURN "person:tobie was created!";
} END;
RETURN Statement
The RETURN has a number of uses...
- Returning a single result from within a transaction...
BEGIN;
CREATE person:one;
CREATE person:two;
RETURN true;
COMMIT;
- Returning a single result from within a block of statements...
CREATE person:main SET data = {
LET $first = 'Tobie';
LET $last = 'Morgan Hitchcock';
LET $birthday = '2922-06-22';
LET $person = SELECT * FROM person WHERE [first, last, birthday] = [$first, $last, $birthday];
RETURN IF $person[0].id THEN
$person[0]
ELSE
CREATE person SET first = $first, last = $last, birthday = $birthday
END;
};
- A RETURN statement just returns a single value. You can therefore return anything you want...
RETURN {
friends_all: (SELECT * FROM person WHERE has_friend = true),
average_age: (23 * 13),
an_array: [1,2,3,4,5],
cofounders = [
person:tobie.*,
person:jaime.*,
]
};
Statement Block
There is no $parent in blocks. The block doesn't need a $parent because it is in the same context. It has access to all of the fields, and all of the variables.
LET Statement
LET-Statement is not of type "value". We can't reassign.
Variables defined within blocks are not available outside of those blocks. This is similar to blocks in Rust or JavaScript. Effectively the variable is available to sub blocks, but not available to parent blocks. Always clear memory
let $usedvariable = NONE;