Adding transaction stuff to everything but PGSQL (need to look it up)
[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 'fetch_assoc' => '%result',
117 'fetch_row' => '%result',
118 'fetch_object' => '%result',
119 'free_result' => '%result',
120 'insert_id' => '%link',
121 'num_rows' => '%result',
122 'affected_rows' => '%result'
123 );
124
125 // ###################################################################
126 /**
127 * Constructor
128 */
129 function __construct(&$registry)
130 {
131 $this->registry =& $registry;
132
133 // because ivars and call_user_func() are conspiring against us...
134 foreach ($this->commands AS $key => $string)
135 {
136 if (strpos($string, '$this->') !== false)
137 {
138 $this->commands["$key"] = array($this, str_replace('$this->', '', $string));
139 }
140 }
141 }
142
143 // ###################################################################
144 /**
145 * (PHP 4) Constructor
146 */
147 function DB_Abstract(&$registry)
148 {
149 $this->__construct($registry);
150 }
151
152 // ###################################################################
153 /**
154 * Initializes the class and all subclasses under a common package name
155 *
156 * @access protected
157 *
158 * @return string The package name
159 */
160 function init_as_package()
161 {
162 if (!defined('ISSO_DB_LAYER'))
163 {
164 define('ISSO_DB_LAYER', get_class($this));
165 trigger_error('ISSO_DB_LAYER was defined automatically by DB::init_as_package(). Define the constant yourself to remove this warning', E_USER_WARNING);
166 }
167
168 return 'db';
169 }
170
171 // ###################################################################
172 /**
173 * Connect to a the specified database
174 *
175 * @access public
176 *
177 * @param string Server name
178 * @param string User name
179 * @param string Password
180 * @param string Database name
181 * @param bool Use p-connect?
182 *
183 * @return bool Result of connect
184 */
185 function connect($server, $user, $password, $database, $pconnect)
186 {
187 $this->registry->check_isso_fields(get_class($this));
188
189 if ($this->dblink == false)
190 {
191 $this->dblink = call_user_func(($pconnect ? $this->commands['pconnect'] : $this->commands['connect']), $server, $user, $password, $database);
192
193 if ($this->dblink == false)
194 {
195 $this->error('DB-Link == false, cannot connect');
196 return false;
197 }
198
199 return true;
200 }
201 }
202
203 // ###################################################################
204 /**
205 * Send a query to the open database link
206 *
207 * @access public
208 *
209 * @param string Query string
210 *
211 * @return integer Result
212 */
213 function query($string)
214 {
215 $time = microtime();
216
217 $this->querystr = $string;
218 $this->result = call_user_func($this->commands['query'], $this->dblink, $string);
219
220 if (!$this->result)
221 {
222 $this->error('Invalid SQL query');
223 }
224
225 $this->history[] = $history = array('query' => $string, 'time' => $this->registry->modules['functions']->fetch_microtime_diff($time), 'trace' => $this->registry->format_debug_trace(debug_backtrace()));
226
227 if (defined('ISSO_SHOW_QUERIES_LIVE'))
228 {
229 if (constant('ISSO_SHOW_QUERIES_LIVE'))
230 {
231 print($this->construct_query_debug($history));
232 }
233 }
234
235 return $this->result;
236 }
237
238 // ###################################################################
239 /**
240 * Escape a string (depending on character set, if supported)
241 *
242 * @access public
243 *
244 * @param string String to be escaped
245 *
246 * @return string Escaped string
247 */
248 function escape_string($string)
249 {
250 return call_user_func($this->commands['escape_string'], $this->dblink, $string);
251 }
252
253 // ###################################################################
254 /**
255 * Fetch the query result as an array
256 *
257 * @access public
258 *
259 * @param integer Result
260 * @param bool Return an associative array?
261 *
262 * @return array A row of the query result
263 */
264 function fetch_array($result, $assoc = true)
265 {
266 return call_user_func($this->commands[ ($assoc ? 'fetch_assoc' : 'fetch_row') ], $result);
267 }
268
269 // ###################################################################
270 /**
271 * Fetch the query result as an object
272 *
273 * @access public
274 *
275 * @param integer Result
276 *
277 * @return object An object with the query result
278 */
279 function fetch_object($result)
280 {
281 return call_user_func($this->commands['fetch_object'], $result);
282 }
283
284 // ###################################################################
285 /**
286 * Send a query and return the first row of the results
287 *
288 * @access public
289 *
290 * @param string Query string
291 * @param string Result return function (in the database layer)
292 *
293 * @return mixed Results in variable formats
294 */
295 function query_first($string, $callback = 'fetch_array')
296 {
297 $resource = $this->query($string);
298 $return = $this->$callback($resource);
299 $this->free_result($resource);
300 return $return;
301 }
302
303 // ###################################################################
304 /**
305 * Free the current query result
306 *
307 * @access public
308 *
309 * @param integer Result
310 */
311 function free_result($result)
312 {
313 call_user_func($this->commands['free_result'], $result);
314 $this->result = null;
315 $this->querystr = '';
316 }
317
318 // ###################################################################
319 /**
320 * Fetch the unique ID of the record just inserted
321 *
322 * @access public
323 *
324 * @return integer Insert-ID
325 */
326 function insert_id()
327 {
328 return call_user_func($this->commands['insert_id'], $this->dblink);
329 }
330
331 // ###################################################################
332 /**
333 * Fetch the number of rows in the result
334 *
335 * @access public
336 *
337 * @param integer Result
338 *
339 * @return integer Number of rows
340 */
341 function num_rows($result)
342 {
343 return call_user_func($this->commands['num_rows'], $result);
344 }
345
346 // ###################################################################
347 /**
348 * Fetch the number of rows affected by the query
349 *
350 * @access public
351 *
352 * @param integer Result
353 *
354 * @return integer Number of affected rows
355 */
356 function affected_rows($result)
357 {
358 return call_user_func($this->commands['affected_rows'], $result);
359 }
360
361 // ###################################################################
362 /**
363 * Sends the command to start a transaction. This command should never
364 * be reached as it's always overridden
365 *
366 * @access public
367 */
368 function transaction_start()
369 {
370 trigger_error('DB_Abstract::transaction_start() needs to be overridden when subclassed', E_USER_ERROR);
371 }
372
373 // ###################################################################
374 /**
375 * Sends the command to set this as a savepoint. This command should never
376 * be reached as it's always overridden
377 *
378 * @access public
379 *
380 * @param string Named savepoint
381 */
382 function transaction_savepoint($name)
383 {
384 trigger_error('DB_Abstract::transaction_savepoint() needs to be overridden when subclassed', E_USER_ERROR);
385 }
386
387 // ###################################################################
388 /**
389 * Sends the command to rollback to a given savepoint. This command
390 * should never be reached as it's always overridden
391 *
392 * @access public
393 *
394 * @param string Named savepoint
395 */
396 function transaction_rollback($name)
397 {
398 trigger_error('DB_Abstract::transaction_rollback() needs to be overridden when subclassed', E_USER_ERROR);
399 }
400
401 // ###################################################################
402 /**
403 * Sends the command to commit the entire transaction. This command
404 * should never be reached as it's always overridden
405 *
406 * @access public
407 */
408 function transaction_commit($name)
409 {
410 trigger_error('DB_Abstract::transaction_commit() needs to be overridden when subclassed', E_USER_ERROR);
411 }
412
413 // ###################################################################
414 /**
415 * Constructs a table of query information output that is used in some
416 * other modules to display a list of queries. This merely formats
417 * a DB->history array entry nicely
418 *
419 * @access public
420 *
421 * @param array An entry from DB->history
422 *
423 * @return string A formatted table block
424 */
425 function construct_query_debug($query)
426 {
427 $block = "<strong>Query:</strong>\n\n<div>" . $this->registry->entity_encode($query['query']) . "</div>\n";
428 $block .= "<tr style=\"background-color: #FFFFFF; text-align: left\">\n\t<td>\n\t\t";
429 $block .= "<strong>Time:</strong> $query[time]<br />\n\t\t<br />\n\t\t";
430 $block .= "<strong>Backtrace:</strong>\n\t\t<div>" . implode("<br />\n", $query['trace']) . "</div>\n\t</td>\n</tr>";
431
432 return $this->registry->message('Query Debug', $block, 1, true, false, 0);
433 }
434
435 // ###################################################################
436 /**
437 * Error wrapper for ISSO->message()
438 *
439 * @access protected
440 *
441 * @param string User defined error message
442 */
443 function error($message)
444 {
445 if ($this->showerrors)
446 {
447 if ($this->dblink)
448 {
449 $this->errnum = call_user_func($this->commands['error_num'], $this->dblink);
450 $this->errstr = call_user_func($this->commands['error_str'], $this->dblink);
451 }
452
453 $style['code'] = 'font-family: \'Courier New\', Courier, mono; font-size: 11px;';
454
455 $message_prepped = "<blockquote>\n<p>";
456 $message_prepped .= "\n\t&raquo; <strong>Query:</strong>\n<br /> <pre style=\"$style[code]\">" . htmlspecialchars($this->querystr) ."</pre>\n<br />";
457 $message_prepped .= "\n\t&raquo; <strong>Error Number:</strong> <span style=\"$style[code]\">" . $this->errnum . "</span>\n<br />";
458 $message_prepped .= "\n\t&raquo; <strong>Error Message:</strong> <span style=\"$style[code]\">" . $this->errstr . "</span>\n<br />";
459 $message_prepped .= "\n\t&raquo; <strong>Additional Notes:</strong> <span style=\"$style[code]\">" . $message . "</span>\n<br />";
460 $message_prepped .= "\n\t&raquo; <strong>File:</strong> <span style=\"$style[code]\">" . $_SERVER['PHP_SELF'] . "</span>\n";
461 $message_prepped .= "\n</p>\n</blockquote>";
462
463 $this->registry->message('Database Error in `<em>' . $this->registry->application . '</em>`', $message_prepped, 3);
464 exit;
465 }
466 }
467 }
468
469 /*=====================================================================*\
470 || ###################################################################
471 || # $HeadURL$
472 || # $Id$
473 || ###################################################################
474 \*=====================================================================*/
475 ?>