Last active
November 24, 2015 13:45
-
-
Save vlastv/3d0b2097af09724fa863 to your computer and use it in GitHub Desktop.
Simple script for checking foreign keys consistent
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
<?php | |
/** | |
* usage: | |
* php mysqlfkc.php mysql://user:pass@host/database | |
*/ | |
require_once 'vendor/autoload.php'; | |
$conn = \Doctrine\DBAL\DriverManager::getConnection([ | |
'url' => $argv[1], | |
]); | |
$sql = $conn->createQueryBuilder() | |
->select( | |
'TABLE_SCHEMA', | |
'TABLE_NAME', | |
'COLUMN_NAME', | |
'REFERENCED_TABLE_SCHEMA', | |
'REFERENCED_TABLE_NAME', | |
'REFERENCED_COLUMN_NAME' | |
) | |
->from('information_schema.KEY_COLUMN_USAGE') | |
->where('REFERENCED_TABLE_SCHEMA IS NOT NULL') | |
->andWhere('TABLE_SCHEMA = ?') | |
->getSQL() | |
; | |
$checks = $conn->fetchAll($sql, [$conn->getDatabase()]); | |
$pat = ' | |
SELECT | |
COUNT(*) | |
FROM | |
%1$s.%2$s AS a | |
LEFT JOIN | |
%4$s.%5$s AS b | |
ON | |
a.%3$s = b.%6$s | |
WHERE | |
a.%3$s IS NOT NULL | |
AND | |
b.%6$s IS NULL | |
'; | |
foreach($checks as $check) { | |
$sql = sprintf( | |
$pat, | |
$check['TABLE_SCHEMA'], | |
$check['TABLE_NAME'], | |
$check['COLUMN_NAME'], | |
$check['REFERENCED_TABLE_SCHEMA'], | |
$check['REFERENCED_TABLE_NAME'], | |
$check['REFERENCED_COLUMN_NAME'] | |
); | |
$count = $conn->fetchColumn($sql); | |
if($count > 0) { | |
print_r($check); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment