xp-forge/sql-parser

v0.4.0 2024-03-24 13:26 UTC

This package is auto-updated.

Last update: 2024-11-24 14:54:02 UTC


README

Build status on GitHub XP Framework Module BSD Licence Requires PHP 7.0+ Supports PHP 8.0+ Latest Stable Version

This library parses SQL statements.

Examples

use text\sql\{Parser, SyntaxError};

$p= new Parser();
try {
  $statement= $p->parse('select * from user where user_id = 1');
} catch (SyntaxError $e) {
  // Handle
}

// new Select(
//   [new All()],
//   [new Table('user')],
//   new Comparison(new Field(null, 'uid'), '=', new Number(1))
// )

Support

This library is not yet complete. Currently, the following are supported:

  • USE database selection
  • SELECT, INSERT, UPDATE and DELETE statements
  • CREATE / DROP TABLE schema modification
  • ALTER TABLE ADD / DROP COLUMN table modification

Other statements may be added via extend():

use text\sql\Parser;

$p= new Parser();

// Incomplete implementation of https://dev.mysql.com/doc/refman/8.0/en/show.html
$p->extend('show', function($parse, $token) {
  return ['show' => $parse->match([
    'events'    => function($parse, $token) { return 'events'; },
    'variables' => function($parse, $token) {
      if ('like' === $parse->token->symbol->id) {
        $parse->forward();
        return ['variables' => $parse->expression()];
      } else {
        return ['variables' => null];
      }
    }
  ])];
});

$statement= $p->parse('show variables like "sql_mode"');

// ['show' => ['variables' => new Text('sql_mode')]]