diff --git a/doc-surrealdb_versioned_docs/version-latest/surrealql/statements/define/table.mdx b/doc-surrealdb_versioned_docs/version-latest/surrealql/statements/define/table.mdx index c430c3e1d..021e318c2 100644 --- a/doc-surrealdb_versioned_docs/version-latest/surrealql/statements/define/table.mdx +++ b/doc-surrealdb_versioned_docs/version-latest/surrealql/statements/define/table.mdx @@ -21,7 +21,7 @@ The `DEFINE TABLE` statement allows you to declare your table by name, enabling DEFINE TABLE [ OVERWRITE | IF NOT EXISTS ] @name [ DROP ] [ SCHEMAFULL | SCHEMALESS ] - [ TYPE [ ANY | NORMAL | RELATION [ IN | FROM ] @table [ OUT | TO ] @table ] ] + [ TYPE [ ANY | NORMAL | RELATION [ IN | FROM ] @table [ OUT | TO ] @table ] [ ENFORCED ] ] [ AS SELECT @projections FROM @tables [ WHERE @condition ] @@ -384,3 +384,73 @@ DEFINE TABLE assigned_to SCHEMAFULL TYPE RELATION IN tag OUT sticky FOR create, select, update, delete WHERE in.owner == $auth.id AND out.author == $auth.id; ``` + +## Using ENFORCED to ensure that related records exist + + + +As relations are represented by standalone tables, they can be constructed before any linked records exist. + +```surql +RELATE city:one->road_to->city:two SET + distance = 12.4, + slope = 5.4; +``` + +```bash title="Output" +[ + { + distance: 12.4f, + id: road_to:pacwucj25a056hhs2s5h, + in: city:one, + out: city:two, + slope: 5.4f + } +] +``` + +As such, a query on the relation will return nothing until the records it has been defined upon are created. + +```surql +SELECT ->road_to->city FROM city; + +CREATE city:one, city:two; +SELECT ->road_to->city FROM city; +``` + +```bash title="Output" +-------- Query -------- + +[] + +-------- Query -------- + +[ + { + "->road_to": { + "->city": [ + city:two + ] + } + }, + { + "->road_to": { + "->city": [] + } + } +] +``` + +If this behaviour is not desirable, the `ENFORCED` clause can be used on a table of `TYPE RELATION` to disallow a `RELATE` statement from working unless it points to existing data. + +```surql +DEFINE TABLE road_to TYPE RELATION IN city OUT city ENFORCED; + +RELATE city:one->road_to->city:three SET + distance = 5.5, + slope = 30.0; +``` + +```bash title="Output" +"The record 'city:three' does not exist" +``` \ No newline at end of file