Lesson 5.3: Defining constraints
Constraining attribute values
The values of string attribute types can be constrained with a regex
statement, which specifies a Java regex pattern string that is validated against when instantiating the attribute type. In the following example, we require that the value of status
instances must be one of "paid", "dispatched", "delivered", "returned", or "canceled".
define
status sub attribute,
value string,
regex "^(paid|dispatched|delivered|returned|canceled)$";
order owns status;
Run and commit
Regex constraints apply directly to attributes, regardless of the owning type. In this example, if another entity or relation type owned status
, it would also be restricted to the preset values.
The |
Constraining attribute ownerships
TypeQL provides syntax for defining key and unique constraints on attribute ownerships via annotations. An annotation is an additional constraint applied to a statement, denoted by an @
prefix. The following example defines five such constraints.
define
id sub attribute, value string;
book owns isbn-13 @key,
owns isbn-10 @unique;
user owns id @key;
order owns id @key;
review owns id @key;
Run and commit
When applied to an ownership statement in a Define query, the @key
and @unique
annotations apply a key or unique constraint respectively to that ownership. This is different to regex
statements, which apply to the attribute itself.
A key constraint requires that instances of the owner type own exactly one instance of the attribute type, and that it must be uniquely owned by the owner type. In the example above, every instance of book
must own exactly one instance of isbn-13
, and no two instances of book
can own the same instance of isbn-13
.
A unique constraint requires only that instances of the attribute type are uniquely owned by the owner type. In the example above, no two instances of book
can own the same instance of isbn-10
, but an instance of book
can own any number of instances of isbn-10
(including none).
Ownership annotations apply to the specific ownerships they are defined on rather than to the attribute in general. In the example above, key constraints are applied to the ownership of |