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 * Abstract database driver class.
21 * @copyright 2008 Petr Skoda (http://skodak.org)
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') ||
die();
27 require_once(__DIR__
.'/database_column_info.php');
28 require_once(__DIR__
.'/moodle_recordset.php');
29 require_once(__DIR__
.'/moodle_transaction.php');
31 /** SQL_PARAMS_NAMED - Bitmask, indicates :name type parameters are supported by db backend. */
32 define('SQL_PARAMS_NAMED', 1);
34 /** SQL_PARAMS_QM - Bitmask, indicates ? type parameters are supported by db backend. */
35 define('SQL_PARAMS_QM', 2);
37 /** SQL_PARAMS_DOLLAR - Bitmask, indicates $1, $2, ... type parameters are supported by db backend. */
38 define('SQL_PARAMS_DOLLAR', 4);
40 /** SQL_QUERY_SELECT - Normal select query, reading only. */
41 define('SQL_QUERY_SELECT', 1);
43 /** SQL_QUERY_INSERT - Insert select query, writing. */
44 define('SQL_QUERY_INSERT', 2);
46 /** SQL_QUERY_UPDATE - Update select query, writing. */
47 define('SQL_QUERY_UPDATE', 3);
49 /** SQL_QUERY_STRUCTURE - Query changing db structure, writing. */
50 define('SQL_QUERY_STRUCTURE', 4);
52 /** SQL_QUERY_AUX - Auxiliary query done by driver, setting connection config, getting table info, etc. */
53 define('SQL_QUERY_AUX', 5);
56 * Abstract class representing moodle database interface.
57 * @link http://docs.moodle.org/dev/DML_functions
60 * @copyright 2008 Petr Skoda (http://skodak.org)
61 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
63 abstract class moodle_database
{
65 /** @var database_manager db manager which allows db structure modifications. */
66 protected $database_manager;
67 /** @var moodle_temptables temptables manager to provide cross-db support for temp tables. */
68 protected $temptables;
69 /** @var array Cache of table info. */
70 protected $tables = null;
72 // db connection options
73 /** @var string db host name. */
75 /** @var string db host user. */
77 /** @var string db host password. */
79 /** @var string db name. */
81 /** @var string Prefix added to table names. */
84 /** @var array Database or driver specific options, such as sockets or TCP/IP db connections. */
87 /** @var bool True means non-moodle external database used.*/
90 /** @var int The database reads (performance counter).*/
92 /** @var int The database writes (performance counter).*/
93 protected $writes = 0;
95 /** @var int Debug level. */
98 /** @var string Last used query sql. */
100 /** @var array Last query parameters. */
101 protected $last_params;
102 /** @var int Last query type. */
103 protected $last_type;
104 /** @var string Last extra info. */
105 protected $last_extrainfo;
106 /** @var float Last time in seconds with millisecond precision. */
107 protected $last_time;
108 /** @var bool Flag indicating logging of query in progress. This helps prevent infinite loops. */
109 private $loggingquery = false;
111 /** @var bool True if the db is used for db sessions. */
112 protected $used_for_db_sessions = false;
114 /** @var array Array containing open transactions. */
115 private $transactions = array();
116 /** @var bool Flag used to force rollback of all current transactions. */
117 private $force_rollback = false;
119 /** @var string MD5 of settings used for connection. Used by MUC as an identifier. */
120 private $settingshash;
123 * @var int internal temporary variable used to fix params. Its used by {@link _fix_sql_params_dollar_callback()}.
125 private $fix_sql_params_i;
127 * @var int internal temporary variable used to guarantee unique parameters in each request. Its used by {@link get_in_or_equal()}.
129 private $inorequaluniqueindex = 1;
132 * Constructor - Instantiates the database, specifying if it's external (connect to other systems) or not (Moodle DB).
133 * Note that this affects the decision of whether prefix checks must be performed or not.
134 * @param bool $external True means that an external database is used.
136 public function __construct($external=false) {
137 $this->external
= $external;
141 * Destructor - cleans up and flushes everything needed.
143 public function __destruct() {
148 * Detects if all needed PHP stuff are installed for DB connectivity.
149 * Note: can be used before connect()
150 * @return mixed True if requirements are met, otherwise a string if something isn't installed.
152 public abstract function driver_installed();
155 * Returns database table prefix
156 * Note: can be used before connect()
157 * @return string The prefix used in the database.
159 public function get_prefix() {
160 return $this->prefix
;
164 * Loads and returns a database instance with the specified type and library.
166 * The loaded class is within lib/dml directory and of the form: $type.'_'.$library.'_moodle_database'
168 * @param string $type Database driver's type. (eg: mysqli, pgsql, mssql, sqldrv, oci, etc.)
169 * @param string $library Database driver's library (native, pdo, etc.)
170 * @param bool $external True if this is an external database.
171 * @return moodle_database driver object or null if error, for example of driver object see {@link mysqli_native_moodle_database}
173 public static function get_driver_instance($type, $library, $external = false) {
176 $classname = $type.'_'.$library.'_moodle_database';
177 $libfile = "$CFG->libdir/dml/$classname.php";
179 if (!file_exists($libfile)) {
183 require_once($libfile);
184 return new $classname($external);
188 * Returns the database family type. (This sort of describes the SQL 'dialect')
189 * Note: can be used before connect()
190 * @return string The db family name (mysql, postgres, mssql, oracle, etc.)
192 public abstract function get_dbfamily();
195 * Returns a more specific database driver type
196 * Note: can be used before connect()
197 * @return string The db type mysqli, pgsql, oci, mssql, sqlsrv
199 protected abstract function get_dbtype();
202 * Returns the general database library name
203 * Note: can be used before connect()
204 * @return string The db library type - pdo, native etc.
206 protected abstract function get_dblibrary();
209 * Returns the localised database type name
210 * Note: can be used before connect()
213 public abstract function get_name();
216 * Returns the localised database configuration help.
217 * Note: can be used before connect()
220 public abstract function get_configuration_help();
223 * Returns the localised database description
224 * Note: can be used before connect()
227 public abstract function get_configuration_hints();
230 * Returns the db related part of config.php
233 public function export_dbconfig() {
234 $cfg = new stdClass();
235 $cfg->dbtype
= $this->get_dbtype();
236 $cfg->dblibrary
= $this->get_dblibrary();
237 $cfg->dbhost
= $this->dbhost
;
238 $cfg->dbname
= $this->dbname
;
239 $cfg->dbuser
= $this->dbuser
;
240 $cfg->dbpass
= $this->dbpass
;
241 $cfg->prefix
= $this->prefix
;
242 if ($this->dboptions
) {
243 $cfg->dboptions
= $this->dboptions
;
250 * Diagnose database and tables, this function is used
251 * to verify database and driver settings, db engine types, etc.
253 * @return string null means everything ok, string means problem found.
255 public function diagnose() {
260 * Connects to the database.
261 * Must be called before other methods.
262 * @param string $dbhost The database host.
263 * @param string $dbuser The database user to connect as.
264 * @param string $dbpass The password to use when connecting to the database.
265 * @param string $dbname The name of the database being connected to.
266 * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
267 * @param array $dboptions driver specific options
269 * @throws dml_connection_exception if error
271 public abstract function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null);
274 * Store various database settings
275 * @param string $dbhost The database host.
276 * @param string $dbuser The database user to connect as.
277 * @param string $dbpass The password to use when connecting to the database.
278 * @param string $dbname The name of the database being connected to.
279 * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
280 * @param array $dboptions driver specific options
283 protected function store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null) {
284 $this->dbhost
= $dbhost;
285 $this->dbuser
= $dbuser;
286 $this->dbpass
= $dbpass;
287 $this->dbname
= $dbname;
288 $this->prefix
= $prefix;
289 $this->dboptions
= (array)$dboptions;
293 * Returns a hash for the settings used during connection.
295 * If not already requested it is generated and stored in a private property.
299 protected function get_settings_hash() {
300 if (empty($this->settingshash
)) {
301 $this->settingshash
= md5($this->dbhost
. $this->dbuser
. $this->dbname
. $this->prefix
);
303 return $this->settingshash
;
307 * Attempt to create the database
308 * @param string $dbhost The database host.
309 * @param string $dbuser The database user to connect as.
310 * @param string $dbpass The password to use when connecting to the database.
311 * @param string $dbname The name of the database being connected to.
312 * @param array $dboptions An array of optional database options (eg: dbport)
314 * @return bool success True for successful connection. False otherwise.
316 public function create_database($dbhost, $dbuser, $dbpass, $dbname, array $dboptions=null) {
321 * Closes the database connection and releases all resources
322 * and memory (especially circular memory references).
323 * Do NOT use connect() again, create a new instance if needed.
326 public function dispose() {
327 if ($this->transactions
) {
328 // this should not happen, it usually indicates wrong catching of exceptions,
329 // because all transactions should be finished manually or in default exception handler.
330 // unfortunately we can not access global $CFG any more and can not print debug,
331 // the diagnostic info should be printed in footer instead
332 $lowesttransaction = end($this->transactions
);
333 $backtrace = $lowesttransaction->get_backtrace();
335 if (defined('PHPUNIT_TEST') and PHPUNIT_TEST
) {
336 //no need to log sudden exits in our PHPUnit test cases
338 error_log('Potential coding error - active database transaction detected when disposing database:'."\n".format_backtrace($backtrace, true));
340 $this->force_transaction_rollback();
342 // Always terminate sessions here to make it consistent,
343 // this is needed because we need to save session to db before closing it.
344 if (function_exists('session_get_instance')) {
345 session_get_instance()->write_close();
347 $this->used_for_db_sessions
= false;
349 if ($this->temptables
) {
350 $this->temptables
->dispose();
351 $this->temptables
= null;
353 if ($this->database_manager
) {
354 $this->database_manager
->dispose();
355 $this->database_manager
= null;
357 $this->tables
= null;
361 * This should be called before each db query.
362 * @param string $sql The query string.
363 * @param array $params An array of parameters.
364 * @param int $type The type of query. ( SQL_QUERY_SELECT | SQL_QUERY_AUX | SQL_QUERY_INSERT | SQL_QUERY_UPDATE | SQL_QUERY_STRUCTURE )
365 * @param mixed $extrainfo This is here for any driver specific extra information.
368 protected function query_start($sql, array $params=null, $type, $extrainfo=null) {
369 if ($this->loggingquery
) {
372 $this->last_sql
= $sql;
373 $this->last_params
= $params;
374 $this->last_type
= $type;
375 $this->last_extrainfo
= $extrainfo;
376 $this->last_time
= microtime(true);
379 case SQL_QUERY_SELECT
:
383 case SQL_QUERY_INSERT
:
384 case SQL_QUERY_UPDATE
:
385 case SQL_QUERY_STRUCTURE
:
389 $this->print_debug($sql, $params);
393 * This should be called immediately after each db query. It does a clean up of resources.
394 * It also throws exceptions if the sql that ran produced errors.
395 * @param mixed $result The db specific result obtained from running a query.
396 * @throws dml_read_exception | dml_write_exception | ddl_change_structure_exception
399 protected function query_end($result) {
400 if ($this->loggingquery
) {
403 if ($result !== false) {
406 $this->last_sql
= null;
407 $this->last_params
= null;
408 $this->print_debug_time();
412 // remember current info, log queries may alter it
413 $type = $this->last_type
;
414 $sql = $this->last_sql
;
415 $params = $this->last_params
;
416 $error = $this->get_last_error();
418 $this->query_log($error);
421 case SQL_QUERY_SELECT
:
423 throw new dml_read_exception($error, $sql, $params);
424 case SQL_QUERY_INSERT
:
425 case SQL_QUERY_UPDATE
:
426 throw new dml_write_exception($error, $sql, $params);
427 case SQL_QUERY_STRUCTURE
:
428 $this->get_manager(); // includes ddl exceptions classes ;-)
429 throw new ddl_change_structure_exception($error, $sql);
434 * This logs the last query based on 'logall', 'logslow' and 'logerrors' options configured via $CFG->dboptions .
435 * @param string|bool $error or false if not error
438 public function query_log($error=false) {
439 $logall = !empty($this->dboptions
['logall']);
440 $logslow = !empty($this->dboptions
['logslow']) ?
$this->dboptions
['logslow'] : false;
441 $logerrors = !empty($this->dboptions
['logerrors']);
442 $iserror = ($error !== false);
444 $time = microtime(true) - $this->last_time
;
446 if ($logall or ($logslow and ($logslow < ($time+
0.00001))) or ($iserror and $logerrors)) {
447 $this->loggingquery
= true;
449 $backtrace = debug_backtrace();
452 array_shift($backtrace);
456 array_shift($backtrace);
458 $log = new stdClass();
459 $log->qtype
= $this->last_type
;
460 $log->sqltext
= $this->last_sql
;
461 $log->sqlparams
= var_export((array)$this->last_params
, true);
462 $log->error
= (int)$iserror;
463 $log->info
= $iserror ?
$error : null;
464 $log->backtrace
= format_backtrace($backtrace, true);
465 $log->exectime
= $time;
466 $log->timelogged
= time();
467 $this->insert_record('log_queries', $log);
468 } catch (Exception
$ignored) {
470 $this->loggingquery
= false;
475 * Returns database server info array
476 * @return array Array containing 'description' and 'version' at least.
478 public abstract function get_server_info();
481 * Returns supported query parameter types
482 * @return int bitmask of accepted SQL_PARAMS_*
484 protected abstract function allowed_param_types();
487 * Returns the last error reported by the database engine.
488 * @return string The error message.
490 public abstract function get_last_error();
493 * Prints sql debug info
494 * @param string $sql The query which is being debugged.
495 * @param array $params The query parameters. (optional)
496 * @param mixed $obj The library specific object. (optional)
499 protected function print_debug($sql, array $params=null, $obj=null) {
500 if (!$this->get_debug()) {
504 echo "--------------------------------\n";
506 if (!is_null($params)) {
507 echo "[".var_export($params, true)."]\n";
509 echo "--------------------------------\n";
513 if (!is_null($params)) {
514 echo "[".s(var_export($params, true))."]\n";
521 * Prints the time a query took to run.
524 protected function print_debug_time() {
525 if (!$this->get_debug()) {
528 $time = microtime(true) - $this->last_time
;
529 $message = "Query took: {$time} seconds.\n";
532 echo "--------------------------------\n";
540 * Returns the SQL WHERE conditions.
541 * @param string $table The table name that these conditions will be validated against.
542 * @param array $conditions The conditions to build the where clause. (must not contain numeric indexes)
543 * @throws dml_exception
544 * @return array An array list containing sql 'where' part and 'params'.
546 protected function where_clause($table, array $conditions=null) {
547 // We accept nulls in conditions
548 $conditions = is_null($conditions) ?
array() : $conditions;
549 // Some checks performed under debugging only
551 $columns = $this->get_columns($table);
552 if (empty($columns)) {
553 // no supported columns means most probably table does not exist
554 throw new dml_exception('ddltablenotexist', $table);
556 foreach ($conditions as $key=>$value) {
557 if (!isset($columns[$key])) {
559 $a->fieldname
= $key;
560 $a->tablename
= $table;
561 throw new dml_exception('ddlfieldnotexist', $a);
563 $column = $columns[$key];
564 if ($column->meta_type
== 'X') {
565 //ok so the column is a text column. sorry no text columns in the where clause conditions
566 throw new dml_exception('textconditionsnotallowed', $conditions);
571 $allowed_types = $this->allowed_param_types();
572 if (empty($conditions)) {
573 return array('', array());
578 foreach ($conditions as $key=>$value) {
580 throw new dml_exception('invalidnumkey');
582 if (is_null($value)) {
583 $where[] = "$key IS NULL";
585 if ($allowed_types & SQL_PARAMS_NAMED
) {
586 // Need to verify key names because they can contain, originally,
587 // spaces and other forbidden chars when using sql_xxx() functions and friends.
588 $normkey = trim(preg_replace('/[^a-zA-Z0-9_-]/', '_', $key), '-_');
589 if ($normkey !== $key) {
590 debugging('Invalid key found in the conditions array.');
592 $where[] = "$key = :$normkey";
593 $params[$normkey] = $value;
595 $where[] = "$key = ?";
600 $where = implode(" AND ", $where);
601 return array($where, $params);
605 * Returns SQL WHERE conditions for the ..._list group of methods.
607 * @param string $field the name of a field.
608 * @param array $values the values field might take.
609 * @return array An array containing sql 'where' part and 'params'
611 protected function where_clause_list($field, array $values) {
612 if (empty($values)) {
613 return array("1 = 2", array()); // Fake condition, won't return rows ever. MDL-17645
616 // Note: Do not use get_in_or_equal() because it can not deal with bools and nulls.
620 $values = (array)$values;
621 foreach ($values as $value) {
622 if (is_bool($value)) {
623 $value = (int)$value;
625 if (is_null($value)) {
626 $select = "$field IS NULL";
632 if ($select !== "") {
633 $select = "$select OR ";
635 $count = count($params);
637 $select = $select."$field = ?";
639 $qs = str_repeat(',?', $count);
640 $qs = ltrim($qs, ',');
641 $select = $select."$field IN ($qs)";
644 return array($select, $params);
648 * Constructs 'IN()' or '=' sql fragment
649 * @param mixed $items A single value or array of values for the expression.
650 * @param int $type Parameter bounding type : SQL_PARAMS_QM or SQL_PARAMS_NAMED.
651 * @param string $prefix Named parameter placeholder prefix (a unique counter value is appended to each parameter name).
652 * @param bool $equal True means we want to equate to the constructed expression, false means we don't want to equate to it.
653 * @param mixed $onemptyitems This defines the behavior when the array of items provided is empty. Defaults to false,
654 * meaning throw exceptions. Other values will become part of the returned SQL fragment.
655 * @throws coding_exception | dml_exception
656 * @return array A list containing the constructed sql fragment and an array of parameters.
658 public function get_in_or_equal($items, $type=SQL_PARAMS_QM
, $prefix='param', $equal=true, $onemptyitems=false) {
660 // default behavior, throw exception on empty array
661 if (is_array($items) and empty($items) and $onemptyitems === false) {
662 throw new coding_exception('moodle_database::get_in_or_equal() does not accept empty arrays');
664 // handle $onemptyitems on empty array of items
665 if (is_array($items) and empty($items)) {
666 if (is_null($onemptyitems)) { // Special case, NULL value
667 $sql = $equal ?
' IS NULL' : ' IS NOT NULL';
668 return (array($sql, array()));
670 $items = array($onemptyitems); // Rest of cases, prepare $items for std processing
674 if ($type == SQL_PARAMS_QM
) {
675 if (!is_array($items) or count($items) == 1) {
676 $sql = $equal ?
'= ?' : '<> ?';
677 $items = (array)$items;
678 $params = array_values($items);
681 $sql = 'IN ('.implode(',', array_fill(0, count($items), '?')).')';
683 $sql = 'NOT IN ('.implode(',', array_fill(0, count($items), '?')).')';
685 $params = array_values($items);
688 } else if ($type == SQL_PARAMS_NAMED
) {
689 if (empty($prefix)) {
693 if (!is_array($items)){
694 $param = $prefix.$this->inorequaluniqueindex++
;
695 $sql = $equal ?
"= :$param" : "<> :$param";
696 $params = array($param=>$items);
697 } else if (count($items) == 1) {
698 $param = $prefix.$this->inorequaluniqueindex++
;
699 $sql = $equal ?
"= :$param" : "<> :$param";
700 $item = reset($items);
701 $params = array($param=>$item);
705 foreach ($items as $item) {
706 $param = $prefix.$this->inorequaluniqueindex++
;
707 $params[$param] = $item;
711 $sql = 'IN ('.implode(',', $sql).')';
713 $sql = 'NOT IN ('.implode(',', $sql).')';
718 throw new dml_exception('typenotimplement');
720 return array($sql, $params);
724 * Converts short table name {tablename} to the real prefixed table name in given sql.
725 * @param string $sql The sql to be operated on.
726 * @return string The sql with tablenames being prefixed with $CFG->prefix
728 protected function fix_table_names($sql) {
729 return preg_replace('/\{([a-z][a-z0-9_]*)\}/', $this->prefix
.'$1', $sql);
733 * Internal private utitlity function used to fix parameters.
734 * Used with {@link preg_replace_callback()}
735 * @param array $match Refer to preg_replace_callback usage for description.
738 private function _fix_sql_params_dollar_callback($match) {
739 $this->fix_sql_params_i++
;
740 return "\$".$this->fix_sql_params_i
;
744 * Detects object parameters and throws exception if found
745 * @param mixed $value
747 * @throws coding_exception if object detected
749 protected function detect_objects($value) {
750 if (is_object($value)) {
751 throw new coding_exception('Invalid database query parameter value', 'Objects are are not allowed: '.get_class($value));
756 * Normalizes sql query parameters and verifies parameters.
757 * @param string $sql The query or part of it.
758 * @param array $params The query parameters.
759 * @return array (sql, params, type of params)
761 public function fix_sql_params($sql, array $params=null) {
762 $params = (array)$params; // mke null array if needed
763 $allowed_types = $this->allowed_param_types();
765 // convert table names
766 $sql = $this->fix_table_names($sql);
768 // cast booleans to 1/0 int and detect forbidden objects
769 foreach ($params as $key => $value) {
770 $this->detect_objects($value);
771 $params[$key] = is_bool($value) ?
(int)$value : $value;
774 // NICOLAS C: Fixed regexp for negative backwards look-ahead of double colons. Thanks for Sam Marshall's help
775 $named_count = preg_match_all('/(?<!:):[a-z][a-z0-9_]*/', $sql, $named_matches); // :: used in pgsql casts
776 $dollar_count = preg_match_all('/\$[1-9][0-9]*/', $sql, $dollar_matches);
777 $q_count = substr_count($sql, '?');
782 $type = SQL_PARAMS_NAMED
;
783 $count = $named_count;
788 throw new dml_exception('mixedtypesqlparam');
790 $type = SQL_PARAMS_DOLLAR
;
791 $count = $dollar_count;
796 throw new dml_exception('mixedtypesqlparam');
798 $type = SQL_PARAMS_QM
;
805 if ($allowed_types & SQL_PARAMS_NAMED
) {
806 return array($sql, array(), SQL_PARAMS_NAMED
);
807 } else if ($allowed_types & SQL_PARAMS_QM
) {
808 return array($sql, array(), SQL_PARAMS_QM
);
810 return array($sql, array(), SQL_PARAMS_DOLLAR
);
814 if ($count > count($params)) {
816 $a->expected
= $count;
817 $a->actual
= count($params);
818 throw new dml_exception('invalidqueryparam', $a);
821 $target_type = $allowed_types;
823 if ($type & $allowed_types) { // bitwise AND
824 if ($count == count($params)) {
825 if ($type == SQL_PARAMS_QM
) {
826 return array($sql, array_values($params), SQL_PARAMS_QM
); // 0-based array required
828 //better do the validation of names below
831 // needs some fixing or validation - there might be more params than needed
832 $target_type = $type;
835 if ($type == SQL_PARAMS_NAMED
) {
836 $finalparams = array();
837 foreach ($named_matches[0] as $key) {
838 $key = trim($key, ':');
839 if (!array_key_exists($key, $params)) {
840 throw new dml_exception('missingkeyinsql', $key, '');
842 if (strlen($key) > 30) {
843 throw new coding_exception(
844 "Placeholder names must be 30 characters or shorter. '" .
845 $key . "' is too long.", $sql);
847 $finalparams[$key] = $params[$key];
849 if ($count != count($finalparams)) {
850 throw new dml_exception('duplicateparaminsql');
853 if ($target_type & SQL_PARAMS_QM
) {
854 $sql = preg_replace('/(?<!:):[a-z][a-z0-9_]*/', '?', $sql);
855 return array($sql, array_values($finalparams), SQL_PARAMS_QM
); // 0-based required
856 } else if ($target_type & SQL_PARAMS_NAMED
) {
857 return array($sql, $finalparams, SQL_PARAMS_NAMED
);
858 } else { // $type & SQL_PARAMS_DOLLAR
859 //lambda-style functions eat memory - we use globals instead :-(
860 $this->fix_sql_params_i
= 0;
861 $sql = preg_replace_callback('/(?<!:):[a-z][a-z0-9_]*/', array($this, '_fix_sql_params_dollar_callback'), $sql);
862 return array($sql, array_values($finalparams), SQL_PARAMS_DOLLAR
); // 0-based required
865 } else if ($type == SQL_PARAMS_DOLLAR
) {
866 if ($target_type & SQL_PARAMS_DOLLAR
) {
867 return array($sql, array_values($params), SQL_PARAMS_DOLLAR
); // 0-based required
868 } else if ($target_type & SQL_PARAMS_QM
) {
869 $sql = preg_replace('/\$[0-9]+/', '?', $sql);
870 return array($sql, array_values($params), SQL_PARAMS_QM
); // 0-based required
871 } else { //$target_type & SQL_PARAMS_NAMED
872 $sql = preg_replace('/\$([0-9]+)/', ':param\\1', $sql);
873 $finalparams = array();
874 foreach ($params as $key=>$param) {
876 $finalparams['param'.$key] = $param;
878 return array($sql, $finalparams, SQL_PARAMS_NAMED
);
881 } else { // $type == SQL_PARAMS_QM
882 if (count($params) != $count) {
883 $params = array_slice($params, 0, $count);
886 if ($target_type & SQL_PARAMS_QM
) {
887 return array($sql, array_values($params), SQL_PARAMS_QM
); // 0-based required
888 } else if ($target_type & SQL_PARAMS_NAMED
) {
889 $finalparams = array();
891 $parts = explode('?', $sql);
892 $sql = array_shift($parts);
893 foreach ($parts as $part) {
894 $param = array_shift($params);
896 $sql .= ':'.$pname.$part;
897 $finalparams[$pname] = $param;
899 return array($sql, $finalparams, SQL_PARAMS_NAMED
);
900 } else { // $type & SQL_PARAMS_DOLLAR
901 //lambda-style functions eat memory - we use globals instead :-(
902 $this->fix_sql_params_i
= 0;
903 $sql = preg_replace_callback('/\?/', array($this, '_fix_sql_params_dollar_callback'), $sql);
904 return array($sql, array_values($params), SQL_PARAMS_DOLLAR
); // 0-based required
910 * Return tables in database WITHOUT current prefix.
911 * @param bool $usecache if true, returns list of cached tables.
912 * @return array of table names in lowercase and without prefix
914 public abstract function get_tables($usecache=true);
917 * Return table indexes - everything lowercased.
918 * @param string $table The table we want to get indexes from.
919 * @return array An associative array of indexes containing 'unique' flag and 'columns' being indexed
921 public abstract function get_indexes($table);
924 * Returns detailed information about columns in table. This information is cached internally.
925 * @param string $table The table's name.
926 * @param bool $usecache Flag to use internal cacheing. The default is true.
927 * @return array of database_column_info objects indexed with column names
929 public abstract function get_columns($table, $usecache=true);
932 * Normalise values based on varying RDBMS's dependencies (booleans, LOBs...)
934 * @param database_column_info $column column metadata corresponding with the value we are going to normalise
935 * @param mixed $value value we are going to normalise
936 * @return mixed the normalised value
938 protected abstract function normalise_value($column, $value);
941 * Resets the internal column details cache
944 public function reset_caches() {
945 $this->tables
= null;
947 $identifiers = array('dbfamily' => $this->get_dbfamily(), 'settings' => $this->get_settings_hash());
948 cache_helper
::purge_by_definition('core', 'databasemeta', $identifiers);
952 * Returns the sql generator used for db manipulation.
953 * Used mostly in upgrade.php scripts.
954 * @return database_manager The instance used to perform ddl operations.
955 * @see lib/ddl/database_manager.php
957 public function get_manager() {
960 if (!$this->database_manager
) {
961 require_once($CFG->libdir
.'/ddllib.php');
963 $classname = $this->get_dbfamily().'_sql_generator';
964 require_once("$CFG->libdir/ddl/$classname.php");
965 $generator = new $classname($this, $this->temptables
);
967 $this->database_manager
= new database_manager($this, $generator);
969 return $this->database_manager
;
973 * Attempts to change db encoding to UTF-8 encoding if possible.
974 * @return bool True is successful.
976 public function change_db_encoding() {
981 * Checks to see if the database is in unicode mode?
984 public function setup_is_unicodedb() {
989 * Enable/disable very detailed debugging.
993 public function set_debug($state) {
994 $this->debug
= $state;
998 * Returns debug status
999 * @return bool $state
1001 public function get_debug() {
1002 return $this->debug
;
1006 * Enable/disable detailed sql logging
1007 * @param bool $state
1009 public function set_logging($state) {
1010 // adodb sql logging shares one table without prefix per db - this is no longer acceptable :-(
1011 // we must create one table shared by all drivers
1015 * Do NOT use in code, this is for use by database_manager only!
1016 * @param string $sql query
1018 * @throws dml_exception A DML specific exception is thrown for any errors.
1020 public abstract function change_database_structure($sql);
1023 * Executes a general sql query. Should be used only when no other method suitable.
1024 * Do NOT use this to make changes in db structure, use database_manager methods instead!
1025 * @param string $sql query
1026 * @param array $params query parameters
1028 * @throws dml_exception A DML specific exception is thrown for any errors.
1030 public abstract function execute($sql, array $params=null);
1033 * Get a number of records as a moodle_recordset where all the given conditions met.
1035 * Selects records from the table $table.
1037 * If specified, only records meeting $conditions.
1039 * If specified, the results will be sorted as specified by $sort. This
1040 * is added to the SQL as "ORDER BY $sort". Example values of $sort
1041 * might be "time ASC" or "time DESC".
1043 * If $fields is specified, only those fields are returned.
1045 * Since this method is a little less readable, use of it should be restricted to
1046 * code where it's possible there might be large datasets being returned. For known
1047 * small datasets use get_records - it leads to simpler code.
1049 * If you only want some of the records, specify $limitfrom and $limitnum.
1050 * The query will skip the first $limitfrom records (according to the sort
1051 * order) and then return the next $limitnum records. If either of $limitfrom
1052 * or $limitnum is specified, both must be present.
1054 * The return value is a moodle_recordset
1055 * if the query succeeds. If an error occurs, false is returned.
1057 * @param string $table the table to query.
1058 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1059 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1060 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
1061 * @param int $limitfrom return a subset of records, starting at this point (optional).
1062 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1063 * @return moodle_recordset A moodle_recordset instance
1064 * @throws dml_exception A DML specific exception is thrown for any errors.
1066 public function get_recordset($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1067 list($select, $params) = $this->where_clause($table, $conditions);
1068 return $this->get_recordset_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1072 * Get a number of records as a moodle_recordset where one field match one list of values.
1074 * Only records where $field takes one of the values $values are returned.
1075 * $values must be an array of values.
1077 * Other arguments and the return type are like {@link function get_recordset}.
1079 * @param string $table the table to query.
1080 * @param string $field a field to check (optional).
1081 * @param array $values array of values the field must have
1082 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1083 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
1084 * @param int $limitfrom return a subset of records, starting at this point (optional).
1085 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1086 * @return moodle_recordset A moodle_recordset instance.
1087 * @throws dml_exception A DML specific exception is thrown for any errors.
1089 public function get_recordset_list($table, $field, array $values, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1090 list($select, $params) = $this->where_clause_list($field, $values);
1091 return $this->get_recordset_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1095 * Get a number of records as a moodle_recordset which match a particular WHERE clause.
1097 * If given, $select is used as the SELECT parameter in the SQL query,
1098 * otherwise all records from the table are returned.
1100 * Other arguments and the return type are like {@link function get_recordset}.
1102 * @param string $table the table to query.
1103 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1104 * @param array $params array of sql parameters
1105 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1106 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
1107 * @param int $limitfrom return a subset of records, starting at this point (optional).
1108 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1109 * @return moodle_recordset A moodle_recordset instance.
1110 * @throws dml_exception A DML specific exception is thrown for any errors.
1112 public function get_recordset_select($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1113 $sql = "SELECT $fields FROM {".$table."}";
1115 $sql .= " WHERE $select";
1118 $sql .= " ORDER BY $sort";
1120 return $this->get_recordset_sql($sql, $params, $limitfrom, $limitnum);
1124 * Get a number of records as a moodle_recordset using a SQL statement.
1126 * Since this method is a little less readable, use of it should be restricted to
1127 * code where it's possible there might be large datasets being returned. For known
1128 * small datasets use get_records_sql - it leads to simpler code.
1130 * The return type is like {@link function get_recordset}.
1132 * @param string $sql the SQL select query to execute.
1133 * @param array $params array of sql parameters
1134 * @param int $limitfrom return a subset of records, starting at this point (optional).
1135 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1136 * @return moodle_recordset A moodle_recordset instance.
1137 * @throws dml_exception A DML specific exception is thrown for any errors.
1139 public abstract function get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0);
1142 * Get all records from a table.
1144 * This method works around potential memory problems and may improve performance,
1145 * this method may block access to table until the recordset is closed.
1147 * @param string $table Name of database table.
1148 * @return moodle_recordset A moodle_recordset instance {@link function get_recordset}.
1149 * @throws dml_exception A DML specific exception is thrown for any errors.
1151 public function export_table_recordset($table) {
1152 return $this->get_recordset($table, array());
1156 * Get a number of records as an array of objects where all the given conditions met.
1158 * If the query succeeds and returns at least one record, the
1159 * return value is an array of objects, one object for each
1160 * record found. The array key is the value from the first
1161 * column of the result set. The object associated with that key
1162 * has a member variable for each column of the results.
1164 * @param string $table the table to query.
1165 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1166 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1167 * @param string $fields a comma separated list of fields to return (optional, by default
1168 * all fields are returned). The first field will be used as key for the
1169 * array so must be a unique field such as 'id'.
1170 * @param int $limitfrom return a subset of records, starting at this point (optional).
1171 * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
1172 * @return array An array of Objects indexed by first column.
1173 * @throws dml_exception A DML specific exception is thrown for any errors.
1175 public function get_records($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1176 list($select, $params) = $this->where_clause($table, $conditions);
1177 return $this->get_records_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1181 * Get a number of records as an array of objects where one field match one list of values.
1183 * Return value is like {@link function get_records}.
1185 * @param string $table The database table to be checked against.
1186 * @param string $field The field to search
1187 * @param array $values An array of values
1188 * @param string $sort Sort order (as valid SQL sort parameter)
1189 * @param string $fields A comma separated list of fields to be returned from the chosen table. If specified,
1190 * the first field should be a unique one such as 'id' since it will be used as a key in the associative
1192 * @param int $limitfrom return a subset of records, starting at this point (optional).
1193 * @param int $limitnum return a subset comprising this many records in total (optional).
1194 * @return array An array of objects indexed by first column
1195 * @throws dml_exception A DML specific exception is thrown for any errors.
1197 public function get_records_list($table, $field, array $values, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1198 list($select, $params) = $this->where_clause_list($field, $values);
1199 return $this->get_records_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1203 * Get a number of records as an array of objects which match a particular WHERE clause.
1205 * Return value is like {@link function get_records}.
1207 * @param string $table The table to query.
1208 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1209 * @param array $params An array of sql parameters
1210 * @param string $sort An order to sort the results in (optional, a valid SQL ORDER BY parameter).
1211 * @param string $fields A comma separated list of fields to return
1212 * (optional, by default all fields are returned). The first field will be used as key for the
1213 * array so must be a unique field such as 'id'.
1214 * @param int $limitfrom return a subset of records, starting at this point (optional).
1215 * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
1216 * @return array of objects indexed by first column
1217 * @throws dml_exception A DML specific exception is thrown for any errors.
1219 public function get_records_select($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1221 $select = "WHERE $select";
1224 $sort = " ORDER BY $sort";
1226 return $this->get_records_sql("SELECT $fields FROM {" . $table . "} $select $sort", $params, $limitfrom, $limitnum);
1230 * Get a number of records as an array of objects using a SQL statement.
1232 * Return value is like {@link function get_records}.
1234 * @param string $sql the SQL select query to execute. The first column of this SELECT statement
1235 * must be a unique value (usually the 'id' field), as it will be used as the key of the
1237 * @param array $params array of sql parameters
1238 * @param int $limitfrom return a subset of records, starting at this point (optional).
1239 * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
1240 * @return array of objects indexed by first column
1241 * @throws dml_exception A DML specific exception is thrown for any errors.
1243 public abstract function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0);
1246 * Get the first two columns from a number of records as an associative array where all the given conditions met.
1248 * Arguments are like {@link function get_recordset}.
1250 * If no errors occur the return value
1251 * is an associative whose keys come from the first field of each record,
1252 * and whose values are the corresponding second fields.
1253 * False is returned if an error occurs.
1255 * @param string $table the table to query.
1256 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1257 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1258 * @param string $fields a comma separated list of fields to return - the number of fields should be 2!
1259 * @param int $limitfrom return a subset of records, starting at this point (optional).
1260 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1261 * @return array an associative array
1262 * @throws dml_exception A DML specific exception is thrown for any errors.
1264 public function get_records_menu($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1266 if ($records = $this->get_records($table, $conditions, $sort, $fields, $limitfrom, $limitnum)) {
1267 foreach ($records as $record) {
1268 $record = (array)$record;
1269 $key = array_shift($record);
1270 $value = array_shift($record);
1271 $menu[$key] = $value;
1278 * Get the first two columns from a number of records as an associative array which match a particular WHERE clause.
1280 * Arguments are like {@link function get_recordset_select}.
1281 * Return value is like {@link function get_records_menu}.
1283 * @param string $table The database table to be checked against.
1284 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1285 * @param array $params array of sql parameters
1286 * @param string $sort Sort order (optional) - a valid SQL order parameter
1287 * @param string $fields A comma separated list of fields to be returned from the chosen table - the number of fields should be 2!
1288 * @param int $limitfrom return a subset of records, starting at this point (optional).
1289 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1290 * @return array an associative array
1291 * @throws dml_exception A DML specific exception is thrown for any errors.
1293 public function get_records_select_menu($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1295 if ($records = $this->get_records_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum)) {
1296 foreach ($records as $record) {
1297 $record = (array)$record;
1298 $key = array_shift($record);
1299 $value = array_shift($record);
1300 $menu[$key] = $value;
1307 * Get the first two columns from a number of records as an associative array using a SQL statement.
1309 * Arguments are like {@link function get_recordset_sql}.
1310 * Return value is like {@link function get_records_menu}.
1312 * @param string $sql The SQL string you wish to be executed.
1313 * @param array $params array of sql parameters
1314 * @param int $limitfrom return a subset of records, starting at this point (optional).
1315 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1316 * @return array an associative array
1317 * @throws dml_exception A DML specific exception is thrown for any errors.
1319 public function get_records_sql_menu($sql, array $params=null, $limitfrom=0, $limitnum=0) {
1321 if ($records = $this->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
1322 foreach ($records as $record) {
1323 $record = (array)$record;
1324 $key = array_shift($record);
1325 $value = array_shift($record);
1326 $menu[$key] = $value;
1333 * Get a single database record as an object where all the given conditions met.
1335 * @param string $table The table to select from.
1336 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1337 * @param string $fields A comma separated list of fields to be returned from the chosen table.
1338 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1339 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1340 * MUST_EXIST means we will throw an exception if no record or multiple records found.
1342 * @todo MDL-30407 MUST_EXIST option should not throw a dml_exception, it should throw a different exception as it's a requested check.
1343 * @return mixed a fieldset object containing the first matching record, false or exception if error not found depending on mode
1344 * @throws dml_exception A DML specific exception is thrown for any errors.
1346 public function get_record($table, array $conditions, $fields='*', $strictness=IGNORE_MISSING
) {
1347 list($select, $params) = $this->where_clause($table, $conditions);
1348 return $this->get_record_select($table, $select, $params, $fields, $strictness);
1352 * Get a single database record as an object which match a particular WHERE clause.
1354 * @param string $table The database table to be checked against.
1355 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1356 * @param array $params array of sql parameters
1357 * @param string $fields A comma separated list of fields to be returned from the chosen table.
1358 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1359 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1360 * MUST_EXIST means throw exception if no record or multiple records found
1361 * @return stdClass|false a fieldset object containing the first matching record, false or exception if error not found depending on mode
1362 * @throws dml_exception A DML specific exception is thrown for any errors.
1364 public function get_record_select($table, $select, array $params=null, $fields='*', $strictness=IGNORE_MISSING
) {
1366 $select = "WHERE $select";
1369 return $this->get_record_sql("SELECT $fields FROM {" . $table . "} $select", $params, $strictness);
1370 } catch (dml_missing_record_exception
$e) {
1371 // create new exception which will contain correct table name
1372 throw new dml_missing_record_exception($table, $e->sql
, $e->params
);
1377 * Get a single database record as an object using a SQL statement.
1379 * The SQL statement should normally only return one record.
1380 * It is recommended to use get_records_sql() if more matches possible!
1382 * @param string $sql The SQL string you wish to be executed, should normally only return one record.
1383 * @param array $params array of sql parameters
1384 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1385 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1386 * MUST_EXIST means throw exception if no record or multiple records found
1387 * @return mixed a fieldset object containing the first matching record, false or exception if error not found depending on mode
1388 * @throws dml_exception A DML specific exception is thrown for any errors.
1390 public function get_record_sql($sql, array $params=null, $strictness=IGNORE_MISSING
) {
1391 $strictness = (int)$strictness; // we support true/false for BC reasons too
1392 if ($strictness == IGNORE_MULTIPLE
) {
1397 if (!$records = $this->get_records_sql($sql, $params, 0, $count)) {
1399 if ($strictness == MUST_EXIST
) {
1400 throw new dml_missing_record_exception('', $sql, $params);
1405 if (count($records) > 1) {
1406 if ($strictness == MUST_EXIST
) {
1407 throw new dml_multiple_records_exception($sql, $params);
1409 debugging('Error: mdb->get_record() found more than one record!');
1412 $return = reset($records);
1417 * Get a single field value from a table record where all the given conditions met.
1419 * @param string $table the table to query.
1420 * @param string $return the field to return the value of.
1421 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1422 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1423 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1424 * MUST_EXIST means throw exception if no record or multiple records found
1425 * @return mixed the specified value false if not found
1426 * @throws dml_exception A DML specific exception is thrown for any errors.
1428 public function get_field($table, $return, array $conditions, $strictness=IGNORE_MISSING
) {
1429 list($select, $params) = $this->where_clause($table, $conditions);
1430 return $this->get_field_select($table, $return, $select, $params, $strictness);
1434 * Get a single field value from a table record which match a particular WHERE clause.
1436 * @param string $table the table to query.
1437 * @param string $return the field to return the value of.
1438 * @param string $select A fragment of SQL to be used in a where clause returning one row with one column
1439 * @param array $params array of sql parameters
1440 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1441 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1442 * MUST_EXIST means throw exception if no record or multiple records found
1443 * @return mixed the specified value false if not found
1444 * @throws dml_exception A DML specific exception is thrown for any errors.
1446 public function get_field_select($table, $return, $select, array $params=null, $strictness=IGNORE_MISSING
) {
1448 $select = "WHERE $select";
1451 return $this->get_field_sql("SELECT $return FROM {" . $table . "} $select", $params, $strictness);
1452 } catch (dml_missing_record_exception
$e) {
1453 // create new exception which will contain correct table name
1454 throw new dml_missing_record_exception($table, $e->sql
, $e->params
);
1459 * Get a single field value (first field) using a SQL statement.
1461 * @param string $sql The SQL query returning one row with one column
1462 * @param array $params array of sql parameters
1463 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1464 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1465 * MUST_EXIST means throw exception if no record or multiple records found
1466 * @return mixed the specified value false if not found
1467 * @throws dml_exception A DML specific exception is thrown for any errors.
1469 public function get_field_sql($sql, array $params=null, $strictness=IGNORE_MISSING
) {
1470 if (!$record = $this->get_record_sql($sql, $params, $strictness)) {
1474 $record = (array)$record;
1475 return reset($record); // first column
1479 * Selects records and return values of chosen field as an array which match a particular WHERE clause.
1481 * @param string $table the table to query.
1482 * @param string $return the field we are intered in
1483 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1484 * @param array $params array of sql parameters
1485 * @return array of values
1486 * @throws dml_exception A DML specific exception is thrown for any errors.
1488 public function get_fieldset_select($table, $return, $select, array $params=null) {
1490 $select = "WHERE $select";
1492 return $this->get_fieldset_sql("SELECT $return FROM {" . $table . "} $select", $params);
1496 * Selects records and return values (first field) as an array using a SQL statement.
1498 * @param string $sql The SQL query
1499 * @param array $params array of sql parameters
1500 * @return array of values
1501 * @throws dml_exception A DML specific exception is thrown for any errors.
1503 public abstract function get_fieldset_sql($sql, array $params=null);
1506 * Insert new record into database, as fast as possible, no safety checks, lobs not supported.
1507 * @param string $table name
1508 * @param mixed $params data record as object or array
1509 * @param bool $returnid Returns id of inserted record.
1510 * @param bool $bulk true means repeated inserts expected
1511 * @param bool $customsequence true if 'id' included in $params, disables $returnid
1512 * @return bool|int true or new id
1513 * @throws dml_exception A DML specific exception is thrown for any errors.
1515 public abstract function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false);
1518 * Insert a record into a table and return the "id" field if required.
1520 * Some conversions and safety checks are carried out. Lobs are supported.
1521 * If the return ID isn't required, then this just reports success as true/false.
1522 * $data is an object containing needed data
1523 * @param string $table The database table to be inserted into
1524 * @param object $dataobject A data object with values for one or more fields in the record
1525 * @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.
1526 * @param bool $bulk Set to true is multiple inserts are expected
1527 * @return bool|int true or new id
1528 * @throws dml_exception A DML specific exception is thrown for any errors.
1530 public abstract function insert_record($table, $dataobject, $returnid=true, $bulk=false);
1533 * Import a record into a table, id field is required.
1534 * Safety checks are NOT carried out. Lobs are supported.
1536 * @param string $table name of database table to be inserted into
1537 * @param object $dataobject A data object with values for one or more fields in the record
1539 * @throws dml_exception A DML specific exception is thrown for any errors.
1541 public abstract function import_record($table, $dataobject);
1544 * Update record in database, as fast as possible, no safety checks, lobs not supported.
1545 * @param string $table name
1546 * @param mixed $params data record as object or array
1547 * @param bool $bulk True means repeated updates expected.
1549 * @throws dml_exception A DML specific exception is thrown for any errors.
1551 public abstract function update_record_raw($table, $params, $bulk=false);
1554 * Update a record in a table
1556 * $dataobject is an object containing needed data
1557 * Relies on $dataobject having a variable "id" to
1558 * specify the record to update
1560 * @param string $table The database table to be checked against.
1561 * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
1562 * @param bool $bulk True means repeated updates expected.
1564 * @throws dml_exception A DML specific exception is thrown for any errors.
1566 public abstract function update_record($table, $dataobject, $bulk=false);
1569 * Set a single field in every table record where all the given conditions met.
1571 * @param string $table The database table to be checked against.
1572 * @param string $newfield the field to set.
1573 * @param string $newvalue the value to set the field to.
1574 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1576 * @throws dml_exception A DML specific exception is thrown for any errors.
1578 public function set_field($table, $newfield, $newvalue, array $conditions=null) {
1579 list($select, $params) = $this->where_clause($table, $conditions);
1580 return $this->set_field_select($table, $newfield, $newvalue, $select, $params);
1584 * Set a single field in every table record which match a particular WHERE clause.
1586 * @param string $table The database table to be checked against.
1587 * @param string $newfield the field to set.
1588 * @param string $newvalue the value to set the field to.
1589 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1590 * @param array $params array of sql parameters
1592 * @throws dml_exception A DML specific exception is thrown for any errors.
1594 public abstract function set_field_select($table, $newfield, $newvalue, $select, array $params=null);
1598 * Count the records in a table where all the given conditions met.
1600 * @param string $table The table to query.
1601 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1602 * @return int The count of records returned from the specified criteria.
1603 * @throws dml_exception A DML specific exception is thrown for any errors.
1605 public function count_records($table, array $conditions=null) {
1606 list($select, $params) = $this->where_clause($table, $conditions);
1607 return $this->count_records_select($table, $select, $params);
1611 * Count the records in a table which match a particular WHERE clause.
1613 * @param string $table The database table to be checked against.
1614 * @param string $select A fragment of SQL to be used in a WHERE clause in the SQL call.
1615 * @param array $params array of sql parameters
1616 * @param string $countitem The count string to be used in the SQL call. Default is COUNT('x').
1617 * @return int The count of records returned from the specified criteria.
1618 * @throws dml_exception A DML specific exception is thrown for any errors.
1620 public function count_records_select($table, $select, array $params=null, $countitem="COUNT('x')") {
1622 $select = "WHERE $select";
1624 return $this->count_records_sql("SELECT $countitem FROM {" . $table . "} $select", $params);
1628 * Get the result of a SQL SELECT COUNT(...) query.
1630 * Given a query that counts rows, return that count. (In fact,
1631 * given any query, return the first field of the first record
1632 * returned. However, this method should only be used for the
1633 * intended purpose.) If an error occurs, 0 is returned.
1635 * @param string $sql The SQL string you wish to be executed.
1636 * @param array $params array of sql parameters
1637 * @return int the count
1638 * @throws dml_exception A DML specific exception is thrown for any errors.
1640 public function count_records_sql($sql, array $params=null) {
1641 $count = $this->get_field_sql($sql, $params);
1642 if ($count === false or !is_number($count) or $count < 0) {
1643 throw new coding_exception("count_records_sql() expects the first field to contain non-negative number from COUNT(), '$count' found instead.");
1649 * Test whether a record exists in a table where all the given conditions met.
1651 * @param string $table The table to check.
1652 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1653 * @return bool true if a matching record exists, else false.
1654 * @throws dml_exception A DML specific exception is thrown for any errors.
1656 public function record_exists($table, array $conditions) {
1657 list($select, $params) = $this->where_clause($table, $conditions);
1658 return $this->record_exists_select($table, $select, $params);
1662 * Test whether any records exists in a table which match a particular WHERE clause.
1664 * @param string $table The database table to be checked against.
1665 * @param string $select A fragment of SQL to be used in a WHERE clause in the SQL call.
1666 * @param array $params array of sql parameters
1667 * @return bool true if a matching record exists, else false.
1668 * @throws dml_exception A DML specific exception is thrown for any errors.
1670 public function record_exists_select($table, $select, array $params=null) {
1672 $select = "WHERE $select";
1674 return $this->record_exists_sql("SELECT 'x' FROM {" . $table . "} $select", $params);
1678 * Test whether a SQL SELECT statement returns any records.
1680 * This function returns true if the SQL statement executes
1681 * without any errors and returns at least one record.
1683 * @param string $sql The SQL statement to execute.
1684 * @param array $params array of sql parameters
1685 * @return bool true if the SQL executes without errors and returns at least one record.
1686 * @throws dml_exception A DML specific exception is thrown for any errors.
1688 public function record_exists_sql($sql, array $params=null) {
1689 $mrs = $this->get_recordset_sql($sql, $params, 0, 1);
1690 $return = $mrs->valid();
1696 * Delete the records from a table where all the given conditions met.
1697 * If conditions not specified, table is truncated.
1699 * @param string $table the table to delete from.
1700 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1701 * @return bool true.
1702 * @throws dml_exception A DML specific exception is thrown for any errors.
1704 public function delete_records($table, array $conditions=null) {
1705 // truncate is drop/create (DDL), not transactional safe,
1706 // so we don't use the shortcut within them. MDL-29198
1707 if (is_null($conditions) && empty($this->transactions
)) {
1708 return $this->execute("TRUNCATE TABLE {".$table."}");
1710 list($select, $params) = $this->where_clause($table, $conditions);
1711 return $this->delete_records_select($table, $select, $params);
1715 * Delete the records from a table where one field match one list of values.
1717 * @param string $table the table to delete from.
1718 * @param string $field The field to search
1719 * @param array $values array of values
1720 * @return bool true.
1721 * @throws dml_exception A DML specific exception is thrown for any errors.
1723 public function delete_records_list($table, $field, array $values) {
1724 list($select, $params) = $this->where_clause_list($field, $values);
1725 return $this->delete_records_select($table, $select, $params);
1729 * Delete one or more records from a table which match a particular WHERE clause.
1731 * @param string $table The database table to be checked against.
1732 * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
1733 * @param array $params array of sql parameters
1734 * @return bool true.
1735 * @throws dml_exception A DML specific exception is thrown for any errors.
1737 public abstract function delete_records_select($table, $select, array $params=null);
1740 * Returns the FROM clause required by some DBs in all SELECT statements.
1742 * To be used in queries not having FROM clause to provide cross_db
1743 * Most DBs don't need it, hence the default is ''
1746 public function sql_null_from_clause() {
1751 * Returns the SQL text to be used in order to perform one bitwise AND operation
1752 * between 2 integers.
1754 * NOTE: The SQL result is a number and can not be used directly in
1755 * SQL condition, please compare it to some number to get a bool!!
1757 * @param int $int1 First integer in the operation.
1758 * @param int $int2 Second integer in the operation.
1759 * @return string The piece of SQL code to be used in your statement.
1761 public function sql_bitand($int1, $int2) {
1762 return '((' . $int1 . ') & (' . $int2 . '))';
1766 * Returns the SQL text to be used in order to perform one bitwise NOT operation
1769 * @param int $int1 The operand integer in the operation.
1770 * @return string The piece of SQL code to be used in your statement.
1772 public function sql_bitnot($int1) {
1773 return '(~(' . $int1 . '))';
1777 * Returns the SQL text to be used in order to perform one bitwise OR operation
1778 * between 2 integers.
1780 * NOTE: The SQL result is a number and can not be used directly in
1781 * SQL condition, please compare it to some number to get a bool!!
1783 * @param int $int1 The first operand integer in the operation.
1784 * @param int $int2 The second operand integer in the operation.
1785 * @return string The piece of SQL code to be used in your statement.
1787 public function sql_bitor($int1, $int2) {
1788 return '((' . $int1 . ') | (' . $int2 . '))';
1792 * Returns the SQL text to be used in order to perform one bitwise XOR operation
1793 * between 2 integers.
1795 * NOTE: The SQL result is a number and can not be used directly in
1796 * SQL condition, please compare it to some number to get a bool!!
1798 * @param int $int1 The first operand integer in the operation.
1799 * @param int $int2 The second operand integer in the operation.
1800 * @return string The piece of SQL code to be used in your statement.
1802 public function sql_bitxor($int1, $int2) {
1803 return '((' . $int1 . ') ^ (' . $int2 . '))';
1807 * Returns the SQL text to be used in order to perform module '%'
1808 * operation - remainder after division
1810 * @param int $int1 The first operand integer in the operation.
1811 * @param int $int2 The second operand integer in the operation.
1812 * @return string The piece of SQL code to be used in your statement.
1814 public function sql_modulo($int1, $int2) {
1815 return '((' . $int1 . ') % (' . $int2 . '))';
1819 * Returns the cross db correct CEIL (ceiling) expression applied to fieldname.
1820 * note: Most DBs use CEIL(), hence it's the default here.
1822 * @param string $fieldname The field (or expression) we are going to ceil.
1823 * @return string The piece of SQL code to be used in your ceiling statement.
1825 public function sql_ceil($fieldname) {
1826 return ' CEIL(' . $fieldname . ')';
1830 * Returns the SQL to be used in order to CAST one CHAR column to INTEGER.
1832 * Be aware that the CHAR column you're trying to cast contains really
1833 * int values or the RDBMS will throw an error!
1835 * @param string $fieldname The name of the field to be casted.
1836 * @param bool $text Specifies if the original column is one TEXT (CLOB) column (true). Defaults to false.
1837 * @return string The piece of SQL code to be used in your statement.
1839 public function sql_cast_char2int($fieldname, $text=false) {
1840 return ' ' . $fieldname . ' ';
1844 * Returns the SQL to be used in order to CAST one CHAR column to REAL number.
1846 * Be aware that the CHAR column you're trying to cast contains really
1847 * numbers or the RDBMS will throw an error!
1849 * @param string $fieldname The name of the field to be casted.
1850 * @param bool $text Specifies if the original column is one TEXT (CLOB) column (true). Defaults to false.
1851 * @return string The piece of SQL code to be used in your statement.
1853 public function sql_cast_char2real($fieldname, $text=false) {
1854 return ' ' . $fieldname . ' ';
1858 * Returns the SQL to be used in order to an UNSIGNED INTEGER column to SIGNED.
1860 * (Only MySQL needs this. MySQL things that 1 * -1 = 18446744073709551615
1861 * if the 1 comes from an unsigned column).
1863 * @deprecated since 2.3
1864 * @param string $fieldname The name of the field to be cast
1865 * @return string The piece of SQL code to be used in your statement.
1867 public function sql_cast_2signed($fieldname) {
1868 return ' ' . $fieldname . ' ';
1872 * Returns the SQL text to be used to compare one TEXT (clob) column with
1873 * one varchar column, because some RDBMS doesn't support such direct
1876 * @param string $fieldname The name of the TEXT field we need to order by
1877 * @param int $numchars Number of chars to use for the ordering (defaults to 32).
1878 * @return string The piece of SQL code to be used in your statement.
1880 public function sql_compare_text($fieldname, $numchars=32) {
1881 return $this->sql_order_by_text($fieldname, $numchars);
1885 * Returns 'LIKE' part of a query.
1887 * @param string $fieldname Usually the name of the table column.
1888 * @param string $param Usually the bound query parameter (?, :named).
1889 * @param bool $casesensitive Use case sensitive search when set to true (default).
1890 * @param bool $accentsensitive Use accent sensitive search when set to true (default). (not all databases support accent insensitive)
1891 * @param bool $notlike True means "NOT LIKE".
1892 * @param string $escapechar The escape char for '%' and '_'.
1893 * @return string The SQL code fragment.
1895 public function sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = '\\') {
1896 if (strpos($param, '%') !== false) {
1897 debugging('Potential SQL injection detected, sql_like() expects bound parameters (? or :named)');
1899 $LIKE = $notlike ?
'NOT LIKE' : 'LIKE';
1900 // by default ignore any sensitiveness - each database does it in a different way
1901 return "$fieldname $LIKE $param ESCAPE '$escapechar'";
1905 * Escape sql LIKE special characters like '_' or '%'.
1906 * @param string $text The string containing characters needing escaping.
1907 * @param string $escapechar The desired escape character, defaults to '\\'.
1908 * @return string The escaped sql LIKE string.
1910 public function sql_like_escape($text, $escapechar = '\\') {
1911 $text = str_replace('_', $escapechar.'_', $text);
1912 $text = str_replace('%', $escapechar.'%', $text);
1917 * Returns the proper SQL to do CONCAT between the elements(fieldnames) passed.
1919 * This function accepts variable number of string parameters.
1920 * All strings/fieldnames will used in the SQL concatenate statement generated.
1922 * @return string The SQL to concatenate strings passed in.
1923 * @uses func_get_args() and thus parameters are unlimited OPTIONAL number of additional field names.
1925 public abstract function sql_concat();
1928 * Returns the proper SQL to do CONCAT between the elements passed
1929 * with a given separator
1931 * @param string $separator The separator desired for the SQL concatenating $elements.
1932 * @param array $elements The array of strings to be concatenated.
1933 * @return string The SQL to concatenate the strings.
1935 public abstract function sql_concat_join($separator="' '", $elements=array());
1938 * Returns the proper SQL (for the dbms in use) to concatenate $firstname and $lastname
1940 * @todo MDL-31233 This may not be needed here.
1942 * @param string $first User's first name (default:'firstname').
1943 * @param string $last User's last name (default:'lastname').
1944 * @return string The SQL to concatenate strings.
1946 function sql_fullname($first='firstname', $last='lastname') {
1947 return $this->sql_concat($first, "' '", $last);
1951 * Returns the SQL text to be used to order by one TEXT (clob) column, because
1952 * some RDBMS doesn't support direct ordering of such fields.
1954 * Note that the use or queries being ordered by TEXT columns must be minimised,
1955 * because it's really slooooooow.
1957 * @param string $fieldname The name of the TEXT field we need to order by.
1958 * @param int $numchars The number of chars to use for the ordering (defaults to 32).
1959 * @return string The piece of SQL code to be used in your statement.
1961 public function sql_order_by_text($fieldname, $numchars=32) {
1966 * Returns the SQL text to be used to calculate the length in characters of one expression.
1967 * @param string $fieldname The fieldname/expression to calculate its length in characters.
1968 * @return string the piece of SQL code to be used in the statement.
1970 public function sql_length($fieldname) {
1971 return ' LENGTH(' . $fieldname . ')';
1975 * Returns the proper substr() SQL text used to extract substrings from DB
1976 * NOTE: this was originally returning only function name
1978 * @param string $expr Some string field, no aggregates.
1979 * @param mixed $start Integer or expression evaluating to integer (1 based value; first char has index 1)
1980 * @param mixed $length Optional integer or expression evaluating to integer.
1981 * @return string The sql substring extraction fragment.
1983 public function sql_substr($expr, $start, $length=false) {
1984 if (count(func_get_args()) < 2) {
1985 throw new coding_exception('moodle_database::sql_substr() requires at least two parameters', 'Originally this function was only returning name of SQL substring function, it now requires all parameters.');
1987 if ($length === false) {
1988 return "SUBSTR($expr, $start)";
1990 return "SUBSTR($expr, $start, $length)";
1995 * Returns the SQL for returning searching one string for the location of another.
1997 * Note, there is no guarantee which order $needle, $haystack will be in
1998 * the resulting SQL so when using this method, and both arguments contain
1999 * placeholders, you should use named placeholders.
2001 * @param string $needle the SQL expression that will be searched for.
2002 * @param string $haystack the SQL expression that will be searched in.
2003 * @return string The required searching SQL part.
2005 public function sql_position($needle, $haystack) {
2006 // Implementation using standard SQL.
2007 return "POSITION(($needle) IN ($haystack))";
2011 * This used to return empty string replacement character.
2013 * @deprecated use bound parameter with empty string instead
2015 * @return string An empty string.
2017 function sql_empty() {
2018 debugging("sql_empty() is deprecated, please use empty string '' as sql parameter value instead", DEBUG_DEVELOPER
);
2023 * Returns the proper SQL to know if one field is empty.
2025 * Note that the function behavior strongly relies on the
2026 * parameters passed describing the field so, please, be accurate
2027 * when specifying them.
2029 * Also, note that this function is not suitable to look for
2030 * fields having NULL contents at all. It's all for empty values!
2032 * This function should be applied in all the places where conditions of
2035 * ... AND fieldname = '';
2037 * are being used. Final result for text fields should be:
2039 * ... AND ' . sql_isempty('tablename', 'fieldname', true/false, true);
2041 * and for varchar fields result should be:
2043 * ... AND fieldname = :empty; "; $params['empty'] = '';
2045 * (see parameters description below)
2047 * @param string $tablename Name of the table (without prefix). Not used for now but can be
2048 * necessary in the future if we want to use some introspection using
2049 * meta information against the DB. /// TODO ///
2050 * @param string $fieldname Name of the field we are going to check
2051 * @param bool $nullablefield For specifying if the field is nullable (true) or no (false) in the DB.
2052 * @param bool $textfield For specifying if it is a text (also called clob) field (true) or a varchar one (false)
2053 * @return string the sql code to be added to check for empty values
2055 public function sql_isempty($tablename, $fieldname, $nullablefield, $textfield) {
2056 return " ($fieldname = '') ";
2060 * Returns the proper SQL to know if one field is not empty.
2062 * Note that the function behavior strongly relies on the
2063 * parameters passed describing the field so, please, be accurate
2064 * when specifying them.
2066 * This function should be applied in all the places where conditions of
2069 * ... AND fieldname != '';
2071 * are being used. Final result for text fields should be:
2073 * ... AND ' . sql_isnotempty('tablename', 'fieldname', true/false, true/false);
2075 * and for varchar fields result should be:
2077 * ... AND fieldname != :empty; "; $params['empty'] = '';
2079 * (see parameters description below)
2081 * @param string $tablename Name of the table (without prefix). This is not used for now but can be
2082 * necessary in the future if we want to use some introspection using
2083 * meta information against the DB.
2084 * @param string $fieldname The name of the field we are going to check.
2085 * @param bool $nullablefield Specifies if the field is nullable (true) or not (false) in the DB.
2086 * @param bool $textfield Specifies if it is a text (also called clob) field (true) or a varchar one (false).
2087 * @return string The sql code to be added to check for non empty values.
2089 public function sql_isnotempty($tablename, $fieldname, $nullablefield, $textfield) {
2090 return ' ( NOT ' . $this->sql_isempty($tablename, $fieldname, $nullablefield, $textfield) . ') ';
2094 * Returns true if this database driver supports regex syntax when searching.
2095 * @return bool True if supported.
2097 public function sql_regex_supported() {
2102 * Returns the driver specific syntax (SQL part) for matching regex positively or negatively (inverted matching).
2103 * Eg: 'REGEXP':'NOT REGEXP' or '~*' : '!~*'
2104 * @param bool $positivematch
2105 * @return string or empty if not supported
2107 public function sql_regex($positivematch=true) {
2112 * Checks and returns true if transactions are supported.
2114 * It is not responsible to run productions servers
2115 * on databases without transaction support ;-)
2117 * Override in driver if needed.
2121 protected function transactions_supported() {
2122 // protected for now, this might be changed to public if really necessary
2127 * Returns true if a transaction is in progress.
2130 public function is_transaction_started() {
2131 return !empty($this->transactions
);
2135 * This is a test that throws an exception if transaction in progress.
2136 * This test does not force rollback of active transactions.
2138 * @throws dml_transaction_exception if stansaction active
2140 public function transactions_forbidden() {
2141 if ($this->is_transaction_started()) {
2142 throw new dml_transaction_exception('This code can not be excecuted in transaction');
2147 * On DBs that support it, switch to transaction mode and begin a transaction
2148 * you'll need to ensure you call allow_commit() on the returned object
2149 * or your changes *will* be lost.
2151 * this is _very_ useful for massive updates
2153 * Delegated database transactions can be nested, but only one actual database
2154 * transaction is used for the outer-most delegated transaction. This method
2155 * returns a transaction object which you should keep until the end of the
2156 * delegated transaction. The actual database transaction will
2157 * only be committed if all the nested delegated transactions commit
2158 * successfully. If any part of the transaction rolls back then the whole
2159 * thing is rolled back.
2161 * @return moodle_transaction
2163 public function start_delegated_transaction() {
2164 $transaction = new moodle_transaction($this);
2165 $this->transactions
[] = $transaction;
2166 if (count($this->transactions
) == 1) {
2167 $this->begin_transaction();
2169 return $transaction;
2173 * Driver specific start of real database transaction,
2174 * this can not be used directly in code.
2177 protected abstract function begin_transaction();
2180 * Indicates delegated transaction finished successfully.
2181 * The real database transaction is committed only if
2182 * all delegated transactions committed.
2183 * @param moodle_transaction $transaction The transaction to commit
2185 * @throws dml_transaction_exception Creates and throws transaction related exceptions.
2187 public function commit_delegated_transaction(moodle_transaction
$transaction) {
2188 if ($transaction->is_disposed()) {
2189 throw new dml_transaction_exception('Transactions already disposed', $transaction);
2191 // mark as disposed so that it can not be used again
2192 $transaction->dispose();
2194 if (empty($this->transactions
)) {
2195 throw new dml_transaction_exception('Transaction not started', $transaction);
2198 if ($this->force_rollback
) {
2199 throw new dml_transaction_exception('Tried to commit transaction after lower level rollback', $transaction);
2202 if ($transaction !== $this->transactions
[count($this->transactions
) - 1]) {
2203 // one incorrect commit at any level rollbacks everything
2204 $this->force_rollback
= true;
2205 throw new dml_transaction_exception('Invalid transaction commit attempt', $transaction);
2208 if (count($this->transactions
) == 1) {
2209 // only commit the top most level
2210 $this->commit_transaction();
2212 array_pop($this->transactions
);
2216 * Driver specific commit of real database transaction,
2217 * this can not be used directly in code.
2220 protected abstract function commit_transaction();
2223 * Call when delegated transaction failed, this rolls back
2224 * all delegated transactions up to the top most level.
2226 * In many cases you do not need to call this method manually,
2227 * because all open delegated transactions are rolled back
2228 * automatically if exceptions not caught.
2230 * @param moodle_transaction $transaction An instance of a moodle_transaction.
2231 * @param Exception $e The related exception to this transaction rollback.
2232 * @return void This does not return, instead the exception passed in will be rethrown.
2234 public function rollback_delegated_transaction(moodle_transaction
$transaction, Exception
$e) {
2235 if ($transaction->is_disposed()) {
2236 throw new dml_transaction_exception('Transactions already disposed', $transaction);
2238 // mark as disposed so that it can not be used again
2239 $transaction->dispose();
2241 // one rollback at any level rollbacks everything
2242 $this->force_rollback
= true;
2244 if (empty($this->transactions
) or $transaction !== $this->transactions
[count($this->transactions
) - 1]) {
2245 // this may or may not be a coding problem, better just rethrow the exception,
2246 // because we do not want to loose the original $e
2250 if (count($this->transactions
) == 1) {
2251 // only rollback the top most level
2252 $this->rollback_transaction();
2254 array_pop($this->transactions
);
2255 if (empty($this->transactions
)) {
2256 // finally top most level rolled back
2257 $this->force_rollback
= false;
2263 * Driver specific abort of real database transaction,
2264 * this can not be used directly in code.
2267 protected abstract function rollback_transaction();
2270 * Force rollback of all delegated transaction.
2271 * Does not throw any exceptions and does not log anything.
2273 * This method should be used only from default exception handlers and other
2278 public function force_transaction_rollback() {
2279 if ($this->transactions
) {
2281 $this->rollback_transaction();
2282 } catch (dml_exception
$e) {
2283 // ignore any sql errors here, the connection might be broken
2287 // now enable transactions again
2288 $this->transactions
= array(); // unfortunately all unfinished exceptions are kept in memory
2289 $this->force_rollback
= false;
2293 * Is session lock supported in this driver?
2296 public function session_lock_supported() {
2301 * Obtains the session lock.
2302 * @param int $rowid The id of the row with session record.
2303 * @param int $timeout The maximum allowed time to wait for the lock in seconds.
2305 * @throws dml_exception A DML specific exception is thrown for any errors.
2307 public function get_session_lock($rowid, $timeout) {
2308 $this->used_for_db_sessions
= true;
2312 * Releases the session lock.
2313 * @param int $rowid The id of the row with session record.
2315 * @throws dml_exception A DML specific exception is thrown for any errors.
2317 public function release_session_lock($rowid) {
2321 * Returns the number of reads done by this database.
2322 * @return int Number of reads.
2324 public function perf_get_reads() {
2325 return $this->reads
;
2329 * Returns the number of writes done by this database.
2330 * @return int Number of writes.
2332 public function perf_get_writes() {
2333 return $this->writes
;
2337 * Returns the number of queries done by this database.
2338 * @return int Number of queries.
2340 public function perf_get_queries() {
2341 return $this->writes +
$this->reads
;