I think this is pretty incredible, and I think it shows that SQLite has a ton of untapped power. When implementing far reaching behavior across our databases we should always first ask whether or not SQLite already provides a tool for this. If it does, then it is far better to delegate that responsibility to SQLite than for us to try to recreate it in our Swift application. After all, SQLite is the true arbiter of the data in our application.
This is looking really great, but we can make some improvements. Right now we are creating our trigger as a SQL string. On the one hand, this isn’t so bad. We have never said that all queries in your app should be written with our query builder. We think it’s incredibly important to be familiar with SQL syntax, and we never want to hide it from you.
But, the primary situation we advocate for writing SQL strings is in migrations, like what we have done when creating and altering our tables. The reason we advocate for SQL strings here is because migrations are little SQL fragments that are frozen in time. Once a migration has been shipped to users it should never be edited. Ever.
And so it’s not appropriate to use static symbols in creating those SQL statements because that would leave us open to accidentally changing those statements later on by doing something seemingly innocuous such as renaming a field in our data types.
However, our trigger is not being created in a migration. In fact, we are installing the trigger after all migrations have run, and it’s only temporary. The trigger will be removed when the app is killed and will be reinstalled when the app starts up again. This means it is perfectly OK to use static symbols in order to construct temporary triggers because they always have access to the most recent form of the schema. They never have to deal with older versions of the schema that are frozen in time.
And so we can actually add a bit of type-safety and schema-safety to the creation of our triggers by using the static symbols created for us by the @Table
macro. Let’s take a look.