00001 <?php
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00029 class SQLStatementExtractor {
00030
00031 protected static $delimiter = ';';
00032
00039 public static function extractFile($filename) {
00040 $buffer = file_get_contents($filename);
00041 if ($buffer === false) {
00042 throw new Exception("Unable to read file: " . $filename);
00043 }
00044 return self::extractStatements(self::getLines($buffer));
00045 }
00046
00053 public static function extract($buffer) {
00054 return self::extractStatements(self::getLines($buffer));
00055 }
00056
00063 protected static function extractStatements($lines) {
00064
00065 $statements = array();
00066 $sql = "";
00067
00068 foreach($lines as $line) {
00069
00070 $line = trim($line);
00071
00072 if (self::startsWith("//", $line) ||
00073 self::startsWith("--", $line) ||
00074 self::startsWith("#", $line)) {
00075 continue;
00076 }
00077
00078 if (strlen($line) > 4 && strtoupper(substr($line,0, 4)) == "REM ") {
00079 continue;
00080 }
00081
00082 $sql .= " " . $line;
00083 $sql = trim($sql);
00084
00085
00086
00087
00088 if (strpos($line, "--") !== false) {
00089 $sql .= "\n";
00090 }
00091
00092 if (self::endsWith(self::$delimiter, $sql)) {
00093 $statements[] = self::substring($sql, 0, strlen($sql)-1 - strlen(self::$delimiter));
00094 $sql = "";
00095 }
00096 }
00097 return $statements;
00098 }
00099
00100
00101
00102
00103
00110 protected static function startsWith($check, $string) {
00111 if ($check === "" || $check === $string) {
00112 return true;
00113 } else {
00114 return (strpos($string, $check) === 0) ? true : false;
00115 }
00116 }
00117
00124 protected static function endsWith($check, $string) {
00125 if ($check === "" || $check === $string) {
00126 return true;
00127 } else {
00128 return (strpos(strrev($string), strrev($check)) === 0) ? true : false;
00129 }
00130 }
00131
00136 protected static function substring($string, $startpos, $endpos = -1) {
00137 $len = strlen($string);
00138 $endpos = (int) (($endpos === -1) ? $len-1 : $endpos);
00139 if ($startpos > $len-1 || $startpos < 0) {
00140 trigger_error("substring(), Startindex out of bounds must be 0<n<$len", E_USER_ERROR);
00141 }
00142 if ($endpos > $len-1 || $endpos < $startpos) {
00143 trigger_error("substring(), Endindex out of bounds must be $startpos<n<".($len-1), E_USER_ERROR);
00144 }
00145 if ($startpos === $endpos) {
00146 return (string) $string{$startpos};
00147 } else {
00148 $len = $endpos-$startpos;
00149 }
00150 return substr($string, $startpos, $len+1);
00151 }
00152
00159 protected static function getLines($buffer) {
00160 $lines = preg_split("/\r?\n|\r/", $buffer);
00161 return $lines;
00162 }
00163
00164 }