Given: MySQL database. Sometimes db schema changes and updates are rolled out (in the form of sql script). In order to guarantee correct order of updates applied (no duplicate updates, no updates missing, etc) I plan to deploy the following solution:
- CREATE TABLE meta (name TEXT PRIMARY KEY, val TEXT);
- INSERT INTO meta VALUES (‘version’,’0′);
Each update script carries a version N which is assigned sequentially. Before executing updates the script checks that the meta.version matches the previous script version N-1. After executing updates meta.version is updated to N. I do not need to protect against multiple scripts running in parallel.
The question: How to check the version and abort the script if it doesn’t match? I figured out that executing
CALL `raise error`
will break the script, but how to execute it conditionally depending on meta.version? No stored procedures allowed. Meaningful error message is a plus. This doesn’t provide a suitable solution.
I think this would best be solved in a shell script, or installer app. You cannot really have any control constructs in SQL script.
A very simple solution would be to create a script that generates the command line for the actual script to execute based on a select on the meta table.
So lets say you have this script,
gen_upgrade_command.sql:Which you run like this
Now,
do_upgrade.batcontains this generated command line:and running
do_upgrade.batwill runupgrade1.sqlOf course you can modify the original script to not select any row at all too, that’s just up to you.