Skip to content

Instantly share code, notes, and snippets.

@pounard
Created March 15, 2016 09:57
Show Gist options
  • Save pounard/0496fcfd5a60097bd924 to your computer and use it in GitHub Desktop.
Save pounard/0496fcfd5a60097bd924 to your computer and use it in GitHub Desktop.
Properly fix table schema adding constraint (MySQL and PostgreSQL working version)
/**
* This function is reentrant.
*/
function mymodule_install_schema_fix() {
$constraints = [
'lo_register_phone' => [
'fk_lo_register_phone_user' => "ALTER TABLE {lo_register_phone} ADD CONSTRAINT {fk_lo_register_phone_user} FOREIGN KEY (uid) REFERENCES {users} (uid) ON DELETE CASCADE",
],
];
foreach ($constraints as $table => $statements) {
if (db_table_exists($table)) {
foreach ($statements as $statement) {
try {
db_query($statement);
} catch (\PDOException $e) {
switch ($e->getCode()) {
case 42710: // PostgreSQL constraint already exists
continue;
case 23000: // MySQL duplicate key in table
continue;
default:
throw $e;
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment