Last active
March 2, 2025 15:19
-
-
Save macsplit/a77c53aff7e2c6242838ffc3517fb802 to your computer and use it in GitHub Desktop.
Format MySQL output as Markdown
This file contains hidden or 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
#!/usr/bin/php | |
<?php | |
// Usage: /usr/bin/mysql DBNAME -u USERNAME -pPASSWORD -t -e "SELECT * FROM mytable" | tabulate | |
define ('MAX_ROW_WIDTH', 140); | |
define ('MAX_DATA_WIDTH', 100); | |
function convert ($table) { | |
if (!preg_match("/\+(?:\-+\+)+/", $table)) | |
return $table; | |
$rows = explode("\n", str_replace("\r\n","\n", $table)); | |
array_shift($rows); | |
$header = array_shift($rows); | |
$line = str_replace("+","|",array_shift($rows)); | |
array_pop($rows); | |
array_pop($rows); | |
if (strlen($header) < MAX_ROW_WIDTH) { | |
$body = implode("\n",$rows); | |
return "\n$header\n$line\n$body\n\n"; | |
} else { | |
$body = "\n"; | |
$header = trim($header,"|"); | |
$columns = array_map('trim', explode("|", $header)); | |
$column_widths = array_map('strlen', $columns); | |
$max_column_width = max($column_widths); | |
$max_data_widths = []; | |
foreach ($rows as $row) { | |
$row = trim($row,"|"); | |
$data = array_map('trim', explode("|", $row)); | |
$data_widths = array_map('strlen', $data); | |
$max_data_widths[] = max($data_widths); | |
} | |
$max_all_data_widths = max($max_data_widths); | |
if ($max_all_data_widths > MAX_DATA_WIDTH) | |
$max_all_data_widths = MAX_DATA_WIDTH; | |
foreach ($rows as $row) { | |
$row = trim($row,"|"); | |
$data = array_map('trim', explode("|", $row)); | |
$body .= "| "; | |
$body .= str_pad("Field",$max_column_width); | |
$body .= " | "; | |
$body .= str_pad("Value",$max_all_data_widths); | |
$body .= " |\n"; | |
$body .= "|-"; | |
$body .= str_repeat("-",$max_column_width); | |
$body .= "-|-"; | |
$body .= str_repeat("-",$max_all_data_widths); | |
$body .= "-|\n"; | |
foreach ($columns as $index => $column) { | |
if (isset($data[$index])) { | |
$name = str_pad($column, $max_column_width); | |
$datum = $data[$index]; | |
$datum = (strlen($datum)>MAX_DATA_WIDTH) ? $datum = substr($datum, 0, MAX_DATA_WIDTH-3)."..." : $datum; | |
$value = str_pad($datum, $max_all_data_widths); | |
$body .= "| $name | $value |\n"; | |
} | |
} | |
$body .= "\n"; | |
} | |
return $body; | |
} | |
} | |
echo convert(file_get_contents("php://stdin")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment