Created
March 15, 2016 09:57
-
-
Save pounard/0496fcfd5a60097bd924 to your computer and use it in GitHub Desktop.
Properly fix table schema adding constraint (MySQL and PostgreSQL working version)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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