Migrations fixes

Fixed a few issues with migrations discovered recently.
Added code to generate sql for automatically creating/dropping the history table when running migrations.