/[drupal]/contributions/sandbox/crell/pdo/pdo.php
ViewVC logotype

Contents of /contributions/sandbox/crell/pdo/pdo.php

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


Revision 1.2 - (show annotations) (download) (as text)
Sun Dec 9 06:54:57 2007 UTC (23 months, 2 weeks ago) by crell
Branch: MAIN
CVS Tags: HEAD
Changes since 1.1: +3 -171 lines
File MIME type: text/x-php
- Factor code out into separate files in a more logical fashion.
1 <?php
2
3 error_reporting(E_ALL | E_STRICT);
4
5 define('DEBUG', TRUE);
6
7 function debug($msg, $label = 'DEBUG', $stealth = FALSE) {
8 if (defined('DEBUG') && DEBUG) {
9 if (is_bool($msg)) $msg = $msg ? 'TRUE' : 'FALSE';
10 $display = $stealth ? ' style="display: none;"' : '';
11 $backtrace = debug_backtrace();
12 $debug = array();
13 $stack = (isset($backtrace[1]['class']) ? "{$backtrace[1]['class']}::" : '')
14 . (isset($backtrace[1]['function']) ? "{$backtrace[1]['function']}" : '');
15 if ($stack) $debug[] = $stack;
16 $debug[] = "Line {$backtrace[0]['line']} of {$backtrace[0]['file']}";
17 $debug = implode('<br />', $debug);
18 print "<pre{$display}>{$label}: {$debug}:<br />" . print_r($msg, 1) . "</pre><br />\n";
19 }
20 }
21
22 //debug(False, 'Something here', TRUE);
23
24 /**
25 * Base Database API class.
26 *
27 * This class provides a Drupal-specific extension of the PDO database abstraction class in PHP.
28 * All database access calls should be issued statically against this class. It acts as a Factory,
29 * returning the appropriate child class for a specific database implmentation based on the
30 * values of the global $db_url array.
31 *
32 */
33 abstract class Database extends PDO {
34
35 /**
36 * The format for getting a random number in this particular database.
37 *
38 * @var string
39 */
40 static public $rand;
41
42 /**
43 * The date() foramt code needed to convert a unix timestamp int
44 * the native timestamp format of this database.
45 *
46 * @var unknown_type
47 */
48 static public $timestamp;
49
50 /**
51 * The date() format code to turn a unix timestamp into
52 * the native date format of the database.
53 *
54 * @var string
55 */
56 static public $time;
57
58 static protected $connections = array();
59
60 static protected $dbUrls = NULL;
61
62 static $activeKey = 'default';
63
64 function __construct($dsn, $username = "", $password = "", $driver_options = array()) {
65 $driver_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION; // Because the other methods don't seem to work right.
66 parent::__construct($dsn, $username, $password, $driver_options);
67 $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('DBStatement' , array($this)));
68 }
69
70 public static function getActiveConnection($target = 'default') {
71 return self::getConnection(self::$activeKey, $target);
72 }
73
74 public static function setActiveConnection($key = 'default') {
75 $old_key = self::$activeKey;
76 self::$activeKey = $key;
77 return $old_key;
78 }
79
80 /**
81 * Parse out the database URLs specified in the config file
82 * and specify defaults where necessary.
83 */
84 protected static function parseUrls() {
85 global $db_url;
86 self::$dbUrls = $db_url;
87 if (! is_array(self::$dbUrls)) {
88 self::$dbUrls = array('default' => self::$dbUrls);
89 }
90 foreach (self::$dbUrls as $index => $url) {
91 if (! is_array(self::$dbUrls[$index])) {
92 self::$dbUrls[$index] = array('default' => $url);
93 }
94 foreach (self::$dbUrls[$index] as $target => $value) {
95 // Each target can also be an array. If it is, we select one entry at random to be
96 // target for this request. That allows us to have multiple slave servers.
97 if (is_array($value)) {
98 self::$dbUrls[$index][$target] = self::$dbUrls[$index][$target][mt_rand(0, count(self::$dbUrls[$index][$target]) - 1)];
99 }
100 }
101 }
102 }
103
104 /**
105 * Open a connection to the server specified by the given
106 * key and target.
107 *
108 * @param $key
109 * @param $target
110 */
111 protected static function openConnection($key, $target) {
112 // Expand out the connection URLs to extended syntax. It makes the parsing
113 // later easier if we take care of all of the conditionals here, once.
114 if (! isset(self::$db_urls)) {
115 self::parseUrls();
116 }
117
118 // If the requested database does not exist then it is an unrecoverable error.
119 // If the requested target does not exist, however, we fall back to the default
120 // target. The target is typically either "default" or "slave", indicating to
121 // use a slave SQL server if one is available. If it's not available, then the
122 // default/master server is the correct server to use.
123 if (! isset(self::$dbUrls[$key])) {
124 throw new Exception('DB does not exist');
125 }
126 if (! isset(self::$dbUrls[$key][$target])) {
127 $target = 'default';
128 }
129
130 // Parse out the connection URL so we can build our connection object.
131 $url = parse_url(self::$dbUrls[$key][$target]);
132 // Decode url-encoded information in the db connection string.
133 $url['user'] = urldecode($url['user']);
134 // Test if database url has a password.
135 $url['pass'] = isset($url['pass']) ? urldecode($url['pass']) : '';
136 $url['host'] = urldecode($url['host']);
137 $url['path'] = urldecode($url['path']);
138 // Allow for non-standard port.
139 if (isset($url['port'])) {
140 $url['host'] = $url['host'] . ':' . $url['port'];
141 }
142
143 // Each supported database type has its own child class for database-specific operations.
144 // Instantiate and return an object of that class, which will still present a unified API.
145 $db_type = 'Database_'. $url['scheme'];
146 $db_file = 'database.'. $url['scheme'] .'.inc';
147 try {
148 require_once($db_file);
149 self::$connections[$key][$target] = new $db_type($url);
150 } catch (PDOException $e) {
151 debug($e->getMessage());
152 //watchdog('database', $e->getMessage());
153 // print some sort of error here.
154 }
155 }
156
157 public static function getConnection($key = 'default', $target = 'default') {
158
159 if (! isset(self::$connections[$key][$target])) {
160 self::openConnection($key, $target);
161 }
162
163 return self::$connections[$key][$target];
164 }
165
166 /**
167 * Append a database prefix to all tables in a query.
168 *
169 * Queries sent to Drupal should wrap all table names in curly brackets. This
170 * function searches for this syntax and adds Drupal's table prefix to all
171 * tables, allowing Drupal to coexist with other systems in the same database if
172 * necessary.
173 *
174 * @param $sql
175 * A string containing a partial or entire SQL query.
176 * @return
177 * The properly-prefixed string.
178 */
179 protected function prefixTables($sql) {
180 global $db_prefix;
181
182 if (is_array($db_prefix)) {
183 if (array_key_exists('default', $db_prefix)) {
184 $tmp = $db_prefix;
185 unset($tmp['default']);
186 foreach ($tmp as $key => $val) {
187 $sql = strtr($sql, array('{' . $key . '}' => $val . $key));
188 }
189 return strtr($sql, array('{' => $db_prefix['default'] , '}' => ''));
190 } else {
191 foreach ($db_prefix as $key => $val) {
192 $sql = strtr($sql, array('{' . $key . '}' => $val . $key));
193 }
194 return strtr($sql, array('{' => '' , '}' => ''));
195 }
196 } else {
197 return strtr($sql, array('{' => $db_prefix , '}' => ''));
198 }
199 }
200
201 protected function runQuery($query, Array $args, $options, $return_affected = FALSE) {
202
203 static $statements = array();
204
205 $query = self::prefixTables($query);
206
207 // Cache each prepared statement, keyed by the query itself. This way,
208 // we get the benefit of prepared statement caching without any extra
209 // work by the module author.
210 if (! isset($statements[$query])) {
211 $statements[$query] = $this->prepare($query);
212 }
213
214 $options += Database::defaultOptions();
215 $statements[$query]->execute($args, $options);
216
217
218 if ($return_affected) {
219 return $statements[$query]->rowCount();
220 } else {
221 return $statements[$query];
222 }
223 }
224
225 /**
226 * Execute a SELECT query on this database object.
227 *
228 * @param $query
229 * A string containing an SQL query.
230 * @param $args
231 * An array of values to substitute into the query at placeholder markers.
232 * @param $options
233 * An array of options on the query. This array is assumed to have all
234 * values populated.
235 * @return
236 * A database query result resource, or FALSE if the query was not executed
237 * correctly.
238 */
239 public function query($query, Array $args, Array $options) {
240
241 // Backward compatibility hack, temporary.
242 $query = str_replace(array('%d' , '%f' , '%b' , "'%s'"), '?', $query);
243
244 return $this->runQuery($query, $args, $options);
245 }
246
247 /**
248 * Run an insert query on this database object.
249 *
250 * @param $table
251 * The database table on which to run the insert query.
252 * @param $fields
253 * An associative array of the values to insert. The keys are the
254 * fields, and the corresponding values are the values to insert.
255 * @return
256 * A database query result resource, or FALSE if the query was not
257 * executed correctly.
258 *
259 */
260 function insert($table, Array $fields, $delay = FALSE) {
261 $insert_fields = array_keys($fields);
262 $insert_values = array_values($fields);
263
264 $placeholders = array_fill(0, count($insert_values), '?');
265
266 $num_affected = $this->runQuery('INSERT INTO {' . $table . '} (' . implode(',', $insert_fields) . ') VALUES (' . implode(',', $placeholders) . ')', $insert_values, array(), TRUE);
267 return $this->lastInsertId();
268 }
269
270 /**
271 * Build the WHERE portion of an SQL query, based on the specified values.
272 *
273 * @todo Add support for non-equality comparisons.
274 * @param $where
275 * Associative array of rules in the WHERE clause. If a key in the array
276 * is numeric, the value is taken as a literal rule. If it is non-numeric,
277 * then it is assumed to be a field name and the corresponding value is the
278 * value that it must hold.
279 * @param $where_type
280 * Whether the values of the WHERE clause should be ANDed or ORed together.
281 *
282 * As an example, this $where clause would be translated as follows:
283 * $where = array('name'=>'foo', 'type'=>'page', 'created < 1147567877')
284 *
285 * WHERE (name='foo') AND ('type'='page') AND (created < 1147567877')
286 * @return
287 * An array containing the where clause with sprintf() markers, and
288 * an array of values to substitute for them.
289 */
290 static function where(Array $where, $where_type = 'AND', $where_keyword = TRUE) {
291 $params = array();
292 $args = array();
293 foreach ($where as $key => $value) {
294 if (is_numeric($key)) {
295 $params[] = $value;
296 } else {
297 switch ($key) {
298 case 'or':
299 list ($sub_params, $sub_args) = self::where($value, 'OR', FALSE);
300 $params[] = ' (' . $sub_params . ') ';
301 $args = array_merge($args, $sub_args);
302 break;
303 case 'and':
304 list ($sub_params, $sub_args) = self::where($value, 'AND', FALSE);
305 $params[] = ' (' . $sub_params . ') ';
306 $args = array_merge($args, $sub_args);
307 break;
308 case 'not':
309 list ($sub_params, $sub_args) = self::where($value, 'AND', FALSE);
310 $params[] = ' NOT (' . $sub_params . ') ';
311 $args = array_merge($args, $sub_args);
312 break;
313 case '<':
314 $operator = '<';
315 $params[] = ' (' . key($value) . $operator . '?) ';
316 $args[] = current($value);
317 break;
318 case '>':
319 $operator = '>';
320 $params[] = ' (' . key($value) . $operator . '?) ';
321 $args[] = current($value);
322 break;
323 case '<=':
324 $operator = '<=';
325 $params[] = ' (' . key($value) . $operator . '?) ';
326 $args[] = current($value);
327 break;
328 case '>=':
329 $operator = '>=';
330 $params[] = ' (' . key($value) . $operator . '?) ';
331 $args[] = current($value);
332 break;
333 default:
334 $operator = '=';
335 if (is_array($value)) {
336 $params[] = ' (' . $key . ' IN (' . array_fill(0, count($value), '?');
337 array_merge($args, $value);
338 } else {
339 $params[] = ' (' . $key . $operator . '?) ';
340 $args[] = $value;
341 }
342 break;
343 }
344 }
345 }
346
347 $return = '';
348 if (sizeof($params)) {
349 $return = ($where_keyword ? ' WHERE ' : ' ') . implode($where_type, $params);
350 }
351
352 return array($return , $args);
353 }
354
355 /**
356 * Run an update query on this database object.
357 *
358 * @param $table
359 * The database table on which to run the update query.
360 * @param $fields
361 * An associative array of the values to update. The keys are the
362 * fields, and the corresponding values are the values to update to.
363 * @param $where
364 * The where rules for this update query.
365 * @param $where_type
366 * Whether to AND or OR the where rules together.
367 * @return
368 * A database query result resource, or FALSE if the query was not
369 * executed correctly.
370 *
371 */
372 function update($table, Array $fields, Array $where, $where_type = 'AND') {
373
374 $update_values = array();
375 $flat_fields = array();
376
377 foreach ($fields as $field => $value) {
378 $update_values[] = $value;
379 $flat_fields[] = $field . '=?';
380 }
381
382 list ($where_string, $where_values) = self::where($where, $where_type);
383
384 $sql = 'UPDATE {' . $table . '} SET ' . implode(', ', $flat_fields) . $where_string;
385
386 return $this->runQuery($sql, array_merge($update_values, $where_values), array(), TRUE);
387 }
388
389 /**
390 * Run a replace query on this database object.
391 *
392 * Depending on the database, that could be separate delete/insert queries
393 * or a single "insert ... on duplicate update ..." query, or something else.
394 * Note that the $where clause must be a simple AND-based equality array, or
395 * it will fail.
396 *
397 * @param $table
398 * The database table on which to run the update query.
399 * @param $fields
400 * An associative array of the values to update. The keys are the
401 * fields, and the corresponding values are the values to update to.
402 * @param $where
403 * The where rules for this update query.
404 * @param $where_type
405 * Whether to AND or OR the where rules together.
406 * @return
407 * A database query result resource, or FALSE if the query was not
408 * executed correctly.
409 *
410 */
411 function replace($table, Array $fields, Array $where) {
412
413 // The following trivial method should be replaced with a database-specific
414 // mechanism if one exists.
415 $num_deleted = $this->delete($table, $where);
416 $fields += $where;
417 $num_inserted = $this->insert($table, $fields);
418 return $num_deleted + $num_inserted;
419 }
420
421 /**
422 * Run a delete query on this database object.
423 *
424 * @param $table
425 * The database table on which to run the delete query.
426 * @param $where
427 * The where rules for this delete query.
428 * @param $where_type
429 * Whether to AND or OR the where rules together.
430 * @return
431 * A database query result resource, or FALSE if the query was not
432 * executed correctly.
433 *
434 */
435 function delete($table, Array $where, $where_type = 'AND') {
436 list ($where_string, $where_values) = self::where($where, $where_type);
437 $sql = 'DELETE FROM {' . $table . '} ' . $where_string;
438 return $this->runQuery($sql, $where_values, array(), TRUE);
439 }
440
441 /**
442 * Return the default query options for any given query.
443 *
444 * @return
445 * An array of default query options.
446 */
447 static function defaultOptions() {
448 return array(
449 'target' => 'default',
450 'database' => NULL,
451 'fetch' => PDO::FETCH_OBJ,
452 );
453 }
454
455 /**
456 * Runs a limited-range query on this database object.
457 *
458 * Use this as a substitute for ->query() when a subset of the query is to be
459 * returned.
460 * User-supplied arguments to the query should be passed in as separate parameters
461 * so that they can be properly escaped to avoid SQL injection attacks.
462 *
463 * @param $query
464 * A string containing an SQL query.
465 * @param $args
466 * An array of values to substitute into the query at placeholder markers.
467 * @param $from
468 * The first result row to return.
469 * @param $count
470 * The maximum number of result rows to return.
471 * @param $options
472 * An array of options on the query. This array is assumed to have all
473 * values populated.
474 * @return
475 * A database query result resource, or FALSE if the query was not executed
476 * correctly.
477 */
478 abstract function queryRange($query, Array $args, $from, $count, Array $options);
479
480 /**
481 * Runs a SELECT query and stores its results in a temporary table.
482 *
483 * Use this as a substitute for db_query() when the results need to stored
484 * in a temporary table. Temporary tables exist for the duration of the page
485 * request.
486 * User-supplied arguments to the query should be passed in as separate parameters
487 * so that they can be properly escaped to avoid SQL injection attacks.
488 *
489 * Note that if you need to know how many results were returned, you should do
490 * a SELECT COUNT(*) on the temporary table afterwards. db_affected_rows() does
491 * not give consistent result across different database types in this case.
492 *
493 * @param $query
494 * A string containing a normal SELECT SQL query.
495 * @param $args
496 * An array of values to substitute into the query at placeholder markers.
497 * @param $tablename
498 * The name of the temporary table to select into. This name will not be
499 * prefixed as there is no risk of collision.
500 * @return
501 * A database query result resource, or FALSE if the query was not executed
502 * correctly.
503 */
504 abstract function queryTemporary($query, Array $args, $tablename);
505
506 }
507
508
509 class DBStatement extends PDOStatement {
510
511 public $dbh;
512
513 protected function __construct($dbh) {
514 $this->dbh = $dbh;
515 $this->setFetchMode(PDO::FETCH_OBJ);
516 }
517
518 public function execute($args, $options) {
519 if (is_string($options['fetch'])) {
520 $this->setFetchMode(PDO::FETCH_CLASS, $options['fetch']);
521 }
522 else {
523 $this->setFetchMode($options['fetch']);
524 }
525 parent::execute($args);
526 }
527
528 public function fetchCol($index = 0) {
529 return $this->fetchAll(PDO::FETCH_COLUMN, $index);
530 }
531
532 public function fetchAllAssoc($key) {
533 $return = array();
534 foreach ($this as $record) {
535 $return[$record->$key] = $record;
536 }
537 return $return;
538 }
539
540 public function fetchOne($index = 0) {
541 return $this->fetchColumn($index);
542 }
543
544 /**
545 * Fetches the next row and returns it as an associative array.
546 *
547 * This method corresponds to PDOStatement::fetchObject(),
548 * but for associative arrays. Why objects get a method of their
549 * own and arrays do not, I do not know.
550 *
551 */
552 public function fetchAssoc() {
553 return $this->fetch(PDO::FETCH_ASSOC);
554 }
555 }
556
557 /**
558 * The following utility functions are simply convenience wrappers.
559 * They should never, ever have any database-specific code in them.
560 */
561
562 function db_query($query, Array $args = array(), Array $options = array()) {
563 // Get default options.
564 $options += Database::defaultOptions();
565
566 if (isset($options['database'])) {
567 return Database::getConnection($options['database'], $options['target'])->query($query, $args, $options);
568 }
569 return Database::getActiveConnection($options['target'])->query($query, $args, $options);
570 }
571
572 function db_query_range($query, Array $args, $from = 0, $count = 0, Array $options = array()) {
573 // Get default options.
574 $options += Database::defaultOptions();
575
576 if (isset($options['database'])) {
577 return Database::getConnection($options['database'], $options['target'])->queryRange($query, $args, $from, $count, $options);
578 }
579 return Database::getActiveConnection($options['target'])->queryRange($query, $args, $from, $count, $options);
580 }
581
582 function db_query_temporary($query, Array $args, $tablename) {
583 return Database::getActiveConnection()->queryTemporary($query, $args, $tablename);
584 }
585
586 function db_insert($table, Array $fields = array(), $delay = FALSE) {
587 return Database::getActiveConnection()->insert($table, $fields, $delay);
588 }
589
590 function db_update($table, Array $fields = array(), $where = array(), $where_type = 'AND', $delay = FALSE) {
591 return Database::getActiveConnection()->update($table, $fields, $where, $where_type, $delay);
592 }
593
594 function db_replace($table, Array $fields = array(), $where = array()) {
595 return Database::getActiveConnection()->replace($table, $fields, $where);
596 }
597
598 function db_delete($table, Array $where = array(), $where_type = 'AND', $delay = FALSE) {
599 return Database::getActiveConnection()->delete($table, $where, $where_type, $delay);
600 }
601
602 function db_set_active($key = 'default') {
603 Database::setActiveConnection($key);
604 }
605
606 // For temporary backward compatibility only.
607 function db_fetch_object(DBStatement $statement) {
608 return $statement->fetch(PDO::FETCH_OBJ);
609 }
610
611 function db_fetch_array(DBStatement $statement) {
612 return $statement->fetch(PDO::FETCH_BOTH);
613 }

  ViewVC Help
Powered by ViewVC 1.1.2