2 /***************************************************************
5 * (c) 2004 Kasper Skaarhoj (kasperYYYY@typo3.com)
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
32 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
35 * [CLASS/FUNCTION INDEX of SCRIPT]
39 * 106: class t3lib_sqlparser
41 * SECTION: SQL Parsing, full queries
42 * 128: function parseSQL($parseString)
43 * 188: function parseSELECT($parseString)
44 * 257: function parseUPDATE($parseString)
45 * 311: function parseINSERT($parseString)
46 * 371: function parseDELETE($parseString)
47 * 409: function parseEXPLAIN($parseString)
48 * 431: function parseCREATETABLE($parseString)
49 * 503: function parseALTERTABLE($parseString)
50 * 572: function parseDROPTABLE($parseString)
52 * SECTION: SQL Parsing, helper functions for parts of queries
53 * 631: function parseFieldList(&$parseString, $stopRegex='')
54 * 749: function parseFromTables(&$parseString, $stopRegex='')
55 * 816: function parseWhereClause(&$parseString, $stopRegex='')
56 * 924: function parseFieldDef(&$parseString, $stopRegex='')
58 * SECTION: Parsing: Helper functions
59 * 985: function nextPart(&$parseString,$regex,$trimAll=FALSE)
60 * 999: function getValue(&$parseString,$comparator='')
61 * 1054: function getValueInQuotes(&$parseString,$quote)
62 * 1079: function parseStripslashes($str)
63 * 1093: function compileAddslashes($str)
64 * 1107: function parseError($msg,$restQuery)
65 * 1121: function trimSQL($str)
67 * SECTION: Compiling queries
68 * 1149: function compileSQL($components)
69 * 1187: function compileSELECT($components)
70 * 1218: function compileUPDATE($components)
71 * 1246: function compileINSERT($components)
72 * 1286: function compileDELETE($components)
73 * 1306: function compileCREATETABLE($components)
74 * 1337: function compileALTERTABLE($components)
76 * SECTION: Compiling queries, helper functions for parts of queries
77 * 1390: function compileFieldList($selectFields)
78 * 1432: function compileFromTables($tablesArray)
79 * 1468: function compileWhereClause($clauseArray)
80 * 1522: function compileFieldCfg($fieldCfg)
83 * 1571: function debug_parseSQLpart($part,$str)
84 * 1593: function debug_parseSQLpartCompare($str,$newStr,$caseInsensitive=FALSE)
85 * 1626: function debug_testSQL($SQLquery)
88 * (This index is automatically created/updated by the extension "extdeveval")
100 * TYPO3 SQL parser class.
102 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
106 class t3lib_sqlparser
{
109 var $parse_error = ''; // Parsing error string
110 var $lastStopKeyWord = ''; // Last stop keyword used.
115 /*************************************
117 * SQL Parsing, full queries
119 **************************************/
122 * Parses any single SQL query
124 * @param string SQL query
125 * @return array Result array with all the parts in - or error message string
126 * @see compileSQL(), debug_testSQL()
128 function parseSQL($parseString) {
130 // Prepare variables:
131 $parseString = $this->trimSQL($parseString);
132 $this->parse_error
= '';
135 // Finding starting keyword of string:
136 $_parseString = $parseString; // Protecting original string...
137 $keyword = $this->nextPart($_parseString, '^(SELECT|UPDATE|INSERT[[:space:]]+INTO|DELETE[[:space:]]+FROM|EXPLAIN|DROP[[:space:]]+TABLE|CREATE[[:space:]]+TABLE|ALTER[[:space:]]+TABLE)[[:space:]]+');
138 $keyword = strtoupper(ereg_replace('[[:space:]]*','',$keyword));
142 // Parsing SELECT query:
143 $result = $this->parseSELECT($parseString);
146 // Parsing UPDATE query:
147 $result = $this->parseUPDATE($parseString);
150 // Parsing INSERT query:
151 $result = $this->parseINSERT($parseString);
154 // Parsing DELETE query:
155 $result = $this->parseDELETE($parseString);
158 // Parsing EXPLAIN SELECT query:
159 $result = $this->parseEXPLAIN($parseString);
162 // Parsing DROP TABLE query:
163 $result = $this->parseDROPTABLE($parseString);
166 // Parsing ALTER TABLE query:
167 $result = $this->parseALTERTABLE($parseString);
170 // Parsing CREATE TABLE query:
171 $result = $this->parseCREATETABLE($parseString);
174 return $this->parseError('"'.$keyword.'" is not a keyword',$parseString);
182 * Parsing SELECT query
184 * @param string SQL string with SELECT query to parse
185 * @return mixed Returns array with components of SELECT query on success, otherwise an error message string.
186 * @see compileSELECT()
188 function parseSELECT($parseString) {
191 $parseString = $this->trimSQL($parseString);
192 $parseString = eregi_replace('^SELECT[[:space:]]+','',$parseString);
194 // Init output variable:
196 $result['type'] = 'SELECT';
198 // Looking for STRAIGHT_JOIN keyword:
199 $result['STRAIGHT_JOIN'] = $this->nextPart($parseString, '^(STRAIGHT_JOIN)[[:space:]]+');
202 $result['SELECT'] = $this->parseFieldList($parseString, '^(FROM)[[:space:]]+');
203 if ($this->parse_error
) { return $this->parse_error
; }
205 // Continue if string is not ended:
209 $result['FROM'] = $this->parseFromTables($parseString, '^(WHERE)[[:space:]]+');
210 if ($this->parse_error
) { return $this->parse_error
; }
212 // If there are more than just the tables (a WHERE clause that would be...)
216 $result['WHERE'] = $this->parseWhereClause($parseString, '^(GROUP[[:space:]]+BY|ORDER[[:space:]]+BY|LIMIT)[[:space:]]+');
217 if ($this->parse_error
) { return $this->parse_error
; }
219 // If the WHERE clause parsing was stopped by GROUP BY, ORDER BY or LIMIT, then proceed with parsing:
220 if ($this->lastStopKeyWord
) {
223 if ($this->lastStopKeyWord
== 'GROUPBY') {
224 $result['GROUPBY'] = $this->parseFieldList($parseString, '^(ORDER[[:space:]]+BY|LIMIT)[[:space:]]+');
225 if ($this->parse_error
) { return $this->parse_error
; }
229 if ($this->lastStopKeyWord
== 'ORDERBY') {
230 $result['ORDERBY'] = $this->parseFieldList($parseString, '^(LIMIT)[[:space:]]+');
231 if ($this->parse_error
) { return $this->parse_error
; }
235 if ($this->lastStopKeyWord
== 'LIMIT') {
236 if (ereg('^([0-9]+|[0-9]+[[:space:]]*,[[:space:]]*[0-9]+)$',trim($parseString))) {
237 $result['LIMIT'] = $parseString;
239 return $this->parseError('No value for limit!',$parseString);
244 } else return $this->parseError('No table to select from!',$parseString);
251 * Parsing UPDATE query
253 * @param string SQL string with UPDATE query to parse
254 * @return mixed Returns array with components of UPDATE query on success, otherwise an error message string.
255 * @see compileUPDATE()
257 function parseUPDATE($parseString) {
260 $parseString = $this->trimSQL($parseString);
261 $parseString = eregi_replace('^UPDATE[[:space:]]+','',$parseString);
263 // Init output variable:
265 $result['type'] = 'UPDATE';
268 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
270 // Continue if string is not ended:
271 if ($result['TABLE']) {
272 if ($parseString && $this->nextPart($parseString, '^(SET)[[:space:]]+')) {
276 // Get field/value pairs:
278 if ($fieldName = $this->nextPart($parseString,'^([[:alnum:]_]+)[[:space:]]*=')) {
279 $this->nextPart($parseString,'^(=)'); // Strip of "=" sign.
280 $value = $this->getValue($parseString);
281 $result['FIELDS'][$fieldName] = $value;
282 } else return $this->parseError('No fieldname found',$parseString);
284 $comma = $this->nextPart($parseString,'^(,)');
288 if ($this->nextPart($parseString,'^(WHERE)')) {
289 $result['WHERE'] = $this->parseWhereClause($parseString);
290 if ($this->parse_error
) { return $this->parse_error
; }
292 } else return $this->parseError('Query missing SET...',$parseString);
293 } else return $this->parseError('No table found!',$parseString);
295 // Should be no more content now:
297 return $this->parseError('Still content in clause after parsing!',$parseString);
305 * Parsing INSERT query
307 * @param string SQL string with INSERT query to parse
308 * @return mixed Returns array with components of INSERT query on success, otherwise an error message string.
309 * @see compileINSERT()
311 function parseINSERT($parseString) {
314 $parseString = $this->trimSQL($parseString);
315 $parseString = eregi_replace('^INSERT[[:space:]]+INTO[[:space:]]+','',$parseString);
317 // Init output variable:
319 $result['type'] = 'INSERT';
322 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)([[:space:]]+|\()');
324 if ($result['TABLE']) {
326 if ($this->nextPart($parseString,'^(VALUES)[[:space:]]+')) { // In this case there are no field names mentioned in the SQL!
327 // Get values/fieldnames (depending...)
328 $result['VALUES_ONLY'] = $this->getValue($parseString,'IN');
329 if ($this->parse_error
) { return $this->parse_error
; }
330 } else { // There are apparently fieldnames listed:
331 $fieldNames = $this->getValue($parseString,'_LIST');
332 if ($this->parse_error
) { return $this->parse_error
; }
334 if ($this->nextPart($parseString,'^(VALUES)[[:space:]]+')) { // "VALUES" keyword binds the fieldnames to values:
336 $values = $this->getValue($parseString,'IN'); // Using the "getValue" function to get the field list...
337 if ($this->parse_error
) { return $this->parse_error
; }
339 foreach($fieldNames as $k => $fN) {
340 if (ereg('^[[:alnum:]_]+$',$fN)) {
341 if (isset($values[$k])) {
342 if (!isset($result['FIELDS'][$fN])) {
343 $result['FIELDS'][$fN] = $values[$k];
344 } else return $this->parseError('Fieldname ("'.$fN.'") already found in list!',$parseString);
345 } else return $this->parseError('No value set!',$parseString);
346 } else return $this->parseError('Invalid fieldname ("'.$fN.'")',$parseString);
348 if (isset($values[$k+
1])) {
349 return $this->parseError('Too many values in list!',$parseString);
351 } else return $this->parseError('VALUES keyword expected',$parseString);
353 } else return $this->parseError('No table found!',$parseString);
355 // Should be no more content now:
357 return $this->parseError('Still content after parsing!',$parseString);
365 * Parsing DELETE query
367 * @param string SQL string with DELETE query to parse
368 * @return mixed Returns array with components of DELETE query on success, otherwise an error message string.
369 * @see compileDELETE()
371 function parseDELETE($parseString) {
374 $parseString = $this->trimSQL($parseString);
375 $parseString = eregi_replace('^DELETE[[:space:]]+FROM[[:space:]]+','',$parseString);
377 // Init output variable:
379 $result['type'] = 'DELETE';
382 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
384 if ($result['TABLE']) {
387 if ($this->nextPart($parseString,'^(WHERE)')) {
388 $result['WHERE'] = $this->parseWhereClause($parseString);
389 if ($this->parse_error
) { return $this->parse_error
; }
391 } else return $this->parseError('No table found!',$parseString);
393 // Should be no more content now:
395 return $this->parseError('Still content in clause after parsing!',$parseString);
403 * Parsing EXPLAIN query
405 * @param string SQL string with EXPLAIN query to parse
406 * @return mixed Returns array with components of EXPLAIN query on success, otherwise an error message string.
409 function parseEXPLAIN($parseString) {
412 $parseString = $this->trimSQL($parseString);
413 $parseString = eregi_replace('^EXPLAIN[[:space:]]+','',$parseString);
415 // Init output variable:
416 $result = $this->parseSELECT($parseString);
417 if (is_array($result)) {
418 $result['type'] = 'EXPLAIN';
425 * Parsing CREATE TABLE query
427 * @param string SQL string starting with CREATE TABLE
428 * @return mixed Returns array with components of CREATE TABLE query on success, otherwise an error message string.
429 * @see compileCREATETABLE()
431 function parseCREATETABLE($parseString) {
433 // Removing CREATE TABLE
434 $parseString = $this->trimSQL($parseString);
435 $parseString = eregi_replace('^CREATE[[:space:]]+TABLE[[:space:]]+','',$parseString);
437 // Init output variable:
439 $result['type'] = 'CREATETABLE';
442 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]*\(',TRUE);
444 if ($result['TABLE']) {
446 // While the parseString is not yet empty:
447 while(strlen($parseString)>0) {
448 if ($key = $this->nextPart($parseString, '^(KEY|PRIMARY KEY)([[:space:]]+|\()')) { // Getting key
449 $key = strtoupper(ereg_replace('[[:space:]]','',$key));
453 $result['KEYS'][$key] = $this->getValue($parseString,'_LIST');
454 if ($this->parse_error
) { return $this->parse_error
; }
457 if ($keyName = $this->nextPart($parseString, '^([[:alnum:]_]+)([[:space:]]+|\()')) {
458 $result['KEYS'][$keyName] = $this->getValue($parseString,'_LIST');
459 if ($this->parse_error
) { return $this->parse_error
; }
460 } else return $this->parseError('No keyname found',$parseString);
463 } elseif ($fieldName = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+')) { // Getting field:
464 $result['FIELDS'][$fieldName]['definition'] = $this->parseFieldDef($parseString);
465 if ($this->parse_error
) { return $this->parse_error
; }
468 // Finding delimiter:
469 $delim = $this->nextPart($parseString, '^(,|\))');
471 return $this->parseError('No delimiter found',$parseString);
472 } elseif ($delim==')') {
477 // Finding what is after the table definition - table type in MySQL
479 if ($this->nextPart($parseString, '^(TYPE[[:space:]]*=)')) {
480 $result['tableType'] = $parseString;
483 } else return $this->parseError('No fieldname found!',$parseString);
485 // Getting table type
486 } else return $this->parseError('No table found!',$parseString);
488 // Should be no more content now:
490 return $this->parseError('Still content in clause after parsing!',$parseString);
497 * Parsing ALTER TABLE query
499 * @param string SQL string starting with ALTER TABLE
500 * @return mixed Returns array with components of ALTER TABLE query on success, otherwise an error message string.
501 * @see compileALTERTABLE()
503 function parseALTERTABLE($parseString) {
505 // Removing ALTER TABLE
506 $parseString = $this->trimSQL($parseString);
507 $parseString = eregi_replace('^ALTER[[:space:]]+TABLE[[:space:]]+','',$parseString);
509 // Init output variable:
511 $result['type'] = 'ALTERTABLE';
514 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
516 if ($result['TABLE']) {
517 if ($result['action'] = $this->nextPart($parseString, '^(CHANGE|DROP[[:space:]]+KEY|DROP[[:space:]]+PRIMARY[[:space:]]+KEY|ADD[[:space:]]+KEY|ADD[[:space:]]+PRIMARY[[:space:]]+KEY|DROP|ADD|RENAME)([[:space:]]+|\()')) {
518 $actionKey = strtoupper(ereg_replace('[[:space:]]','',$result['action']));
521 if (t3lib_div
::inList('ADDPRIMARYKEY,DROPPRIMARYKEY',$actionKey) ||
$fieldKey = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+')) {
525 $result['FIELD'] = $fieldKey;
526 $result['definition'] = $this->parseFieldDef($parseString);
527 if ($this->parse_error
) { return $this->parse_error
; }
531 $result['FIELD'] = $fieldKey;
534 $result['FIELD'] = $fieldKey;
535 if ($result['newField'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+')) {
536 $result['definition'] = $this->parseFieldDef($parseString);
537 if ($this->parse_error
) { return $this->parse_error
; }
538 } else return $this->parseError('No NEW field name found',$parseString);
542 case 'ADDPRIMARYKEY':
543 $result['KEY'] = $fieldKey;
544 $result['fields'] = $this->getValue($parseString,'_LIST');
545 if ($this->parse_error
) { return $this->parse_error
; }
548 $result['KEY'] = $fieldKey;
550 case 'DROPPRIMARYKEY':
554 } else return $this->parseError('No field name found',$parseString);
555 } else return $this->parseError('No action CHANGE, DROP or ADD found!',$parseString);
556 } else return $this->parseError('No table found!',$parseString);
558 // Should be no more content now:
560 return $this->parseError('Still content in clause after parsing!',$parseString);
567 * Parsing DROP TABLE query
569 * @param string SQL string starting with DROP TABLE
570 * @return mixed Returns array with components of DROP TABLE query on success, otherwise an error message string.
572 function parseDROPTABLE($parseString) {
574 // Removing DROP TABLE
575 $parseString = $this->trimSQL($parseString);
576 $parseString = eregi_replace('^DROP[[:space:]]+TABLE[[:space:]]+','',$parseString);
578 // Init output variable:
580 $result['type'] = 'DROPTABLE';
583 $result['ifExists'] = $this->nextPart($parseString, '^(IF[[:space:]]+EXISTS[[:space:]]+)');
586 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
588 if ($result['TABLE']) {
590 // Should be no more content now:
592 return $this->parseError('Still content in clause after parsing!',$parseString);
596 } else return $this->parseError('No table found!',$parseString);
615 /**************************************
617 * SQL Parsing, helper functions for parts of queries
619 **************************************/
622 * Parsing the fields in the "SELECT [$selectFields] FROM" part of a query into an array.
623 * The output from this function can be compiled back into a field list with ->compileFieldList()
624 * 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!
626 * @param string The string with fieldnames, eg. "title, uid AS myUid, max(tstamp), count(*)" etc. NOTICE: passed by reference!
627 * @param string Regular expressing to STOP parsing, eg. '^(FROM)([[:space:]]*)'
628 * @return array If successful parsing, returns an array, otherwise an error string.
629 * @see compileFieldList()
631 function parseFieldList(&$parseString, $stopRegex='') {
633 // Prepare variables:
634 $parseString = $this->trimSQL($parseString);
635 $this->lastStopKeyWord
= '';
636 $this->parse_error
= '';
639 $stack = array(); // Contains the parsed content
640 $pnt = 0; // Pointer to positions in $stack
641 $level = 0; // Indicates the parenthesis level we are at.
642 $loopExit = 0; // Recursivity brake.
644 // $parseString is continously shortend by the process and we keep parsing it till it is zero:
645 while (strlen($parseString)) {
647 // Checking if we are inside / outside parenthesis (in case of a function like count(), max(), min() etc...):
648 if ($level>0) { // Inside parenthesis here (does NOT detect if values in quotes are used, the only token is ")" or "("):
650 // Accumulate function content until next () parenthesis:
651 $funcContent = $this->nextPart($parseString,'^([^()]*.)');
652 $stack[$pnt]['func_content.'][] = array(
654 'func_content' => substr($funcContent,0,-1)
656 $stack[$pnt]['func_content'].= $funcContent;
659 switch(substr($stack[$pnt]['func_content'],-1)) {
665 if (!$level) { // If this was the last parenthesis:
666 $stack[$pnt]['func_content'] = substr($stack[$pnt]['func_content'],0,-1);
667 $parseString = ltrim($parseString); // Remove any whitespace after the parenthesis.
671 } else { // Outside parenthesis, looking for next field:
673 // Looking for a known function (only known functions supported)
674 $func = $this->nextPart($parseString,'^(count|max|min|floor|sum|avg)[[:space:]]*\(');
676 $parseString = trim(substr($parseString,1)); // Strip of "("
677 $stack[$pnt]['type'] = 'function';
678 $stack[$pnt]['function'] = $func;
679 $level++
; // increse parenthesis level counter.
681 // Otherwise, look for regular fieldname:
682 if ($fieldName = $this->nextPart($parseString,'^([[:alnum:]\*._]+)(,|[[:space:]]+)')) {
683 $stack[$pnt]['type'] = 'field';
685 // Explode fieldname into field and table:
686 $tableField = explode('.',$fieldName,2);
687 if (count($tableField)==2) {
688 $stack[$pnt]['table'] = $tableField[0];
689 $stack[$pnt]['field'] = $tableField[1];
691 $stack[$pnt]['table'] = '';
692 $stack[$pnt]['field'] = $tableField[0];
695 return $this->parseError('No field name found as expected',$parseString);
700 // After a function or field we look for "AS" alias and a comma to separate to the next field in the list:
703 // Looking for "AS" alias:
704 if ($as = $this->nextPart($parseString,'^(AS)[[:space:]]+')) {
705 $stack[$pnt]['as'] = $this->nextPart($parseString,'^([[:alnum:]_]+)(,|[[:space:]]+)');
706 $stack[$pnt]['as_keyword'] = $as;
709 // Looking for "ASC" or "DESC" keywords (for ORDER BY)
710 if ($sDir = $this->nextPart($parseString,'^(ASC|DESC)([[:space:]]+|,)')) {
711 $stack[$pnt]['sortDir'] = $sDir;
714 // Looking for stop-keywords:
715 if ($stopRegex && $this->lastStopKeyWord
= $this->nextPart($parseString, $stopRegex)) {
716 $this->lastStopKeyWord
= strtoupper(ereg_replace('[[:space:]]*','',$this->lastStopKeyWord
));
720 // Looking for comma (since the stop-keyword did not trigger a return...)
721 if (strlen($parseString) && !$this->nextPart($parseString,'^(,)')) {
722 return $this->parseError('No comma found as expected',$parseString);
725 // Increasing pointer:
729 // Check recursivity brake:
732 return $this->parseError('More than 500 loops, exiting prematurely...',$parseString);
736 // Return result array:
741 * Parsing the tablenames in the "FROM [$parseString] WHERE" part of a query into an array.
742 * The success of this parsing determines if that part of the query is supported by TYPO3.
744 * @param string list of tables, eg. "pages, tt_content" or "pages A, pages B". NOTICE: passed by reference!
745 * @param string Regular expressing to STOP parsing, eg. '^(WHERE)([[:space:]]*)'
746 * @return array If successful parsing, returns an array, otherwise an error string.
747 * @see compileFromTables()
749 function parseFromTables(&$parseString, $stopRegex='') {
751 // Prepare variables:
752 $parseString = $this->trimSQL($parseString);
753 $this->lastStopKeyWord
= '';
754 $this->parse_error
= '';
756 $stack = array(); // Contains the parsed content
757 $pnt = 0; // Pointer to positions in $stack
758 $loopExit = 0; // Recursivity brake.
760 // $parseString is continously shortend by the process and we keep parsing it till it is zero:
761 while (strlen($parseString)) {
763 // Looking for the table:
764 if ($stack[$pnt]['table'] = $this->nextPart($parseString,'^([[:alnum:]_]+)(,|[[:space:]]+)')) {
765 if ($as = $this->nextPart($parseString,'^(AS)[[:space:]]+')) {
766 $stack[$pnt]['as'] = $this->nextPart($parseString,'^([[:alnum:]_]+)(,|[[:space:]]+)');
767 $stack[$pnt]['as_keyword'] = $as;
769 } else return $this->parseError('No table name found as expected!',$parseString);
772 if ($join = $this->nextPart($parseString,'^(JOIN|LEFT[[:space:]]+JOIN)[[:space:]]+')) {
773 $stack[$pnt]['JOIN']['type'] = $join;
774 if ($stack[$pnt]['JOIN']['withTable'] = $this->nextPart($parseString,'^([[:alnum:]_]+)[[:space:]]+ON[[:space:]]+',1)) {
775 $field1 = $this->nextPart($parseString,'^([[:alnum:]_.]+)[[:space:]]*=[[:space:]]*',1);
776 $field2 = $this->nextPart($parseString,'^([[:alnum:]_.]+)[[:space:]]+');
777 if ($field1 && $field2) {
778 $stack[$pnt]['JOIN']['ON'] = array($field1,$field2);
779 } else return $this->parseError('No join fields found!',$parseString);
780 } else return $this->parseError('No join table found!',$parseString);
783 // Looking for stop-keywords:
784 if ($stopRegex && $this->lastStopKeyWord
= $this->nextPart($parseString, $stopRegex)) {
785 $this->lastStopKeyWord
= strtoupper(ereg_replace('[[:space:]]*','',$this->lastStopKeyWord
));
789 // Looking for comma:
790 if (strlen($parseString) && !$this->nextPart($parseString,'^(,)')) {
791 return $this->parseError('No comma found as expected',$parseString);
794 // Increasing pointer:
797 // Check recursivity brake:
800 return $this->parseError('More than 500 loops, exiting prematurely...',$parseString);
804 // Return result array:
809 * Parsing the WHERE clause fields in the "WHERE [$parseString] ..." part of a query into a multidimensional array.
810 * The success of this parsing determines if that part of the query is supported by TYPO3.
812 * @param string WHERE clause to parse. NOTICE: passed by reference!
813 * @param string Regular expressing to STOP parsing, eg. '^(GROUP BY|ORDER BY|LIMIT)([[:space:]]*)'
814 * @return mixed If successful parsing, returns an array, otherwise an error string.
816 function parseWhereClause(&$parseString, $stopRegex='') {
818 // Prepare variables:
819 $parseString = $this->trimSQL($parseString);
820 $this->lastStopKeyWord
= '';
821 $this->parse_error
= '';
823 $stack = array(0 => array()); // Contains the parsed content
824 $pnt = array(0 => 0); // Pointer to positions in $stack
825 $level = 0; // Determines parenthesis level
826 $loopExit = 0; // Recursivity brake.
828 // $parseString is continously shortend by the process and we keep parsing it till it is zero:
829 while (strlen($parseString)) {
831 // Look for next parenthesis level:
832 $newLevel = $this->nextPart($parseString,'^([(])');
833 if ($newLevel=='(') { // If new level is started, manage stack/pointers:
834 $level++
; // Increase level
835 $pnt[$level] = 0; // Reset pointer for this level
836 $stack[$level] = array(); // Reset stack for this level
837 } else { // If no new level is started, just parse the current level:
839 // Find "modifyer", eg. "NOT or !"
840 $stack[$level][$pnt[$level]]['modifier'] = trim($this->nextPart($parseString,'^(!|NOT[[:space:]]+)'));
843 if ($fieldName = $this->nextPart($parseString,'^([[:alnum:]._]+)([[:space:]]+|&|<=|>=|<|>|=|!=|IS)')) {
845 // Parse field name into field and table:
846 $tableField = explode('.',$fieldName,2);
847 if (count($tableField)==2) {
848 $stack[$level][$pnt[$level]]['table'] = $tableField[0];
849 $stack[$level][$pnt[$level]]['field'] = $tableField[1];
851 $stack[$level][$pnt[$level]]['table'] = '';
852 $stack[$level][$pnt[$level]]['field'] = $tableField[0];
855 return $this->parseError('No field name found as expected',$parseString);
858 // See if the value is calculated. Support only for "&" (boolean AND) at the moment:
859 $stack[$level][$pnt[$level]]['calc'] = $this->nextPart($parseString,'^(&)');
860 if (strlen($stack[$level][$pnt[$level]]['calc'])) {
861 // Finding value for calculation:
862 $stack[$level][$pnt[$level]]['calc_value'] = $this->getValue($parseString);
865 // Find "comparator":
866 $stack[$level][$pnt[$level]]['comparator'] = $this->nextPart($parseString,'^(<=|>=|<|>|=|!=|NOT[[:space:]]+IN|IN|NOT[[:space:]]+LIKE|LIKE|IS)');
867 if (strlen($stack[$level][$pnt[$level]]['comparator'])) {
868 // Finding value for comparator:
869 $stack[$level][$pnt[$level]]['value'] = $this->getValue($parseString,$stack[$level][$pnt[$level]]['comparator']);
870 if ($this->parse_error
) { return $this->parse_error
; }
873 // Finished, increase pointer:
876 // Checking if the current level is ended, in that case do stack management:
877 while ($this->nextPart($parseString,'^([)])')) {
878 $level--; // Decrease level:
879 $stack[$level][$pnt[$level]]['sub'] = $stack[$level+
1]; // Copy stack
880 $pnt[$level]++
; // Increase pointer of the new level
882 // Make recursivity check:
885 return $this->parseError('More than 500 loops (in search for exit parenthesis), exiting prematurely...',$parseString);
889 // Detecting the operator for the next level; support for AND, OR and &&):
890 $op = $this->nextPart($parseString,'^(AND|OR|AND[[:space:]]+NOT)(\(|[[:space:]]+)');
892 $stack[$level][$pnt[$level]]['operator'] = $op;
893 } elseif (strlen($parseString)) {
895 // Looking for stop-keywords:
896 if ($stopRegex && $this->lastStopKeyWord
= $this->nextPart($parseString, $stopRegex)) {
897 $this->lastStopKeyWord
= strtoupper(ereg_replace('[[:space:]]*','',$this->lastStopKeyWord
));
900 return $this->parseError('No operator, but parsing not finished.',$parseString);
905 // Make recursivity check:
908 return $this->parseError('More than 500 loops, exiting prematurely...',$parseString);
912 // Return the stacks lowest level:
917 * Parsing the WHERE clause fields in the "WHERE [$parseString] ..." part of a query into a multidimensional array.
918 * The success of this parsing determines if that part of the query is supported by TYPO3.
920 * @param string WHERE clause to parse. NOTICE: passed by reference!
921 * @param string Regular expressing to STOP parsing, eg. '^(GROUP BY|ORDER BY|LIMIT)([[:space:]]*)'
922 * @return mixed If successful parsing, returns an array, otherwise an error string.
924 function parseFieldDef(&$parseString, $stopRegex='') {
925 // Prepare variables:
926 $parseString = $this->trimSQL($parseString);
927 $this->lastStopKeyWord
= '';
928 $this->parse_error
= '';
933 if ($result['fieldType'] = $this->nextPart($parseString,'^(int|smallint|tinyint|mediumint|double|varchar|char|text|tinytext|mediumtext|blob|tinyblob|mediumblob|longblob)([[:space:]]+|\()')) {
935 // Looking for value:
936 if (substr($parseString,0,1)=='(') {
937 $parseString = substr($parseString,1);
938 if ($result['value'] = $this->nextPart($parseString,'^([^)]*)')) {
939 $parseString = ltrim(substr($parseString,1));
940 } else return $this->parseError('No end-parenthesis for value found!',$parseString);
943 // Looking for keywords
944 while($keyword = $this->nextPart($parseString,'^(DEFAULT|NOT[[:space:]]+NULL|AUTO_INCREMENT|UNSIGNED)([[:space:]]+|,|\))')) {
945 $keywordCmp = strtoupper(ereg_replace('[[:space:]]*','',$keyword));
947 $result['featureIndex'][$keywordCmp]['keyword'] = $keyword;
949 switch($keywordCmp) {
951 $result['featureIndex'][$keywordCmp]['value'] = $this->getValue($parseString);
955 } else return $this->parseError('Field type unknown!',$parseString);
970 /************************************
972 * Parsing: Helper functions
974 ************************************/
977 * Strips of a part of the parseString and returns the matching part.
978 * Helper function for the parsing methods.
980 * @param string 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.
981 * @param string 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())
982 * @param boolean If set the full match of the regex is stripped of the beginning of the string!
983 * @return string The value of the first parenthesis level of the REGEX.
985 function nextPart(&$parseString,$regex,$trimAll=FALSE) {
986 if (eregi($regex,$parseString.' ', $reg)) { // Adding space char because [[:space:]]+ is often a requirement in regex's
987 $parseString = ltrim(substr($parseString,strlen($reg[$trimAll?
0:1])));
993 * Finds value in beginning of $parseString, returns result and strips it of parseString
995 * @param string The parseString, eg. "(0,1,2,3) ..." or "('asdf','qwer') ..." or "1234 ..." or "'My string value here' ..."
996 * @param string 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)
997 * @return string The value (string/integer). Otherwise an array with error message in first key (0)
999 function getValue(&$parseString,$comparator='') {
1000 if (t3lib_div
::inList('NOTIN,IN,_LIST',strtoupper(ereg_replace('[[:space:]]','',$comparator)))) { // List of values:
1001 if ($this->nextPart($parseString,'^([(])')) {
1002 $listValues = array();
1005 while($comma==',') {
1006 $listValues[] = $this->getValue($parseString);
1007 $comma = $this->nextPart($parseString,'^([,])');
1010 $out = $this->nextPart($parseString,'^([)])');
1012 if ($comparator=='_LIST') {
1014 foreach ($listValues as $vArr) {
1015 $kVals[] = $vArr[0];
1021 } else return array($this->parseError('No ) parenthesis in list',$parseString));
1022 } else return array($this->parseError('No ( parenthesis starting the list',$parseString));
1024 } else { // Just plain string value, in quotes or not:
1027 $firstChar = substr($parseString,0,1);
1029 switch($firstChar) {
1031 return array($this->getValueInQuotes($parseString,'"'),'"');
1034 return array($this->getValueInQuotes($parseString,"'"),"'");
1037 if (eregi('^([[:alnum:]._-]+)',$parseString, $reg)) {
1038 $parseString = ltrim(substr($parseString,strlen($reg[0])));
1039 return array($reg[1]);
1047 * Get value in quotes from $parseString.
1048 * NOTICE: If a query being parsed was prepared for another database than MySQL this function should probably be changed
1050 * @param string String from which to find value in quotes. Notice that $parseString is passed by reference and is shortend by the output of this function.
1051 * @param string The quote used; input either " or '
1052 * @return string The value, passed through stripslashes() !
1054 function getValueInQuotes(&$parseString,$quote) {
1056 $parts = explode($quote,substr($parseString,1));
1058 foreach($parts as $k => $v) {
1062 ereg('[\]*$',$v,$reg);
1063 if (strlen($reg[0])%2
) {
1066 $parseString = ltrim(substr($parseString,strlen($buffer)+
2));
1067 return $this->parseStripslashes($buffer);
1073 * Strip slashes function used for parsing
1074 * NOTICE: If a query being parsed was prepared for another database than MySQL this function should probably be changed
1076 * @param string Input string
1077 * @return string Output string
1079 function parseStripslashes($str) {
1080 $search = array('\\\\', '\\\'', '\\"', '\0', '\n', '\r', '\Z');
1081 $replace = array('\\', '\'', '"', "\x00", "\x0a", "\x0d", "\x1a");
1083 return str_replace($search, $replace, $str);
1087 * Add slashes function used for compiling queries
1088 * NOTICE: If a query being parsed was prepared for another database than MySQL this function should probably be changed
1090 * @param string Input string
1091 * @return string Output string
1093 function compileAddslashes($str) {
1094 $search = array('\\', '\'', '"', "\x00", "\x0a", "\x0d", "\x1a");
1095 $replace = array('\\\\', '\\\'', '\\"', '\0', '\n', '\r', '\Z');
1097 return str_replace($search, $replace, $str);
1101 * Setting the internal error message value, $this->parse_error and returns that value.
1103 * @param string Input error message
1104 * @param string Remaining query to parse.
1105 * @return string Error message.
1107 function parseError($msg,$restQuery) {
1108 $this->parse_error
= 'SQL engine parse ERROR: '.$msg.': near "'.substr($restQuery,0,50).'"';
1109 return $this->parse_error
;
1113 * Trimming SQL as preparation for parsing.
1114 * ";" in the end is stripped of.
1115 * White space is trimmed away around the value
1116 * A single space-char is added in the end
1118 * @param string Input string
1119 * @return string Output string
1121 function trimSQL($str) {
1122 return trim(ereg_replace('[[:space:];]*$','',$str)).' ';
1136 /*************************
1140 *************************/
1143 * Compiles an SQL query from components
1145 * @param array Array of SQL query components
1146 * @return string SQL query
1149 function compileSQL($components) {
1150 switch($components['type']) {
1152 $query = $this->compileSELECT($components);
1155 $query = $this->compileUPDATE($components);
1158 $query = $this->compileINSERT($components);
1161 $query = $this->compileDELETE($components);
1164 $query = 'EXPLAIN '.$this->compileSELECT($components);
1167 $query = 'DROP TABLE'.($components['ifExists']?
' IF EXISTS':'').' '.$components['TABLE'];
1170 $query = $this->compileCREATETABLE($components);
1173 $query = $this->compileALTERTABLE($components);
1181 * Compiles a SELECT statement from components array
1183 * @param array Array of SQL query components
1184 * @return string SQL SELECT query
1185 * @see parseSELECT()
1187 function compileSELECT($components) {
1190 $where = $this->compileWhereClause($components['WHERE']);
1191 $groupBy = $this->compileFieldList($components['GROUPBY']);
1192 $orderBy = $this->compileFieldList($components['ORDERBY']);
1193 $limit = $components['LIMIT'];
1196 $query = 'SELECT '.($components['STRAIGHT_JOIN'] ?
$components['STRAIGHT_JOIN'].'' : '').'
1197 '.$this->compileFieldList($components['SELECT']).'
1198 FROM '.$this->compileFromTables($components['FROM']).
1200 WHERE '.$where : '').
1202 GROUP BY '.$groupBy : '').
1204 ORDER BY '.$orderBy : '').
1206 LIMIT '.$limit : '');
1212 * Compiles an UPDATE statement from components array
1214 * @param array Array of SQL query components
1215 * @return string SQL UPDATE query
1216 * @see parseUPDATE()
1218 function compileUPDATE($components) {
1221 $where = $this->compileWhereClause($components['WHERE']);
1225 foreach($components['FIELDS'] as $fN => $fV) {
1226 $fields[]=$fN.'='.$fV[1].$this->compileAddslashes($fV[0]).$fV[1];
1230 $query = 'UPDATE '.$components['TABLE'].' SET
1234 WHERE '.$where : '');
1240 * Compiles an INSERT statement from components array
1242 * @param array Array of SQL query components
1243 * @return string SQL INSERT query
1244 * @see parseINSERT()
1246 function compileINSERT($components) {
1248 if ($components['VALUES_ONLY']) {
1251 foreach($components['VALUES_ONLY'] as $fV) {
1252 $fields[]=$fV[1].$this->compileAddslashes($fV[0]).$fV[1];
1256 $query = 'INSERT INTO '.$components['TABLE'].'
1263 foreach($components['FIELDS'] as $fN => $fV) {
1264 $fields[$fN]=$fV[1].$this->compileAddslashes($fV[0]).$fV[1];
1268 $query = 'INSERT INTO '.$components['TABLE'].'
1270 ',array_keys($fields)).')
1280 * Compiles an DELETE statement from components array
1282 * @param array Array of SQL query components
1283 * @return string SQL DELETE query
1284 * @see parseDELETE()
1286 function compileDELETE($components) {
1289 $where = $this->compileWhereClause($components['WHERE']);
1292 $query = 'DELETE FROM '.$components['TABLE'].
1294 WHERE '.$where : '');
1300 * Compiles a CREATE TABLE statement from components array
1302 * @param array Array of SQL query components
1303 * @return string SQL CREATE TABLE query
1304 * @see parseCREATETABLE()
1306 function compileCREATETABLE($components) {
1308 // Create fields and keys:
1309 $fieldsKeys = array();
1310 foreach($components['FIELDS'] as $fN => $fCfg) {
1311 $fieldsKeys[]=$fN.' '.$this->compileFieldCfg($fCfg['definition']);
1313 foreach($components['KEYS'] as $kN => $kCfg) {
1314 if ($kN == 'PRIMARYKEY') {
1315 $fieldsKeys[]='PRIMARY KEY ('.implode(',', $kCfg).')';
1317 $fieldsKeys[]='KEY '.$kN.' ('.implode(',', $kCfg).')';
1322 $query = 'CREATE TABLE '.$components['TABLE'].' (
1325 )'.($components['tableType'] ?
' TYPE='.$components['tableType'] : '');
1331 * Compiles an ALTER TABLE statement from components array
1333 * @param array Array of SQL query components
1334 * @return string SQL ALTER TABLE query
1335 * @see parseALTERTABLE()
1337 function compileALTERTABLE($components) {
1340 $query = 'ALTER TABLE '.$components['TABLE'].' '.$components['action'].' '.($components['FIELD']?
$components['FIELD']:$components['KEY']);
1342 // Based on action, add the final part:
1343 switch(strtoupper(ereg_replace('[[:space:]]','',$components['action']))) {
1345 $query.=' '.$this->compileFieldCfg($components['definition']);
1348 $query.=' '.$components['newField'].' '.$this->compileFieldCfg($components['definition']);
1354 case 'ADDPRIMARYKEY':
1355 $query.=' ('.implode(',',$components['fields']).')';
1376 /**************************************
1378 * Compiling queries, helper functions for parts of queries
1380 **************************************/
1383 * Compiles a "SELECT [output] FROM..:" field list based on input array (made with ->parseFieldList())
1384 * Can also compile field lists for ORDER BY and GROUP BY.
1386 * @param array Array of select fields, (made with ->parseFieldList())
1387 * @return string Select field string
1388 * @see parseFieldList()
1390 function compileFieldList($selectFields) {
1392 // Prepare buffer variable:
1393 $outputParts = array();
1395 // Traverse the selectFields if any:
1396 if (is_array($selectFields)) {
1397 foreach($selectFields as $k => $v) {
1400 switch($v['type']) {
1402 $outputParts[$k] = $v['function'].'('.$v['func_content'].')';
1405 $outputParts[$k] = ($v['table']?
$v['table'].'.':'').$v['field'];
1411 $outputParts[$k].= ' '.$v['as_keyword'].' '.$v['as'];
1414 // Specifically for ORDER BY and GROUP BY field lists:
1415 if ($v['sortDir']) {
1416 $outputParts[$k].= ' '.$v['sortDir'];
1421 // Return imploded buffer:
1422 return implode(', ',$outputParts);
1426 * Compiles a "FROM [output] WHERE..:" table list based on input array (made with ->parseFromTables())
1428 * @param array Array of table names, (made with ->parseFromTables())
1429 * @return string Table name string
1430 * @see parseFromTables()
1432 function compileFromTables($tablesArray) {
1434 // Prepare buffer variable:
1435 $outputParts = array();
1437 // Traverse the table names:
1438 if (is_array($tablesArray)) {
1439 foreach($tablesArray as $k => $v) {
1442 $outputParts[$k] = $v['table'];
1444 // Add alias AS if there:
1446 $outputParts[$k].= ' '.$v['as_keyword'].' '.$v['as'];
1449 if (is_array($v['JOIN'])) {
1450 $outputParts[$k].= ' '.$v['JOIN']['type'].' '.$v['JOIN']['withTable'].' ON '.implode('=',$v['JOIN']['ON']);
1456 // Return imploded buffer:
1457 return implode(', ',$outputParts);
1461 * Implodes an array of WHERE clause configuration into a WHERE clause.
1462 * NOTICE: MIGHT BY A TEMPORARY FUNCTION. Use for debugging only!
1464 * @param array WHERE clause configuration
1465 * @return string WHERE clause as string.
1466 * @see explodeWhereClause()
1468 function compileWhereClause($clauseArray) {
1470 // Prepare buffer variable:
1473 // Traverse clause array:
1474 if (is_array($clauseArray)) {
1475 foreach($clauseArray as $k => $v) {
1478 $output.=$v['operator'] ?
' '.$v['operator'] : '';
1480 // Look for sublevel:
1481 if (is_array($v['sub'])) {
1482 $output.=' ('.trim($this->compileWhereClause($v['sub'])).')';
1485 // Set field/table with modifying prefix if any:
1486 $output.=' '.trim($v['modifier'].' '.($v['table']?
$v['table'].'.':'').$v['field']);
1488 // Set calculation, if any:
1490 $output.=$v['calc'].$v['calc_value'][1].$this->compileAddslashes($v['calc_value'][0]).$v['calc_value'][1];
1494 if ($v['comparator']) {
1495 $output.=' '.$v['comparator'];
1497 // Detecting value type; list or plain:
1498 if (t3lib_div
::inList('NOTIN,IN',strtoupper(ereg_replace('[[:space:]]','',$v['comparator'])))) {
1499 $valueBuffer = array();
1500 foreach($v['value'] as $realValue) {
1501 $valueBuffer[]=$realValue[1].$this->compileAddslashes($realValue[0]).$realValue[1];
1503 $output.=' ('.trim(implode(',',$valueBuffer)).')';
1505 $output.=' '.$v['value'][1].$this->compileAddslashes($v['value'][0]).$v['value'][1];
1512 // Return output buffer:
1517 * Compile field definition
1519 * @param array Field definition parts
1520 * @return string Field definition string
1522 function compileFieldCfg($fieldCfg) {
1525 $cfg = $fieldCfg['fieldType'];
1527 // Add value, if any:
1528 if (strlen($fieldCfg['value'])) {
1529 $cfg.='('.$fieldCfg['value'].')';
1532 // Add additional features:
1533 if (is_array($fieldCfg['featureIndex'])) {
1534 foreach($fieldCfg['featureIndex'] as $featureDef) {
1535 $cfg.=' '.$featureDef['keyword'];
1537 // Add value if found:
1538 if (is_array($featureDef['value'])) {
1539 $cfg.=' '.$featureDef['value'][1].$this->compileAddslashes($featureDef['value'][0]).$featureDef['value'][1];
1544 // Return field definition string:
1558 /*************************
1562 *************************/
1565 * Check parsability of input SQL part string; Will parse and re-compile after which it is compared
1567 * @param string Part definition of string; "SELECT" = fieldlist (also ORDER BY and GROUP BY), "FROM" = table list, "WHERE" = Where clause.
1568 * @param string SQL string to verify parsability of
1569 * @return mixed Returns array with string 1 and 2 if error, otherwise false
1571 function debug_parseSQLpart($part,$str) {
1574 return $this->debug_parseSQLpartCompare($str,$this->compileFieldList($this->parseFieldList($str)));
1577 return $this->debug_parseSQLpartCompare($str,$this->compileFromTables($this->parseFromTables($str)));
1580 return $this->debug_parseSQLpartCompare($str,$this->compileWhereClause($this->parseWhereClause($str)));
1586 * Compare two query strins by stripping away whitespace.
1588 * @param string SQL String 1
1589 * @param string SQL string 2
1590 * @param boolean If true, the strings are compared insensitive to case
1591 * @return mixed Returns array with string 1 and 2 if error, otherwise false
1593 function debug_parseSQLpartCompare($str,$newStr,$caseInsensitive=FALSE) {
1594 if ($caseInsensitive) {
1595 $str1 = strtoupper($str);
1596 $str2 = strtoupper($newStr);
1602 // Fixing escaped chars:
1603 $search = array('\0', '\n', '\r', '\Z');
1604 $replace = array("\x00", "\x0a", "\x0d", "\x1a");
1605 $str1 = str_replace($search, $replace, $str1);
1606 $str2 = str_replace($search, $replace, $str2);
1608 # Normally, commented out since they are needed only in tricky cases...
1609 # $str1 = stripslashes($str1);
1610 # $str2 = stripslashes($str2);
1612 if (strcmp(ereg_replace('[[:space:]]','',$this->trimSQL($str1)),ereg_replace('[[:space:]]','',$this->trimSQL($str2)))) {
1614 ereg_replace('[[:space:]]+',' ',$str),
1615 ereg_replace('[[:space:]]+',' ',$newStr),
1621 * 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
1623 * @param string SQL query
1624 * @return string Query if all is well, otherwise exit.
1626 function debug_testSQL($SQLquery) {
1628 #debug(array($SQLquery));
1630 // Getting result array:
1631 $parseResult = $this->parseSQL($SQLquery);
1633 // If result array was returned, proceed. Otherwise show error and exit.
1634 if (is_array($parseResult)) {
1636 // Re-compile query:
1637 $newQuery = $this->compileSQL($parseResult);
1639 // TEST the new query:
1640 $testResult = $this->debug_parseSQLpartCompare($SQLquery, $newQuery);
1642 // Return new query if OK, otherwise show error and exit:
1643 if (!is_array($testResult)) {
1646 debug(array('ERROR MESSAGE'=>'Input query did not match the parsed and recompiled query exactly (not observing whitespace)', 'TEST result' => $testResult),'SQL parsing failed:');
1650 debug(array('query' => $SQLquery, 'ERROR MESSAGE'=>$parseResult),'SQL parsing failed:');
1657 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE
]['XCLASS']['t3lib/class.t3lib_sqlparser.php']) {
1658 include_once($TYPO3_CONF_VARS[TYPO3_MODE
]['XCLASS']['t3lib/class.t3lib_sqlparser.php']);