00001 <?php
00002
00015
00016
00017
00018 class SQLParser {
00019
00021 var $driver;
00022
00024 var $dataSource;
00025
00027 var $debug;
00028
00029 var $errorMsg;
00030
00032 var $commentDelim;
00033
00035 var $statementDelim;
00036
00042 function SQLParser($driver, &$dataSource, $debug = false) {
00043 $this->driver = $driver;
00044 $this->dataSource = &$dataSource;
00045 $this->debug = $debug;
00046 $this->errorMsg = array();
00047 $this->commentDelim = '(\-\-|#)';
00048 $this->statementDelim = ';';
00049 }
00050
00057 function executeFile($file, $failOnError = true) {
00058 if (!file_exists($file) || !is_readable($file)) {
00059 array_push($this->errorMsg, "$file does not exist or is not readble!");
00060 return false;
00061 }
00062
00063
00064 $sql = join('', file($file));
00065 $this->stripComments($sql);
00066 $statements = &$this->parseStatements($sql);
00067
00068
00069 for ($i=0, $count=count($statements); $i < $count; $i++) {
00070 if ($this->debug) {
00071 echo 'Executing: ', $statements[$i], "\n\n";
00072 }
00073
00074 $this->dataSource->execute($statements[$i]);
00075
00076 if ($this->dataSource->errorNo() != 0) {
00077
00078 array_push($this->errorMsg, $this->dataSource->errorMsg());
00079
00080 if ($failOnError) {
00081
00082 return false;
00083 } else {
00084 $error = true;
00085 }
00086 }
00087 }
00088
00089 return isset($error) ? false : true;
00090 }
00091
00096 function stripComments(&$sql) {
00097 $sql = trim(String::regexp_replace(sprintf('/^\s*%s(.*)$/m', $this->commentDelim), '', $sql));
00098 }
00099
00105 function &parseStatements(&$sql) {
00106 $statements = array();
00107 $statementsTmp = explode($this->statementDelim, $sql);
00108
00109 $currentStatement = '';
00110 $numSingleQuotes = $numEscapedSingleQuotes = 0;
00111
00112
00113 for ($i=0, $count=count($statementsTmp); $i < $count; $i++) {
00114
00115 $numSingleQuotes += String::substr_count($statementsTmp[$i], "'");
00116
00117
00118 $numEscapedSingleQuotes += String::regexp_match_all("/(?<!\\\\)(\\\\\\\\)*\\\\'/", $statementsTmp[$i], $matches);
00119
00120 $currentStatement .= $statementsTmp[$i];
00121
00122 if (($numSingleQuotes - $numEscapedSingleQuotes) % 2 == 0) {
00123
00124 if (trim($currentStatement) !== '') {
00125 array_push($statements, trim($currentStatement));
00126 }
00127 $currentStatement = '';
00128 $numSingleQuotes = $numEscapedSingleQuotes = 0;
00129
00130 } else {
00131
00132 $currentStatement .= $this->statementDelim;
00133 }
00134 }
00135
00136 return $statements;
00137 }
00138
00143 function getErrorMsg() {
00144 return count($this->errorMsg) == 0 ? null : array_pop($this->errorMsg);
00145 }
00146
00147 }
00148
00149 ?>