

One of the most convenient parts of SurrealDB is the ability to define an event whenever a record is created, updated, or deleted (or any combination of the three).
In the last chapter we created some books using this CREATE statement, but we haven't defined any fields yet.
Three of those fields should always be present, so let's officially define them now.
An english_title should also be present, but we can use an event to fill it out or check to see if it has been entered. This is because:
If the book is written in English, the english_title field should be the same as title. We don't want user error to result in title and english_title being different.
If the book is written in another language, we should check to see if english_title has been filled out. If not, throw an error.
The DEFINE EVENT syntax looks like this.
It also gives access to the type of event (either "CREATE", "UPDATE", or "DELETE") through a parameter called $event, along with $before and $after for the record before and after the change was made.
To create our event, we will use the following:
WHEN $event = "CREATE" to do this check when a book is first created,
Check if $after.language = 'en', and UPDATE the english_title field with $after.title if so,
If $after.language is not equal to 'en' and there is no english_title field filled in, then throw an error using the THROW keyword and a custom message.
With this event defined, we can enter a book without an english_title field but the field will be filled in using the title field.
Note that the first response is the output of the CREATE statement, which doesn't include english_title. It's at this point that the event jumps in and adds the field.
And if we try to enter this next French book, the query will fail because we forgot to fill out the english_title.
The output this time doesn't show the initial CREATE statement before the event, because statements in SurrealDB are all run within their own transaction, including their events. Since the CREATE statement led to an event which failed, the entire statement is rolled back and the book is never created.