Suppress errors in query()
[isso.git] / db.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # app [#]version[#]
5 || # Copyright ©2002-[#]year[#] Iris Studios, Inc.
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 [#]gpl[#] 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
24 * db.php
25 *
26 * @package ISSO
27 */
28
29 /**
30 * Abstract Database Layer
31 *
32 * This class provides an abstract template for all RDBMS layers. All
33 * ISSO abstraction layers should inherit this class. It provides error
34 * reporting, SQL analysis, and general connection functionality.
35 *
36 * Constants:
37 * [required] ISSO_DB_LAYER - The name of the DB layer module used in the application
38 * ISSO_SHOW_QUERIES_LIVE - Show queries in page output as they are sent
39 *
40 * @author Iris Studios, Inc.
41 * @copyright Copyright ©2002 - [#]year[#], Iris Studios, Inc.
42 * @version $Revision$
43 * @package ISSO
44 *
45 */
46 class DB_Abstract
47 {
48 /**
49 * Framework registry object
50 * @var object
51 * @access protected
52 */
53 var $registry = null;
54
55 /**
56 * Determines whether or not errors should be shown
57 * @var bool
58 * @access public
59 */
60 var $showerrors = true;
61
62 /**
63 * Current error number
64 * @var integer
65 * @access protected
66 */
67 var $errnum = 0;
68
69 /**
70 * Description of current error
71 * @var string
72 * @access protected
73 */
74 var $errstr = '';
75
76 /**
77 * Currend open MySQL connexion
78 * @var resource
79 * @access protected
80 */
81 var $dblink = null;
82
83 /**
84 * Current query ID
85 * @var integer
86 * @access protected
87 */
88 var $result = null;
89
90 /**
91 * Current query string
92 * @var string
93 * @access protected
94 */
95 var $querystr = '';
96
97 /**
98 * History of all executed queryies
99 * @var array
100 * @access protected
101 */
102 var $history = array();
103
104 /**
105 * Command mapping list
106 * @var array
107 * @access protected
108 */
109 var $commands = array(
110 'pconnect' => '%server %user %password %database',
111 'connect' => '%server %user %password %database',
112 'query' => '%link %query',
113 'error_num' => '%link',
114 'error_str' => '%link',
115 'escape_string' => '%link %string',
116 'escape_binary' => '%string',
117 'unescape_binary' => '%string',
118 'fetch_assoc' => '%result',
119 'fetch_row' => '%result',
120 'fetch_object' => '%result',
121 'free_result' => '%result',
122 'insert_id' => '%link',
123 'num_rows' => '%result',
124 'affected_rows' => '%result'
125 );
126
127 // ###################################################################
128 /**
129 * Constructor
130 */
131 function __construct(&$registry)
132 {
133 $this->registry =& $registry;
134
135 // because ivars and call_user_func() are conspiring against us...
136 foreach ($this->commands AS $key => $string)
137 {
138 if (strpos($string, '$this->') !== false)
139 {
140 $this->commands["$key"] = array($this, str_replace('$this->', '', $string));
141 }
142 }
143 }
144
145 // ###################################################################
146 /**
147 * (PHP 4) Constructor
148 */
149 function DB_Abstract(&$registry)
150 {
151 $this->__construct($registry);
152 }
153
154 // ###################################################################
155 /**
156 * Initializes the class and all subclasses under a common package name
157 *
158 * @access protected
159 *
160 * @return string The package name
161 */
162 function init_as_package()
163 {
164 if (!defined('ISSO_DB_LAYER'))
165 {
166 define('ISSO_DB_LAYER', get_class($this));
167 trigger_error('ISSO_DB_LAYER was defined automatically by DB::init_as_package(). Define the constant yourself to remove this warning', E_USER_WARNING);
168 }
169
170 return 'db';
171 }
172
173 // ###################################################################
174 /**
175 * Connect to a the specified database
176 *
177 * @access public
178 *
179 * @param string Server name
180 * @param string User name
181 * @param string Password
182 * @param string Database name
183 * @param bool Use p-connect?
184 *
185 * @return bool Result of connect
186 */
187 function connect($server, $user, $password, $database, $pconnect)
188 {
189 $this->registry->check_isso_fields(get_class($this));
190
191 if ($this->dblink == false)
192 {
193 $this->dblink = call_user_func(($pconnect ? $this->commands['pconnect'] : $this->commands['connect']), $server, $user, $password, $database);
194
195 if ($this->dblink == false)
196 {
197 $this->error('DB-Link == false, cannot connect');
198 return false;
199 }
200
201 return true;
202 }
203 }
204
205 // ###################################################################
206 /**
207 * Send a query to the open database link
208 *
209 * @access public
210 *
211 * @param string Query string
212 *
213 * @return integer Result
214 */
215 function query($string)
216 {
217 $time = microtime();
218
219 $this->querystr = $string;
220 $this->result = @call_user_func($this->commands['query'], $this->dblink, $string);
221
222 if (!$this->result)
223 {
224 $this->error('Invalid SQL query');
225 }
226
227 $this->history[] = $history = array('query' => $string, 'time' => ($this->registry->is_loaded('functions') ? $this->registry->modules['functions']->fetch_microtime_diff($time) : 0), 'trace' => $this->registry->format_debug_trace(debug_backtrace()));
228
229 if (defined('ISSO_SHOW_QUERIES_LIVE'))
230 {
231 if (constant('ISSO_SHOW_QUERIES_LIVE'))
232 {
233 print($this->construct_query_debug($history));
234 }
235 }
236
237 return $this->result;
238 }
239
240 // ###################################################################
241 /**
242 * Escape a string (depending on character set, if supported)
243 *
244 * @access public
245 *
246 * @param string String to be escaped
247 *
248 * @return string Escaped string
249 */
250 function escape_string($string)
251 {
252 return call_user_func($this->commands['escape_string'], $this->dblink, $string);
253 }
254
255 // ###################################################################
256 /**
257 * Escapes a binary string for insertion into the database
258 *
259 * @access public
260 *
261 * @param string Unescaped data
262 *
263 * @return string Escaped binary data
264 */
265 function escape_binary($binary)
266 {
267 return call_user_func($this->commands['escape_binary'], $binary);
268 }
269
270 // ###################################################################
271 /**
272 * Unescapes a binary string that was fetched from the database
273 *
274 * @access public
275 *
276 * @param string Escaped data
277 *
278 * @return string Unescaped binary data
279 */
280 function unescape_binary($binary)
281 {
282 return call_user_func($this->commands['unescape_binary'], $binary);
283 }
284
285 // ###################################################################
286 /**
287 * Fetch the query result as an array
288 *
289 * @access public
290 *
291 * @param integer Result
292 * @param bool Return an associative array?
293 *
294 * @return array A row of the query result
295 */
296 function fetch_array($result, $assoc = true)
297 {
298 return call_user_func($this->commands[ ($assoc ? 'fetch_assoc' : 'fetch_row') ], $result);
299 }
300
301 // ###################################################################
302 /**
303 * Fetch the query result as an object
304 *
305 * @access public
306 *
307 * @param integer Result
308 *
309 * @return object An object with the query result
310 */
311 function fetch_object($result)
312 {
313 return call_user_func($this->commands['fetch_object'], $result);
314 }
315
316 // ###################################################################
317 /**
318 * Send a query and return the first row of the results
319 *
320 * @access public
321 *
322 * @param string Query string
323 * @param string Result return function (in the database layer)
324 *
325 * @return mixed Results in variable formats
326 */
327 function query_first($string, $callback = 'fetch_array')
328 {
329 $resource = $this->query($string);
330 $return = $this->$callback($resource);
331 $this->free_result($resource);
332 return $return;
333 }
334
335 // ###################################################################
336 /**
337 * Free the current query result
338 *
339 * @access public
340 *
341 * @param integer Result
342 */
343 function free_result($result)
344 {
345 call_user_func($this->commands['free_result'], $result);
346 $this->result = null;
347 $this->querystr = '';
348 }
349
350 // ###################################################################
351 /**
352 * Fetch the unique ID of the record just inserted
353 *
354 * @access public
355 *
356 * @return integer Insert-ID
357 */
358 function insert_id()
359 {
360 return call_user_func($this->commands['insert_id'], $this->dblink);
361 }
362
363 // ###################################################################
364 /**
365 * Fetch the number of rows in the result
366 *
367 * @access public
368 *
369 * @param integer Result
370 *
371 * @return integer Number of rows
372 */
373 function num_rows($result)
374 {
375 return call_user_func($this->commands['num_rows'], $result);
376 }
377
378 // ###################################################################
379 /**
380 * Fetch the number of rows affected by the query
381 *
382 * @access public
383 *
384 * @param integer Result
385 *
386 * @return integer Number of affected rows
387 */
388 function affected_rows($result)
389 {
390 return call_user_func($this->commands['affected_rows'], $result);
391 }
392
393 // ###################################################################
394 /**
395 * Sends the command to start a transaction. This command should never
396 * be reached as it's always overridden
397 *
398 * @access public
399 */
400 function transaction_start()
401 {
402 trigger_error('DB_Abstract::transaction_start() needs to be overridden when subclassed', E_USER_ERROR);
403 }
404
405 // ###################################################################
406 /**
407 * Sends the command to set this as a savepoint. This command should never
408 * be reached as it's always overridden
409 *
410 * @access public
411 *
412 * @param string Named savepoint
413 */
414 function transaction_savepoint($name)
415 {
416 trigger_error('DB_Abstract::transaction_savepoint() needs to be overridden when subclassed', E_USER_ERROR);
417 }
418
419 // ###################################################################
420 /**
421 * Sends the command to rollback to a given savepoint. This command
422 * should never be reached as it's always overridden
423 *
424 * @access public
425 *
426 * @param string Named savepoint
427 */
428 function transaction_rollback($name)
429 {
430 trigger_error('DB_Abstract::transaction_rollback() needs to be overridden when subclassed', E_USER_ERROR);
431 }
432
433 // ###################################################################
434 /**
435 * Sends the command to commit the entire transaction. This command
436 * should never be reached as it's always overridden
437 *
438 * @access public
439 */
440 function transaction_commit($name)
441 {
442 trigger_error('DB_Abstract::transaction_commit() needs to be overridden when subclassed', E_USER_ERROR);
443 }
444
445 // ###################################################################
446 /**
447 * Constructs a table of query information output that is used in some
448 * other modules to display a list of queries. This merely formats
449 * a DB->history array entry nicely
450 *
451 * @access public
452 *
453 * @param array An entry from DB->history
454 *
455 * @return string A formatted table block
456 */
457 function construct_query_debug($query)
458 {
459 $block = "<strong>Query:</strong>\n\n<div>" . $this->registry->entity_encode($query['query']) . "</div>\n";
460 $block .= "<tr style=\"background-color: #FFFFFF; text-align: left\">\n\t<td>\n\t\t";
461 $block .= "<strong>Time:</strong> $query[time]<br />\n\t\t<br />\n\t\t";
462 $block .= "<strong>Backtrace:</strong>\n\t\t<div>" . implode("<br />\n", $query['trace']) . "</div>\n\t</td>\n</tr>";
463
464 return $this->registry->message('Query Debug', $block, 1, true, false, 0);
465 }
466
467 // ###################################################################
468 /**
469 * Error wrapper for ISSO->message()
470 *
471 * @access protected
472 *
473 * @param string User defined error message
474 */
475 function error($message)
476 {
477 if ($this->showerrors)
478 {
479 if ($this->dblink)
480 {
481 $this->errnum = call_user_func($this->commands['error_num'], $this->dblink);
482 $this->errstr = call_user_func($this->commands['error_str'], $this->dblink);
483 }
484
485 $style['code'] = 'font-family: \'Courier New\', Courier, mono; font-size: 11px;';
486
487 $message_prepped = "<blockquote>\n<p>";
488 $message_prepped .= "\n\t&raquo; <strong>Query:</strong>\n<br /> <pre style=\"$style[code]\">" . htmlspecialchars($this->querystr) ."</pre>\n<br />";
489 $message_prepped .= "\n\t&raquo; <strong>Error Number:</strong> <span style=\"$style[code]\">" . $this->errnum . "</span>\n<br />";
490 $message_prepped .= "\n\t&raquo; <strong>Error Message:</strong> <span style=\"$style[code]\">" . $this->errstr . "</span>\n<br />";
491 $message_prepped .= "\n\t&raquo; <strong>Additional Notes:</strong> <span style=\"$style[code]\">" . $message . "</span>\n<br />";
492 $message_prepped .= "\n\t&raquo; <strong>File:</strong> <span style=\"$style[code]\">" . $_SERVER['PHP_SELF'] . "</span>\n";
493 $message_prepped .= "\n</p>\n</blockquote>";
494
495 $this->registry->message('Database Error in `<em>' . $this->registry->application . '</em>`', $message_prepped, 3);
496 exit;
497 }
498 }
499 }
500
501 /*=====================================================================*\
502 || ###################################################################
503 || # $HeadURL$
504 || # $Id$
505 || ###################################################################
506 \*=====================================================================*/
507 ?>