mysqldump schema only, schema update without drop
I'm looking at using the git pre-commit hook to export a MySQL db schema prior to commiting chan开发者_StackOverflow中文版ges so that other developers can update their own databases with a SQL script from the git repo.
By default a mysqldump (I'm using --no-data) will drop existing tables before rebuilding them which isn't what I'm after. I'm wondering if anyone knows of a way to do a mysqldump or similar to describe the db schemas with SQL to update tables if they exists instead of a drop and rebuild. I realize this might be a long shot but if anyone could point me in the right direction it would be great.
How would MySQL know what to update? It can't know what state someone else's database will be in, so it can't know what updates to apply. Also, updates frequently require more than just changing the schema; they might require changes to data that already exists, or might need data to be moved from the old schema to the new one. You will never get something which will automatically detect all of that.
The right solution is to write migrations. Every time you change the database, instead of just changing the schema of your development copy yourself, you write a script to update from the previous schema to the new one (and usually a script to downgrade back to the previous schema, so you can do that if you need to roll back an update). That script does anything you need to change the schema, move data around, and the like.
Most modern web frameworks, like Ruby on Rails, have support for migrations to make it easier to keep track of what migrations you've already run. If you're not using a framework that supports migrations, it wouldn't be too hart to write your own scripts for applying migrations. Just number each migration, or put a date in it, and keep a table in your database storing only the current version of the schema that you're on. When you run your migrate script, if there are any migrations newer than that current version, apply those scripts in order, and then update the number in the database that says what version you're on.
精彩评论