Skip to content

Instantly share code, notes, and snippets.

@endam
Last active June 10, 2016 10:09
Show Gist options
  • Save endam/5f09f894ec0f2a1dd2d9349dcf232473 to your computer and use it in GitHub Desktop.
Save endam/5f09f894ec0f2a1dd2d9349dcf232473 to your computer and use it in GitHub Desktop.
SQL整形スクリプト
#!/usr/bin/php
<?php
if (empty($argv[1])) {
echo "ファイル名が指定されていません\n";
exit;
}
$filePath = $argv[1];
$sql = file_get_contents($filePath);
$url = 'http://sqlformat.org/api/v1/format';
$query = [
'sql' => $sql,
//'reindent' => 1,
'keyword_case' => 'upper'
];
$queryStr = http_build_query($query);
$headers = [
"Content-Type: application/x-www-form-urlencoded",
"Content-Length: " . strlen($queryStr)
];
$options = [
'http' => [
'method' => 'POST',
'header' => implode("\r\n", $headers),
'content' => $queryStr
]
];
$context = stream_context_create($options);
$contents = file_get_contents($url, false, $context);
$results = json_decode($contents);
$formatSql = $results->result;
// カラムの型を小文字から大文字に変換
$formatSql = preg_replace_callback(
'/ (tinyint|int|datetime|date|varchar|char|text)/',
function ($matches) {
return strtoupper($matches[0]);
},
$formatSql
);
file_put_contents($filePath, $formatSql);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment