I’m reorganizing our MySQL database, changing MyISAM tables to InnoDB and setting foreign keys, and I’m wondering if there’s a way to link the column settings also?
Example:
in my useraccount table, the user column is varchar(20). In all my other tables another user column to record who entered the record, also varchar(20).
I’m wondering how I might go about linking all those dependent user columns, like if I had to change the useraccount.user column to varchar(40), can I set all other table user columns to cascade to varchar(40) as well?
I’m sure I could use the information schema to write a PHP script to do this but I’d rather have the database modify itself without outside help if possible. Could this be done through a trigger on the schema record for the username.user column? And if so could I then also make a trigger to automatically add foreign key constraints on any new table where a ‘user’ column gets added?
seems like it should be possible but I’ll admit I don’t know MySQL well enough to go screwing around with schema tables 😉
Edit: Here is some sample SQL I wrote to find the mismatched tables
SELECT TABLE_NAME, COLUMN_TYPE
FROM information_schema.COLUMNS
WHERE TABLE_NAME != 'user_accounts'
AND COLUMN_NAME = 'user'
AND COLUMN_TYPE != (
SELECT COLUMN_TYPE
FROM information_schema.COLUMNS
WHERE TABLE_NAME = 'user_accounts'
AND COLUMN_NAME = 'user'
)
Ideally I’d like to use this information_schema result to loop through each row of the above result and ALTER the tables to change the Column Types to match the column type of user_account.user
In SQL, DDL doesn’t cascade.
In standard SQL, you’d use domains (which MySQL unfortunately doesn’t support). Let’s say you had this PostgreSQL code stored in your version control system.
When the need arises, you can change one line of code in version control . . .
. . . dump the data, load the new schema, reload the data, and you’re done. But be warned that this can take quite a while on a huge database. (Moving the data takes the most time.)
You can accomplish the same thing in MySQL, even though it doesn’t support the CREATE DOMAIN statement. Instead of SQL, use the m4 macro processor.
Then run that code through m4 as part of your makefile. m4 will replace USER_DOMAIN with ‘varchar(15) not null’.
Now changing to varchar(20) is still only a one-line change.