3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
20 * Abstract database driver class.
25 * @copyright 2008 Petr Skoda (http://skodak.org)
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') || die();
31 require_once($CFG->libdir.'/dml/database_column_info.php');
32 require_once($CFG->libdir.'/dml/moodle_recordset.php');
33 require_once($CFG->libdir.'/dml/moodle_transaction.php');
35 /// GLOBAL CONSTANTS /////////////////////////////////////////////////////////
37 /** SQL_PARAMS_NAMED - Bitmask, indicates :name type parameters are supported by db backend. */
38 define('SQL_PARAMS_NAMED', 1);
40 /** SQL_PARAMS_QM - Bitmask, indicates ? type parameters are supported by db backend. */
41 define('SQL_PARAMS_QM', 2);
43 /** SQL_PARAMS_DOLLAR - Bitmask, indicates $1, $2, ... type parameters are supported by db backend. */
44 define('SQL_PARAMS_DOLLAR', 4);
46 /** SQL_QUERY_SELECT - Normal select query, reading only. */
47 define('SQL_QUERY_SELECT', 1);
49 /** SQL_QUERY_INSERT - Insert select query, writing. */
50 define('SQL_QUERY_INSERT', 2);
52 /** SQL_QUERY_UPDATE - Update select query, writing. */
53 define('SQL_QUERY_UPDATE', 3);
55 /** SQL_QUERY_STRUCTURE - Query changing db structure, writing. */
56 define('SQL_QUERY_STRUCTURE', 4);
58 /** SQL_QUERY_AUX - Auxiliary query done by driver, setting connection config, getting table info, etc. */
59 define('SQL_QUERY_AUX', 5);
62 * Abstract class representing moodle database interface.
63 * @link http://docs.moodle.org/dev/DML_functions
67 * @copyright 2008 Petr Skoda (http://skodak.org)
68 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
70 abstract class moodle_database {
72 /** @var database_manager db manager which allows db structure modifications. */
73 protected $database_manager;
74 /** @var moodle_temptables temptables manager to provide cross-db support for temp tables. */
75 protected $temptables;
76 /** @var array Cache of column info. */
77 protected $columns = array(); // I wish we had a shared memory cache for this :-(
78 /** @var array Cache of table info. */
79 protected $tables = null;
81 // db connection options
82 /** @var string db host name. */
84 /** @var string db host user. */
86 /** @var string db host password. */
88 /** @var string db name. */
90 /** @var string Prefix added to table names. */
93 /** @var array Database or driver specific options, such as sockets or TCPIP db connections. */
96 /** @var bool True means non-moodle external database used.*/
99 /** @var int The database reads (performance counter).*/
100 protected $reads = 0;
101 /** @var int The database writes (performance counter).*/
102 protected $writes = 0;
104 /** @var int Debug level. */
105 protected $debug = 0;
107 /** @var string Last used query sql. */
109 /** @var array Last query parameters. */
110 protected $last_params;
111 /** @var int Last query type. */
112 protected $last_type;
113 /** @var string Last extra info. */
114 protected $last_extrainfo;
115 /** @var float Last time in seconds with millisecond precision. */
116 protected $last_time;
117 /** @var bool Flag indicating logging of query in progress. This helps prevent infinite loops. */
118 private $loggingquery = false;
120 /** @var bool True if the db is used for db sessions. */
121 protected $used_for_db_sessions = false;
123 /** @var array Array containing open transactions. */
124 private $transactions = array();
125 /** @var bool Flag used to force rollback of all current transactions. */
126 private $force_rollback = false;
129 * @var int internal temporary variable used to fix params. Its used by {@link _fix_sql_params_dollar_callback()}.
131 private $fix_sql_params_i;
133 * @var int internal temporary variable used to guarantee unique parameters in each request. Its used by {@link get_in_or_equal()}.
135 private $inorequaluniqueindex = 1;
138 * Constructor - Instantiates the database, specifying if it's external (connect to other systems) or not (Moodle DB).
139 * Note that this affects the decision of whether prefix checks must be performed or not.
140 * @param bool $external True means that an external database is used.
142 public function __construct($external=false) {
143 $this->external = $external;
147 * Destructor - cleans up and flushes everything needed.
149 public function __destruct() {
154 * Detects if all needed PHP stuff are installed for DB connectivity.
155 * Note: can be used before connect()
156 * @return mixed True if requirements are met, otherwise a string if something isn't installed.
158 public abstract function driver_installed();
161 * Returns database table prefix
162 * Note: can be used before connect()
163 * @return string The prefix used in the database.
165 public function get_prefix() {
166 return $this->prefix;
170 * Loads and returns a database instance with the specified type and library.
172 * The loaded class is within lib/dml directory and of the form: $type.'_'.$library.'_moodle_database'
174 * @param string $type Database driver's type. (eg: mysqli, pgsql, mssql, sqldrv, oci, etc.)
175 * @param string $library Database driver's library (native, pdo, etc.)
176 * @param bool $external True if this is an external database.
177 * @return moodle_database driver object or null if error, for example of driver object see {@link mysqli_native_moodle_database}
179 public static function get_driver_instance($type, $library, $external = false) {
182 $classname = $type.'_'.$library.'_moodle_database';
183 $libfile = "$CFG->libdir/dml/$classname.php";
185 if (!file_exists($libfile)) {
189 require_once($libfile);
190 return new $classname($external);
194 * Returns the database family type. (This sort of describes the SQL 'dialect')
195 * Note: can be used before connect()
196 * @return string The db family name (mysql, postgres, mssql, oracle, etc.)
198 public abstract function get_dbfamily();
201 * Returns a more specific database driver type
202 * Note: can be used before connect()
203 * @return string The db type mysqli, pgsql, oci, mssql, sqlsrv
205 protected abstract function get_dbtype();
208 * Returns the general database library name
209 * Note: can be used before connect()
210 * @return string The db library type - pdo, native etc.
212 protected abstract function get_dblibrary();
215 * Returns the localised database type name
216 * Note: can be used before connect()
219 public abstract function get_name();
222 * Returns the localised database configuration help.
223 * Note: can be used before connect()
226 public abstract function get_configuration_help();
229 * Returns the localised database description
230 * Note: can be used before connect()
233 public abstract function get_configuration_hints();
236 * Returns the db related part of config.php
239 public function export_dbconfig() {
240 $cfg = new stdClass();
241 $cfg->dbtype = $this->get_dbtype();
242 $cfg->dblibrary = $this->get_dblibrary();
243 $cfg->dbhost = $this->dbhost;
244 $cfg->dbname = $this->dbname;
245 $cfg->dbuser = $this->dbuser;
246 $cfg->dbpass = $this->dbpass;
247 $cfg->prefix = $this->prefix;
248 if ($this->dboptions) {
249 $cfg->dboptions = $this->dboptions;
256 * Diagnose database and tables, this function is used
257 * to verify database and driver settings, db engine types, etc.
259 * @return string null means everything ok, string means problem found.
261 public function diagnose() {
266 * Connects to the database.
267 * Must be called before other methods.
268 * @param string $dbhost The database host.
269 * @param string $dbuser The database user to connect as.
270 * @param string $dbpass The password to use when connecting to the database.
271 * @param string $dbname The name of the database being connected to.
272 * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
273 * @param array $dboptions driver specific options
275 * @throws dml_connection_exception if error
277 public abstract function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null);
280 * Store various database settings
281 * @param string $dbhost The database host.
282 * @param string $dbuser The database user to connect as.
283 * @param string $dbpass The password to use when connecting to the database.
284 * @param string $dbname The name of the database being connected to.
285 * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
286 * @param array $dboptions driver specific options
289 protected function store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null) {
290 $this->dbhost = $dbhost;
291 $this->dbuser = $dbuser;
292 $this->dbpass = $dbpass;
293 $this->dbname = $dbname;
294 $this->prefix = $prefix;
295 $this->dboptions = (array)$dboptions;
299 * Attempt to create the database
300 * @param string $dbhost The database host.
301 * @param string $dbuser The database user to connect as.
302 * @param string $dbpass The password to use when connecting to the database.
303 * @param string $dbname The name of the database being connected to.
304 * @param array $dboptions An array of optional database options (eg: dbport)
306 * @return bool success True for successful connection. False otherwise.
308 public function create_database($dbhost, $dbuser, $dbpass, $dbname, array $dboptions=null) {
313 * Closes the database connection and releases all resources
314 * and memory (especially circular memory references).
315 * Do NOT use connect() again, create a new instance if needed.
318 public function dispose() {
319 if ($this->transactions) {
320 // this should not happen, it usually indicates wrong catching of exceptions,
321 // because all transactions should be finished manually or in default exception handler.
322 // unfortunately we can not access global $CFG any more and can not print debug,
323 // the diagnostic info should be printed in footer instead
324 $lowesttransaction = end($this->transactions);
325 $backtrace = $lowesttransaction->get_backtrace();
327 error_log('Potential coding error - active database transaction detected when disposing database:'."\n".format_backtrace($backtrace, true));
328 $this->force_transaction_rollback();
330 if ($this->used_for_db_sessions) {
331 // this is needed because we need to save session to db before closing it
332 session_get_instance()->write_close();
333 $this->used_for_db_sessions = false;
335 if ($this->temptables) {
336 $this->temptables->dispose();
337 $this->temptables = null;
339 if ($this->database_manager) {
340 $this->database_manager->dispose();
341 $this->database_manager = null;
343 $this->columns = array();
344 $this->tables = null;
348 * This should be called before each db query.
349 * @param string $sql The query string.
350 * @param array $params An array of parameters.
351 * @param int $type The type of query. ( SQL_QUERY_SELECT | SQL_QUERY_AUX | SQL_QUERY_INSERT | SQL_QUERY_UPDATE | SQL_QUERY_STRUCTURE )
352 * @param mixed $extrainfo This is here for any driver specific extra information.
355 protected function query_start($sql, array $params=null, $type, $extrainfo=null) {
356 if ($this->loggingquery) {
359 $this->last_sql = $sql;
360 $this->last_params = $params;
361 $this->last_type = $type;
362 $this->last_extrainfo = $extrainfo;
363 $this->last_time = microtime(true);
366 case SQL_QUERY_SELECT:
370 case SQL_QUERY_INSERT:
371 case SQL_QUERY_UPDATE:
372 case SQL_QUERY_STRUCTURE:
376 $this->print_debug($sql, $params);
380 * This should be called immediately after each db query. It does a clean up of resources.
381 * It also throws exceptions if the sql that ran produced errors.
382 * @param mixed $result The db specific result obtained from running a query.
383 * @throws dml_read_exception | dml_write_exception | ddl_change_structure_exception
386 protected function query_end($result) {
387 if ($this->loggingquery) {
390 if ($result !== false) {
393 $this->last_sql = null;
394 $this->last_params = null;
398 // remember current info, log queries may alter it
399 $type = $this->last_type;
400 $sql = $this->last_sql;
401 $params = $this->last_params;
402 $time = microtime(true) - $this->last_time;
403 $error = $this->get_last_error();
405 $this->query_log($error);
408 case SQL_QUERY_SELECT:
410 throw new dml_read_exception($error, $sql, $params);
411 case SQL_QUERY_INSERT:
412 case SQL_QUERY_UPDATE:
413 throw new dml_write_exception($error, $sql, $params);
414 case SQL_QUERY_STRUCTURE:
415 $this->get_manager(); // includes ddl exceptions classes ;-)
416 throw new ddl_change_structure_exception($error, $sql);
421 * This logs the last query based on 'logall', 'logslow' and 'logerrors' options configured via $CFG->dboptions .
422 * @param mixed string error or false if not error
425 public function query_log($error=false) {
426 $logall = !empty($this->dboptions['logall']);
427 $logslow = !empty($this->dboptions['logslow']) ? $this->dboptions['logslow'] : false;
428 $logerrors = !empty($this->dboptions['logerrors']);
429 $iserror = ($error !== false);
431 $time = microtime(true) - $this->last_time;
433 if ($logall or ($logslow and ($logslow < ($time+0.00001))) or ($iserror and $logerrors)) {
434 $this->loggingquery = true;
436 $backtrace = debug_backtrace();
439 array_shift($backtrace);
443 array_shift($backtrace);
445 $log = new stdClass();
446 $log->qtype = $this->last_type;
447 $log->sqltext = $this->last_sql;
448 $log->sqlparams = var_export((array)$this->last_params, true);
449 $log->error = (int)$iserror;
450 $log->info = $iserror ? $error : null;
451 $log->backtrace = format_backtrace($backtrace, true);
452 $log->exectime = $time;
453 $log->timelogged = time();
454 $this->insert_record('log_queries', $log);
455 } catch (Exception $ignored) {
457 $this->loggingquery = false;
462 * Returns database server info array
463 * @return array Array containing 'description' and 'version' atleast.
465 public abstract function get_server_info();
468 * Returns supported query parameter types
469 * @return int bitmask of accepted SQL_PARAMS_*
471 protected abstract function allowed_param_types();
474 * Returns the last error reported by the database engine.
475 * @return string The error message.
477 public abstract function get_last_error();
480 * Prints sql debug info
481 * @param string $sql The query which is being debugged.
482 * @param array $params The query parameters. (optional)
483 * @param mixed $obj The library specific object. (optional)
486 protected function print_debug($sql, array $params=null, $obj=null) {
487 if (!$this->get_debug()) {
491 echo "--------------------------------\n";
493 if (!is_null($params)) {
494 echo "[".var_export($params, true)."]\n";
496 echo "--------------------------------\n";
500 if (!is_null($params)) {
501 echo "[".s(var_export($params, true))."]\n";
508 * Returns the SQL WHERE conditions.
509 * @param string $table The table name that these conditions will be validated against.
510 * @param array $conditions The conditions to build the where clause. (must not contain numeric indexes)
511 * @throws dml_exception
512 * @return array An array list containing sql 'where' part and 'params'.
514 protected function where_clause($table, array $conditions=null) {
515 // We accept nulls in conditions
516 $conditions = is_null($conditions) ? array() : $conditions;
517 // Some checks performed under debugging only
519 $columns = $this->get_columns($table);
520 if (empty($columns)) {
521 // no supported columns means most probably table does not exist
522 throw new dml_exception('ddltablenotexist', $table);
524 foreach ($conditions as $key=>$value) {
525 if (!isset($columns[$key])) {
527 $a->fieldname = $key;
528 $a->tablename = $table;
529 throw new dml_exception('ddlfieldnotexist', $a);
531 $column = $columns[$key];
532 if ($column->meta_type == 'X') {
533 //ok so the column is a text column. sorry no text columns in the where clause conditions
534 throw new dml_exception('textconditionsnotallowed', $conditions);
539 $allowed_types = $this->allowed_param_types();
540 if (empty($conditions)) {
541 return array('', array());
546 foreach ($conditions as $key=>$value) {
548 throw new dml_exception('invalidnumkey');
550 if (is_null($value)) {
551 $where[] = "$key IS NULL";
553 if ($allowed_types & SQL_PARAMS_NAMED) {
554 // Need to verify key names because they can contain, originally,
555 // spaces and other forbidden chars when using sql_xxx() functions and friends.
556 $normkey = trim(preg_replace('/[^a-zA-Z0-9_-]/', '_', $key), '-_');
557 if ($normkey !== $key) {
558 debugging('Invalid key found in the conditions array.');
560 $where[] = "$key = :$normkey";
561 $params[$normkey] = $value;
563 $where[] = "$key = ?";
568 $where = implode(" AND ", $where);
569 return array($where, $params);
573 * Returns SQL WHERE conditions for the ..._list group of methods.
575 * @param string $field the name of a field.
576 * @param array $values the values field might take.
577 * @return array An array containing sql 'where' part and 'params'
579 protected function where_clause_list($field, array $values) {
582 $values = (array)$values;
583 foreach ($values as $value) {
584 if (is_bool($value)) {
585 $value = (int)$value;
587 if (is_null($value)) {
588 $select[] = "$field IS NULL";
590 $select[] = "$field = ?";
594 $select = implode(" OR ", $select);
595 return array($select, $params);
599 * Constructs 'IN()' or '=' sql fragment
600 * @param mixed $items A single value or array of values for the expression.
601 * @param int $type Parameter bounding type : SQL_PARAMS_QM or SQL_PARAMS_NAMED.
602 * @param string $prefix Named parameter placeholder prefix (a unique counter value is appended to each parameter name).
603 * @param bool $equal True means we want to equate to the constructed expression, false means we don't want to equate to it.
604 * @param mixed $onemptyitems This defines the behavior when the array of items provided is empty. Defaults to false,
605 * meaning throw exceptions. Other values will become part of the returned SQL fragment.
606 * @throws coding_exception | dml_exception
607 * @return array A list containing the constructed sql fragment and an array of parameters.
609 public function get_in_or_equal($items, $type=SQL_PARAMS_QM, $prefix='param', $equal=true, $onemptyitems=false) {
611 // default behavior, throw exception on empty array
612 if (is_array($items) and empty($items) and $onemptyitems === false) {
613 throw new coding_exception('moodle_database::get_in_or_equal() does not accept empty arrays');
615 // handle $onemptyitems on empty array of items
616 if (is_array($items) and empty($items)) {
617 if (is_null($onemptyitems)) { // Special case, NULL value
618 $sql = $equal ? ' IS NULL' : ' IS NOT NULL';
619 return (array($sql, array()));
621 $items = array($onemptyitems); // Rest of cases, prepare $items for std processing
625 if ($type == SQL_PARAMS_QM) {
626 if (!is_array($items) or count($items) == 1) {
627 $sql = $equal ? '= ?' : '<> ?';
628 $items = (array)$items;
629 $params = array_values($items);
632 $sql = 'IN ('.implode(',', array_fill(0, count($items), '?')).')';
634 $sql = 'NOT IN ('.implode(',', array_fill(0, count($items), '?')).')';
636 $params = array_values($items);
639 } else if ($type == SQL_PARAMS_NAMED) {
640 if (empty($prefix)) {
644 if (!is_array($items)){
645 $param = $prefix.$this->inorequaluniqueindex++;
646 $sql = $equal ? "= :$param" : "<> :$param";
647 $params = array($param=>$items);
648 } else if (count($items) == 1) {
649 $param = $prefix.$this->inorequaluniqueindex++;
650 $sql = $equal ? "= :$param" : "<> :$param";
651 $item = reset($items);
652 $params = array($param=>$item);
656 foreach ($items as $item) {
657 $param = $prefix.$this->inorequaluniqueindex++;
658 $params[$param] = $item;
662 $sql = 'IN ('.implode(',', $sql).')';
664 $sql = 'NOT IN ('.implode(',', $sql).')';
669 throw new dml_exception('typenotimplement');
671 return array($sql, $params);
675 * Converts short table name {tablename} to the real prefixed table name in given sql.
676 * @param string $sql The sql to be operated on.
677 * @return string The sql with tablenames being prefixed with $CFG->prefix
679 protected function fix_table_names($sql) {
680 return preg_replace('/\{([a-z][a-z0-9_]*)\}/', $this->prefix.'$1', $sql);
684 * Internal private utitlity function used to fix parameters.
685 * Used with {@link preg_replace_callback()}
686 * @param array $match Refer to preg_replace_callback usage for description.
688 private function _fix_sql_params_dollar_callback($match) {
689 $this->fix_sql_params_i++;
690 return "\$".$this->fix_sql_params_i;
694 * Normalizes sql query parameters and verifies parameters.
695 * @param string $sql The query or part of it.
696 * @param array $params The query parameters.
697 * @return array (sql, params, type of params)
699 public function fix_sql_params($sql, array $params=null) {
700 $params = (array)$params; // mke null array if needed
701 $allowed_types = $this->allowed_param_types();
703 // convert table names
704 $sql = $this->fix_table_names($sql);
706 // cast booleans to 1/0 int
707 foreach ($params as $key => $value) {
708 $params[$key] = is_bool($value) ? (int)$value : $value;
711 // NICOLAS C: Fixed regexp for negative backwards lookahead of double colons. Thanks for Sam Marshall's help
712 $named_count = preg_match_all('/(?<!:):[a-z][a-z0-9_]*/', $sql, $named_matches); // :: used in pgsql casts
713 $dollar_count = preg_match_all('/\$[1-9][0-9]*/', $sql, $dollar_matches);
714 $q_count = substr_count($sql, '?');
719 $type = SQL_PARAMS_NAMED;
720 $count = $named_count;
725 throw new dml_exception('mixedtypesqlparam');
727 $type = SQL_PARAMS_DOLLAR;
728 $count = $dollar_count;
733 throw new dml_exception('mixedtypesqlparam');
735 $type = SQL_PARAMS_QM;
742 if ($allowed_types & SQL_PARAMS_NAMED) {
743 return array($sql, array(), SQL_PARAMS_NAMED);
744 } else if ($allowed_types & SQL_PARAMS_QM) {
745 return array($sql, array(), SQL_PARAMS_QM);
747 return array($sql, array(), SQL_PARAMS_DOLLAR);
751 if ($count > count($params)) {
753 $a->expected = $count;
754 $a->actual = count($params);
755 throw new dml_exception('invalidqueryparam', $a);
758 $target_type = $allowed_types;
760 if ($type & $allowed_types) { // bitwise AND
761 if ($count == count($params)) {
762 if ($type == SQL_PARAMS_QM) {
763 return array($sql, array_values($params), SQL_PARAMS_QM); // 0-based array required
765 //better do the validation of names below
768 // needs some fixing or validation - there might be more params than needed
769 $target_type = $type;
772 if ($type == SQL_PARAMS_NAMED) {
773 $finalparams = array();
774 foreach ($named_matches[0] as $key) {
775 $key = trim($key, ':');
776 if (!array_key_exists($key, $params)) {
777 throw new dml_exception('missingkeyinsql', $key, '');
779 if (strlen($key) > 30) {
780 throw new coding_exception(
781 "Placeholder names must be 30 characters or shorter. '" .
782 $key . "' is too long.", $sql);
784 $finalparams[$key] = $params[$key];
786 if ($count != count($finalparams)) {
787 throw new dml_exception('duplicateparaminsql');
790 if ($target_type & SQL_PARAMS_QM) {
791 $sql = preg_replace('/(?<!:):[a-z][a-z0-9_]*/', '?', $sql);
792 return array($sql, array_values($finalparams), SQL_PARAMS_QM); // 0-based required
793 } else if ($target_type & SQL_PARAMS_NAMED) {
794 return array($sql, $finalparams, SQL_PARAMS_NAMED);
795 } else { // $type & SQL_PARAMS_DOLLAR
796 //lambda-style functions eat memory - we use globals instead :-(
797 $this->fix_sql_params_i = 0;
798 $sql = preg_replace_callback('/(?<!:):[a-z][a-z0-9_]*/', array($this, '_fix_sql_params_dollar_callback'), $sql);
799 return array($sql, array_values($finalparams), SQL_PARAMS_DOLLAR); // 0-based required
802 } else if ($type == SQL_PARAMS_DOLLAR) {
803 if ($target_type & SQL_PARAMS_DOLLAR) {
804 return array($sql, array_values($params), SQL_PARAMS_DOLLAR); // 0-based required
805 } else if ($target_type & SQL_PARAMS_QM) {
806 $sql = preg_replace('/\$[0-9]+/', '?', $sql);
807 return array($sql, array_values($params), SQL_PARAMS_QM); // 0-based required
808 } else { //$target_type & SQL_PARAMS_NAMED
809 $sql = preg_replace('/\$([0-9]+)/', ':param\\1', $sql);
810 $finalparams = array();
811 foreach ($params as $key=>$param) {
813 $finalparams['param'.$key] = $param;
815 return array($sql, $finalparams, SQL_PARAMS_NAMED);
818 } else { // $type == SQL_PARAMS_QM
819 if (count($params) != $count) {
820 $params = array_slice($params, 0, $count);
823 if ($target_type & SQL_PARAMS_QM) {
824 return array($sql, array_values($params), SQL_PARAMS_QM); // 0-based required
825 } else if ($target_type & SQL_PARAMS_NAMED) {
826 $finalparams = array();
828 $parts = explode('?', $sql);
829 $sql = array_shift($parts);
830 foreach ($parts as $part) {
831 $param = array_shift($params);
833 $sql .= ':'.$pname.$part;
834 $finalparams[$pname] = $param;
836 return array($sql, $finalparams, SQL_PARAMS_NAMED);
837 } else { // $type & SQL_PARAMS_DOLLAR
838 //lambda-style functions eat memory - we use globals instead :-(
839 $this->fix_sql_params_i = 0;
840 $sql = preg_replace_callback('/\?/', array($this, '_fix_sql_params_dollar_callback'), $sql);
841 return array($sql, array_values($params), SQL_PARAMS_DOLLAR); // 0-based required
847 * Return tables in database WITHOUT current prefix.
848 * @param bool $usecache if true, returns list of cached tables.
849 * @return array of table names in lowercase and without prefix
851 public abstract function get_tables($usecache=true);
854 * Return table indexes - everything lowercased.
855 * @param string $table The table we want to get indexes from.
856 * @return array An associative array of indexes containing 'unique' flag and 'columns' being indexed
858 public abstract function get_indexes($table);
861 * Returns detailed information about columns in table. This information is cached internally.
862 * @param string $table The table's name.
863 * @param bool $usecache Flag to use internal cacheing. The default is true.
864 * @return array of database_column_info objects indexed with column names
866 public abstract function get_columns($table, $usecache=true);
869 * Normalise values based on varying RDBMS's dependencies (booleans, LOBs...)
871 * @param database_column_info $column column metadata corresponding with the value we are going to normalise
872 * @param mixed $value value we are going to normalise
873 * @return mixed the normalised value
875 protected abstract function normalise_value($column, $value);
878 * Resets the internal column details cache
881 public function reset_caches() {
882 $this->columns = array();
883 $this->tables = null;
887 * Returns the sql generator used for db manipulation.
888 * Used mostly in upgrade.php scripts.
889 * @return database_manager The instance used to perform ddl operations.
890 * @see lib/ddl/database_manager.php
892 public function get_manager() {
895 if (!$this->database_manager) {
896 require_once($CFG->libdir.'/ddllib.php');
898 $classname = $this->get_dbfamily().'_sql_generator';
899 require_once("$CFG->libdir/ddl/$classname.php");
900 $generator = new $classname($this, $this->temptables);
902 $this->database_manager = new database_manager($this, $generator);
904 return $this->database_manager;
908 * Attempts to change db encoding to UTF-8 encoding if possible.
909 * @return bool True is successful.
911 public function change_db_encoding() {
916 * Checks to see if the database is in unicode mode?
919 public function setup_is_unicodedb() {
924 * Enable/disable very detailed debugging.
928 public function set_debug($state) {
929 $this->debug = $state;
933 * Returns debug status
934 * @return bool $state
936 public function get_debug() {
941 * Enable/disable detailed sql logging
944 public function set_logging($state) {
945 // adodb sql logging shares one table without prefix per db - this is no longer acceptable :-(
946 // we must create one table shared by all drivers
950 * Do NOT use in code, this is for use by database_manager only!
951 * @param string $sql query
953 * @throws dml_exception A DML specific exception is thrown for any errors.
955 public abstract function change_database_structure($sql);
958 * Executes a general sql query. Should be used only when no other method suitable.
959 * Do NOT use this to make changes in db structure, use database_manager methods instead!
960 * @param string $sql query
961 * @param array $params query parameters
963 * @throws dml_exception A DML specific exception is thrown for any errors.
965 public abstract function execute($sql, array $params=null);
968 * Get a number of records as a moodle_recordset where all the given conditions met.
970 * Selects records from the table $table.
972 * If specified, only records meeting $conditions.
974 * If specified, the results will be sorted as specified by $sort. This
975 * is added to the SQL as "ORDER BY $sort". Example values of $sort
976 * might be "time ASC" or "time DESC".
978 * If $fields is specified, only those fields are returned.
980 * Since this method is a little less readable, use of it should be restricted to
981 * code where it's possible there might be large datasets being returned. For known
982 * small datasets use get_records - it leads to simpler code.
984 * If you only want some of the records, specify $limitfrom and $limitnum.
985 * The query will skip the first $limitfrom records (according to the sort
986 * order) and then return the next $limitnum records. If either of $limitfrom
987 * or $limitnum is specified, both must be present.
989 * The return value is a moodle_recordset
990 * if the query succeeds. If an error occurs, false is returned.
992 * @param string $table the table to query.
993 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
994 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
995 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
996 * @param int $limitfrom return a subset of records, starting at this point (optional).
997 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
998 * @return moodle_recordset A moodle_recordset instance
999 * @throws dml_exception A DML specific exception is thrown for any errors.
1001 public function get_recordset($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1002 list($select, $params) = $this->where_clause($table, $conditions);
1003 return $this->get_recordset_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1007 * Get a number of records as a moodle_recordset where one field match one list of values.
1009 * Only records where $field takes one of the values $values are returned.
1010 * $values must be an array of values.
1012 * Other arguments and the return type are like {@link function get_recordset}.
1014 * @param string $table the table to query.
1015 * @param string $field a field to check (optional).
1016 * @param array $values array of values the field must have
1017 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1018 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
1019 * @param int $limitfrom return a subset of records, starting at this point (optional).
1020 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1021 * @return moodle_recordset A moodle_recordset instance.
1022 * @throws dml_exception A DML specific exception is thrown for any errors.
1024 public function get_recordset_list($table, $field, array $values, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1025 list($select, $params) = $this->where_clause_list($field, $values);
1026 if (empty($select)) {
1027 $select = '1 = 2'; /// Fake condition, won't return rows ever. MDL-17645
1030 return $this->get_recordset_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1034 * Get a number of records as a moodle_recordset which match a particular WHERE clause.
1036 * If given, $select is used as the SELECT parameter in the SQL query,
1037 * otherwise all records from the table are returned.
1039 * Other arguments and the return type are like {@link function get_recordset}.
1041 * @param string $table the table to query.
1042 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1043 * @param array $params array of sql parameters
1044 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1045 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
1046 * @param int $limitfrom return a subset of records, starting at this point (optional).
1047 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1048 * @return moodle_recordset A moodle_recordset instance.
1049 * @throws dml_exception A DML specific exception is thrown for any errors.
1051 public function get_recordset_select($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1052 $sql = "SELECT $fields FROM {".$table."}";
1054 $sql .= " WHERE $select";
1057 $sql .= " ORDER BY $sort";
1059 return $this->get_recordset_sql($sql, $params, $limitfrom, $limitnum);
1063 * Get a number of records as a moodle_recordset using a SQL statement.
1065 * Since this method is a little less readable, use of it should be restricted to
1066 * code where it's possible there might be large datasets being returned. For known
1067 * small datasets use get_records_sql - it leads to simpler code.
1069 * The return type is like {@link function get_recordset}.
1071 * @param string $sql the SQL select query to execute.
1072 * @param array $params array of sql parameters
1073 * @param int $limitfrom return a subset of records, starting at this point (optional).
1074 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1075 * @return moodle_recordset A moodle_recordset instance.
1076 * @throws dml_exception A DML specific exception is thrown for any errors.
1078 public abstract function get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0);
1081 * Get a number of records as an array of objects where all the given conditions met.
1083 * If the query succeeds and returns at least one record, the
1084 * return value is an array of objects, one object for each
1085 * record found. The array key is the value from the first
1086 * column of the result set. The object associated with that key
1087 * has a member variable for each column of the results.
1089 * @param string $table the table to query.
1090 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1091 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1092 * @param string $fields a comma separated list of fields to return (optional, by default
1093 * all fields are returned). The first field will be used as key for the
1094 * array so must be a unique field such as 'id'.
1095 * @param int $limitfrom return a subset of records, starting at this point (optional).
1096 * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
1097 * @return array An array of Objects indexed by first column.
1098 * @throws dml_exception A DML specific exception is thrown for any errors.
1100 public function get_records($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1101 list($select, $params) = $this->where_clause($table, $conditions);
1102 return $this->get_records_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1106 * Get a number of records as an array of objects where one field match one list of values.
1108 * Return value is like {@link function get_records}.
1110 * @param string $table The database table to be checked against.
1111 * @param string $field The field to search
1112 * @param array $values An array of values
1113 * @param string $sort Sort order (as valid SQL sort parameter)
1114 * @param string $fields A comma separated list of fields to be returned from the chosen table. If specified,
1115 * the first field should be a unique one such as 'id' since it will be used as a key in the associative
1117 * @return array An array of objects indexed by first column
1118 * @throws dml_exception A DML specific exception is thrown for any errors.
1120 public function get_records_list($table, $field, array $values, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1121 list($select, $params) = $this->where_clause_list($field, $values);
1122 if (empty($select)) {
1123 // nothing to return
1126 return $this->get_records_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1130 * Get a number of records as an array of objects which match a particular WHERE clause.
1132 * Return value is like {@link function get_records}.
1134 * @param string $table The table to query.
1135 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1136 * @param array $params An array of sql parameters
1137 * @param string $sort An order to sort the results in (optional, a valid SQL ORDER BY parameter).
1138 * @param string $fields A comma separated list of fields to return
1139 * (optional, by default all fields are returned). The first field will be used as key for the
1140 * array so must be a unique field such as 'id'.
1141 * @param int $limitfrom return a subset of records, starting at this point (optional).
1142 * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
1143 * @return array of objects indexed by first column
1144 * @throws dml_exception A DML specific exception is thrown for any errors.
1146 public function get_records_select($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1148 $select = "WHERE $select";
1151 $sort = " ORDER BY $sort";
1153 return $this->get_records_sql("SELECT $fields FROM {" . $table . "} $select $sort", $params, $limitfrom, $limitnum);
1157 * Get a number of records as an array of objects using a SQL statement.
1159 * Return value is like {@link function get_records}.
1161 * @param string $sql the SQL select query to execute. The first column of this SELECT statement
1162 * must be a unique value (usually the 'id' field), as it will be used as the key of the
1164 * @param array $params array of sql parameters
1165 * @param int $limitfrom return a subset of records, starting at this point (optional).
1166 * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
1167 * @return array of objects indexed by first column
1168 * @throws dml_exception A DML specific exception is thrown for any errors.
1170 public abstract function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0);
1173 * Get the first two columns from a number of records as an associative array where all the given conditions met.
1175 * Arguments are like {@link function get_recordset}.
1177 * If no errors occur the return value
1178 * is an associative whose keys come from the first field of each record,
1179 * and whose values are the corresponding second fields.
1180 * False is returned if an error occurs.
1182 * @param string $table the table to query.
1183 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1184 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1185 * @param string $fields a comma separated list of fields to return - the number of fields should be 2!
1186 * @param int $limitfrom return a subset of records, starting at this point (optional).
1187 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1188 * @return array an associative array
1189 * @throws dml_exception A DML specific exception is thrown for any errors.
1191 public function get_records_menu($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1193 if ($records = $this->get_records($table, $conditions, $sort, $fields, $limitfrom, $limitnum)) {
1194 foreach ($records as $record) {
1195 $record = (array)$record;
1196 $key = array_shift($record);
1197 $value = array_shift($record);
1198 $menu[$key] = $value;
1205 * Get the first two columns from a number of records as an associative array which match a particular WHERE clause.
1207 * Arguments are like {@link function get_recordset_select}.
1208 * Return value is like {@link function get_records_menu}.
1210 * @param string $table The database table to be checked against.
1211 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1212 * @param array $params array of sql parameters
1213 * @param string $sort Sort order (optional) - a valid SQL order parameter
1214 * @param string $fields A comma separated list of fields to be returned from the chosen table - the number of fields should be 2!
1215 * @param int $limitfrom return a subset of records, starting at this point (optional).
1216 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1217 * @return array an associative array
1218 * @throws dml_exception A DML specific exception is thrown for any errors.
1220 public function get_records_select_menu($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1222 if ($records = $this->get_records_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum)) {
1223 foreach ($records as $record) {
1224 $record = (array)$record;
1225 $key = array_shift($record);
1226 $value = array_shift($record);
1227 $menu[$key] = $value;
1234 * Get the first two columns from a number of records as an associative array using a SQL statement.
1236 * Arguments are like {@link function get_recordset_sql}.
1237 * Return value is like {@link function get_records_menu}.
1239 * @param string $sql The SQL string you wish to be executed.
1240 * @param array $params array of sql parameters
1241 * @param int $limitfrom return a subset of records, starting at this point (optional).
1242 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1243 * @return array an associative array
1244 * @throws dml_exception A DML specific exception is thrown for any errors.
1246 public function get_records_sql_menu($sql, array $params=null, $limitfrom=0, $limitnum=0) {
1248 if ($records = $this->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
1249 foreach ($records as $record) {
1250 $record = (array)$record;
1251 $key = array_shift($record);
1252 $value = array_shift($record);
1253 $menu[$key] = $value;
1260 * Get a single database record as an object where all the given conditions met.
1262 * @param string $table The table to select from.
1263 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1264 * @param string $fields A comma separated list of fields to be returned from the chosen table.
1265 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1266 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1267 * MUST_EXIST means we will throw an exception if no record or multiple records found.
1269 * @todo MDL-30407 MUST_EXIST option should not throw a dml_exception, it should throw a different exception as it's a requested check.
1270 * @return mixed a fieldset object containing the first matching record, false or exception if error not found depending on mode
1271 * @throws dml_exception A DML specific exception is thrown for any errors.
1273 public function get_record($table, array $conditions, $fields='*', $strictness=IGNORE_MISSING) {
1274 list($select, $params) = $this->where_clause($table, $conditions);
1275 return $this->get_record_select($table, $select, $params, $fields, $strictness);
1279 * Get a single database record as an object which match a particular WHERE clause.
1281 * @param string $table The database table to be checked against.
1282 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1283 * @param array $params array of sql parameters
1284 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1285 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1286 * MUST_EXIST means throw exception if no record or multiple records found
1287 * @return mixed a fieldset object containing the first matching record, false or exception if error not found depending on mode
1288 * @throws dml_exception A DML specific exception is thrown for any errors.
1290 public function get_record_select($table, $select, array $params=null, $fields='*', $strictness=IGNORE_MISSING) {
1292 $select = "WHERE $select";
1295 return $this->get_record_sql("SELECT $fields FROM {" . $table . "} $select", $params, $strictness);
1296 } catch (dml_missing_record_exception $e) {
1297 // create new exception which will contain correct table name
1298 throw new dml_missing_record_exception($table, $e->sql, $e->params);
1303 * Get a single database record as an object using a SQL statement.
1305 * The SQL statement should normally only return one record.
1306 * It is recommended to use get_records_sql() if more matches possible!
1308 * @param string $sql The SQL string you wish to be executed, should normally only return one record.
1309 * @param array $params array of sql parameters
1310 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1311 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1312 * MUST_EXIST means throw exception if no record or multiple records found
1313 * @return mixed a fieldset object containing the first matching record, false or exception if error not found depending on mode
1314 * @throws dml_exception A DML specific exception is thrown for any errors.
1316 public function get_record_sql($sql, array $params=null, $strictness=IGNORE_MISSING) {
1317 $strictness = (int)$strictness; // we support true/false for BC reasons too
1318 if ($strictness == IGNORE_MULTIPLE) {
1323 if (!$records = $this->get_records_sql($sql, $params, 0, $count)) {
1325 if ($strictness == MUST_EXIST) {
1326 throw new dml_missing_record_exception('', $sql, $params);
1331 if (count($records) > 1) {
1332 if ($strictness == MUST_EXIST) {
1333 throw new dml_multiple_records_exception($sql, $params);
1335 debugging('Error: mdb->get_record() found more than one record!');
1338 $return = reset($records);
1343 * Get a single field value from a table record where all the given conditions met.
1345 * @param string $table the table to query.
1346 * @param string $return the field to return the value of.
1347 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1348 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1349 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1350 * MUST_EXIST means throw exception if no record or multiple records found
1351 * @return mixed the specified value false if not found
1352 * @throws dml_exception A DML specific exception is thrown for any errors.
1354 public function get_field($table, $return, array $conditions, $strictness=IGNORE_MISSING) {
1355 list($select, $params) = $this->where_clause($table, $conditions);
1356 return $this->get_field_select($table, $return, $select, $params, $strictness);
1360 * Get a single field value from a table record which match a particular WHERE clause.
1362 * @param string $table the table to query.
1363 * @param string $return the field to return the value of.
1364 * @param string $select A fragment of SQL to be used in a where clause returning one row with one column
1365 * @param array $params array of sql parameters
1366 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1367 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1368 * MUST_EXIST means throw exception if no record or multiple records found
1369 * @return mixed the specified value false if not found
1370 * @throws dml_exception A DML specific exception is thrown for any errors.
1372 public function get_field_select($table, $return, $select, array $params=null, $strictness=IGNORE_MISSING) {
1374 $select = "WHERE $select";
1377 return $this->get_field_sql("SELECT $return FROM {" . $table . "} $select", $params, $strictness);
1378 } catch (dml_missing_record_exception $e) {
1379 // create new exception which will contain correct table name
1380 throw new dml_missing_record_exception($table, $e->sql, $e->params);
1385 * Get a single field value (first field) using a SQL statement.
1387 * @param string $table the table to query.
1388 * @param string $return the field to return the value of.
1389 * @param string $sql The SQL query returning one row with one column
1390 * @param array $params array of sql parameters
1391 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1392 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1393 * MUST_EXIST means throw exception if no record or multiple records found
1394 * @return mixed the specified value false if not found
1395 * @throws dml_exception A DML specific exception is thrown for any errors.
1397 public function get_field_sql($sql, array $params=null, $strictness=IGNORE_MISSING) {
1398 if (!$record = $this->get_record_sql($sql, $params, $strictness)) {
1402 $record = (array)$record;
1403 return reset($record); // first column
1407 * Selects records and return values of chosen field as an array which match a particular WHERE clause.
1409 * @param string $table the table to query.
1410 * @param string $return the field we are intered in
1411 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1412 * @param array $params array of sql parameters
1413 * @return array of values
1414 * @throws dml_exception A DML specific exception is thrown for any errors.
1416 public function get_fieldset_select($table, $return, $select, array $params=null) {
1418 $select = "WHERE $select";
1420 return $this->get_fieldset_sql("SELECT $return FROM {" . $table . "} $select", $params);
1424 * Selects records and return values (first field) as an array using a SQL statement.
1426 * @param string $sql The SQL query
1427 * @param array $params array of sql parameters
1428 * @return array of values
1429 * @throws dml_exception A DML specific exception is thrown for any errors.
1431 public abstract function get_fieldset_sql($sql, array $params=null);
1434 * Insert new record into database, as fast as possible, no safety checks, lobs not supported.
1435 * @param string $table name
1436 * @param mixed $params data record as object or array
1437 * @param bool $returnid Returns id of inserted record.
1438 * @param bool $bulk true means repeated inserts expected
1439 * @param bool $customsequence true if 'id' included in $params, disables $returnid
1440 * @return bool|int true or new id
1441 * @throws dml_exception A DML specific exception is thrown for any errors.
1443 public abstract function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false);
1446 * Insert a record into a table and return the "id" field if required.
1448 * Some conversions and safety checks are carried out. Lobs are supported.
1449 * If the return ID isn't required, then this just reports success as true/false.
1450 * $data is an object containing needed data
1451 * @param string $table The database table to be inserted into
1452 * @param object $data A data object with values for one or more fields in the record
1453 * @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.
1454 * @return bool|int true or new id
1455 * @throws dml_exception A DML specific exception is thrown for any errors.
1457 public abstract function insert_record($table, $dataobject, $returnid=true, $bulk=false);
1460 * Import a record into a table, id field is required.
1461 * Safety checks are NOT carried out. Lobs are supported.
1463 * @param string $table name of database table to be inserted into
1464 * @param object $dataobject A data object with values for one or more fields in the record
1466 * @throws dml_exception A DML specific exception is thrown for any errors.
1468 public abstract function import_record($table, $dataobject);
1471 * Update record in database, as fast as possible, no safety checks, lobs not supported.
1472 * @param string $table name
1473 * @param mixed $params data record as object or array
1474 * @param bool $bulk True means repeated updates expected.
1476 * @throws dml_exception A DML specific exception is thrown for any errors.
1478 public abstract function update_record_raw($table, $params, $bulk=false);
1481 * Update a record in a table
1483 * $dataobject is an object containing needed data
1484 * Relies on $dataobject having a variable "id" to
1485 * specify the record to update
1487 * @param string $table The database table to be checked against.
1488 * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
1489 * @param bool $bulk True means repeated updates expected.
1491 * @throws dml_exception A DML specific exception is thrown for any errors.
1493 public abstract function update_record($table, $dataobject, $bulk=false);
1497 * Set a single field in every table record where all the given conditions met.
1499 * @param string $table The database table to be checked against.
1500 * @param string $newfield the field to set.
1501 * @param string $newvalue the value to set the field to.
1502 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1504 * @throws dml_exception A DML specific exception is thrown for any errors.
1506 public function set_field($table, $newfield, $newvalue, array $conditions=null) {
1507 list($select, $params) = $this->where_clause($table, $conditions);
1508 return $this->set_field_select($table, $newfield, $newvalue, $select, $params);
1512 * Set a single field in every table record which match a particular WHERE clause.
1514 * @param string $table The database table to be checked against.
1515 * @param string $newfield the field to set.
1516 * @param string $newvalue the value to set the field to.
1517 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1518 * @param array $params array of sql parameters
1520 * @throws dml_exception A DML specific exception is thrown for any errors.
1522 public abstract function set_field_select($table, $newfield, $newvalue, $select, array $params=null);
1526 * Count the records in a table where all the given conditions met.
1528 * @param string $table The table to query.
1529 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1530 * @return int The count of records returned from the specified criteria.
1531 * @throws dml_exception A DML specific exception is thrown for any errors.
1533 public function count_records($table, array $conditions=null) {
1534 list($select, $params) = $this->where_clause($table, $conditions);
1535 return $this->count_records_select($table, $select, $params);
1539 * Count the records in a table which match a particular WHERE clause.
1541 * @param string $table The database table to be checked against.
1542 * @param string $select A fragment of SQL to be used in a WHERE clause in the SQL call.
1543 * @param array $params array of sql parameters
1544 * @param string $countitem The count string to be used in the SQL call. Default is COUNT('x').
1545 * @return int The count of records returned from the specified criteria.
1546 * @throws dml_exception A DML specific exception is thrown for any errors.
1548 public function count_records_select($table, $select, array $params=null, $countitem="COUNT('x')") {
1550 $select = "WHERE $select";
1552 return $this->count_records_sql("SELECT $countitem FROM {" . $table . "} $select", $params);
1556 * Get the result of a SQL SELECT COUNT(...) query.
1558 * Given a query that counts rows, return that count. (In fact,
1559 * given any query, return the first field of the first record
1560 * returned. However, this method should only be used for the
1561 * intended purpose.) If an error occurs, 0 is returned.
1563 * @param string $sql The SQL string you wish to be executed.
1564 * @param array $params array of sql parameters
1565 * @return int the count
1566 * @throws dml_exception A DML specific exception is thrown for any errors.
1568 public function count_records_sql($sql, array $params=null) {
1569 if ($count = $this->get_field_sql($sql, $params)) {
1577 * Test whether a record exists in a table where all the given conditions met.
1579 * The record to test is specified by giving up to three fields that must
1580 * equal the corresponding values.
1582 * @param string $table The table to check.
1583 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1584 * @return bool true if a matching record exists, else false.
1585 * @throws dml_exception A DML specific exception is thrown for any errors.
1587 public function record_exists($table, array $conditions) {
1588 list($select, $params) = $this->where_clause($table, $conditions);
1589 return $this->record_exists_select($table, $select, $params);
1593 * Test whether any records exists in a table which match a particular WHERE clause.
1595 * @param string $table The database table to be checked against.
1596 * @param string $select A fragment of SQL to be used in a WHERE clause in the SQL call.
1597 * @param array $params array of sql parameters
1598 * @return bool true if a matching record exists, else false.
1599 * @throws dml_exception A DML specific exception is thrown for any errors.
1601 public function record_exists_select($table, $select, array $params=null) {
1603 $select = "WHERE $select";
1605 return $this->record_exists_sql("SELECT 'x' FROM {" . $table . "} $select", $params);
1609 * Test whether a SQL SELECT statement returns any records.
1611 * This function returns true if the SQL statement executes
1612 * without any errors and returns at least one record.
1614 * @param string $sql The SQL statement to execute.
1615 * @param array $params array of sql parameters
1616 * @return bool true if the SQL executes without errors and returns at least one record.
1617 * @throws dml_exception A DML specific exception is thrown for any errors.
1619 public function record_exists_sql($sql, array $params=null) {
1620 $mrs = $this->get_recordset_sql($sql, $params, 0, 1);
1621 $return = $mrs->valid();
1627 * Delete the records from a table where all the given conditions met.
1628 * If conditions not specified, table is truncated.
1630 * @param string $table the table to delete from.
1631 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1632 * @return bool true.
1633 * @throws dml_exception A DML specific exception is thrown for any errors.
1635 public function delete_records($table, array $conditions=null) {
1636 // truncate is drop/create (DDL), not transactional safe,
1637 // so we don't use the shortcut within them. MDL-29198
1638 if (is_null($conditions) && empty($this->transactions)) {
1639 return $this->execute("TRUNCATE TABLE {".$table."}");
1641 list($select, $params) = $this->where_clause($table, $conditions);
1642 return $this->delete_records_select($table, $select, $params);
1646 * Delete the records from a table where one field match one list of values.
1648 * @param string $table the table to delete from.
1649 * @param string $field The field to search
1650 * @param array $values array of values
1651 * @return bool true.
1652 * @throws dml_exception A DML specific exception is thrown for any errors.
1654 public function delete_records_list($table, $field, array $values) {
1655 list($select, $params) = $this->where_clause_list($field, $values);
1656 if (empty($select)) {
1657 // nothing to delete
1660 return $this->delete_records_select($table, $select, $params);
1664 * Delete one or more records from a table which match a particular WHERE clause.
1666 * @param string $table The database table to be checked against.
1667 * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
1668 * @param array $params array of sql parameters
1669 * @return bool true.
1670 * @throws dml_exception A DML specific exception is thrown for any errors.
1672 public abstract function delete_records_select($table, $select, array $params=null);
1678 * Returns the FROM clause required by some DBs in all SELECT statements.
1680 * To be used in queries not having FROM clause to provide cross_db
1681 * Most DBs don't need it, hence the default is ''
1684 public function sql_null_from_clause() {
1689 * Returns the SQL text to be used in order to perform one bitwise AND operation
1690 * between 2 integers.
1692 * NOTE: The SQL result is a number and can not be used directly in
1693 * SQL condition, please compare it to some number to get a bool!!
1695 * @param int $int1 First integer in the operation.
1696 * @param int $int2 Second integer in the operation.
1697 * @return string The piece of SQL code to be used in your statement.
1699 public function sql_bitand($int1, $int2) {
1700 return '((' . $int1 . ') & (' . $int2 . '))';
1704 * Returns the SQL text to be used in order to perform one bitwise NOT operation
1707 * @param int $int1 The operand integer in the operation.
1708 * @return string The piece of SQL code to be used in your statement.
1710 public function sql_bitnot($int1) {
1711 return '(~(' . $int1 . '))';
1715 * Returns the SQL text to be used in order to perform one bitwise OR operation
1716 * between 2 integers.
1718 * NOTE: The SQL result is a number and can not be used directly in
1719 * SQL condition, please compare it to some number to get a bool!!
1721 * @param int $int1 The first operand integer in the operation.
1722 * @param int $int2 The second operand integer in the operation.
1723 * @return string The piece of SQL code to be used in your statement.
1725 public function sql_bitor($int1, $int2) {
1726 return '((' . $int1 . ') | (' . $int2 . '))';
1730 * Returns the SQL text to be used in order to perform one bitwise XOR operation
1731 * between 2 integers.
1733 * NOTE: The SQL result is a number and can not be used directly in
1734 * SQL condition, please compare it to some number to get a bool!!
1736 * @param int $int1 The first operand integer in the operation.
1737 * @param int $int2 The second operand integer in the operation.
1738 * @return string The piece of SQL code to be used in your statement.
1740 public function sql_bitxor($int1, $int2) {
1741 return '((' . $int1 . ') ^ (' . $int2 . '))';
1745 * Returns the SQL text to be used in order to perform module '%'
1746 * operation - remainder after division
1748 * @param int $int1 The first operand integer in the operation.
1749 * @param int $int2 The second operand integer in the operation.
1750 * @return string The piece of SQL code to be used in your statement.
1752 public function sql_modulo($int1, $int2) {
1753 return '((' . $int1 . ') % (' . $int2 . '))';
1757 * Returns the cross db correct CEIL (ceiling) expression applied to fieldname.
1758 * note: Most DBs use CEIL(), hence it's the default here.
1760 * @param string $fieldname The field (or expression) we are going to ceil.
1761 * @return string The piece of SQL code to be used in your ceiling statement.
1763 public function sql_ceil($fieldname) {
1764 return ' CEIL(' . $fieldname . ')';
1768 * Returns the SQL to be used in order to CAST one CHAR column to INTEGER.
1770 * Be aware that the CHAR column you're trying to cast contains really
1771 * int values or the RDBMS will throw an error!
1773 * @param string $fieldname The name of the field to be casted.
1774 * @param bool $text Specifies if the original column is one TEXT (CLOB) column (true). Defaults to false.
1775 * @return string The piece of SQL code to be used in your statement.
1777 public function sql_cast_char2int($fieldname, $text=false) {
1778 return ' ' . $fieldname . ' ';
1782 * Returns the SQL to be used in order to CAST one CHAR column to REAL number.
1784 * Be aware that the CHAR column you're trying to cast contains really
1785 * numbers or the RDBMS will throw an error!
1787 * @param string $fieldname The name of the field to be casted.
1788 * @param bool $text Specifies if the original column is one TEXT (CLOB) column (true). Defaults to false.
1789 * @return string The piece of SQL code to be used in your statement.
1791 public function sql_cast_char2real($fieldname, $text=false) {
1792 return ' ' . $fieldname . ' ';
1796 * Returns the SQL to be used in order to an UNSIGNED INTEGER column to SIGNED.
1798 * (Only MySQL needs this. MySQL things that 1 * -1 = 18446744073709551615
1799 * if the 1 comes from an unsigned column).
1801 * @deprecated since 2.3
1802 * @param string $fieldname The name of the field to be cast
1803 * @return string The piece of SQL code to be used in your statement.
1805 public function sql_cast_2signed($fieldname) {
1806 return ' ' . $fieldname . ' ';
1810 * Returns the SQL text to be used to compare one TEXT (clob) column with
1811 * one varchar column, because some RDBMS doesn't support such direct
1814 * @param string $fieldname The name of the TEXT field we need to order by
1815 * @param int $numchars Number of chars to use for the ordering (defaults to 32).
1816 * @return string The piece of SQL code to be used in your statement.
1818 public function sql_compare_text($fieldname, $numchars=32) {
1819 return $this->sql_order_by_text($fieldname, $numchars);
1823 * Returns 'LIKE' part of a query.
1825 * @param string $fieldname Usually the name of the table column.
1826 * @param string $param Usually the bound query parameter (?, :named).
1827 * @param bool $casesensitive Use case sensitive search when set to true (default).
1828 * @param bool $accentsensitive Use accent sensitive search when set to true (default). (not all databases support accent insensitive)
1829 * @param bool $notlike True means "NOT LIKE".
1830 * @param string $escapechar The escape char for '%' and '_'.
1831 * @return string The SQL code fragment.
1833 public function sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = '\\') {
1834 if (strpos($param, '%') !== false) {
1835 debugging('Potential SQL injection detected, sql_like() expects bound parameters (? or :named)');
1837 $LIKE = $notlike ? 'NOT LIKE' : 'LIKE';
1838 // by default ignore any sensitiveness - each database does it in a different way
1839 return "$fieldname $LIKE $param ESCAPE '$escapechar'";
1843 * Escape sql LIKE special characters like '_' or '%'.
1844 * @param string $text The string containing characters needing escaping.
1845 * @param string $escapechar The desired escape character, defaults to '\\'.
1846 * @return string The escaped sql LIKE string.
1848 public function sql_like_escape($text, $escapechar = '\\') {
1849 $text = str_replace('_', $escapechar.'_', $text);
1850 $text = str_replace('%', $escapechar.'%', $text);
1855 * Returns the proper SQL to do LIKE in a case-insensitive way.
1857 * Note the LIKE are case sensitive for Oracle. Oracle 10g is required to use
1858 * the case insensitive search using regexp_like() or NLS_COMP=LINGUISTIC :-(
1859 * See http://docs.moodle.org/en/XMLDB_Problems#Case-insensitive_searches
1861 * @deprecated since Moodle 2.0 MDL-23925 - please do not use this function any more.
1862 * @todo MDL-31280 to remove deprecated functions prior to 2.3 release.
1863 * @return string Do not use this function!
1866 public function sql_ilike() {
1867 debugging('sql_ilike() is deprecated, please use sql_like() instead');
1872 * Returns the proper SQL to do CONCAT between the elements(fieldnames) passed.
1874 * This function accepts variable number of string parameters.
1875 * All strings/fieldnames will used in the SQL concatenate statement generated.
1877 * @return string The SQL to concatenate strings passed in.
1878 * @uses func_get_args() and thus parameters are unlimited OPTIONAL number of additional field names.
1880 public abstract function sql_concat();
1883 * Returns the proper SQL to do CONCAT between the elements passed
1884 * with a given separator
1886 * @param string $separator The separator desired for the SQL concatenating $elements.
1887 * @param array $elements The array of strings to be concatenated.
1888 * @return string The SQL to concatenate the strings.
1890 public abstract function sql_concat_join($separator="' '", $elements=array());
1893 * Returns the proper SQL (for the dbms in use) to concatenate $firstname and $lastname
1895 * @todo MDL-31233 This may not be needed here.
1897 * @param string $first User's first name (default:'firstname').
1898 * @param string $last User's last name (default:'lastname').
1899 * @return string The SQL to concatenate strings.
1901 function sql_fullname($first='firstname', $last='lastname') {
1902 return $this->sql_concat($first, "' '", $last);
1906 * Returns the SQL text to be used to order by one TEXT (clob) column, because
1907 * some RDBMS doesn't support direct ordering of such fields.
1909 * Note that the use or queries being ordered by TEXT columns must be minimised,
1910 * because it's really slooooooow.
1912 * @param string $fieldname The name of the TEXT field we need to order by.
1913 * @param string $numchars The number of chars to use for the ordering (defaults to 32).
1914 * @return string The piece of SQL code to be used in your statement.
1916 public function sql_order_by_text($fieldname, $numchars=32) {
1921 * Returns the SQL text to be used to calculate the length in characters of one expression.
1922 * @param string $fieldname The fieldname/expression to calculate its length in characters.
1923 * @return string the piece of SQL code to be used in the statement.
1925 public function sql_length($fieldname) {
1926 return ' LENGTH(' . $fieldname . ')';
1930 * Returns the proper substr() SQL text used to extract substrings from DB
1931 * NOTE: this was originally returning only function name
1933 * @param string $expr Some string field, no aggregates.
1934 * @param mixed $start Integer or expression evaluating to integer (1 based value; first char has index 1)
1935 * @param mixed $length Optional integer or expression evaluating to integer.
1936 * @return string The sql substring extraction fragment.
1938 public function sql_substr($expr, $start, $length=false) {
1939 if (count(func_get_args()) < 2) {
1940 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.');
1942 if ($length === false) {
1943 return "SUBSTR($expr, $start)";
1945 return "SUBSTR($expr, $start, $length)";
1950 * Returns the SQL for returning searching one string for the location of another.
1952 * Note, there is no guarantee which order $needle, $haystack will be in
1953 * the resulting SQL so when using this method, and both arguments contain
1954 * placeholders, you should use named placeholders.
1956 * @param string $needle the SQL expression that will be searched for.
1957 * @param string $haystack the SQL expression that will be searched in.
1958 * @return string The required searching SQL part.
1960 public function sql_position($needle, $haystack) {
1961 // Implementation using standard SQL.
1962 return "POSITION(($needle) IN ($haystack))";
1966 * Returns the empty string char used by every supported DB. To be used when
1967 * we are searching for that values in our queries. Only Oracle uses this
1968 * for now (will be out, once we migrate to proper NULLs if that days arrives)
1969 * @return string An empty string.
1971 function sql_empty() {
1976 * Returns the proper SQL to know if one field is empty.
1978 * Note that the function behavior strongly relies on the
1979 * parameters passed describing the field so, please, be accurate
1980 * when specifying them.
1982 * Also, note that this function is not suitable to look for
1983 * fields having NULL contents at all. It's all for empty values!
1985 * This function should be applied in all the places where conditions of
1988 * ... AND fieldname = '';
1990 * are being used. Final result should be:
1992 * ... AND ' . sql_isempty('tablename', 'fieldname', true/false, true/false);
1994 * (see parameters description below)
1996 * @param string $tablename Name of the table (without prefix). Not used for now but can be
1997 * necessary in the future if we want to use some introspection using
1998 * meta information against the DB. /// TODO ///
1999 * @param string $fieldname Name of the field we are going to check
2000 * @param bool $nullablefield For specifying if the field is nullable (true) or no (false) in the DB.
2001 * @param bool $textfield For specifying if it is a text (also called clob) field (true) or a varchar one (false)
2002 * @return string the sql code to be added to check for empty values
2004 public function sql_isempty($tablename, $fieldname, $nullablefield, $textfield) {
2005 return " ($fieldname = '') ";
2009 * Returns the proper SQL to know if one field is not empty.
2011 * Note that the function behavior strongly relies on the
2012 * parameters passed describing the field so, please, be accurate
2013 * when specifying them.
2015 * This function should be applied in all the places where conditions of
2018 * ... AND fieldname != '';
2020 * are being used. Final result should be:
2022 * ... AND ' . sql_isnotempty('tablename', 'fieldname', true/false, true/false);
2024 * (see parameters description below)
2026 * @param string $tablename Name of the table (without prefix). This is not used for now but can be
2027 * necessary in the future if we want to use some introspection using
2028 * meta information against the DB.
2029 * @param string $fieldname The name of the field we are going to check.
2030 * @param bool $nullablefield Specifies if the field is nullable (true) or not (false) in the DB.
2031 * @param bool $textfield Specifies if it is a text (also called clob) field (true) or a varchar one (false).
2032 * @return string The sql code to be added to check for non empty values.
2034 public function sql_isnotempty($tablename, $fieldname, $nullablefield, $textfield) {
2035 return ' ( NOT ' . $this->sql_isempty($tablename, $fieldname, $nullablefield, $textfield) . ') ';
2039 * Returns true if this database driver supports regex syntax when searching.
2040 * @return bool True if supported.
2042 public function sql_regex_supported() {
2047 * Returns the driver specific syntax (SQL part) for matching regex positively or negatively (inverted matching).
2048 * Eg: 'REGEXP':'NOT REGEXP' or '~*' : '!~*'
2049 * @param bool $positivematch
2050 * @return string or empty if not supported
2052 public function sql_regex($positivematch=true) {
2059 * Checks and returns true if transactions are supported.
2061 * It is not responsible to run productions servers
2062 * on databases without transaction support ;-)
2064 * Override in driver if needed.
2068 protected function transactions_supported() {
2069 // protected for now, this might be changed to public if really necessary
2074 * Returns true if a transaction is in progress.
2077 public function is_transaction_started() {
2078 return !empty($this->transactions);
2082 * This is a test that throws an exception if transaction in progress.
2083 * This test does not force rollback of active transactions.
2086 public function transactions_forbidden() {
2087 if ($this->is_transaction_started()) {
2088 throw new dml_transaction_exception('This code can not be excecuted in transaction');
2093 * On DBs that support it, switch to transaction mode and begin a transaction
2094 * you'll need to ensure you call allow_commit() on the returned object
2095 * or your changes *will* be lost.
2097 * this is _very_ useful for massive updates
2099 * Delegated database transactions can be nested, but only one actual database
2100 * transaction is used for the outer-most delegated transaction. This method
2101 * returns a transaction object which you should keep until the end of the
2102 * delegated transaction. The actual database transaction will
2103 * only be committed if all the nested delegated transactions commit
2104 * successfully. If any part of the transaction rolls back then the whole
2105 * thing is rolled back.
2107 * @return moodle_transaction
2109 public function start_delegated_transaction() {
2110 $transaction = new moodle_transaction($this);
2111 $this->transactions[] = $transaction;
2112 if (count($this->transactions) == 1) {
2113 $this->begin_transaction();
2115 return $transaction;
2119 * Driver specific start of real database transaction,
2120 * this can not be used directly in code.
2123 protected abstract function begin_transaction();
2126 * Indicates delegated transaction finished successfully.
2127 * The real database transaction is committed only if
2128 * all delegated transactions committed.
2130 * @throws dml_transaction_exception Creates and throws transaction related exceptions.
2132 public function commit_delegated_transaction(moodle_transaction $transaction) {
2133 if ($transaction->is_disposed()) {
2134 throw new dml_transaction_exception('Transactions already disposed', $transaction);
2136 // mark as disposed so that it can not be used again
2137 $transaction->dispose();
2139 if (empty($this->transactions)) {
2140 throw new dml_transaction_exception('Transaction not started', $transaction);
2143 if ($this->force_rollback) {
2144 throw new dml_transaction_exception('Tried to commit transaction after lower level rollback', $transaction);
2147 if ($transaction !== $this->transactions[count($this->transactions) - 1]) {
2148 // one incorrect commit at any level rollbacks everything
2149 $this->force_rollback = true;
2150 throw new dml_transaction_exception('Invalid transaction commit attempt', $transaction);
2153 if (count($this->transactions) == 1) {
2154 // only commit the top most level
2155 $this->commit_transaction();
2157 array_pop($this->transactions);
2161 * Driver specific commit of real database transaction,
2162 * this can not be used directly in code.
2165 protected abstract function commit_transaction();
2168 * Call when delegated transaction failed, this rolls back
2169 * all delegated transactions up to the top most level.
2171 * In many cases you do not need to call this method manually,
2172 * because all open delegated transactions are rolled back
2173 * automatically if exceptions not caught.
2175 * @param moodle_transaction $transaction An instance of a moodle_transaction.
2176 * @param Exception $e The related exception to this transaction rollback.
2177 * @return void This does not return, instead the exception passed in will be rethrown.
2179 public function rollback_delegated_transaction(moodle_transaction $transaction, Exception $e) {
2180 if ($transaction->is_disposed()) {
2181 throw new dml_transaction_exception('Transactions already disposed', $transaction);
2183 // mark as disposed so that it can not be used again
2184 $transaction->dispose();
2186 // one rollback at any level rollbacks everything
2187 $this->force_rollback = true;
2189 if (empty($this->transactions) or $transaction !== $this->transactions[count($this->transactions) - 1]) {
2190 // this may or may not be a coding problem, better just rethrow the exception,
2191 // because we do not want to loose the original $e
2195 if (count($this->transactions) == 1) {
2196 // only rollback the top most level
2197 $this->rollback_transaction();
2199 array_pop($this->transactions);
2200 if (empty($this->transactions)) {
2201 // finally top most level rolled back
2202 $this->force_rollback = false;
2208 * Driver specific abort of real database transaction,
2209 * this can not be used directly in code.
2212 protected abstract function rollback_transaction();
2215 * Force rollback of all delegated transaction.
2216 * Does not throw any exceptions and does not log anything.
2218 * This method should be used only from default exception handlers and other
2223 public function force_transaction_rollback() {
2224 if ($this->transactions) {
2226 $this->rollback_transaction();
2227 } catch (dml_exception $e) {
2228 // ignore any sql errors here, the connection might be broken
2232 // now enable transactions again
2233 $this->transactions = array(); // unfortunately all unfinished exceptions are kept in memory
2234 $this->force_rollback = false;
2239 * Is session lock supported in this driver?
2242 public function session_lock_supported() {
2247 * Obtains the session lock.
2248 * @param int $rowid The id of the row with session record.
2249 * @param int $timeout The maximum allowed time to wait for the lock in seconds.
2251 * @throws dml_exception A DML specific exception is thrown for any errors.
2253 public function get_session_lock($rowid, $timeout) {
2254 $this->used_for_db_sessions = true;
2258 * Releases the session lock.
2259 * @param int $rowid The id of the row with session record.
2261 * @throws dml_exception A DML specific exception is thrown for any errors.
2263 public function release_session_lock($rowid) {
2266 /// performance and logging
2268 * Returns the number of reads done by this database.
2269 * @return int Number of reads.
2271 public function perf_get_reads() {
2272 return $this->reads;
2276 * Returns the number of writes done by this database.
2277 * @return int Number of writes.
2279 public function perf_get_writes() {
2280 return $this->writes;
2284 * Returns the number of queries done by this database.
2285 * @return int Number of queries.
2287 public function perf_get_queries() {
2288 return $this->writes + $this->reads;