2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Experimental pdo database class
21 * @copyright 2008 Andrei Bautu
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') ||
die();
27 require_once(__DIR__
.'/moodle_database.php');
28 require_once(__DIR__
.'/pdo_moodle_recordset.php');
31 * Experimental pdo database class
34 * @copyright 2008 Andrei Bautu
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 abstract class pdo_moodle_database
extends moodle_database
{
40 protected $lastError = null;
43 * Constructor - instantiates the database, specifying if it's external (connect to other systems) or no (Moodle DB)
44 * note this has effect to decide if prefix checks must be performed or no
45 * @param bool true means external database used
47 public function __construct($external=false) {
48 parent
::__construct($external);
53 * Must be called before other methods.
54 * @param string $dbhost The database host.
55 * @param string $dbuser The database username.
56 * @param string $dbpass The database username's password.
57 * @param string $dbname The name of the database being connected to.
58 * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
59 * @param array $dboptions driver specific options
60 * @return bool success
62 public function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null) {
63 $driverstatus = $this->driver_installed();
65 if ($driverstatus !== true) {
66 throw new dml_exception('dbdriverproblem', $driverstatus);
69 $this->store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions);
72 $this->pdb
= new PDO($this->get_dsn(), $this->dbuser
, $this->dbpass
, $this->get_pdooptions());
73 // generic PDO settings to match adodb's default; subclasses can change this in configure_dbconnection
74 $this->pdb
->setAttribute(PDO
::ATTR_CASE
, PDO
::CASE_LOWER
);
75 $this->pdb
->setAttribute(PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_EXCEPTION
);
76 $this->configure_dbconnection();
78 } catch (PDOException
$ex) {
79 throw new dml_connection_exception($ex->getMessage());
85 * Returns the driver-dependent DSN for PDO based on members stored by connect.
86 * Must be called after connect (or after $dbname, $dbhost, etc. members have been set).
87 * @return string driver-dependent DSN
89 abstract protected function get_dsn();
92 * Returns the driver-dependent connection attributes for PDO based on members stored by connect.
93 * Must be called after $dbname, $dbhost, etc. members have been set.
94 * @return array A key=>value array of PDO driver-specific connection options
96 protected function get_pdooptions() {
97 return array(PDO
::ATTR_PERSISTENT
=> !empty($this->dboptions
['dbpersist']));
100 protected function configure_dbconnection() {
101 //TODO: not needed preconfigure_dbconnection() stuff for PDO drivers?
105 * Returns general database library name
106 * Note: can be used before connect()
107 * @return string db type pdo, native
109 protected function get_dblibrary() {
114 * Returns localised database type name
115 * Note: can be used before connect()
118 public function get_name() {
119 return get_string('pdo'.$this->get_dbtype(), 'install');
123 * Returns localised database configuration help.
124 * Note: can be used before connect()
127 public function get_configuration_help() {
128 return get_string('pdo'.$this->get_dbtype().'help', 'install');
132 * Returns localised database description
133 * Note: can be used before connect()
136 public function get_configuration_hints() {
137 return get_string('databasesettingssub_' . $this->get_dbtype() . '_pdo', 'install');
141 * Returns database server info array
142 * @return array Array containing 'description' and 'version' info
144 public function get_server_info() {
147 $result['description'] = $this->pdb
->getAttribute(PDO
::ATTR_SERVER_INFO
);
148 } catch(PDOException
$ex) {}
150 $result['version'] = $this->pdb
->getAttribute(PDO
::ATTR_SERVER_VERSION
);
151 } catch(PDOException
$ex) {}
156 * Returns supported query parameter types
157 * @return int bitmask of accepted SQL_PARAMS_*
159 protected function allowed_param_types() {
160 return SQL_PARAMS_QM | SQL_PARAMS_NAMED
;
164 * Returns last error reported by database engine.
165 * @return string error message
167 public function get_last_error() {
168 return $this->lastError
;
172 * Function to print/save/ignore debugging messages related to SQL queries.
174 protected function debug_query($sql, $params = null) {
175 echo '<hr /> (', $this->get_dbtype(), '): ', htmlentities($sql, ENT_QUOTES
, 'UTF-8');
177 echo ' (parameters ';
185 * Do NOT use in code, to be used by database_manager only!
186 * @param string $sql query
187 * @return bool success
189 public function change_database_structure($sql) {
191 $this->query_start($sql, null, SQL_QUERY_STRUCTURE
);
194 $this->pdb
->exec($sql);
195 $this->reset_caches();
196 } catch (PDOException
$ex) {
197 $this->lastError
= $ex->getMessage();
200 $this->query_end($result);
204 public function delete_records_select($table, $select, array $params=null) {
205 $sql = "DELETE FROM {{$table}}";
207 $sql .= " WHERE $select";
209 return $this->execute($sql, $params);
213 * Factory method that creates a recordset for return by a query. The generic pdo_moodle_recordset
214 * class should fit most cases, but pdo_moodle_database subclasses can override this method to return
215 * a subclass of pdo_moodle_recordset.
216 * @param object $sth instance of PDOStatement
217 * @return object instance of pdo_moodle_recordset
219 protected function create_recordset($sth) {
220 return new pdo_moodle_recordset($sth);
224 * Execute general sql query. Should be used only when no other method suitable.
225 * Do NOT use this to make changes in db structure, use database_manager methods instead!
226 * @param string $sql query
227 * @param array $params query parameters
228 * @return bool success
230 public function execute($sql, array $params=null) {
231 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
234 $this->query_start($sql, $params, SQL_QUERY_UPDATE
);
237 $sth = $this->pdb
->prepare($sql);
238 $sth->execute($params);
239 } catch (PDOException
$ex) {
240 $this->lastError
= $ex->getMessage();
244 $this->query_end($result);
249 * Get a number of records as an moodle_recordset. $sql must be a complete SQL query.
250 * Since this method is a little less readable, use of it should be restricted to
251 * code where it's possible there might be large datasets being returned. For known
252 * small datasets use get_records_sql - it leads to simpler code.
254 * The return type is like:
255 * @see function get_recordset.
257 * @param string $sql the SQL select query to execute.
258 * @param array $params array of sql parameters
259 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
260 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
261 * @return moodle_recordset instance
263 public function get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
267 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
268 $sql = $this->get_limit_clauses($sql, $limitfrom, $limitnum);
269 $this->query_start($sql, $params, SQL_QUERY_SELECT
);
272 $sth = $this->pdb
->prepare($sql);
273 $sth->execute($params);
274 $result = $this->create_recordset($sth);
275 } catch (PDOException
$ex) {
276 $this->lastError
= $ex->getMessage();
280 $this->query_end($result);
285 * Selects rows and return values of first column as array.
287 * @param string $sql The SQL query
288 * @param array $params array of sql parameters
289 * @return array of values
291 public function get_fieldset_sql($sql, array $params=null) {
292 $rs = $this->get_recordset_sql($sql, $params);
294 $rs->close(); // Not going to iterate (but exit), close rs
298 foreach($rs as $value) {
299 $result[] = reset($value);
306 * Get a number of records as an array of objects.
308 * Return value is like:
309 * @see function get_records.
311 * @param string $sql the SQL select query to execute. The first column of this SELECT statement
312 * must be a unique value (usually the 'id' field), as it will be used as the key of the
314 * @param array $params array of sql parameters
315 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
316 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
317 * @return array of objects, or empty array if no records were found, or false if an error occurred.
319 public function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
320 $rs = $this->get_recordset_sql($sql, $params, $limitfrom, $limitnum);
322 $rs->close(); // Not going to iterate (but exit), close rs
326 $debugging = debugging('', DEBUG_DEVELOPER
);
327 foreach($rs as $value) {
328 $key = reset($value);
329 if ($debugging && array_key_exists($key, $objects)) {
330 debugging("Did you remember to make the first column something unique in your call to get_records? Duplicate value '$key' found in column first column of '$sql'.", DEBUG_DEVELOPER
);
332 $objects[$key] = (object)$value;
339 * Insert new record into database, as fast as possible, no safety checks, lobs not supported.
340 * @param string $table name
341 * @param mixed $params data record as object or array
342 * @param bool $returnit return it of inserted record
343 * @param bool $bulk true means repeated inserts expected
344 * @param bool $customsequence true if 'id' included in $params, disables $returnid
345 * @return bool|int true or new id
347 public function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false) {
348 if (!is_array($params)) {
349 $params = (array)$params;
352 if ($customsequence) {
353 if (!isset($params['id'])) {
354 throw new coding_exception('moodle_database::insert_record_raw() id field must be specified if custom sequences used.');
358 unset($params['id']);
361 if (empty($params)) {
362 throw new coding_exception('moodle_database::insert_record_raw() no fields found.');
365 $fields = implode(',', array_keys($params));
366 $qms = array_fill(0, count($params), '?');
367 $qms = implode(',', $qms);
369 $sql = "INSERT INTO {{$table}} ($fields) VALUES($qms)";
370 if (!$this->execute($sql, $params)) {
376 if ($id = $this->pdb
->lastInsertId()) {
383 * Insert a record into a table and return the "id" field if required,
384 * Some conversions and safety checks are carried out. Lobs are supported.
385 * If the return ID isn't required, then this just reports success as true/false.
386 * $data is an object containing needed data
387 * @param string $table The database table to be inserted into
388 * @param object $data A data object with values for one or more fields in the record
389 * @param bool $returnid Should the id of the newly created record entry be returned? If this option is not requested then true/false is returned.
390 * @param bool $bulk true means repeated inserts expected
391 * @return bool|int true or new id
393 public function insert_record($table, $dataobject, $returnid=true, $bulk=false) {
394 $dataobject = (array)$dataobject;
396 $columns = $this->get_columns($table);
399 foreach ($dataobject as $field=>$value) {
400 if ($field === 'id') {
403 if (!isset($columns[$field])) {
406 $column = $columns[$field];
407 if (is_bool($value)) {
408 $value = (int)$value; // prevent "false" problems
410 $cleaned[$field] = $value;
413 if (empty($cleaned)) {
417 return $this->insert_record_raw($table, $cleaned, $returnid, $bulk);
421 * Update record in database, as fast as possible, no safety checks, lobs not supported.
422 * @param string $table name
423 * @param mixed $params data record as object or array
424 * @param bool true means repeated updates expected
425 * @return bool success
427 public function update_record_raw($table, $params, $bulk=false) {
428 $params = (array)$params;
430 if (!isset($params['id'])) {
431 throw new coding_exception('moodle_database::update_record_raw() id field must be specified.');
434 unset($params['id']);
436 if (empty($params)) {
437 throw new coding_exception('moodle_database::update_record_raw() no fields found.');
441 foreach ($params as $field=>$value) {
442 $sets[] = "$field = ?";
445 $params[] = $id; // last ? in WHERE condition
447 $sets = implode(',', $sets);
448 $sql = "UPDATE {{$table}} SET $sets WHERE id=?";
449 return $this->execute($sql, $params);
453 * Update a record in a table
455 * $dataobject is an object containing needed data
456 * Relies on $dataobject having a variable "id" to
457 * specify the record to update
459 * @param string $table The database table to be checked against.
460 * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
461 * @param bool true means repeated updates expected
462 * @return bool success
464 public function update_record($table, $dataobject, $bulk=false) {
465 $dataobject = (array)$dataobject;
467 $columns = $this->get_columns($table);
470 foreach ($dataobject as $field=>$value) {
471 if (!isset($columns[$field])) {
474 if (is_bool($value)) {
475 $value = (int)$value; // prevent "false" problems
477 $cleaned[$field] = $value;
480 return $this->update_record_raw($table, $cleaned, $bulk);
484 * Set a single field in every table row where the select statement evaluates to true.
486 * @param string $table The database table to be checked against.
487 * @param string $newfield the field to set.
488 * @param string $newvalue the value to set the field to.
489 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
490 * @param array $params array of sql parameters
491 * @return bool success
493 public function set_field_select($table, $newfield, $newvalue, $select, array $params=null) {
495 $select = "WHERE $select";
497 if (is_null($params)) {
500 list($select, $params, $type) = $this->fix_sql_params($select, $params);
502 if (is_bool($newvalue)) {
503 $newvalue = (int)$newvalue; // prevent "false" problems
505 if (is_null($newvalue)) {
506 $newfield = "$newfield = NULL";
508 // make sure SET and WHERE clauses use the same type of parameters,
509 // because we don't support different types in the same query
511 case SQL_PARAMS_NAMED
:
512 $newfield = "$newfield = :newvalueforupdate";
513 $params['newvalueforupdate'] = $newvalue;
516 $newfield = "$newfield = ?";
517 array_unshift($params, $newvalue);
520 $this->lastError
= __FILE__
. ' LINE: ' . __LINE__
. '.';
521 print_error(unknowparamtype
, 'error', '', $this->lastError
);
524 $sql = "UPDATE {{$table}} SET $newfield $select";
525 return $this->execute($sql, $params);
528 public function sql_concat() {
532 public function sql_concat_join($separator="' '", $elements=array()) {
536 protected function begin_transaction() {
537 $this->query_start('', NULL, SQL_QUERY_AUX
);
539 $this->pdb
->beginTransaction();
540 } catch(PDOException
$ex) {
541 $this->lastError
= $ex->getMessage();
543 $this->query_end($result);
546 protected function commit_transaction() {
547 $this->query_start('', NULL, SQL_QUERY_AUX
);
550 $this->pdb
->commit();
551 } catch(PDOException
$ex) {
552 $this->lastError
= $ex->getMessage();
554 $this->query_end($result);
557 protected function rollback_transaction() {
558 $this->query_start('', NULL, SQL_QUERY_AUX
);
561 $this->pdb
->rollBack();
562 } catch(PDOException
$ex) {
563 $this->lastError
= $ex->getMessage();
565 $this->query_end($result);
569 * Import a record into a table, id field is required.
570 * Basic safety checks only. Lobs are supported.
571 * @param string $table name of database table to be inserted into
572 * @param mixed $dataobject object or array with fields in the record
573 * @return bool success
575 public function import_record($table, $dataobject) {
576 $dataobject = (object)$dataobject;
578 $columns = $this->get_columns($table);
580 foreach ($dataobject as $field=>$value) {
581 if (!isset($columns[$field])) {
584 $cleaned[$field] = $value;
587 return $this->insert_record_raw($table, $cleaned, false, true, true);
591 * Called before each db query.
593 * Overridden to ensure $this->lastErorr is reset each query
596 * @param array array of parameters
597 * @param int $type type of query
598 * @param mixed $extrainfo driver specific extra information
601 protected function query_start($sql, array $params=null, $type, $extrainfo=null) {
602 $this->lastError
= null;
603 parent
::query_start($sql, $params, $type, $extrainfo);