31 private $start = null;
38 private $limit = null;
46 private $bufferSize = 30;
52 private $buffer = null;
60 private $bufferStartPos = null;
66 private $currPos = null;
70 private $decorator = null;
79 public function __construct( $sql, $db, $bufferSize=30, $decorator = null){
83 $this->bufferSize = $bufferSize;
85 $this->bufferStartPos = null;
86 $this->currPos = $this->start;
88 $this->decorator = $decorator;
90 if ( preg_match(
'/^([\s\S]+)\slimit\s+(\d+)(\s*,\s*(\d+)\s*)?\s*$/i', $this->sql, $matches) ){
91 $this->sql = $matches[1];
92 if ( isset($matches[4]) ){
93 $this->limit = intval($matches[4]);
94 $this->start = intval($matches[2]);
97 $this->limit = intval($matches[2]);
100 if ( isset($this->limit) and $this->limit < $this->bufferSize ) $this->bufferSize = $this->limit;
107 $this->buffer = null;
115 $this->currPos = $this->start;
117 if ( !isset($this->bufferStartPos) ){
120 }
else if ( $this->bufferStartPos > $this->start ){
123 $this->buffer = null;
124 $this->bufferStartPos = null;
133 return $this->sql.
' limit '.$start.
', '.$limit;
139 private function loadBuffer(){
140 if ( $this->currPos >= $this->bufferStartPos + $this->bufferSize ){
141 $this->bufferStartPos += $this->bufferSize;
142 }
else if ( !isset($this->bufferStartPos) ){
143 $this->bufferStartPos = $this->start;
148 $q[
'-skip'] = $this->bufferStartPos;
149 $q[
'-limit'] = $this->bufferSize;
150 if ( isset($this->limit ) ){
151 $q[
'-limit'] = min($this->bufferSize, $this->start+$this->limit-$this->bufferStartPos);
153 if ( $q[
'-limit'] > 0 ){
154 $this->buffer = array();
155 $res = mysql_query($this->
getQuery($q[
'-skip'], $q[
'-limit']), $this->
db);
156 if ( !$res )
throw new Exception(mysql_error($this->
db));
158 while ($row = mysql_fetch_object($res) ){
159 if ( isset($this->decorator) and is_callable($this->decorator) ){
160 $row = call_user_func($this->decorator, $row);
162 $this->buffer[] = $row;
164 @mysql_free_result($res);
166 $this->buffer = array();
177 return $this->buffer[$this->currPos-$this->bufferStartPos];
185 return $this->currPos;
200 return isset($this->buffer[$this->currPos-$this->bufferStartPos]);