2 namespace TYPO3\CMS\Core\Database
;
4 /***************************************************************
7 * (c) 2004-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
10 * This script is part of the TYPO3 project. The TYPO3 project is
11 * free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * The GNU General Public License can be found at
17 * http://www.gnu.org/copyleft/gpl.html.
18 * A copy is found in the textfile GPL.txt and important notices to the license
19 * from the author is found in LICENSE.txt distributed with these scripts.
22 * This script is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * This copyright notice MUST APPEAR in all copies of the script!
28 ***************************************************************/
32 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
35 * TYPO3 SQL parser class.
37 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
42 // Parsing error string
44 * @todo Define visibility
46 public $parse_error = '';
48 // Last stop keyword used.
50 * @todo Define visibility
52 public $lastStopKeyWord = '';
54 /*************************************
56 * SQL Parsing, full queries
58 **************************************/
60 * Parses any single SQL query
62 * @param string $parseString SQL query
63 * @return array Result array with all the parts in - or error message string
64 * @see compileSQL(), debug_testSQL()
66 public function parseSQL($parseString) {
68 $parseString = $this->trimSQL($parseString);
69 $this->parse_error
= '';
71 // Finding starting keyword of string:
72 $_parseString = $parseString;
73 // Protecting original string...
74 $keyword = $this->nextPart($_parseString, '^(SELECT|UPDATE|INSERT[[:space:]]+INTO|DELETE[[:space:]]+FROM|EXPLAIN|DROP[[:space:]]+TABLE|CREATE[[:space:]]+TABLE|CREATE[[:space:]]+DATABASE|ALTER[[:space:]]+TABLE|TRUNCATE[[:space:]]+TABLE)[[:space:]]+');
75 $keyword = strtoupper(str_replace(array(' ', TAB
, CR
, LF
), '', $keyword));
78 // Parsing SELECT query:
79 $result = $this->parseSELECT($parseString);
82 // Parsing UPDATE query:
83 $result = $this->parseUPDATE($parseString);
86 // Parsing INSERT query:
87 $result = $this->parseINSERT($parseString);
90 // Parsing DELETE query:
91 $result = $this->parseDELETE($parseString);
94 // Parsing EXPLAIN SELECT query:
95 $result = $this->parseEXPLAIN($parseString);
98 // Parsing DROP TABLE query:
99 $result = $this->parseDROPTABLE($parseString);
102 // Parsing ALTER TABLE query:
103 $result = $this->parseALTERTABLE($parseString);
106 // Parsing CREATE TABLE query:
107 $result = $this->parseCREATETABLE($parseString);
109 case 'CREATEDATABASE':
110 // Parsing CREATE DATABASE query:
111 $result = $this->parseCREATEDATABASE($parseString);
113 case 'TRUNCATETABLE':
114 // Parsing TRUNCATE TABLE query:
115 $result = $this->parseTRUNCATETABLE($parseString);
118 $result = $this->parseError('"' . $keyword . '" is not a keyword', $parseString);
125 * Parsing SELECT query
127 * @param string $parseString SQL string with SELECT query to parse
128 * @param array $parameterReferences Array holding references to either named (:name) or question mark (?) parameters found
129 * @return mixed Returns array with components of SELECT query on success, otherwise an error message string.
130 * @see compileSELECT()
132 protected function parseSELECT($parseString, &$parameterReferences = NULL) {
134 $parseString = $this->trimSQL($parseString);
135 $parseString = ltrim(substr($parseString, 6));
136 // Init output variable:
138 if ($parameterReferences === NULL) {
139 $result['parameters'] = array();
140 $parameterReferences = &$result['parameters'];
142 $result['type'] = 'SELECT';
143 // Looking for STRAIGHT_JOIN keyword:
144 $result['STRAIGHT_JOIN'] = $this->nextPart($parseString, '^(STRAIGHT_JOIN)[[:space:]]+');
146 $result['SELECT'] = $this->parseFieldList($parseString, '^(FROM)[[:space:]]+');
147 if ($this->parse_error
) {
148 return $this->parse_error
;
150 // Continue if string is not ended:
153 $result['FROM'] = $this->parseFromTables($parseString, '^(WHERE)[[:space:]]+');
154 if ($this->parse_error
) {
155 return $this->parse_error
;
157 // If there are more than just the tables (a WHERE clause that would be...)
160 $result['WHERE'] = $this->parseWhereClause($parseString, '^(GROUP[[:space:]]+BY|ORDER[[:space:]]+BY|LIMIT)[[:space:]]+', $parameterReferences);
161 if ($this->parse_error
) {
162 return $this->parse_error
;
164 // If the WHERE clause parsing was stopped by GROUP BY, ORDER BY or LIMIT, then proceed with parsing:
165 if ($this->lastStopKeyWord
) {
167 if ($this->lastStopKeyWord
== 'GROUPBY') {
168 $result['GROUPBY'] = $this->parseFieldList($parseString, '^(ORDER[[:space:]]+BY|LIMIT)[[:space:]]+');
169 if ($this->parse_error
) {
170 return $this->parse_error
;
174 if ($this->lastStopKeyWord
== 'ORDERBY') {
175 $result['ORDERBY'] = $this->parseFieldList($parseString, '^(LIMIT)[[:space:]]+');
176 if ($this->parse_error
) {
177 return $this->parse_error
;
181 if ($this->lastStopKeyWord
== 'LIMIT') {
182 if (preg_match('/^([0-9]+|[0-9]+[[:space:]]*,[[:space:]]*[0-9]+)$/', trim($parseString))) {
183 $result['LIMIT'] = $parseString;
185 return $this->parseError('No value for limit!', $parseString);
191 return $this->parseError('No table to select from!', $parseString);
193 // Store current parseString in the result array for possible further processing (e.g., subquery support by DBAL)
194 $result['parseString'] = $parseString;
200 * Parsing UPDATE query
202 * @param string $parseString SQL string with UPDATE query to parse
203 * @return mixed Returns array with components of UPDATE query on success, otherwise an error message string.
204 * @see compileUPDATE()
206 protected function parseUPDATE($parseString) {
208 $parseString = $this->trimSQL($parseString);
209 $parseString = ltrim(substr($parseString, 6));
210 // Init output variable:
212 $result['type'] = 'UPDATE';
214 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
215 // Continue if string is not ended:
216 if ($result['TABLE']) {
217 if ($parseString && $this->nextPart($parseString, '^(SET)[[:space:]]+')) {
219 // Get field/value pairs:
221 if ($fieldName = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]*=')) {
222 // Strip of "=" sign.
223 $this->nextPart($parseString, '^(=)');
224 $value = $this->getValue($parseString);
225 $result['FIELDS'][$fieldName] = $value;
227 return $this->parseError('No fieldname found', $parseString);
229 $comma = $this->nextPart($parseString, '^(,)');
232 if ($this->nextPart($parseString, '^(WHERE)')) {
233 $result['WHERE'] = $this->parseWhereClause($parseString);
234 if ($this->parse_error
) {
235 return $this->parse_error
;
239 return $this->parseError('Query missing SET...', $parseString);
242 return $this->parseError('No table found!', $parseString);
244 // Should be no more content now:
246 return $this->parseError('Still content in clause after parsing!', $parseString);
253 * Parsing INSERT query
255 * @param string $parseString SQL string with INSERT query to parse
256 * @return mixed Returns array with components of INSERT query on success, otherwise an error message string.
257 * @see compileINSERT()
259 protected function parseINSERT($parseString) {
261 $parseString = $this->trimSQL($parseString);
262 $parseString = ltrim(substr(ltrim(substr($parseString, 6)), 4));
263 // Init output variable:
265 $result['type'] = 'INSERT';
267 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)([[:space:]]+|\\()');
268 if ($result['TABLE']) {
269 // In this case there are no field names mentioned in the SQL!
270 if ($this->nextPart($parseString, '^(VALUES)([[:space:]]+|\\()')) {
271 // Get values/fieldnames (depending...)
272 $result['VALUES_ONLY'] = $this->getValue($parseString, 'IN');
273 if ($this->parse_error
) {
274 return $this->parse_error
;
276 if (preg_match('/^,/', $parseString)) {
277 $result['VALUES_ONLY'] = array($result['VALUES_ONLY']);
278 $result['EXTENDED'] = '1';
279 while ($this->nextPart($parseString, '^(,)') === ',') {
280 $result['VALUES_ONLY'][] = $this->getValue($parseString, 'IN');
281 if ($this->parse_error
) {
282 return $this->parse_error
;
287 // There are apparently fieldnames listed:
288 $fieldNames = $this->getValue($parseString, '_LIST');
289 if ($this->parse_error
) {
290 return $this->parse_error
;
292 // "VALUES" keyword binds the fieldnames to values:
293 if ($this->nextPart($parseString, '^(VALUES)([[:space:]]+|\\()')) {
294 $result['FIELDS'] = array();
296 // Using the "getValue" function to get the field list...
297 $values = $this->getValue($parseString, 'IN');
298 if ($this->parse_error
) {
299 return $this->parse_error
;
301 $insertValues = array();
302 foreach ($fieldNames as $k => $fN) {
303 if (preg_match('/^[[:alnum:]_]+$/', $fN)) {
304 if (isset($values[$k])) {
305 if (!isset($insertValues[$fN])) {
306 $insertValues[$fN] = $values[$k];
308 return $this->parseError('Fieldname ("' . $fN . '") already found in list!', $parseString);
311 return $this->parseError('No value set!', $parseString);
314 return $this->parseError('Invalid fieldname ("' . $fN . '")', $parseString);
317 if (isset($values[$k +
1])) {
318 return $this->parseError('Too many values in list!', $parseString);
320 $result['FIELDS'][] = $insertValues;
321 } while ($this->nextPart($parseString, '^(,)') === ',');
322 if (count($result['FIELDS']) === 1) {
323 $result['FIELDS'] = $result['FIELDS'][0];
325 $result['EXTENDED'] = '1';
328 return $this->parseError('VALUES keyword expected', $parseString);
332 return $this->parseError('No table found!', $parseString);
334 // Should be no more content now:
336 return $this->parseError('Still content after parsing!', $parseString);
343 * Parsing DELETE query
345 * @param string $parseString SQL string with DELETE query to parse
346 * @return mixed Returns array with components of DELETE query on success, otherwise an error message string.
347 * @see compileDELETE()
349 protected function parseDELETE($parseString) {
351 $parseString = $this->trimSQL($parseString);
352 $parseString = ltrim(substr(ltrim(substr($parseString, 6)), 4));
353 // Init output variable:
355 $result['type'] = 'DELETE';
357 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
358 if ($result['TABLE']) {
360 if ($this->nextPart($parseString, '^(WHERE)')) {
361 $result['WHERE'] = $this->parseWhereClause($parseString);
362 if ($this->parse_error
) {
363 return $this->parse_error
;
367 return $this->parseError('No table found!', $parseString);
369 // Should be no more content now:
371 return $this->parseError('Still content in clause after parsing!', $parseString);
378 * Parsing EXPLAIN query
380 * @param string $parseString SQL string with EXPLAIN query to parse
381 * @return mixed Returns array with components of EXPLAIN query on success, otherwise an error message string.
384 protected function parseEXPLAIN($parseString) {
386 $parseString = $this->trimSQL($parseString);
387 $parseString = ltrim(substr($parseString, 6));
388 // Init output variable:
389 $result = $this->parseSELECT($parseString);
390 if (is_array($result)) {
391 $result['type'] = 'EXPLAIN';
397 * Parsing CREATE TABLE query
399 * @param string $parseString SQL string starting with CREATE TABLE
400 * @return mixed Returns array with components of CREATE TABLE query on success, otherwise an error message string.
401 * @see compileCREATETABLE()
403 protected function parseCREATETABLE($parseString) {
404 // Removing CREATE TABLE
405 $parseString = $this->trimSQL($parseString);
406 $parseString = ltrim(substr(ltrim(substr($parseString, 6)), 5));
407 // Init output variable:
409 $result['type'] = 'CREATETABLE';
411 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]*\\(', TRUE);
412 if ($result['TABLE']) {
413 // While the parseString is not yet empty:
414 while (strlen($parseString) > 0) {
416 if ($key = $this->nextPart($parseString, '^(KEY|PRIMARY KEY|UNIQUE KEY|UNIQUE)([[:space:]]+|\\()')) {
417 $key = strtoupper(str_replace(array(' ', TAB
, CR
, LF
), '', $key));
420 $result['KEYS']['PRIMARYKEY'] = $this->getValue($parseString, '_LIST');
421 if ($this->parse_error
) {
422 return $this->parse_error
;
428 if ($keyName = $this->nextPart($parseString, '^([[:alnum:]_]+)([[:space:]]+|\\()')) {
429 $result['KEYS']['UNIQUE'] = array($keyName => $this->getValue($parseString, '_LIST'));
430 if ($this->parse_error
) {
431 return $this->parse_error
;
434 return $this->parseError('No keyname found', $parseString);
438 if ($keyName = $this->nextPart($parseString, '^([[:alnum:]_]+)([[:space:]]+|\\()')) {
439 $result['KEYS'][$keyName] = $this->getValue($parseString, '_LIST', 'INDEX');
440 if ($this->parse_error
) {
441 return $this->parse_error
;
444 return $this->parseError('No keyname found', $parseString);
448 } elseif ($fieldName = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+')) {
450 $result['FIELDS'][$fieldName]['definition'] = $this->parseFieldDef($parseString);
451 if ($this->parse_error
) {
452 return $this->parse_error
;
455 // Finding delimiter:
456 $delim = $this->nextPart($parseString, '^(,|\\))');
458 return $this->parseError('No delimiter found', $parseString);
459 } elseif ($delim == ')') {
463 // Finding what is after the table definition - table type in MySQL
465 if ($this->nextPart($parseString, '^((ENGINE|TYPE)[[:space:]]*=)')) {
466 $result['tableType'] = $parseString;
470 return $this->parseError('No fieldname found!', $parseString);
473 return $this->parseError('No table found!', $parseString);
475 // Should be no more content now:
477 return $this->parseError('Still content in clause after parsing!', $parseString);
483 * Parsing ALTER TABLE query
485 * @param string $parseString SQL string starting with ALTER TABLE
486 * @return mixed Returns array with components of ALTER TABLE query on success, otherwise an error message string.
487 * @see compileALTERTABLE()
489 protected function parseALTERTABLE($parseString) {
490 // Removing ALTER TABLE
491 $parseString = $this->trimSQL($parseString);
492 $parseString = ltrim(substr(ltrim(substr($parseString, 5)), 5));
493 // Init output variable:
495 $result['type'] = 'ALTERTABLE';
497 $hasBackquote = $this->nextPart($parseString, '^(`)') === '`';
498 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)' . ($hasBackquote ?
'`' : '') . '[[:space:]]+');
499 if ($hasBackquote && $this->nextPart($parseString, '^(`)') !== '`') {
500 return $this->parseError('No end backquote found!', $parseString);
502 if ($result['TABLE']) {
503 if ($result['action'] = $this->nextPart($parseString, '^(CHANGE|DROP[[:space:]]+KEY|DROP[[:space:]]+PRIMARY[[:space:]]+KEY|ADD[[:space:]]+KEY|ADD[[:space:]]+PRIMARY[[:space:]]+KEY|ADD[[:space:]]+UNIQUE|DROP|ADD|RENAME|DEFAULT[[:space:]]+CHARACTER[[:space:]]+SET|ENGINE)([[:space:]]+|\\(|=)')) {
504 $actionKey = strtoupper(str_replace(array(' ', TAB
, CR
, LF
), '', $result['action']));
506 if (\TYPO3\CMS\Core\Utility\GeneralUtility
::inList('ADDPRIMARYKEY,DROPPRIMARYKEY,ENGINE', $actionKey) ||
($fieldKey = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+'))) {
507 switch ($actionKey) {
509 $result['FIELD'] = $fieldKey;
510 $result['definition'] = $this->parseFieldDef($parseString);
511 if ($this->parse_error
) {
512 return $this->parse_error
;
518 $result['FIELD'] = $fieldKey;
521 $result['FIELD'] = $fieldKey;
522 if ($result['newField'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+')) {
523 $result['definition'] = $this->parseFieldDef($parseString);
524 if ($this->parse_error
) {
525 return $this->parse_error
;
528 return $this->parseError('No NEW field name found', $parseString);
533 case 'ADDPRIMARYKEY':
536 $result['KEY'] = $fieldKey;
537 $result['fields'] = $this->getValue($parseString, '_LIST', 'INDEX');
538 if ($this->parse_error
) {
539 return $this->parse_error
;
543 $result['KEY'] = $fieldKey;
545 case 'DROPPRIMARYKEY':
548 case 'DEFAULTCHARACTERSET':
549 $result['charset'] = $fieldKey;
552 $result['engine'] = $this->nextPart($parseString, '^=[[:space:]]*([[:alnum:]]+)[[:space:]]+', TRUE);
556 return $this->parseError('No field name found', $parseString);
559 return $this->parseError('No action CHANGE, DROP or ADD found!', $parseString);
562 return $this->parseError('No table found!', $parseString);
564 // Should be no more content now:
566 return $this->parseError('Still content in clause after parsing!', $parseString);
572 * Parsing DROP TABLE query
574 * @param string $parseString SQL string starting with DROP TABLE
575 * @return mixed Returns array with components of DROP TABLE query on success, otherwise an error message string.
577 protected function parseDROPTABLE($parseString) {
578 // Removing DROP TABLE
579 $parseString = $this->trimSQL($parseString);
580 $parseString = ltrim(substr(ltrim(substr($parseString, 4)), 5));
581 // Init output variable:
583 $result['type'] = 'DROPTABLE';
585 $result['ifExists'] = $this->nextPart($parseString, '^(IF[[:space:]]+EXISTS[[:space:]]+)');
587 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
588 if ($result['TABLE']) {
589 // Should be no more content now:
591 return $this->parseError('Still content in clause after parsing!', $parseString);
595 return $this->parseError('No table found!', $parseString);
600 * Parsing CREATE DATABASE query
602 * @param string $parseString SQL string starting with CREATE DATABASE
603 * @return mixed Returns array with components of CREATE DATABASE query on success, otherwise an error message string.
605 protected function parseCREATEDATABASE($parseString) {
606 // Removing CREATE DATABASE
607 $parseString = $this->trimSQL($parseString);
608 $parseString = ltrim(substr(ltrim(substr($parseString, 6)), 8));
609 // Init output variable:
611 $result['type'] = 'CREATEDATABASE';
613 $result['DATABASE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
614 if ($result['DATABASE']) {
615 // Should be no more content now:
617 return $this->parseError('Still content in clause after parsing!', $parseString);
621 return $this->parseError('No database found!', $parseString);
626 * Parsing TRUNCATE TABLE query
628 * @param string $parseString SQL string starting with TRUNCATE TABLE
629 * @return mixed Returns array with components of TRUNCATE TABLE query on success, otherwise an error message string.
631 protected function parseTRUNCATETABLE($parseString) {
632 // Removing TRUNCATE TABLE
633 $parseString = $this->trimSQL($parseString);
634 $parseString = ltrim(substr(ltrim(substr($parseString, 8)), 5));
635 // Init output variable:
637 $result['type'] = 'TRUNCATETABLE';
639 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
640 if ($result['TABLE']) {
641 // Should be no more content now:
643 return $this->parseError('Still content in clause after parsing!', $parseString);
647 return $this->parseError('No table found!', $parseString);
651 /**************************************
653 * SQL Parsing, helper functions for parts of queries
655 **************************************/
657 * Parsing the fields in the "SELECT [$selectFields] FROM" part of a query into an array.
658 * The output from this function can be compiled back into a field list with ->compileFieldList()
659 * Will detect the keywords "DESC" and "ASC" after the table name; thus is can be used for parsing the more simply ORDER BY and GROUP BY field lists as well!
661 * @param string $parseString The string with fieldnames, eg. "title, uid AS myUid, max(tstamp), count(*)" etc. NOTICE: passed by reference!
662 * @param string $stopRegex Regular expressing to STOP parsing, eg. '^(FROM)([[:space:]]*)'
663 * @return array If successful parsing, returns an array, otherwise an error string.
664 * @see compileFieldList()
666 public function parseFieldList(&$parseString, $stopRegex = '') {
668 // Contains the parsed content
669 if (strlen($parseString) == 0) {
672 // FIXME - should never happen, why does it?
673 // Pointer to positions in $stack
675 // Indicates the parenthesis level we are at.
677 // Recursivity brake.
679 // Prepare variables:
680 $parseString = $this->trimSQL($parseString);
681 $this->lastStopKeyWord
= '';
682 $this->parse_error
= '';
683 // Parse any SQL hint / comments
684 $stack[$pnt]['comments'] = $this->nextPart($parseString, '^(\\/\\*.*\\*\\/)');
685 // $parseString is continuously shortened by the process and we keep parsing it till it is zero:
686 while (strlen($parseString)) {
687 // Checking if we are inside / outside parenthesis (in case of a function like count(), max(), min() etc...):
688 // Inside parenthesis here (does NOT detect if values in quotes are used, the only token is ")" or "("):
690 // Accumulate function content until next () parenthesis:
691 $funcContent = $this->nextPart($parseString, '^([^()]*.)');
692 $stack[$pnt]['func_content.'][] = array(
694 'func_content' => substr($funcContent, 0, -1)
696 $stack[$pnt]['func_content'] .= $funcContent;
698 switch (substr($stack[$pnt]['func_content'], -1)) {
704 // If this was the last parenthesis:
706 $stack[$pnt]['func_content'] = substr($stack[$pnt]['func_content'], 0, -1);
707 // Remove any whitespace after the parenthesis.
708 $parseString = ltrim($parseString);
713 // Outside parenthesis, looking for next field:
714 // Looking for a flow-control construct (only known constructs supported)
715 if (preg_match('/^case([[:space:]][[:alnum:]\\*._]+)?[[:space:]]when/i', $parseString)) {
716 $stack[$pnt]['type'] = 'flow-control';
717 $stack[$pnt]['flow-control'] = $this->parseCaseStatement($parseString);
718 // Looking for "AS" alias:
719 if ($as = $this->nextPart($parseString, '^(AS)[[:space:]]+')) {
720 $stack[$pnt]['as'] = $this->nextPart($parseString, '^([[:alnum:]_]+)(,|[[:space:]]+)');
721 $stack[$pnt]['as_keyword'] = $as;
724 // Looking for a known function (only known functions supported)
725 $func = $this->nextPart($parseString, '^(count|max|min|floor|sum|avg)[[:space:]]*\\(');
728 $parseString = trim(substr($parseString, 1));
729 $stack[$pnt]['type'] = 'function';
730 $stack[$pnt]['function'] = $func;
731 // increse parenthesis level counter.
734 $stack[$pnt]['distinct'] = $this->nextPart($parseString, '^(distinct[[:space:]]+)');
735 // Otherwise, look for regular fieldname:
736 if (($fieldName = $this->nextPart($parseString, '^([[:alnum:]\\*._]+)(,|[[:space:]]+)')) !== '') {
737 $stack[$pnt]['type'] = 'field';
738 // Explode fieldname into field and table:
739 $tableField = explode('.', $fieldName, 2);
740 if (count($tableField) == 2) {
741 $stack[$pnt]['table'] = $tableField[0];
742 $stack[$pnt]['field'] = $tableField[1];
744 $stack[$pnt]['table'] = '';
745 $stack[$pnt]['field'] = $tableField[0];
748 return $this->parseError('No field name found as expected in parseFieldList()', $parseString);
753 // After a function or field we look for "AS" alias and a comma to separate to the next field in the list:
755 // Looking for "AS" alias:
756 if ($as = $this->nextPart($parseString, '^(AS)[[:space:]]+')) {
757 $stack[$pnt]['as'] = $this->nextPart($parseString, '^([[:alnum:]_]+)(,|[[:space:]]+)');
758 $stack[$pnt]['as_keyword'] = $as;
760 // Looking for "ASC" or "DESC" keywords (for ORDER BY)
761 if ($sDir = $this->nextPart($parseString, '^(ASC|DESC)([[:space:]]+|,)')) {
762 $stack[$pnt]['sortDir'] = $sDir;
764 // Looking for stop-keywords:
765 if ($stopRegex && ($this->lastStopKeyWord
= $this->nextPart($parseString, $stopRegex))) {
766 $this->lastStopKeyWord
= strtoupper(str_replace(array(' ', TAB
, CR
, LF
), '', $this->lastStopKeyWord
));
769 // Looking for comma (since the stop-keyword did not trigger a return...)
770 if (strlen($parseString) && !$this->nextPart($parseString, '^(,)')) {
771 return $this->parseError('No comma found as expected in parseFieldList()', $parseString);
773 // Increasing pointer:
776 // Check recursivity brake:
778 if ($loopExit > 500) {
779 return $this->parseError('More than 500 loops, exiting prematurely in parseFieldList()...', $parseString);
782 // Return result array:
787 * Parsing a CASE ... WHEN flow-control construct.
788 * The output from this function can be compiled back with ->compileCaseStatement()
790 * @param string $parseString The string with the CASE ... WHEN construct, eg. "CASE field WHEN 1 THEN 0 ELSE ..." etc. NOTICE: passed by reference!
791 * @return array If successful parsing, returns an array, otherwise an error string.
792 * @see compileCaseConstruct()
794 protected function parseCaseStatement(&$parseString) {
796 $result['type'] = $this->nextPart($parseString, '^(case)[[:space:]]+');
797 if (!preg_match('/^when[[:space:]]+/i', $parseString)) {
798 $value = $this->getValue($parseString);
799 if (!(isset($value[1]) ||
is_numeric($value[0]))) {
800 $result['case_field'] = $value[0];
802 $result['case_value'] = $value;
805 $result['when'] = array();
806 while ($this->nextPart($parseString, '^(when)[[:space:]]')) {
808 $when['when_value'] = $this->parseWhereClause($parseString, '^(then)[[:space:]]+');
809 $when['then_value'] = $this->getValue($parseString);
810 $result['when'][] = $when;
812 if ($this->nextPart($parseString, '^(else)[[:space:]]+')) {
813 $result['else'] = $this->getValue($parseString);
815 if (!$this->nextPart($parseString, '^(end)[[:space:]]+')) {
816 return $this->parseError('No "end" keyword found as expected in parseCaseStatement()', $parseString);
822 * Parsing the tablenames in the "FROM [$parseString] WHERE" part of a query into an array.
823 * The success of this parsing determines if that part of the query is supported by TYPO3.
825 * @param string $parseString List of tables, eg. "pages, tt_content" or "pages A, pages B". NOTICE: passed by reference!
826 * @param string $stopRegex Regular expressing to STOP parsing, eg. '^(WHERE)([[:space:]]*)'
827 * @return array If successful parsing, returns an array, otherwise an error string.
828 * @see compileFromTables()
830 public function parseFromTables(&$parseString, $stopRegex = '') {
831 // Prepare variables:
832 $parseString = $this->trimSQL($parseString);
833 $this->lastStopKeyWord
= '';
834 $this->parse_error
= '';
835 // Contains the parsed content
837 // Pointer to positions in $stack
839 // Recursivity brake.
841 // $parseString is continously shortend by the process and we keep parsing it till it is zero:
842 while (strlen($parseString)) {
843 // Looking for the table:
844 if ($stack[$pnt]['table'] = $this->nextPart($parseString, '^([[:alnum:]_]+)(,|[[:space:]]+)')) {
845 // Looking for stop-keywords before fetching potential table alias:
846 if ($stopRegex && ($this->lastStopKeyWord
= $this->nextPart($parseString, $stopRegex))) {
847 $this->lastStopKeyWord
= strtoupper(str_replace(array(' ', TAB
, CR
, LF
), '', $this->lastStopKeyWord
));
850 if (!preg_match('/^(LEFT|RIGHT|JOIN|INNER)[[:space:]]+/i', $parseString)) {
851 $stack[$pnt]['as_keyword'] = $this->nextPart($parseString, '^(AS[[:space:]]+)');
852 $stack[$pnt]['as'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]*');
855 return $this->parseError('No table name found as expected in parseFromTables()!', $parseString);
859 while ($join = $this->nextPart($parseString, '^(LEFT[[:space:]]+JOIN|LEFT[[:space:]]+OUTER[[:space:]]+JOIN|RIGHT[[:space:]]+JOIN|RIGHT[[:space:]]+OUTER[[:space:]]+JOIN|INNER[[:space:]]+JOIN|JOIN)[[:space:]]+')) {
860 $stack[$pnt]['JOIN'][$joinCnt]['type'] = $join;
861 if ($stack[$pnt]['JOIN'][$joinCnt]['withTable'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+', 1)) {
862 if (!preg_match('/^ON[[:space:]]+/i', $parseString)) {
863 $stack[$pnt]['JOIN'][$joinCnt]['as_keyword'] = $this->nextPart($parseString, '^(AS[[:space:]]+)');
864 $stack[$pnt]['JOIN'][$joinCnt]['as'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
866 if (!$this->nextPart($parseString, '^(ON[[:space:]]+)')) {
867 return $this->parseError('No join condition found in parseFromTables()!', $parseString);
869 $stack[$pnt]['JOIN'][$joinCnt]['ON'] = array();
870 $condition = array('operator' => '');
871 $parseCondition = TRUE;
872 while ($parseCondition) {
873 if (($fieldName = $this->nextPart($parseString, '^([[:alnum:]._]+)[[:space:]]*(<=|>=|<|>|=|!=)')) !== '') {
874 // Parse field name into field and table:
875 $tableField = explode('.', $fieldName, 2);
876 $condition['left'] = array();
877 if (count($tableField) == 2) {
878 $condition['left']['table'] = $tableField[0];
879 $condition['left']['field'] = $tableField[1];
881 $condition['left']['table'] = '';
882 $condition['left']['field'] = $tableField[0];
885 return $this->parseError('No join field found in parseFromTables()!', $parseString);
887 // Find "comparator":
888 $condition['comparator'] = $this->nextPart($parseString, '^(<=|>=|<|>|=|!=)');
889 if (($fieldName = $this->nextPart($parseString, '^([[:alnum:]._]+)')) !== '') {
890 // Parse field name into field and table:
891 $tableField = explode('.', $fieldName, 2);
892 $condition['right'] = array();
893 if (count($tableField) == 2) {
894 $condition['right']['table'] = $tableField[0];
895 $condition['right']['field'] = $tableField[1];
897 $condition['right']['table'] = '';
898 $condition['right']['field'] = $tableField[0];
901 return $this->parseError('No join field found in parseFromTables()!', $parseString);
903 $stack[$pnt]['JOIN'][$joinCnt]['ON'][] = $condition;
904 if (($operator = $this->nextPart($parseString, '^(AND|OR)')) !== '') {
905 $condition = array('operator' => $operator);
907 $parseCondition = FALSE;
912 return $this->parseError('No join table found in parseFromTables()!', $parseString);
915 // Looking for stop-keywords:
916 if ($stopRegex && ($this->lastStopKeyWord
= $this->nextPart($parseString, $stopRegex))) {
917 $this->lastStopKeyWord
= strtoupper(str_replace(array(' ', TAB
, CR
, LF
), '', $this->lastStopKeyWord
));
920 // Looking for comma:
921 if (strlen($parseString) && !$this->nextPart($parseString, '^(,)')) {
922 return $this->parseError('No comma found as expected in parseFromTables()', $parseString);
924 // Increasing pointer:
926 // Check recursivity brake:
928 if ($loopExit > 500) {
929 return $this->parseError('More than 500 loops, exiting prematurely in parseFromTables()...', $parseString);
932 // Return result array:
937 * Parsing the WHERE clause fields in the "WHERE [$parseString] ..." part of a query into a multidimensional array.
938 * The success of this parsing determines if that part of the query is supported by TYPO3.
940 * @param string $parseString WHERE clause to parse. NOTICE: passed by reference!
941 * @param string $stopRegex Regular expressing to STOP parsing, eg. '^(GROUP BY|ORDER BY|LIMIT)([[:space:]]*)'
942 * @param array $parameterReferences Array holding references to either named (:name) or question mark (?) parameters found
943 * @return mixed If successful parsing, returns an array, otherwise an error string.
945 public function parseWhereClause(&$parseString, $stopRegex = '', array &$parameterReferences = array()) {
946 // Prepare variables:
947 $parseString = $this->trimSQL($parseString);
948 $this->lastStopKeyWord
= '';
949 $this->parse_error
= '';
950 // Contains the parsed content
951 $stack = array(0 => array());
952 // Pointer to positions in $stack
953 $pnt = array(0 => 0);
954 // Determines parenthesis level
956 // Recursivity brake.
958 // $parseString is continously shortend by the process and we keep parsing it till it is zero:
959 while (strlen($parseString)) {
960 // Look for next parenthesis level:
961 $newLevel = $this->nextPart($parseString, '^([(])');
962 // If new level is started, manage stack/pointers:
963 if ($newLevel == '(') {
966 // Reset pointer for this level
968 // Reset stack for this level
969 $stack[$level] = array();
971 // If no new level is started, just parse the current level:
972 // Find "modifier", eg. "NOT or !"
973 $stack[$level][$pnt[$level]]['modifier'] = trim($this->nextPart($parseString, '^(!|NOT[[:space:]]+)'));
974 // See if condition is EXISTS with a subquery
975 if (preg_match('/^EXISTS[[:space:]]*[(]/i', $parseString)) {
976 $stack[$level][$pnt[$level]]['func']['type'] = $this->nextPart($parseString, '^(EXISTS)[[:space:]]*');
978 $parseString = trim(substr($parseString, 1));
979 $stack[$level][$pnt[$level]]['func']['subquery'] = $this->parseSELECT($parseString, $parameterReferences);
980 // Seek to new position in parseString after parsing of the subquery
981 $parseString = $stack[$level][$pnt[$level]]['func']['subquery']['parseString'];
982 unset($stack[$level][$pnt[$level]]['func']['subquery']['parseString']);
983 if (!$this->nextPart($parseString, '^([)])')) {
984 return 'No ) parenthesis at end of subquery';
987 // See if LOCATE function is found
988 if (preg_match('/^LOCATE[[:space:]]*[(]/i', $parseString)) {
989 $stack[$level][$pnt[$level]]['func']['type'] = $this->nextPart($parseString, '^(LOCATE)[[:space:]]*');
991 $parseString = trim(substr($parseString, 1));
992 $stack[$level][$pnt[$level]]['func']['substr'] = $this->getValue($parseString);
993 if (!$this->nextPart($parseString, '^(,)')) {
994 return $this->parseError('No comma found as expected in parseWhereClause()', $parseString);
996 if ($fieldName = $this->nextPart($parseString, '^([[:alnum:]\\*._]+)[[:space:]]*')) {
997 // Parse field name into field and table:
998 $tableField = explode('.', $fieldName, 2);
999 if (count($tableField) == 2) {
1000 $stack[$level][$pnt[$level]]['func']['table'] = $tableField[0];
1001 $stack[$level][$pnt[$level]]['func']['field'] = $tableField[1];
1003 $stack[$level][$pnt[$level]]['func']['table'] = '';
1004 $stack[$level][$pnt[$level]]['func']['field'] = $tableField[0];
1007 return $this->parseError('No field name found as expected in parseWhereClause()', $parseString);
1009 if ($this->nextPart($parseString, '^(,)')) {
1010 $stack[$level][$pnt[$level]]['func']['pos'] = $this->getValue($parseString);
1012 if (!$this->nextPart($parseString, '^([)])')) {
1013 return $this->parseError('No ) parenthesis at end of function', $parseString);
1015 } elseif (preg_match('/^IFNULL[[:space:]]*[(]/i', $parseString)) {
1016 $stack[$level][$pnt[$level]]['func']['type'] = $this->nextPart($parseString, '^(IFNULL)[[:space:]]*');
1017 $parseString = trim(substr($parseString, 1));
1019 if ($fieldName = $this->nextPart($parseString, '^([[:alnum:]\\*._]+)[[:space:]]*')) {
1020 // Parse field name into field and table:
1021 $tableField = explode('.', $fieldName, 2);
1022 if (count($tableField) == 2) {
1023 $stack[$level][$pnt[$level]]['func']['table'] = $tableField[0];
1024 $stack[$level][$pnt[$level]]['func']['field'] = $tableField[1];
1026 $stack[$level][$pnt[$level]]['func']['table'] = '';
1027 $stack[$level][$pnt[$level]]['func']['field'] = $tableField[0];
1030 return $this->parseError('No field name found as expected in parseWhereClause()', $parseString);
1032 if ($this->nextPart($parseString, '^(,)')) {
1033 $stack[$level][$pnt[$level]]['func']['default'] = $this->getValue($parseString);
1035 if (!$this->nextPart($parseString, '^([)])')) {
1036 return $this->parseError('No ) parenthesis at end of function', $parseString);
1038 } elseif (preg_match('/^FIND_IN_SET[[:space:]]*[(]/i', $parseString)) {
1039 $stack[$level][$pnt[$level]]['func']['type'] = $this->nextPart($parseString, '^(FIND_IN_SET)[[:space:]]*');
1041 $parseString = trim(substr($parseString, 1));
1042 if ($str = $this->getValue($parseString)) {
1043 $stack[$level][$pnt[$level]]['func']['str'] = $str;
1044 if ($fieldName = $this->nextPart($parseString, '^,[[:space:]]*([[:alnum:]._]+)[[:space:]]*', TRUE)) {
1045 // Parse field name into field and table:
1046 $tableField = explode('.', $fieldName, 2);
1047 if (count($tableField) == 2) {
1048 $stack[$level][$pnt[$level]]['func']['table'] = $tableField[0];
1049 $stack[$level][$pnt[$level]]['func']['field'] = $tableField[1];
1051 $stack[$level][$pnt[$level]]['func']['table'] = '';
1052 $stack[$level][$pnt[$level]]['func']['field'] = $tableField[0];
1055 return $this->parseError('No field name found as expected in parseWhereClause()', $parseString);
1057 if (!$this->nextPart($parseString, '^([)])')) {
1058 return $this->parseError('No ) parenthesis at end of function', $parseString);
1061 return $this->parseError('No item to look for found as expected in parseWhereClause()', $parseString);
1064 // Support calculated value only for:
1065 // - "&" (boolean AND)
1067 // - "-" (substraction)
1068 // - "*" (multiplication)
1071 $calcOperators = '&|\\+|-|\\*|\\/|%';
1073 if (($fieldName = $this->nextPart($parseString, '^([[:alnum:]._]+)([[:space:]]+|' . $calcOperators . '|<=|>=|<|>|=|!=|IS)')) !== '') {
1074 // Parse field name into field and table:
1075 $tableField = explode('.', $fieldName, 2);
1076 if (count($tableField) == 2) {
1077 $stack[$level][$pnt[$level]]['table'] = $tableField[0];
1078 $stack[$level][$pnt[$level]]['field'] = $tableField[1];
1080 $stack[$level][$pnt[$level]]['table'] = '';
1081 $stack[$level][$pnt[$level]]['field'] = $tableField[0];
1084 return $this->parseError('No field name found as expected in parseWhereClause()', $parseString);
1086 // See if the value is calculated:
1087 $stack[$level][$pnt[$level]]['calc'] = $this->nextPart($parseString, '^(' . $calcOperators . ')');
1088 if (strlen($stack[$level][$pnt[$level]]['calc'])) {
1089 // Finding value for calculation:
1090 $calc_value = $this->getValue($parseString);
1091 $stack[$level][$pnt[$level]]['calc_value'] = $calc_value;
1092 if (count($calc_value) == 1 && is_string($calc_value[0])) {
1093 // Value is a field, store it to allow DBAL to post-process it (quoting, remapping)
1094 $tableField = explode('.', $calc_value[0], 2);
1095 if (count($tableField) == 2) {
1096 $stack[$level][$pnt[$level]]['calc_table'] = $tableField[0];
1097 $stack[$level][$pnt[$level]]['calc_field'] = $tableField[1];
1099 $stack[$level][$pnt[$level]]['calc_table'] = '';
1100 $stack[$level][$pnt[$level]]['calc_field'] = $tableField[0];
1105 // Find "comparator":
1106 $comparatorPatterns = array(
1114 'NOT[[:space:]]+IN',
1116 'NOT[[:space:]]+LIKE[[:space:]]+BINARY',
1117 'LIKE[[:space:]]+BINARY',
1118 'NOT[[:space:]]+LIKE',
1120 'IS[[:space:]]+NOT',
1123 'NOT[[:space]]+BETWEEN'
1125 $stack[$level][$pnt[$level]]['comparator'] = $this->nextPart($parseString, '^(' . implode('|', $comparatorPatterns) . ')');
1126 if (strlen($stack[$level][$pnt[$level]]['comparator'])) {
1127 if (preg_match('/^CONCAT[[:space:]]*\\(/', $parseString)) {
1128 $this->nextPart($parseString, '^(CONCAT[[:space:]]?[(])');
1130 'operator' => 'CONCAT',
1134 while ($fieldName = $this->nextPart($parseString, '^([[:alnum:]._]+)')) {
1135 // Parse field name into field and table:
1136 $tableField = explode('.', $fieldName, 2);
1137 if (count($tableField) == 2) {
1138 $values['args'][$cnt]['table'] = $tableField[0];
1139 $values['args'][$cnt]['field'] = $tableField[1];
1141 $values['args'][$cnt]['table'] = '';
1142 $values['args'][$cnt]['field'] = $tableField[0];
1144 // Looking for comma:
1145 $this->nextPart($parseString, '^(,)');
1148 // Look for ending parenthesis:
1149 $this->nextPart($parseString, '([)])');
1150 $stack[$level][$pnt[$level]]['value'] = $values;
1152 if (\TYPO3\CMS\Core\Utility\GeneralUtility
::inList('IN,NOT IN', $stack[$level][$pnt[$level]]['comparator']) && preg_match('/^[(][[:space:]]*SELECT[[:space:]]+/', $parseString)) {
1153 $this->nextPart($parseString, '^([(])');
1154 $stack[$level][$pnt[$level]]['subquery'] = $this->parseSELECT($parseString, $parameterReferences);
1155 // Seek to new position in parseString after parsing of the subquery
1156 $parseString = $stack[$level][$pnt[$level]]['subquery']['parseString'];
1157 unset($stack[$level][$pnt[$level]]['subquery']['parseString']);
1158 if (!$this->nextPart($parseString, '^([)])')) {
1159 return 'No ) parenthesis at end of subquery';
1162 if (\TYPO3\CMS\Core\Utility\GeneralUtility
::inList('BETWEEN,NOT BETWEEN', $stack[$level][$pnt[$level]]['comparator'])) {
1163 $stack[$level][$pnt[$level]]['values'] = array();
1164 $stack[$level][$pnt[$level]]['values'][0] = $this->getValue($parseString);
1165 if (!$this->nextPart($parseString, '^(AND)')) {
1166 return $this->parseError('No AND operator found as expected in parseWhereClause()', $parseString);
1168 $stack[$level][$pnt[$level]]['values'][1] = $this->getValue($parseString);
1170 // Finding value for comparator:
1171 $stack[$level][$pnt[$level]]['value'] = &$this->getValueOrParameter($parseString, $stack[$level][$pnt[$level]]['comparator'], '', $parameterReferences);
1172 if ($this->parse_error
) {
1173 return $this->parse_error
;
1180 // Finished, increase pointer:
1182 // Checking if we are back to level 0 and we should still decrease level,
1183 // meaning we were probably parsing as subquery and should return here:
1184 if ($level === 0 && preg_match('/^[)]/', $parseString)) {
1185 // Return the stacks lowest level:
1188 // Checking if we are back to level 0 and we should still decrease level,
1189 // meaning we were probably parsing a subquery and should return here:
1190 if ($level === 0 && preg_match('/^[)]/', $parseString)) {
1191 // Return the stacks lowest level:
1194 // Checking if the current level is ended, in that case do stack management:
1195 while ($this->nextPart($parseString, '^([)])')) {
1199 $stack[$level][$pnt[$level]]['sub'] = $stack[$level +
1];
1200 // Increase pointer of the new level
1202 // Make recursivity check:
1204 if ($loopExit > 500) {
1205 return $this->parseError('More than 500 loops (in search for exit parenthesis), exiting prematurely in parseWhereClause()...', $parseString);
1208 // Detecting the operator for the next level:
1209 $op = $this->nextPart($parseString, '^(AND[[:space:]]+NOT|&&[[:space:]]+NOT|OR[[:space:]]+NOT|OR[[:space:]]+NOT|\\|\\|[[:space:]]+NOT|AND|&&|OR|\\|\\|)(\\(|[[:space:]]+)');
1211 // Normalize boolean operator
1212 $op = str_replace(array('&&', '||'), array('AND', 'OR'), $op);
1213 $stack[$level][$pnt[$level]]['operator'] = $op;
1214 } elseif (strlen($parseString)) {
1215 // Looking for stop-keywords:
1216 if ($stopRegex && ($this->lastStopKeyWord
= $this->nextPart($parseString, $stopRegex))) {
1217 $this->lastStopKeyWord
= strtoupper(str_replace(array(' ', TAB
, CR
, LF
), '', $this->lastStopKeyWord
));
1220 return $this->parseError('No operator, but parsing not finished in parseWhereClause().', $parseString);
1224 // Make recursivity check:
1226 if ($loopExit > 500) {
1227 return $this->parseError('More than 500 loops, exiting prematurely in parseWhereClause()...', $parseString);
1230 // Return the stacks lowest level:
1235 * Parsing the WHERE clause fields in the "WHERE [$parseString] ..." part of a query into a multidimensional array.
1236 * The success of this parsing determines if that part of the query is supported by TYPO3.
1238 * @param string $parseString WHERE clause to parse. NOTICE: passed by reference!
1239 * @param string $stopRegex Regular expressing to STOP parsing, eg. '^(GROUP BY|ORDER BY|LIMIT)([[:space:]]*)'
1240 * @return mixed If successful parsing, returns an array, otherwise an error string.
1242 public function parseFieldDef(&$parseString, $stopRegex = '') {
1243 // Prepare variables:
1244 $parseString = $this->trimSQL($parseString);
1245 $this->lastStopKeyWord
= '';
1246 $this->parse_error
= '';
1249 if ($result['fieldType'] = $this->nextPart($parseString, '^(int|smallint|tinyint|mediumint|bigint|double|numeric|decimal|float|varchar|char|text|tinytext|mediumtext|longtext|blob|tinyblob|mediumblob|longblob)([[:space:],]+|\\()')) {
1250 // Looking for value:
1251 if (substr($parseString, 0, 1) == '(') {
1252 $parseString = substr($parseString, 1);
1253 if ($result['value'] = $this->nextPart($parseString, '^([^)]*)')) {
1254 $parseString = ltrim(substr($parseString, 1));
1256 return $this->parseError('No end-parenthesis for value found in parseFieldDef()!', $parseString);
1259 // Looking for keywords
1260 while ($keyword = $this->nextPart($parseString, '^(DEFAULT|NOT[[:space:]]+NULL|AUTO_INCREMENT|UNSIGNED)([[:space:]]+|,|\\))')) {
1261 $keywordCmp = strtoupper(str_replace(array(' ', TAB
, CR
, LF
), '', $keyword));
1262 $result['featureIndex'][$keywordCmp]['keyword'] = $keyword;
1263 switch ($keywordCmp) {
1265 $result['featureIndex'][$keywordCmp]['value'] = $this->getValue($parseString);
1270 return $this->parseError('Field type unknown in parseFieldDef()!', $parseString);
1275 /************************************
1277 * Parsing: Helper functions
1279 ************************************/
1281 * Strips off a part of the parseString and returns the matching part.
1282 * Helper function for the parsing methods.
1284 * @param string $parseString Parse string; if $regex finds anything the value of the first () level will be stripped of the string in the beginning. Further $parseString is left-trimmed (on success). Notice; parsestring is passed by reference.
1285 * @param string $regex Regex to find a matching part in the beginning of the string. Rules: You MUST start the regex with "^" (finding stuff in the beginning of string) and the result of the first parenthesis is what will be returned to you (and stripped of the string). Eg. '^(AND|OR|&&)[[:space:]]+' will return AND, OR or && if found and having one of more whitespaces after it, plus shorten $parseString with that match and any space after (by ltrim())
1286 * @param boolean $trimAll If set the full match of the regex is stripped of the beginning of the string!
1287 * @return string The value of the first parenthesis level of the REGEX.
1289 protected function nextPart(&$parseString, $regex, $trimAll = FALSE) {
1291 // Adding space char because [[:space:]]+ is often a requirement in regex's
1292 if (preg_match('/' . $regex . '/i', $parseString . ' ', $reg)) {
1293 $parseString = ltrim(substr($parseString, strlen($reg[$trimAll ?
0 : 1])));
1301 * Finds value or either named (:name) or question mark (?) parameter markers at the beginning
1302 * of $parseString, returns result and strips it of parseString.
1303 * This method returns a pointer to the parameter or value that was found. In case of a parameter
1304 * the pointer is a reference to the corresponding item in array $parameterReferences.
1306 * @param string $parseString The parseString
1307 * @param string $comparator The comparator used before.
1308 * @param string $mode The mode, e.g., "INDEX
1309 * @param mixed The value (string/integer) or parameter (:name/?). Otherwise an array with error message in first key (0)
1311 protected function &getValueOrParameter(&$parseString, $comparator = '', $mode = '', array &$parameterReferences = array()) {
1312 $parameter = $this->nextPart($parseString, '^(\\:[[:alnum:]_]+|\\?)');
1313 if ($parameter === '?') {
1314 if (!isset($parameterReferences['?'])) {
1315 $parameterReferences['?'] = array();
1317 $value = array('?');
1318 $parameterReferences['?'][] = &$value;
1319 } elseif ($parameter !== '') {
1321 if (isset($parameterReferences[$parameter])) {
1322 // Use the same reference as last time we encountered this parameter
1323 $value = &$parameterReferences[$parameter];
1325 $value = array($parameter);
1326 $parameterReferences[$parameter] = &$value;
1329 $value = $this->getValue($parseString, $comparator, $mode);
1335 * Finds value in beginning of $parseString, returns result and strips it of parseString
1337 * @param string $parseString The parseString, eg. "(0,1,2,3) ..." or "('asdf','qwer') ..." or "1234 ..." or "'My string value here' ...
1338 * @param string $comparator The comparator used before. If "NOT IN" or "IN" then the value is expected to be a list of values. Otherwise just an integer (un-quoted) or string (quoted)
1339 * @param string $mode The mode, eg. "INDEX
1340 * @return mixed The value (string/integer). Otherwise an array with error message in first key (0)
1342 protected function getValue(&$parseString, $comparator = '', $mode = '') {
1344 if (\TYPO3\CMS\Core\Utility\GeneralUtility
::inList('NOTIN,IN,_LIST', strtoupper(str_replace(array(' ', LF
, CR
, TAB
), '', $comparator)))) {
1346 if ($this->nextPart($parseString, '^([(])')) {
1347 $listValues = array();
1349 while ($comma == ',') {
1350 $listValues[] = $this->getValue($parseString);
1351 if ($mode === 'INDEX') {
1352 // Remove any length restriction on INDEX definition
1353 $this->nextPart($parseString, '^([(]\\d+[)])');
1355 $comma = $this->nextPart($parseString, '^([,])');
1357 $out = $this->nextPart($parseString, '^([)])');
1359 if ($comparator == '_LIST') {
1361 foreach ($listValues as $vArr) {
1362 $kVals[] = $vArr[0];
1369 return array($this->parseError('No ) parenthesis in list', $parseString));
1372 return array($this->parseError('No ( parenthesis starting the list', $parseString));
1375 // Just plain string value, in quotes or not:
1377 $firstChar = substr($parseString, 0, 1);
1378 switch ($firstChar) {
1380 $value = array($this->getValueInQuotes($parseString, '"'), '"');
1383 $value = array($this->getValueInQuotes($parseString, '\''), '\'');
1387 if (preg_match('/^([[:alnum:]._-]+)/i', $parseString, $reg)) {
1388 $parseString = ltrim(substr($parseString, strlen($reg[0])));
1389 $value = array($reg[1]);
1398 * Get value in quotes from $parseString.
1399 * NOTICE: If a query being parsed was prepared for another database than MySQL this function should probably be changed
1401 * @param string $parseString String from which to find value in quotes. Notice that $parseString is passed by reference and is shortend by the output of this function.
1402 * @param string $quote The quote used; input either " or '
1403 * @return string The value, passed through stripslashes() !
1405 protected function getValueInQuotes(&$parseString, $quote) {
1406 $parts = explode($quote, substr($parseString, 1));
1408 foreach ($parts as $k => $v) {
1411 preg_match('/\\\\$/', $v, $reg);
1412 if ($reg and strlen($reg[0]) %
2) {
1415 $parseString = ltrim(substr($parseString, strlen($buffer) +
2));
1416 return $this->parseStripslashes($buffer);
1422 * Strip slashes function used for parsing
1423 * NOTICE: If a query being parsed was prepared for another database than MySQL this function should probably be changed
1425 * @param string $str Input string
1426 * @return string Output string
1428 protected function parseStripslashes($str) {
1429 $search = array('\\\\', '\\\'', '\\"', '\0', '\n', '\r', '\Z');
1430 $replace = array('\\', '\'', '"', "\x00", "\x0a", "\x0d", "\x1a");
1432 return str_replace($search, $replace, $str);
1436 * Add slashes function used for compiling queries
1437 * NOTICE: If a query being parsed was prepared for another database than MySQL this function should probably be changed
1439 * @param string $str Input string
1440 * @return string Output string
1442 protected function compileAddslashes($str) {
1443 $search = array('\\', '\'', '"', "\x00", "\x0a", "\x0d", "\x1a");
1444 $replace = array('\\\\', '\\\'', '\\"', '\0', '\n', '\r', '\Z');
1446 return str_replace($search, $replace, $str);
1450 * Setting the internal error message value, $this->parse_error and returns that value.
1452 * @param string $msg Input error message
1453 * @param string $restQuery Remaining query to parse.
1454 * @return string Error message.
1456 protected function parseError($msg, $restQuery) {
1457 $this->parse_error
= 'SQL engine parse ERROR: ' . $msg . ': near "' . substr($restQuery, 0, 50) . '"';
1458 return $this->parse_error
;
1462 * Trimming SQL as preparation for parsing.
1463 * ";" in the end is stripped of.
1464 * White space is trimmed away around the value
1465 * A single space-char is added in the end
1467 * @param string $str Input string
1468 * @return string Output string
1470 protected function trimSQL($str) {
1471 return rtrim(rtrim(trim($str), ';')) . ' ';
1474 /*************************
1478 *************************/
1480 * Compiles an SQL query from components
1482 * @param array $components Array of SQL query components
1483 * @return string SQL query
1486 public function compileSQL($components) {
1487 switch ($components['type']) {
1489 $query = $this->compileSELECT($components);
1492 $query = $this->compileUPDATE($components);
1495 $query = $this->compileINSERT($components);
1498 $query = $this->compileDELETE($components);
1501 $query = 'EXPLAIN ' . $this->compileSELECT($components);
1504 $query = 'DROP TABLE' . ($components['ifExists'] ?
' IF EXISTS' : '') . ' ' . $components['TABLE'];
1507 $query = $this->compileCREATETABLE($components);
1510 $query = $this->compileALTERTABLE($components);
1512 case 'TRUNCATETABLE':
1513 $query = $this->compileTRUNCATETABLE($components);
1520 * Compiles a SELECT statement from components array
1522 * @param array $components Array of SQL query components
1523 * @return string SQL SELECT query
1524 * @see parseSELECT()
1526 protected function compileSELECT($components) {
1528 $where = $this->compileWhereClause($components['WHERE']);
1529 $groupBy = $this->compileFieldList($components['GROUPBY']);
1530 $orderBy = $this->compileFieldList($components['ORDERBY']);
1531 $limit = $components['LIMIT'];
1533 $query = 'SELECT ' . ($components['STRAIGHT_JOIN'] ?
$components['STRAIGHT_JOIN'] . '' : '') . '
1534 ' . $this->compileFieldList($components['SELECT']) . '
1535 FROM ' . $this->compileFromTables($components['FROM']) . (strlen($where) ?
'
1536 WHERE ' . $where : '') . (strlen($groupBy) ?
'
1537 GROUP BY ' . $groupBy : '') . (strlen($orderBy) ?
'
1538 ORDER BY ' . $orderBy : '') . (strlen($limit) ?
'
1539 LIMIT ' . $limit : '');
1544 * Compiles an UPDATE statement from components array
1546 * @param array $components Array of SQL query components
1547 * @return string SQL UPDATE query
1548 * @see parseUPDATE()
1550 protected function compileUPDATE($components) {
1552 $where = $this->compileWhereClause($components['WHERE']);
1555 foreach ($components['FIELDS'] as $fN => $fV) {
1556 $fields[] = $fN . '=' . $fV[1] . $this->compileAddslashes($fV[0]) . $fV[1];
1559 $query = 'UPDATE ' . $components['TABLE'] . ' SET
1562 ' . (strlen($where) ?
'
1563 WHERE ' . $where : '');
1568 * Compiles an INSERT statement from components array
1570 * @param array $components Array of SQL query components
1571 * @return string SQL INSERT query
1572 * @see parseINSERT()
1574 protected function compileINSERT($components) {
1576 if (isset($components['VALUES_ONLY']) && is_array($components['VALUES_ONLY'])) {
1577 $valuesComponents = $components['EXTENDED'] === '1' ?
$components['VALUES_ONLY'] : array($components['VALUES_ONLY']);
1578 $tableFields = array();
1580 $valuesComponents = $components['EXTENDED'] === '1' ?
$components['FIELDS'] : array($components['FIELDS']);
1581 $tableFields = array_keys($valuesComponents[0]);
1583 foreach ($valuesComponents as $valuesComponent) {
1585 foreach ($valuesComponent as $fV) {
1586 $fields[] = $fV[1] . $this->compileAddslashes($fV[0]) . $fV[1];
1588 $values[] = '(' . implode(',
1592 $query = 'INSERT INTO ' . $components['TABLE'];
1593 if (count($tableFields)) {
1596 ', $tableFields) . ')';
1606 * Compiles an DELETE statement from components array
1608 * @param array $components Array of SQL query components
1609 * @return string SQL DELETE query
1610 * @see parseDELETE()
1612 protected function compileDELETE($components) {
1614 $where = $this->compileWhereClause($components['WHERE']);
1616 $query = 'DELETE FROM ' . $components['TABLE'] . (strlen($where) ?
'
1617 WHERE ' . $where : '');
1622 * Compiles a CREATE TABLE statement from components array
1624 * @param array $components Array of SQL query components
1625 * @return string SQL CREATE TABLE query
1626 * @see parseCREATETABLE()
1628 protected function compileCREATETABLE($components) {
1629 // Create fields and keys:
1630 $fieldsKeys = array();
1631 foreach ($components['FIELDS'] as $fN => $fCfg) {
1632 $fieldsKeys[] = $fN . ' ' . $this->compileFieldCfg($fCfg['definition']);
1634 foreach ($components['KEYS'] as $kN => $kCfg) {
1635 if ($kN === 'PRIMARYKEY') {
1636 $fieldsKeys[] = 'PRIMARY KEY (' . implode(',', $kCfg) . ')';
1637 } elseif ($kN === 'UNIQUE') {
1639 $fields = current($kCfg);
1640 $fieldsKeys[] = 'UNIQUE KEY ' . $key . ' (' . implode(',', $fields) . ')';
1642 $fieldsKeys[] = 'KEY ' . $kN . ' (' . implode(',', $kCfg) . ')';
1646 $query = 'CREATE TABLE ' . $components['TABLE'] . ' (
1649 )' . ($components['tableType'] ?
' TYPE=' . $components['tableType'] : '');
1654 * Compiles an ALTER TABLE statement from components array
1656 * @param array $components Array of SQL query components
1657 * @return string SQL ALTER TABLE query
1658 * @see parseALTERTABLE()
1660 protected function compileALTERTABLE($components) {
1662 $query = 'ALTER TABLE ' . $components['TABLE'] . ' ' . $components['action'] . ' ' . ($components['FIELD'] ?
$components['FIELD'] : $components['KEY']);
1663 // Based on action, add the final part:
1664 switch (strtoupper(str_replace(array(' ', TAB
, CR
, LF
), '', $components['action']))) {
1666 $query .= ' ' . $this->compileFieldCfg($components['definition']);
1669 $query .= ' ' . $components['newField'] . ' ' . $this->compileFieldCfg($components['definition']);
1677 case 'ADDPRIMARYKEY':
1680 $query .= ' (' . implode(',', $components['fields']) . ')';
1682 case 'DEFAULTCHARACTERSET':
1683 $query .= $components['charset'];
1686 $query .= '= ' . $components['engine'];
1694 * Compiles a TRUNCATE TABLE statement from components array
1696 * @param array $components Array of SQL query components
1697 * @return string SQL TRUNCATE TABLE query
1698 * @see parseTRUNCATETABLE()
1700 protected function compileTRUNCATETABLE(array $components) {
1702 $query = 'TRUNCATE TABLE ' . $components['TABLE'];
1707 /**************************************
1709 * Compiling queries, helper functions for parts of queries
1711 **************************************/
1713 * Compiles a "SELECT [output] FROM..:" field list based on input array (made with ->parseFieldList())
1714 * Can also compile field lists for ORDER BY and GROUP BY.
1716 * @param array $selectFields Array of select fields, (made with ->parseFieldList())
1717 * @param boolean $compileComments Whether comments should be compiled
1718 * @return string Select field string
1719 * @see parseFieldList()
1721 public function compileFieldList($selectFields, $compileComments = TRUE) {
1722 // Prepare buffer variable:
1724 // Traverse the selectFields if any:
1725 if (is_array($selectFields)) {
1726 $outputParts = array();
1727 foreach ($selectFields as $k => $v) {
1729 switch ($v['type']) {
1731 $outputParts[$k] = $v['function'] . '(' . $v['func_content'] . ')';
1733 case 'flow-control':
1734 if ($v['flow-control']['type'] === 'CASE') {
1735 $outputParts[$k] = $this->compileCaseStatement($v['flow-control']);
1739 $outputParts[$k] = ($v['distinct'] ?
$v['distinct'] : '') . ($v['table'] ?
$v['table'] . '.' : '') . $v['field'];
1744 $outputParts[$k] .= ' ' . $v['as_keyword'] . ' ' . $v['as'];
1746 // Specifically for ORDER BY and GROUP BY field lists:
1747 if ($v['sortDir']) {
1748 $outputParts[$k] .= ' ' . $v['sortDir'];
1751 if ($compileComments && $selectFields[0]['comments']) {
1752 $fields = $selectFields[0]['comments'] . ' ';
1754 $fields .= implode(', ', $outputParts);
1760 * Compiles a CASE ... WHEN flow-control construct based on input array (made with ->parseCaseStatement())
1762 * @param array $components Array of case components, (made with ->parseCaseStatement())
1763 * @return string Case when string
1764 * @see parseCaseStatement()
1766 protected function compileCaseStatement(array $components) {
1767 $statement = 'CASE';
1768 if (isset($components['case_field'])) {
1769 $statement .= ' ' . $components['case_field'];
1770 } elseif (isset($components['case_value'])) {
1771 $statement .= ' ' . $components['case_value'][1] . $components['case_value'][0] . $components['case_value'][1];
1773 foreach ($components['when'] as $when) {
1774 $statement .= ' WHEN ';
1775 $statement .= $this->compileWhereClause($when['when_value']);
1776 $statement .= ' THEN ';
1777 $statement .= $when['then_value'][1] . $when['then_value'][0] . $when['then_value'][1];
1779 if (isset($components['else'])) {
1780 $statement .= ' ELSE ';
1781 $statement .= $components['else'][1] . $components['else'][0] . $components['else'][1];
1783 $statement .= ' END';
1788 * Compiles a "FROM [output] WHERE..:" table list based on input array (made with ->parseFromTables())
1790 * @param array $tablesArray Array of table names, (made with ->parseFromTables())
1791 * @return string Table name string
1792 * @see parseFromTables()
1794 public function compileFromTables($tablesArray) {
1795 // Prepare buffer variable:
1796 $outputParts = array();
1797 // Traverse the table names:
1798 if (is_array($tablesArray)) {
1799 foreach ($tablesArray as $k => $v) {
1801 $outputParts[$k] = $v['table'];
1802 // Add alias AS if there:
1804 $outputParts[$k] .= ' ' . $v['as_keyword'] . ' ' . $v['as'];
1806 if (is_array($v['JOIN'])) {
1807 foreach ($v['JOIN'] as $join) {
1808 $outputParts[$k] .= ' ' . $join['type'] . ' ' . $join['withTable'];
1809 // Add alias AS if there:
1810 if (isset($join['as']) && $join['as']) {
1811 $outputParts[$k] .= ' ' . $join['as_keyword'] . ' ' . $join['as'];
1813 $outputParts[$k] .= ' ON ';
1814 foreach ($join['ON'] as $condition) {
1815 if ($condition['operator'] !== '') {
1816 $outputParts[$k] .= ' ' . $condition['operator'] . ' ';
1818 $outputParts[$k] .= $condition['left']['table'] ?
$condition['left']['table'] . '.' : '';
1819 $outputParts[$k] .= $condition['left']['field'];
1820 $outputParts[$k] .= $condition['comparator'];
1821 $outputParts[$k] .= $condition['right']['table'] ?
$condition['right']['table'] . '.' : '';
1822 $outputParts[$k] .= $condition['right']['field'];
1828 // Return imploded buffer:
1829 return implode(', ', $outputParts);
1833 * Implodes an array of WHERE clause configuration into a WHERE clause.
1835 * @param array $clauseArray WHERE clause configuration
1836 * @return string WHERE clause as string.
1837 * @see explodeWhereClause()
1839 public function compileWhereClause($clauseArray) {
1840 // Prepare buffer variable:
1842 // Traverse clause array:
1843 if (is_array($clauseArray)) {
1844 foreach ($clauseArray as $k => $v) {
1846 $output .= $v['operator'] ?
' ' . $v['operator'] : '';
1847 // Look for sublevel:
1848 if (is_array($v['sub'])) {
1849 $output .= ' (' . trim($this->compileWhereClause($v['sub'])) . ')';
1850 } elseif (isset($v['func']) && $v['func']['type'] === 'EXISTS') {
1851 $output .= ' ' . trim($v['modifier']) . ' EXISTS (' . $this->compileSELECT($v['func']['subquery']) . ')';
1853 if (isset($v['func']) && $v['func']['type'] === 'LOCATE') {
1854 $output .= ' ' . trim($v['modifier']) . ' LOCATE(';
1855 $output .= $v['func']['substr'][1] . $v['func']['substr'][0] . $v['func']['substr'][1];
1856 $output .= ', ' . ($v['func']['table'] ?
$v['func']['table'] . '.' : '') . $v['func']['field'];
1857 $output .= isset($v['func']['pos']) ?
', ' . $v['func']['pos'][0] : '';
1859 } elseif (isset($v['func']) && $v['func']['type'] === 'IFNULL') {
1860 $output .= ' ' . trim($v['modifier']) . ' IFNULL(';
1861 $output .= ($v['func']['table'] ?
$v['func']['table'] . '.' : '') . $v['func']['field'];
1862 $output .= ', ' . $v['func']['default'][1] . $this->compileAddslashes($v['func']['default'][0]) . $v['func']['default'][1];
1864 } elseif (isset($v['func']) && $v['func']['type'] === 'FIND_IN_SET') {
1865 $output .= ' ' . trim($v['modifier']) . ' FIND_IN_SET(';
1866 $output .= $v['func']['str'][1] . $v['func']['str'][0] . $v['func']['str'][1];
1867 $output .= ', ' . ($v['func']['table'] ?
$v['func']['table'] . '.' : '') . $v['func']['field'];
1870 // Set field/table with modifying prefix if any:
1871 $output .= ' ' . trim(($v['modifier'] . ' ' . ($v['table'] ?
$v['table'] . '.' : '') . $v['field']));
1872 // Set calculation, if any:
1874 $output .= $v['calc'] . $v['calc_value'][1] . $this->compileAddslashes($v['calc_value'][0]) . $v['calc_value'][1];
1878 if ($v['comparator']) {
1879 $output .= ' ' . $v['comparator'];
1880 // Detecting value type; list or plain:
1881 if (\TYPO3\CMS\Core\Utility\GeneralUtility
::inList('NOTIN,IN', strtoupper(str_replace(array(' ', TAB
, CR
, LF
), '', $v['comparator'])))) {
1882 if (isset($v['subquery'])) {
1883 $output .= ' (' . $this->compileSELECT($v['subquery']) . ')';
1885 $valueBuffer = array();
1886 foreach ($v['value'] as $realValue) {
1887 $valueBuffer[] = $realValue[1] . $this->compileAddslashes($realValue[0]) . $realValue[1];
1889 $output .= ' (' . trim(implode(',', $valueBuffer)) . ')';
1892 if (\TYPO3\CMS\Core\Utility\GeneralUtility
::inList('BETWEEN,NOT BETWEEN', $v['comparator'])) {
1893 $lbound = $v['values'][0];
1894 $ubound = $v['values'][1];
1895 $output .= ' ' . $lbound[1] . $this->compileAddslashes($lbound[0]) . $lbound[1];
1897 $output .= $ubound[1] . $this->compileAddslashes($ubound[0]) . $ubound[1];
1899 if (isset($v['value']['operator'])) {
1901 foreach ($v['value']['args'] as $fieldDef) {
1902 $values[] = ($fieldDef['table'] ?
$fieldDef['table'] . '.' : '') . $fieldDef['field'];
1904 $output .= ' ' . $v['value']['operator'] . '(' . implode(',', $values) . ')';
1906 $output .= ' ' . $v['value'][1] . $this->compileAddslashes($v['value'][0]) . $v['value'][1];
1914 // Return output buffer:
1919 * Compile field definition
1921 * @param array $fieldCfg Field definition parts
1922 * @return string Field definition string
1924 public function compileFieldCfg($fieldCfg) {
1926 $cfg = $fieldCfg['fieldType'];
1927 // Add value, if any:
1928 if (strlen($fieldCfg['value'])) {
1929 $cfg .= '(' . $fieldCfg['value'] . ')';
1931 // Add additional features:
1932 if (is_array($fieldCfg['featureIndex'])) {
1933 foreach ($fieldCfg['featureIndex'] as $featureDef) {
1934 $cfg .= ' ' . $featureDef['keyword'];
1935 // Add value if found:
1936 if (is_array($featureDef['value'])) {
1937 $cfg .= ' ' . $featureDef['value'][1] . $this->compileAddslashes($featureDef['value'][0]) . $featureDef['value'][1];
1941 // Return field definition string:
1945 /*************************
1949 *************************/
1951 * Check parsability of input SQL part string; Will parse and re-compile after which it is compared
1953 * @param string $part Part definition of string; "SELECT" = fieldlist (also ORDER BY and GROUP BY), "FROM" = table list, "WHERE" = Where clause.
1954 * @param string $str SQL string to verify parsability of
1955 * @return mixed Returns array with string 1 and 2 if error, otherwise FALSE
1957 public function debug_parseSQLpart($part, $str) {
1961 $retVal = $this->debug_parseSQLpartCompare($str, $this->compileFieldList($this->parseFieldList($str)));
1964 $retVal = $this->debug_parseSQLpartCompare($str, $this->compileFromTables($this->parseFromTables($str)));
1967 $retVal = $this->debug_parseSQLpartCompare($str, $this->compileWhereClause($this->parseWhereClause($str)));
1974 * Compare two query strins by stripping away whitespace.
1976 * @param string $str SQL String 1
1977 * @param string $newStr SQL string 2
1978 * @param boolean $caseInsensitive If TRUE, the strings are compared insensitive to case
1979 * @return mixed Returns array with string 1 and 2 if error, otherwise FALSE
1981 public function debug_parseSQLpartCompare($str, $newStr, $caseInsensitive = FALSE) {
1982 if ($caseInsensitive) {
1983 $str1 = strtoupper($str);
1984 $str2 = strtoupper($newStr);
1990 // Fixing escaped chars:
1991 $search = array('\0', '\n', '\r', '\Z');
1992 $replace = array("\x00", "\x0a", "\x0d", "\x1a");
1993 $str1 = str_replace($search, $replace, $str1);
1994 $str2 = str_replace($search, $replace, $str2);
1996 if (strcmp(str_replace(array(' ', TAB
, CR
, LF
), '', $this->trimSQL($str1)), str_replace(array(' ', TAB
, CR
, LF
), '', $this->trimSQL($str2)))) {
1998 str_replace(array(' ', TAB
, CR
, LF
), ' ', $str),
1999 str_replace(array(' ', TAB
, CR
, LF
), ' ', $newStr),
2005 * Performs the ultimate test of the parser: Direct a SQL query in; You will get it back (through the parsed and re-compiled) if no problems, otherwise the script will print the error and exit
2007 * @param string $SQLquery SQL query
2008 * @return string Query if all is well, otherwise exit.
2010 public function debug_testSQL($SQLquery) {
2011 // Getting result array:
2012 $parseResult = $this->parseSQL($SQLquery);
2013 // If result array was returned, proceed. Otherwise show error and exit.
2014 if (is_array($parseResult)) {
2015 // Re-compile query:
2016 $newQuery = $this->compileSQL($parseResult);
2017 // TEST the new query:
2018 $testResult = $this->debug_parseSQLpartCompare($SQLquery, $newQuery);
2019 // Return new query if OK, otherwise show error and exit:
2020 if (!is_array($testResult)) {
2023 debug(array('ERROR MESSAGE' => 'Input query did not match the parsed and recompiled query exactly (not observing whitespace)', 'TEST result' => $testResult), 'SQL parsing failed:');
2027 debug(array('query' => $SQLquery, 'ERROR MESSAGE' => $parseResult), 'SQL parsing failed:');