I’m given an SQL query that change the database schema in a certain way. How can I produce an SQL query that will reverse the schema change of the given query, so that executing the original query and the reverse query would have no effect on the schema.
For example, given
ALTER TABLE t ADD COLUMN a INTEGER
I’ll produce
ALTER TABLE t DROP COLUMN a
PS, I understand that I might lose some data, for instance if I drop and create a column the data there would be lost. I can withstand this.
PS2, I assume that I can look into the current schema, to find out what dropped column/tables were.
PS3, generic answer is nice, but DB specific answers are OK as well.
There is no ready-made, built-in solution for this. You will have to write some code, possibly a lot.
There are a number of “schema diff” type tools out there. You could possibly put one of those into use. For example, create your original schema, make a copy, run the schema-altering command on the copy, then run a reverse schema diff, which should give you the command that undoes the first command. Depending on your exact requirements, you could script this to some degree. But it might be messy.