Persistence Callbacks: Type-Safe Triggers

Episode #331 • Jul 14, 2025 • Subscriber-Only

We build a bunch of triggers in a schema-safe, type-safe way using APIs from the StructuredQueries library, including a callback that ensures the Reminders app always has at least one list, and a callback that helps us support drag–drop positional ordering of lists.

Previous episode
Persistence Callbacks: Type-Safe Triggers
Locked

Unlock This Episode

Our Free plan includes 1 subscriber-only episode of your choice, plus weekly updates from our newsletter.

Sign in with GitHub

Introduction

Brandon

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.

Stephen

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.

Brandon

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.

Stephen

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.

Type-safe triggers


References

Downloads

Get started with our free plan

Our free plan includes 1 subscriber-only episode of your choice, access to 73 free episodes with transcripts and code samples, and weekly updates from our newsletter.

View plans and pricing