Conditional writes (if)
|
Version |
if blocks serve as the write-stage equivalent to try blocks.
if { <condition>; <condition>; [...] } then {
<write-pattern>;
<write-pattern>;
[...]
};
Unlike try blocks - which could not be nested, the explicit conditions in if blocks allow them to be nested
Examples
Schema for the examples
#!test[schema]
define
attribute id, value string;
attribute age, value integer;
attribute height, value integer;
attribute address, value string;
entity person,
owns id @key, owns age, owns height, owns address,
plays pet-ownership:owner,
plays insurance-policy:primary,
plays insurance-policy:additional;
entity pet,
owns address,
plays pet-ownership:pet,
plays insurance-policy:additional;
relation pet-ownership, relates owner, relates pet;
relation insurance-policy,
relates primary @card(1),
relates additional @card(0..);
Insert
Creates a new insurance-policy covering a person, and adds any pets as additional coverage.
Rows are still returned even if the person has no pets.
#!test[write]
match
$p isa person, has id $id;
insert
$i isa insurance-policy, links (primary: $p);
match
try { $_ isa pet-ownership, links (owner: $p, pet: $q); };
insert
if { isset $q; } then {
$i links (additional: $q);
};
Put
The same applies for put. The matching behaviour of
if { <condition>; } then { <body>; }; in a put stage
is the same as try { <condition>; <body>; };
#!test[write]
match
$p isa person, has id $id;
put
$i isa insurance-policy, links (primary: $p);
match
try { $_ isa pet-ownership, links (owner: $p, pet: $q); };
put
if { isset $q; } then {
$i links (additional: $q);
};
Update
Update the address of a person, and any pets they may have.
#!test[write, given=id;new-address]
given $id: id, $new-address: string;
match
$p isa person, has id $id, has address $old-address;
update
$p has address == $new-address;
match
try { $_ isa pet-ownership, links (owner: $p, pet: $q); };
update
if { isset $q; } then {
$q has address == $new-address;
};
Delete
Matches person`s, and removes their `age and height if they had any.
Without the try, only person`s with both `age and height would be matched.
#!test[write]
match
$p isa person, has id $id;
try { $p has age $age; };
try { $p has height $height; };
delete
if { isset $age; } then { has $age of $p; };
if { isset $height; } then { has $height of $p; };