Enforcing XOR (Either/Or) Fields in SurrealDB
Blog post from SurrealDB
Abdelrahman Omar, a Rust software engineer, discusses how SurrealDB can simplify tech stacks by eliminating the need for separate caching and relational databases, using an example of enforcing XOR (Either/Or) constraints in database schema design. In scenarios where a record should contain one of two possible fields, such as a repository owned by either a user or an organization but not both or neither, Omar demonstrates how to apply XOR constraints in SurrealDB using DEFINE statements and VALUE clauses. By testing four possible cases, he illustrates how the database handles constraints, throwing errors when both or neither fields are set, and offering a cleaner solution using a single field type. The methodology reflects typical SQL practices with CHECK constraints, moving validation logic into the schema to ensure the database remains the single source of truth.