We now have the ability to bake validation rules directly into our database. Every single time we assign or remove a tag from a reminder, our validation logic will run, and if the configuration of tags is invalid an error will be emitted that can be easily intercepted and displayed from Swift. It’s just really incredible to see how easy it is to install little validation rules like this at a global level without worrying about auditing every single place a reminder is edited to make sure we are enforcing this rule. And of course, like everything we do in this modern persistence series, this validation logic is 100% unit testable since our tests use the actual database connection, but we won’t explore that right now.
Let’s move onto our final topic for SQLite triggers. So far we have explored some of the more typical use cases for triggers. We’ve performed an update when a database event happens, such as refreshing updated at timestamps on a record. We’ve performed an insert when a database event happens, such as making sure that we always have at least one reminders list in the database. And we just explored raising errors after certain database events when we detect an invalid configuration of the data in our database.
The final form of trigger we are going to explore is calling out to actual Swift code when a database event happens. This can be great for performing little bits of extra logic that are not purely just database transformations, such as inserts, updates, or deletes. We will begin by exploring this by adding a very simple user experience improvement to our app.
Let’s check it out!