A validating SQL lexer and parser with a focus on MySQL dialect.
Please use Composer to install:
composer require phpmyadmin/sql-parserThe API documentation is available at https://develdocs.phpmyadmin.net/sql-parser/.
Command line utility to syntax highlight SQL query:
./vendor/bin/highlight-query --query "SELECT 1"Command line utility to lint SQL query:
./vendor/bin/lint-query --query "SELECT 1"Command line utility to tokenize SQL query:
./vendor/bin/tokenize-query --query "SELECT 1"All commands are able to parse input from stdin (standard in), such as:
echo"SELECT 1"| ./vendor/bin/highlight-query
cat example.sql | ./vendor/bin/lint-queryechoPhpMyAdmin\SqlParser\Utils\Formatter::format($query, ['type' => 'html']);usePhpMyAdmin\SqlParser\Parser;
usePhpMyAdmin\SqlParser\Utils\Query;
$query = 'OPTIMIZE TABLE tbl';
$parser = newParser($query);
$flags = Query::getFlags($parser->statements[0]);
echo$flags->queryType?->value;require__DIR__ . '/vendor/autoload.php';
$query1 = 'select * from a';
$parser = newPhpMyAdmin\SqlParser\Parser($query1);
// inspect queryvar_dump($parser->statements[0]); // outputs object(PhpMyAdmin\SqlParser\Statements\SelectStatement)// modify query by replacing table a with table b$table2 = new \PhpMyAdmin\SqlParser\Components\Expression('', 'b', '', '');
$parser->statements[0]->from[0] = $table2;
// build query again from an array of object(PhpMyAdmin\SqlParser\Statements\SelectStatement) to a string$statement = $parser->statements[0];
$query2 = $statement->build();
var_dump($query2); // outputs string(19) 'SELECT * FROM `b` '// Change SQL modePhpMyAdmin\SqlParser\Context::setMode(PhpMyAdmin\SqlParser\Context::SQL_MODE_ANSI_QUOTES);
// build the query again using different quotes$query2 = $statement->build();
var_dump($query2); // outputs string(19) 'SELECT * FROM "b" 'You can localize error messages installing phpmyadmin/motranslator version 5.0 or newer:
composer require phpmyadmin/motranslator:^5.0The locale is automatically detected from your environment, you can also set a different locale
From cli:
LC_ALL=pl ./vendor/bin/lint-query --query "SELECT 1"From php:
require__DIR__ . '/vendor/autoload.php';
$GLOBALS['lang'] = 'pl';
$query1 = 'select * from a';
$parser = newPhpMyAdmin\SqlParser\Parser($query1);This library was originally created during the Google Summer of Code 2015 and has been used by phpMyAdmin since version 4.5.

