Database results are now independent objects as opposed to being a resource identifie...
[isso.git] / Db.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework
5 || # Copyright (c)2002-2007 Blue Static
6 || #
7 || # This program is free software; you can redistribute it and/or modify
8 || # it under the terms of the GNU General Public License as published by
9 || # the Free Software Foundation; version 2 of the License.
10 || #
11 || # This program is distributed in the hope that it will be useful, but
12 || # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 || # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 || # more details.
15 || #
16 || # You should have received a copy of the GNU General Public License along
17 || # with this program; if not, write to the Free Software Foundation, Inc.,
18 || # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
19 || ###################################################################
20 \*=====================================================================*/
21
22 /**
23 * Abstract Database Layer (Db.php)
24 *
25 * @package ISSO
26 */
27
28 require_once('ISSO/Functions.php');
29
30 /**
31 * Abstract Database Layer
32 *
33 * This class provides an abstract template for all RDBMS layers. All
34 * ISSO abstraction layers should inherit this class. It provides error
35 * reporting, SQL analysis, and general connection functionality.
36 *
37 * Constants:
38 * ISSO_SHOW_QUERIES_LIVE - Show queries in page output as they are sent
39 *
40 * @author Blue Static
41 * @copyright Copyright (c)2002 - 2007, Blue Static
42 * @package ISSO
43 *
44 */
45 abstract class BSDb
46 {
47 /**
48 * Determines whether or not errors should be shown
49 * @var bool
50 */
51 public $showerrors = true;
52
53 /**
54 * Current error number
55 * @var integer
56 */
57 protected $errnum = 0;
58
59 /**
60 * Description of current error
61 * @var string
62 */
63 protected $errstr = '';
64
65 /**
66 * Currend open database connection
67 * @var integer
68 */
69 protected $dblink = null;
70
71 /**
72 * Current query ID
73 * @var integer
74 */
75 protected $result = null;
76
77 /**
78 * Current query string
79 * @var string
80 */
81 protected $querystr = '';
82
83 /**
84 * History of all executed queryies
85 * @var array
86 */
87 protected $history = array();
88
89 // ###################################################################
90 /**
91 * Returns the history information array
92 *
93 * @return array History record
94 */
95 public function getHistory()
96 {
97 return $this->history;
98 }
99
100 // ###################################################################
101 /**
102 * Connect to a the specified database
103 *
104 * @param string Server name
105 * @param string User name
106 * @param string Password
107 * @param string Database name
108 *
109 * @return bool Result of connect
110 */
111 public function connect($server, $user, $password, $database)
112 {
113 if ($this->dblink == false)
114 {
115 $this->dblink = $this->_connect($server, $user, $password, $database);
116
117 if ($this->dblink == false)
118 {
119 throw new BSDbException('Connect Failed', -1, 'DB-Link == false; connect failed');
120 return false;
121 }
122
123 return true;
124 }
125 }
126
127 /**
128 * Abstract function that returns a database link after establishing a connection. This just
129 * calls the function and does not do any checking
130 *
131 * @param string Server name
132 * @param string User name
133 * @param string Password
134 * @param string Database name
135 *
136 * @return integer Database link
137 */
138 protected abstract function _connect($server, $user, $password, $database);
139
140 // ###################################################################
141 /**
142 * Send a query to the open database link
143 *
144 * @param string Query string
145 *
146 * @return BSDbResult Result object, or NULL
147 */
148 public function query($string)
149 {
150 $time = microtime();
151
152 $this->querystr = $string;
153 $this->result = $this->_query($string);
154
155 if (!$this->result)
156 {
157 throw new BSDbException($this->_errorString(), $this->_errorNumber(), $string);
158 }
159
160 $this->history[] = $history = array('query' => $string, 'time' => BSFunctions::FetchMicrotimeDiff($time), 'trace' => BSFunctions::FormatBacktrace(debug_backtrace()));
161
162 if (defined('ISSO_SHOW_QUERIES_LIVE'))
163 {
164 if (constant('ISSO_SHOW_QUERIES_LIVE'))
165 {
166 print($this->_constructDebugQuery($history));
167 }
168 }
169
170 if (strtoupper(substr(trim($string), 0, 6)) == 'SELECT')
171 {
172 $class = get_class($this) . 'Result';
173 return new $class($this->result);
174 }
175 }
176
177 /**
178 * Abstract function that executes the query command on the database
179 *
180 * @param string Query string
181 *
182 * @return integer Result ID
183 */
184 protected abstract function _query($query);
185
186 // ###################################################################
187 /**
188 * Escape a string (depending on character set, if supported)
189 *
190 * @param string String to be escaped
191 *
192 * @return string Escaped string
193 */
194 public function escapeString($string)
195 {
196 return $this->_escapeString($string);
197 }
198
199 /**
200 * Abstract function that calls the escape_string() method
201 *
202 * @param string String to escape
203 *
204 * @return string Escaped string
205 */
206 protected abstract function _escapeString($string);
207
208 // ###################################################################
209 /**
210 * Escapes a binary string for insertion into the database
211 *
212 * @param string Unescaped data
213 *
214 * @return string Escaped binary data
215 */
216 public function escapeBinary($binary)
217 {
218 return $this->_escapeBinary($binary);
219 }
220
221 /**
222 * Abstract function that calls escape_binary()
223 *
224 * @param string Binary to escape
225 *
226 * @return string Escaped binary
227 */
228 protected abstract function _escapeBinary($string);
229
230 // ###################################################################
231 /**
232 * Unescapes a binary string that was fetched from the database
233 *
234 * @param string Escaped data
235 *
236 * @return string Unescaped binary data
237 */
238 public function unescapeBinary($binary)
239 {
240 return $this->_unescapeBinary($binary);
241 }
242
243 /**
244 * Abstract function that calls unescape_binary()
245 *
246 * @param string Escaped data
247 *
248 * @return string Data that has been unescaped
249 */
250 protected abstract function _unescapeBinary($string);
251
252 // ###################################################################
253 /**
254 * Send a query and return the first row of the results
255 *
256 * @param string Query string
257 * @param string Result return function (in the database layer)
258 *
259 * @return mixed Results in variable formats
260 */
261 public function queryFirst($string, $callback = 'fetchArray')
262 {
263 $resource = $this->query($string);
264 if ($resource)
265 {
266 $return = $resource->$callback();
267 $resource->free();
268 return $return;
269 }
270 else
271 {
272 return false;
273 }
274 }
275
276 // ###################################################################
277 /**
278 * Returns the errror number
279 */
280 public abstract function _errorNumber();
281
282 /**
283 * Returns the error string
284 */
285 public abstract function _errorString();
286
287 // ###################################################################
288 /**
289 * Sends the command to start a transaction. This command should never
290 * be reached as it's always overridden
291 */
292 public abstract function begin();
293
294 // ###################################################################
295 /**
296 * Sends the command to rollback to a given savepoint. This command
297 * should never be reached as it's always overridden
298 *
299 * @param string Named savepoint
300 */
301 public abstract function rollback();
302
303 // ###################################################################
304 /**
305 * Sends the command to commit the entire transaction. This command
306 * should never be reached as it's always overridden
307 */
308 public abstract function commit();
309 }
310
311 /**
312 * Database Result
313 *
314 * This class holds result information for a database result
315 *
316 * @author rsesek
317 * @copyright Copyright (c)2002 - 2007, Blue Static
318 * @package ISSO
319 *
320 */
321 abstract class BSDbResult
322 {
323 /**
324 * The result resource
325 * @var resource
326 */
327 private $result;
328
329 // ###################################################################
330 /**
331 * Sets the resource and returns a result object
332 *
333 * @param resource The result of the query
334 */
335 public function __construct($result)
336 {
337 $this->result = $result;
338 }
339
340 // ###################################################################
341 /**
342 * Fetch the query result as an array
343 *
344 * @param integer Result
345 * @param bool Return an associative array?
346 *
347 * @return array A row of the query result
348 */
349 public function fetchArray($assoc = true)
350 {
351 return $this->{($assoc ? '_fetchAssocArray' : '_fetchRowArray')}($this->result);
352 }
353
354 /**
355 * Abstract function that returns an associative array of given result
356 *
357 * @param integer Result
358 *
359 * @return array Result array
360 */
361 protected abstract function _fetchAssocArray($result);
362
363 /**
364 * Abstract function that returns a row array of given result
365 *
366 * @param integer Result
367 *
368 * @return array Result array
369 */
370 protected abstract function _fetchRowArray($result);
371
372 // ###################################################################
373 /**
374 * Fetch the query result as an object
375 *
376 * @param integer Result
377 *
378 * @return object An object with the query result
379 */
380 public function fetchObject()
381 {
382 return $this->_fetchObject($this->result);
383 }
384
385 /**
386 * Abstract function that returns an object for a given result
387 *
388 * @param integer Result
389 *
390 * @return object Row object
391 */
392 public abstract function _fetchObject($result);
393
394 // ###################################################################
395 /**
396 * Free the current query result
397 *
398 * @param integer Result
399 */
400 public function free()
401 {
402 $this->_freeResult($result);
403 }
404
405 /**
406 * Abstract function that frees a given result
407 *
408 * @param integer Result ID
409 */
410 protected abstract function _freeResult($result);
411
412 // ###################################################################
413 /**
414 * Fetch the unique ID of the record just inserted
415 *
416 * @return integer Insert-ID
417 */
418 public function insertId()
419 {
420 return $this->_insertID();
421 }
422
423 /**
424 * Abstract function that returns the ID of the most recently-inserted
425 * record
426 *
427 * @return integer Insertion ID
428 */
429 protected abstract function _insertId();
430
431 // ###################################################################
432 /**
433 * Fetch the number of rows in the result
434 *
435 * @param integer Result
436 *
437 * @return integer Number of rows
438 */
439 public function size()
440 {
441 return $this->_numRows($this->result);
442 }
443
444 /**
445 * Abstract function that returns the number of rows in the result
446 *
447 * @param integer Result ID
448 *
449 * @return integer Number of rows
450 */
451 protected abstract function _numRows($result);
452
453 // ###################################################################
454 /**
455 * Fetch the number of rows affected by the query
456 *
457 * @param integer Result
458 *
459 * @return integer Number of affected rows
460 */
461 public function affectedRows()
462 {
463 return $this->_affectedRows($this->result);
464 }
465
466 /**
467 * Abstract function that returns the number of affected rows in the result
468 *
469 * @param integer Result ID
470 *
471 * @return integer Number of rows
472 */
473 protected abstract function _affectedRows($result);
474 }
475
476 /**
477 * Database Exception
478 *
479 * Exception handler class for the database classes
480 *
481 * @author Blue Static
482 * @copyright Copyright (c)2002 - 2007, Blue Static
483 * @package ISSO
484 *
485 */
486 class BSDbException extends Exception
487 {
488 /**
489 * The query string that caused the error
490 * @var string
491 */
492 private $query;
493
494 // ###################################################################
495 /**
496 * Initializes a new database exception
497 *
498 * @param string The error message
499 * @param ineger MySQL error code
500 * @param sring Query string that caused the error
501 */
502 public function __construct($error, $errorNum, $query)
503 {
504 $this->query = $query;
505 parent::__construct($error, $errorNum);
506 }
507
508 // ###################################################################
509 /**
510 * Returns the query that failed
511 *
512 * @return string
513 */
514 public function getQuery()
515 {
516 return $this->query;
517 }
518 }
519
520 ?>