sqlparser.class.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. <?php
  2. require __DIR__ . '/vendor/autoload.php';
  3. class sqlparser
  4. {
  5. /**
  6. * Parser object of SqlParser.
  7. *
  8. * @var object
  9. * @access public
  10. */
  11. public $parser;
  12. /**
  13. * Statements of parser.
  14. *
  15. * @var array
  16. * @access public
  17. */
  18. public $statements;
  19. /**
  20. * First statement.
  21. *
  22. * @var object
  23. * @access public
  24. */
  25. public $statement;
  26. /**
  27. * Count statements.
  28. *
  29. * @var int
  30. * @access public
  31. */
  32. public $statementsCount = 0;
  33. /**
  34. * Is first statemnt select type.
  35. *
  36. * @var bool
  37. * @access public
  38. */
  39. public $isSelect = false;
  40. /**
  41. * DAO
  42. *
  43. * @var object
  44. * @access public
  45. */
  46. public $dao = null;
  47. /**
  48. * Origin tables.
  49. *
  50. * @var array
  51. * @access public
  52. */
  53. public $originTables = array();
  54. /**
  55. * Columns.
  56. *
  57. * @var array
  58. * @access public
  59. */
  60. public $columns = array();
  61. /**
  62. * Tables.
  63. *
  64. * @var array
  65. * @access public
  66. */
  67. public $tables = array();
  68. public function __construct($query = '')
  69. {
  70. $query = $this->skipLineBreak($query);
  71. if(empty($query)) return;
  72. $this->parser = new PhpMyAdmin\SqlParser\Parser($query);
  73. $this->statements = $this->parser->statements;
  74. $this->statementsCount = count($this->statements);
  75. $this->statement = $this->statementsCount > 0 ? current($this->statements) : null;
  76. $this->isSelect = $this->statement instanceof PhpMyAdmin\SqlParser\Statements\SelectStatement === true;
  77. }
  78. /**
  79. * Set dao.
  80. *
  81. * @param object $dao
  82. * @access public
  83. * @return void
  84. */
  85. public function setDAO($dao)
  86. {
  87. $this->dao = $dao;
  88. }
  89. /**
  90. * Parse statement.
  91. *
  92. * @access public
  93. * @return void
  94. */
  95. public function parseStatement()
  96. {
  97. if(empty($this->statement)) return;
  98. $this->columns = $this->parseColumns();
  99. $this->tables = $this->parseTables();
  100. }
  101. /**
  102. * Create statement.
  103. *
  104. * @access public
  105. * @return void
  106. */
  107. public function createStatement()
  108. {
  109. $this->statement = new PhpMyAdmin\SqlParser\Statements\SelectStatement();
  110. }
  111. /**
  112. * Set from.
  113. *
  114. * @param object $from
  115. * @access public
  116. * @return void
  117. */
  118. public function setFrom($from)
  119. {
  120. $this->statement->from = array($from);
  121. }
  122. /**
  123. * Add select.
  124. *
  125. * @param array|object $exprs
  126. * @access public
  127. * @return void
  128. */
  129. public function addSelect($exprs)
  130. {
  131. if(empty($exprs)) return;
  132. if($exprs instanceof PhpMyAdmin\SqlParser\Components\Expression)
  133. {
  134. $this->statement->expr[] = $exprs;
  135. return;
  136. }
  137. foreach($exprs as $expr) $this->addSelect($expr);
  138. }
  139. /**
  140. * Add join.
  141. *
  142. * @param array|object $joins
  143. * @access public
  144. * @return void
  145. */
  146. public function addJoin($joins)
  147. {
  148. if(empty($joins)) return;
  149. if($joins instanceof PhpMyAdmin\SqlParser\Components\JoinKeyword)
  150. {
  151. $this->statement->join[] = $joins;
  152. return;
  153. }
  154. foreach($joins as $join) $this->addJoin($join);
  155. }
  156. /**
  157. * Add where.
  158. *
  159. * @param array|object $wheres
  160. * @access public
  161. * @return void
  162. */
  163. public function addWhere($wheres)
  164. {
  165. if(empty($wheres)) return;
  166. if($wheres instanceof PhpMyAdmin\SqlParser\Components\Condition)
  167. {
  168. $this->statement->where[] = $wheres;
  169. return;
  170. }
  171. foreach($wheres as $where) $this->addWhere($where);
  172. }
  173. /**
  174. * Add group.
  175. *
  176. * @param array|object $groups
  177. * @access public
  178. * @return void
  179. */
  180. public function addGroup($groups)
  181. {
  182. if(empty($groups)) return;
  183. if($groups instanceof PhpMyAdmin\SqlParser\Components\GroupKeyword)
  184. {
  185. $this->statement->group[] = $groups;
  186. return;
  187. }
  188. foreach($groups as $group) $this->addGroup($group);
  189. }
  190. /**
  191. * Get function.
  192. *
  193. * @param string $name
  194. * @param mixed $args
  195. * @access public
  196. * @return string
  197. */
  198. public function getFunction($name, ...$args)
  199. {
  200. $name = strtoupper($name);
  201. $argStr = implode(', ', $args);
  202. $argStr = str_replace(PHP_EOL, '', $argStr);
  203. return "$name($argStr)";
  204. }
  205. /**
  206. * Get expression.
  207. *
  208. * @param string|array $table
  209. * @param string $column
  210. * @param string $alias
  211. * @param string $function
  212. * @access public
  213. * @return PhpMyAdmin\SqlParser\Components\Expression
  214. */
  215. public function getExpression($table = null, $column = null, $alias = null, $function = null)
  216. {
  217. if(is_array($table)) return call_user_func_array(array($this, 'getExpression'), $table);
  218. $expression = new PhpMyAdmin\SqlParser\Components\Expression();
  219. if(!empty($function))
  220. {
  221. $expression->function = $function;
  222. $expression->expr = $this->getFunction($function, $expression->build($this->getExpression($table, $column)));
  223. }
  224. else
  225. {
  226. if($column === '*')
  227. {
  228. $table = $this->trimExpr($table);
  229. $expression->expr = empty($table) ? '*' : "`$table`.*";
  230. }
  231. else
  232. {
  233. $expression->table = $table;
  234. $expression->column = $column;
  235. }
  236. }
  237. $expression->alias = $alias;
  238. return $expression;
  239. }
  240. /**
  241. * operatorCondition
  242. *
  243. * @param string $type
  244. * @access public
  245. * @return void
  246. */
  247. public function operatorCondition($type)
  248. {
  249. $condition = new PhpMyAdmin\SqlParser\Components\Condition();
  250. $condition->isOperator = true;
  251. $condition->expr = strtoupper($type);
  252. return $condition;
  253. }
  254. /**
  255. * Get condition.
  256. *
  257. * @param mixed $tableA
  258. * @param mixed $columnA
  259. * @param string $operator
  260. * @param mixed $tableB
  261. * @param mixed $columnB
  262. * @param mixed $group
  263. * @access public
  264. * @return object
  265. */
  266. public function getCondition($tableA = null, $columnA = null, $operator = '', $tableB = null, $columnB = null, $group = 1, $quote = true)
  267. {
  268. if(is_array($tableA)) return call_user_func_array(array($this, 'getCondition'), $tableA);
  269. $condition = new PhpMyAdmin\SqlParser\Components\Condition();
  270. $tableA = $this->trimExpr($tableA);
  271. $columnA = $this->trimExpr($columnA);
  272. $tableB = $this->trimExpr($tableB);
  273. $expr = '';
  274. if(empty($operator))
  275. {
  276. $expr = $columnA;
  277. }
  278. else
  279. {
  280. /* 如果tableB不为空,那么columnB就是字段,需要trim('`')。*/
  281. if(!empty($tableB)) $columnB = $this->trimExpr($columnB);
  282. /* 如果tableB为空,那么columnB是值,需要trim("'")。*/
  283. if(empty($tableB)) $columnB = $this->trimExpr($columnB, "'");
  284. $columnB = empty($tableB) && $quote ? "'$columnB'" : $columnB;
  285. $exprA = empty($tableA) ? "`$columnA`" : "`$tableA`.`$columnA`";
  286. $exprB = empty($tableB) ? $columnB : "`$tableB`.`$columnB`";
  287. $operator = strtoupper($operator);
  288. $expr = "$exprA $operator $exprB";
  289. }
  290. $condition->expr = $expr;
  291. $condition->group = $group;
  292. return $condition;
  293. }
  294. /**
  295. * Get conditions from array.
  296. *
  297. * @param array $conditions
  298. * @access public
  299. * @return array
  300. */
  301. public function getConditionsFromArray($conditions)
  302. {
  303. if(is_string($conditions)) return $this->operatorCondition($conditions);
  304. $first = current($conditions);
  305. if(!is_array($first) && !in_array($first, array('and', 'or'))) return $this->getCondition($conditions);
  306. $conditionExprs = array();
  307. foreach($conditions as $condition) $conditionExprs[] = $this->getConditionsFromArray($condition);
  308. return $conditionExprs;
  309. }
  310. /**
  311. * Get left join.
  312. *
  313. * @param string $table
  314. * @param string $alias
  315. * @param array $on
  316. * @access public
  317. * @return object
  318. */
  319. public function getLeftJoin($table, $alias, $on)
  320. {
  321. $left = new PhpMyAdmin\SqlParser\Components\JoinKeyword();
  322. $left->type = 'LEFT';
  323. $left->expr = $this->getExpression($table, null, $alias);
  324. $left->on = $this->combineConditions($on);
  325. return $left;
  326. }
  327. /**
  328. * Get group.
  329. *
  330. * @param object $expr
  331. * @access public
  332. * @return void
  333. */
  334. public function getGroup($expr)
  335. {
  336. $group = new PhpMyAdmin\SqlParser\Components\GroupKeyword();
  337. $group->expr = $expr;
  338. return $group;
  339. }
  340. /**
  341. * Combine conditions.
  342. *
  343. * @param array|object $conditions
  344. * @access public
  345. * @return array
  346. */
  347. public function combineConditions($conditions, $quote = false)
  348. {
  349. if(empty($conditions)) return array();
  350. if($conditions instanceof PhpMyAdmin\SqlParser\Components\Condition === true) return $conditions;
  351. $first = reset($conditions);
  352. $last = end($conditions);
  353. if($quote)
  354. {
  355. $first = $this->addQuote($first, 'left');
  356. $last = $this->addQuote($last, 'right');
  357. }
  358. $quote = true;
  359. if(is_array($first)) $first = $this->combineConditions($first, $quote);
  360. if(is_array($last)) $last = $this->combineConditions($last, $quote);
  361. $conditions[0] = $first;
  362. $conditions[count($conditions) - 1] = $last;
  363. return $conditions;
  364. }
  365. public function addQuote($conditions, $side)
  366. {
  367. if($conditions instanceof PhpMyAdmin\SqlParser\Components\Condition === true)
  368. {
  369. $expr = $conditions->expr;
  370. $conditions->expr = $side == 'left' ? '(' . $expr : $expr . ')';
  371. return $conditions;
  372. }
  373. $condition = $side == 'left' ? current($conditions) : end($conditions);
  374. $index = $side == 'left' ? 0 : count($conditions) - 1;
  375. $conditions[$index] = $this->addQuote($condition, $side);
  376. return $conditions;
  377. }
  378. /**
  379. * Match columns with table.
  380. *
  381. * @access public
  382. * @return array
  383. */
  384. public function matchColumnsWithTable()
  385. {
  386. if(empty($this->statement)) return array();
  387. if(count($this->tables) == 1) return $this->combineSingleTable();
  388. return $this->combineMultipleTable();
  389. }
  390. /**
  391. * Trim expr.
  392. *
  393. * @param string $expr
  394. * @access private
  395. * @return string
  396. */
  397. private function trimExpr($expr, $char = '`')
  398. {
  399. if(empty($expr)) return $expr;
  400. return trim(trim($expr), $char);
  401. }
  402. /**
  403. * Combine single table to columns.
  404. *
  405. * @access private
  406. * @return array
  407. */
  408. private function combineSingleTable()
  409. {
  410. $combineColumns = array();
  411. $fromTable = current($this->tables);
  412. foreach($this->columns as $columnName => $column)
  413. {
  414. $column['table'] = array_merge($fromTable, array('column' => $column['origin']));
  415. $combineColumns[$columnName] = $column;
  416. }
  417. return $combineColumns;
  418. }
  419. /**
  420. * Combine multiple table to columns.
  421. *
  422. * @access private
  423. * @return array
  424. */
  425. private function combineMultipleTable()
  426. {
  427. foreach($this->columns as $columnName => $column)
  428. {
  429. $column['table'] = $this->searchTables($column['table'], $this->tables, $column['origin']);
  430. $combineColumns[$columnName] = $column;
  431. }
  432. return $combineColumns;
  433. }
  434. /**
  435. * Search table from origin tables.
  436. *
  437. * @param string $tableName
  438. * @param string $tables
  439. * @param string $column
  440. * @access private
  441. * @return string|false
  442. */
  443. private function searchTables($tableName, $tables, $column)
  444. {
  445. /* 如果能使用别名匹配上,那么直接返回。*/
  446. /* If it can be matched using an alias, then it returns. */
  447. foreach($tables as $table) if($tableName == $table['alias']) return array_merge($table, array('column' => $column));
  448. /* 如果匹配不上,则字段没有使用别名进行限制,那么需要通过字段去遍历所有表。*/
  449. /* If it doesn't match, then the field is not aliased, and you need to iterate over all tables using the field. */
  450. foreach($tables as $table)
  451. {
  452. $isTable = $table['isTable'];
  453. $originTable = $table['originTable'];
  454. /* 如果是原始表,并且列在原始表中存在,那么返回这个表。*/
  455. /* If it is the original table and the column exists in the original table, then the table is returned. */
  456. if($isTable && $this->columnExistInOriginTable($originTable, $column)) return array_merge($table, array('column' => $column));
  457. /* 如果不是原始表,并且列在子句中存在,那么返回子句中这个字段对应的表。*/
  458. /* If it is not the original table and the column exists in the clause, then the table corresponding to the field in the clause is returned. */
  459. if(!$isTable && isset($originTable[$column])) return array_merge($originTable[$column]['table'], array('column' => $originTable[$column]['origin']));
  460. }
  461. return false;
  462. }
  463. /**
  464. * Parse columns.
  465. *
  466. * @access private
  467. * @return void
  468. */
  469. private function parseColumns()
  470. {
  471. $fields = array();
  472. foreach($this->statement->expr as $expr)
  473. {
  474. /* 获取查询数据后真正展示出来的列名 */
  475. $columnName = empty($expr->alias) ? $expr->column : $expr->alias;
  476. $fields[$columnName] = array('origin' => $expr->column, 'table' => $expr->table);
  477. }
  478. return $fields;
  479. }
  480. /**
  481. * Parse tables.
  482. *
  483. * @access private
  484. * @return void
  485. */
  486. private function parseTables()
  487. {
  488. $from = current($this->statement->from);
  489. $joins = $this->statement->join;
  490. $tables = array();
  491. $tables[] = $this->parseTable($from, 'from');
  492. if(!empty($joins)) foreach($joins as $join) $tables[] = $this->parseTable($join->expr, 'join');
  493. return $tables;
  494. }
  495. /**
  496. * Parse table.
  497. *
  498. * @param object $expr
  499. * @param string $type
  500. * @access private
  501. * @return void
  502. */
  503. private function parseTable($expr, $type)
  504. {
  505. $isTable = empty($expr->subquery);
  506. $table = array('alias' => $expr->alias, 'isTable' => $isTable, 'type' => $type);
  507. $table['originTable'] = $this->getOriginTable($expr->expr, $isTable);
  508. return $table;
  509. }
  510. /**
  511. * Get origin table from table name or expr.
  512. *
  513. * @param string $table
  514. * @param bool $isTable
  515. * @access private
  516. * @return string|array
  517. */
  518. private function getOriginTable($table, $isTable)
  519. {
  520. if(!$isTable)
  521. {
  522. $parser = new sqlparser($table);
  523. $parser->setDAO($this->dao);
  524. $parser->parseStatement();
  525. return $parser->matchColumnsWithTable();
  526. }
  527. $this->storeOriginTable($table);
  528. return $table;
  529. }
  530. /**
  531. * Judge column exist in origin table or not.
  532. *
  533. * @param string $table
  534. * @param string $column
  535. * @access private
  536. * @return bool
  537. */
  538. private function columnExistInOriginTable($table, $column)
  539. {
  540. $originTable = $this->getOriginTableColumns($table);
  541. if(!$originTable) return false;
  542. return isset($originTable[$column]);
  543. }
  544. /**
  545. * Get origin table columns.
  546. *
  547. * @param string $table
  548. * @access private
  549. * @return array|null
  550. */
  551. private function getOriginTableColumns($table)
  552. {
  553. $originTables = $this->originTables;
  554. return isset($originTables[$table]) ? $originTables[$table] : null;
  555. }
  556. /**
  557. * Store origin table.
  558. *
  559. * @param string $table
  560. * @access private
  561. * @return void
  562. */
  563. private function storeOriginTable($table)
  564. {
  565. if(!isset($this->originTables[$table])) $this->originTables[$table] = $this->dao->descTable($table);
  566. }
  567. /**
  568. * Skip line break in sql.
  569. *
  570. * @param string $sql
  571. * @access private
  572. * @return string
  573. */
  574. private function skipLineBreak($sql)
  575. {
  576. if(empty($sql)) return $sql;
  577. $sql = str_replace("\n\t", " ", $sql);
  578. $sql = str_replace("\t\n", " ", $sql);
  579. $sql = str_replace("\n\r", " ", $sql);
  580. $sql = str_replace("\r\n", " ", $sql);
  581. $sql = str_replace("\r", " ", $sql);
  582. $sql = str_replace("\n", " ", $sql);
  583. return $sql;
  584. }
  585. }