3 ms·
I have mixed feelings about using stored procedures and triggers. I was once working on a Postgres app and started storing some logic in the DB. I had some trig
by polyrand 3y ago
I have mixed feelings about using stored procedures and triggers. I was once working on a Postgres app and started storing some logic in the DB. I had some triggers that would automatically set values when a user state changed (e.g: when the user changed to 'inactive', the trigger would also update the tables related to subscriptions, API keys, etc).
As another "performance" trick, I was using multiple CTEs with the `RETURNING` clause to execute multiple operations in a single query.
Everything was OK when I was working on that app daily. But then I stopped working on it for a few months, and when I came back, I regretted using those tricks. For example, now I need to verify the triggers to make sure that changing a value won't change other tables that I forgot about. Also, I can't compose the SQL queries I wrote because each query does "everything at once". I would have rather paid the cost of doing 3 queries, and in exchange I could have reused some of those queries in different parts of the application [^1].
Of course, the app didn't even get close to the scale at which 1 query vs. 3 queries matter.
I still appreciate and like having some business logic in the DB, specially `CHECK` constraints. But the tooling for regular programming languages makes everything easier. Having the logic in the DB is a double-edged sword.
[^1]: This can become relevant when building an admin interface/CLI, since you may want to execute partial changes vs. the "everything at once" changes in the user-facing application.