Do you ever find yourself doing some debugging with error_log()
or its friends? Does that debugging ever involve SQL queries? Are you tired of staring at grey queries all the time? I have just the product for you!
Introducing Syntax Highlighting SQL in Terminal! Brought to you by our friends at Large Language Models, Incorporated, this new PHP function will use ANSI escape sequences to colorize your SQL queries for easier viewing and debugging!
<?php
/**
* Highlights SQL queries.
*
* This method takes a SQL query as input and returns the query with syntax highlighting applied.
*
* @param string $sql The SQL query to highlight.
*
* @return string The highlighted SQL query.
*/
function highlight_sql( string $sql ): string {
$keywords = array(
'SELECT',
'FROM',
'WHERE',
'AND',
'OR',
'INSERT',
'INTO',
'VALUES',
'UPDATE',
'SET',
'DELETE',
'CREATE',
'TABLE',
'ALTER',
'DROP',
'JOIN',
'INNER',
'LEFT',
'RIGHT',
'ON',
'AS',
'DISTINCT',
'GROUP',
'BY',
'ORDER',
'HAVING',
'LIMIT',
'OFFSET',
'UNION',
'ALL',
'COUNT',
'SUM',
'AVG',
'MIN',
'MAX',
'LIKE',
'IN',
'BETWEEN',
'IS',
'NULL',
'NOT',
'PRIMARY',
'KEY',
'FOREIGN',
'REFERENCES',
'DEFAULT',
'AUTO_INCREMENT',
);
$functions = array(
'COUNT',
'SUM',
'AVG',
'MIN',
'MAX',
'NOW',
'CURDATE',
'CURTIME',
'DATE',
'TIME',
'YEAR',
'MONTH',
'DAY',
'HOUR',
'MINUTE',
'SECOND',
'TIMESTAMP',
);
$colors = array(
'keyword' => "\033[1;34m", // Blue.
'function' => "\033[1;32m", // Green.
'string' => "\033[1;33m", // Yellow.
'comment' => "\033[1;90m", // Bright Black (Gray).
'reset' => "\033[0m",
);
// Highlight comments.
$sql = preg_replace( '/\/\*.*?\*\//s', $colors['comment'] . '$0' . $colors['reset'], $sql );
// Highlight single-quoted strings.
$sql = preg_replace( '/\'[^\']*\'/', $colors['string'] . '$0' . $colors['reset'], $sql );
// Highlight double-quoted strings.
$sql = preg_replace( '/"[^"]*"/', $colors['string'] . '$0' . $colors['reset'], $sql );
// Highlight functions.
foreach ( $functions as $function ) {
$sql = preg_replace( '/\b' . preg_quote($function, '/') . '\b/i', $colors['function'] . '$0' . $colors['reset'], $sql );
}
// Highlight keywords.
foreach ( $keywords as $keyword ) {
$sql = preg_replace( '/\b' . preg_quote($keyword, '/') . '\b/i', $colors['keyword'] . '$0' . $colors['reset'], $sql );
}
return $sql;
}
echo highlight_sql( 'SELECT COUNT(*) AS total FROM users WHERE id = 1 AND user_id = "example"; /* YEAH! Comment! */' ) . PHP_EOL;
Code language: PHP (php)
Don’t blame me if this breaks anything, use at your own debugging risk.
Leave a Reply