A validating SQL lexer and parser with a focus on MySQL dialect.
Latest commit 641f59c Jan 21, 2017 @nijel nijel committed on GitHub Merge pull request #125 from remicollet/patch-1
Update .gitattributes


SQL Parser

A validating SQL lexer and parser with a focus on MySQL dialect.

Code status

Build Status Code Coverage codecov.io Scrutinizer Code Quality Translation status


Please use Composer to install:

composer require phpmyadmin/sql-parser


The API documentation is available at https://develdocs.phpmyadmin.net/sql-parser/.


Command line utilities

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"

Formatting SQL query

echo SqlParser\Utils\Formatter::format($query, array('type' => 'html'));

Discoverying query type

use SqlParser\Parser;
use SqlParser\Utils\Query;

$query = 'OPTIMIZE TABLE tbl';
$parser = new Parser($query);
$flags = Query::getFlags($parser->statements[0]);

echo $flags['querytype'];

Parsing and building SQL query

require __DIR__."/vendor/autoload.php";

$query1 = "select * from a";
$parser = new SqlParser\Parser($query1);

// inspect query
var_dump($parser->statements[0]); // outputs object(SqlParser\Statements\SelectStatement)

// modify query by replacing table a with table b
$table2 = new \SqlParser\Components\Expression("", "b", "", "");
$parser->statements[0]->from[0] = $table2;

// build query again from an array of object(SqlParser\Statements\SelectStatement) to a string
$statement = $parser->statements[0];
$query2 = $statement->build();
var_dump($query2); // outputs string(19) "SELECT  * FROM `b` "

// Change SQL mode

// build the query again using different quotes
$query2 = $statement->build();
var_dump($query2); // outputs string(19) "SELECT  * FROM "b" "

More information

This library was originally created during the Google Summer of Code 2015 and has been used by phpMyAdmin since version 4.5.