php-sql-parser
repository·master·Indexed 20 days ago
https://github.com/greenlion/php-sql-parserA pure PHP, non-validating SQL parser primarily focused on the MySQL dialect. It converts SQL queries into structured associative arrays for programmatic analysis, supporting statement types such as SELECT, INSERT, UPDATE, DELETE, REPLACE, RENAME, SHOW, SET, DROP, CREATE INDEX, CREATE TABLE, EXPLAIN, and DESCRIBE. The library includes the PHPSQLParser class for generating parse trees and the PHPSQLCreator class for reconstructing SQL statements from those trees.
What's inside php-sql-parser
- PHP-SQL-Parser is a pure PHP, non-validating SQL parser specifically focused on the MySQL dialect. It is designed to provide complete and accurate support for MySQL syntax, though it is not optimized for high-performance scenarios. It is expected that the input queries provided to the parser are syntactically valid.
Using PHP-SQL-Parser with other SQL dialects
masterBecause the MySQL dialect is closely aligned with SQL-92, the parser can be used for most other database applications. If you are working with a different SQL dialect, you may need to modify the reserved words to ensure correct parsing. Refer to theParserManualfor details on customizing reserved words.Understand the Parse Tree structure
masterThe output of the parser is an associative array where the top-level keys represent major SQL sections (e.g.,
SELECT,FROM,WHERE).Each section contains an array of items. Each item represents a specific SQL component such as:
colref: A column reference.table: A table reference (Note: even single tables are treated as joins, though they may lack join criteria).operator: A comparison or logical operator.const: A literal value.
Each item typically contains metadata like
expr_type,base_expr, and optionallyposition(if requested) orsub_tree.<?php require_once('php-sql-parser.php'); $parser = new PHPSQLParser( 'SELECT a from some_table an_alias WHERE d > 5; ', true); print_r($parser->parsed);Check code quality using phpcs
masterRun the
phpcscommand-line tool to check your source code against the PhOSCo standard. You can redirect the output to a file for later review usingvior another editor.phpcs --standard=/path/to/the/PhOSCo/folder /path/to/the/src/folder >/tmp/code-errors.txt vi /tmp/code-errors.txtIntegrate CodeSniffer as an external tool in Eclipse
masterYou can automate code checking within Eclipse by configuring
phpcsas an external tool. Follow these steps:- Open the External tool configuration window.
- Set the Name to
CodeSniffer. - Set the Location to
/usr/bin/phpcs. - Set the Arguments to:
--standard="${project_loc}/libs/codesniffer/PhOSCo" "${selected_resource_loc}". - Configure parameters on the Build tab as needed.
- Click Apply and Close.
To use it, select a folder or
*.phpfiles, execute the "CodeSniffer" external tool, and review the errors in the Eclipse console output.Install PHP-SQL-Parser via Packagist
masterThe recommended way to install PHP-SQL-Parser is via Composer using the Packagist repository. This ensures you get the latest version and manage dependencies correctly.
composer require greenlion/php-sql-parserInstall PHP_CodeSniffer
masterYou can install PHP_CodeSniffer using the PEAR package manager.
pear install PHP_CodeSnifferDownload PHP-SQL-Parser from GitHub
masterYou can clone the repository directly from GitHub to use the source code.
git clone https://github.com/greenlion/PHP-SQL-ParserRun the included examples
masterTo explore the parser's capabilities, you can run the provided
example.phpfile located in the root directory. This file contains numerous usage scenarios. You can also find additional examples within the/testsfolder.Run the example using the PHP CLI:
php examples/example.phpIntegrate php-sql-parser into your application
masterTo use the parser in your PHP project, follow these steps:
- Download the stable version from the Downloads wiki and unzip it into your include directory.
- Include the main file in your application using
require_once('php-sql-parser.php'). - Instantiate
PHPSQLParserand call theparse()method to get the associative array representation of your SQL.
Generating keyword positions: If you need to know the exact position of elements within the original SQL string, pass
trueas the second argument to theparse()method. This will store the position within everybase_exprentry.require_once('php-sql-parser.php'); // Basic parsing $parser = new PHPSQLParser(); $parsed = $parser->parse($sql); print_r($parsed); // Parsing with keyword positions $parser = new PHPSQLParser(); $parsed = $parser->parse($sql, true); print_r($parsed);Understand the structured output format
masterWhen parsing supported MySQL statements (like
SELECT), the parser returns a structured associative array representing the components of the query (e.g.,OPTIONS,SELECT,FROM,WHERE). Each component contains detailed information such as expression types (expr_type), base expressions (base_expr), aliases, and sub-trees.Example of a parsed
SELECTstatement structure:Array ( [OPTIONS] => Array ( [0] => STRAIGHT_JOIN ) [SELECT] => Array ( [0] => Array ( [expr_type] => colref [base_expr] => a [sub_tree] => [alias] => `a` ) // ... other columns ) [FROM] => Array ( [0] => Array ( [table] => some_table [alias] => an_alias [join_type] => JOIN // ... other table details ) ) [WHERE] => Array ( [0] => Array ( [expr_type] => colref [base_expr] => d [sub_tree] => ) [1] => Array ( [expr_type] => operator [base_expr] => > [sub_tree] => ) [2] => Array ( [expr_type] => const [base_expr] => 5 [sub_tree] => ) ) )SELECT STRAIGHT_JOIN a, b, c FROM some_table an_alias WHERE d > 5;Parse complex SQL queries with PHPSQLParser
masterThe
PHPSQLParserclass can be used to parse highly complex MySQL-dialect SQL statements, including those with subqueries, CASE statements, multiple JOIN types (LEFT, INNER, USING, ON), aggregate functions, and various clauses likeHAVING,GROUP BY, andLIMIT.When initializing the parser, you can pass a second boolean parameter to enable specific parsing behaviors (as shown in the example). The resulting parsed structure is accessible via the
parsedproperty, which returns a multi-dimensional associative array representing the Abstract Syntax Tree (AST) of the query.require_once('php-sql-parser.php'); $sql = 'select DISTINCT 1+2 c1, 1+ 2 as `c2`, sum(c2),sum(c3) as sum_c3,"Status" = CASE WHEN quantity > 0 THEN \'in stock\' ELSE \'out of stock\' END case_statement , t4.c1, (select c1+c2 from t1 inner_t1 limit 1) as subquery into @a1, @a2, @a3 from t1 the_t1 left outer join t2 using(c1,c2) join t3 as tX ON tX.c1 = the_t1.c1 join t4 t4_x using(x) where c1 = 1 and c2 in (1,2,3, "apple") and exists ( select 1 from some_other_table another_table where x > 1) and ("zebra" = "orange" or 1 = 1) group by 1, 2 having sum(c2) > 1 ORDER BY 2, c1 DESC LIMIT 0, 10 into outfile "/xyz" FOR UPDATE LOCK IN SHARE MODE'; $parser = new PHPSQLParser($sql, true); print_r($parser->parsed);