Merge branch 'MDL-75105_401_STABLE' of https://github.com/marxjohnson/moodle into...
[moodle.git] / lib / dml / moodle_database.php
blob89c145523251950c4b1d40e8f286780a8ae66a9a
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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/>.
17 /**
18 * Abstract database driver class.
20 * @package core_dml
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);
55 /** SQL_QUERY_AUX_READONLY - Auxiliary query that can be done using the readonly connection:
56 * database parameters, table/index/column lists, if not within transaction/ddl. */
57 define('SQL_QUERY_AUX_READONLY', 6);
59 /**
60 * Abstract class representing moodle database interface.
61 * @link http://docs.moodle.org/dev/DML_functions
63 * @package core_dml
64 * @copyright 2008 Petr Skoda (http://skodak.org)
65 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
67 abstract class moodle_database {
69 /** @var database_manager db manager which allows db structure modifications. */
70 protected $database_manager;
71 /** @var moodle_temptables temptables manager to provide cross-db support for temp tables. */
72 protected $temptables;
73 /** @var array Cache of table info. */
74 protected $tables = null;
76 // db connection options
77 /** @var string db host name. */
78 protected $dbhost;
79 /** @var string db host user. */
80 protected $dbuser;
81 /** @var string db host password. */
82 protected $dbpass;
83 /** @var string db name. */
84 protected $dbname;
85 /** @var string Prefix added to table names. */
86 protected $prefix;
88 /** @var array Database or driver specific options, such as sockets or TCP/IP db connections. */
89 protected $dboptions;
91 /** @var bool True means non-moodle external database used.*/
92 protected $external;
94 /** @var int The database reads (performance counter).*/
95 protected $reads = 0;
96 /** @var int The database writes (performance counter).*/
97 protected $writes = 0;
98 /** @var float Time queries took to finish, seconds with microseconds.*/
99 protected $queriestime = 0;
101 /** @var int Debug level. */
102 protected $debug = 0;
104 /** @var string Last used query sql. */
105 protected $last_sql;
106 /** @var array Last query parameters. */
107 protected $last_params;
108 /** @var int Last query type. */
109 protected $last_type;
110 /** @var string Last extra info. */
111 protected $last_extrainfo;
112 /** @var float Last time in seconds with millisecond precision. */
113 protected $last_time;
114 /** @var bool Flag indicating logging of query in progress. This helps prevent infinite loops. */
115 protected $loggingquery = false;
117 /** @var bool True if the db is used for db sessions. */
118 protected $used_for_db_sessions = false;
120 /** @var array Array containing open transactions. */
121 protected $transactions = array();
122 /** @var bool Flag used to force rollback of all current transactions. */
123 private $force_rollback = false;
125 /** @var string MD5 of settings used for connection. Used by MUC as an identifier. */
126 private $settingshash;
128 /** @var cache_application for column info */
129 protected $metacache;
131 /** @var cache_request for column info on temp tables */
132 protected $metacachetemp;
134 /** @var bool flag marking database instance as disposed */
135 protected $disposed;
138 * @var int internal temporary variable used to fix params. Its used by {@link _fix_sql_params_dollar_callback()}.
140 private $fix_sql_params_i;
142 * @var int internal temporary variable used to guarantee unique parameters in each request. Its used by {@link get_in_or_equal()}.
144 protected $inorequaluniqueindex = 1;
147 * @var boolean variable use to temporarily disable logging.
149 protected $skiplogging = false;
152 * Constructor - Instantiates the database, specifying if it's external (connect to other systems) or not (Moodle DB).
153 * Note that this affects the decision of whether prefix checks must be performed or not.
154 * @param bool $external True means that an external database is used.
156 public function __construct($external=false) {
157 $this->external = $external;
161 * Destructor - cleans up and flushes everything needed.
163 public function __destruct() {
164 $this->dispose();
168 * Detects if all needed PHP stuff are installed for DB connectivity.
169 * Note: can be used before connect()
170 * @return mixed True if requirements are met, otherwise a string if something isn't installed.
172 public abstract function driver_installed();
175 * Returns database table prefix
176 * Note: can be used before connect()
177 * @return string The prefix used in the database.
179 public function get_prefix() {
180 return $this->prefix;
184 * Loads and returns a database instance with the specified type and library.
186 * The loaded class is within lib/dml directory and of the form: $type.'_'.$library.'_moodle_database'
188 * @param string $type Database driver's type. (eg: mysqli, pgsql, mssql, sqldrv, oci, etc.)
189 * @param string $library Database driver's library (native, pdo, etc.)
190 * @param bool $external True if this is an external database.
191 * @return moodle_database driver object or null if error, for example of driver object see {@link mysqli_native_moodle_database}
193 public static function get_driver_instance($type, $library, $external = false) {
194 global $CFG;
196 $classname = $type.'_'.$library.'_moodle_database';
197 $libfile = "$CFG->libdir/dml/$classname.php";
199 if (!file_exists($libfile)) {
200 return null;
203 require_once($libfile);
204 return new $classname($external);
208 * Returns the database vendor.
209 * Note: can be used before connect()
210 * @return string The db vendor name, usually the same as db family name.
212 public function get_dbvendor() {
213 return $this->get_dbfamily();
217 * Returns the database family type. (This sort of describes the SQL 'dialect')
218 * Note: can be used before connect()
219 * @return string The db family name (mysql, postgres, mssql, oracle, etc.)
221 public abstract function get_dbfamily();
224 * Returns a more specific database driver type
225 * Note: can be used before connect()
226 * @return string The db type mysqli, pgsql, oci, mssql, sqlsrv
228 protected abstract function get_dbtype();
231 * Returns the general database library name
232 * Note: can be used before connect()
233 * @return string The db library type - pdo, native etc.
235 protected abstract function get_dblibrary();
238 * Returns the localised database type name
239 * Note: can be used before connect()
240 * @return string
242 public abstract function get_name();
245 * Returns the localised database configuration help.
246 * Note: can be used before connect()
247 * @return string
249 public abstract function get_configuration_help();
252 * Returns the localised database description
253 * Note: can be used before connect()
254 * @deprecated since 2.6
255 * @return string
257 public function get_configuration_hints() {
258 debugging('$DB->get_configuration_hints() method is deprecated, use $DB->get_configuration_help() instead');
259 return $this->get_configuration_help();
263 * Returns the db related part of config.php
264 * @return stdClass
266 public function export_dbconfig() {
267 $cfg = new stdClass();
268 $cfg->dbtype = $this->get_dbtype();
269 $cfg->dblibrary = $this->get_dblibrary();
270 $cfg->dbhost = $this->dbhost;
271 $cfg->dbname = $this->dbname;
272 $cfg->dbuser = $this->dbuser;
273 $cfg->dbpass = $this->dbpass;
274 $cfg->prefix = $this->prefix;
275 if ($this->dboptions) {
276 $cfg->dboptions = $this->dboptions;
279 return $cfg;
283 * Diagnose database and tables, this function is used
284 * to verify database and driver settings, db engine types, etc.
286 * @return string null means everything ok, string means problem found.
288 public function diagnose() {
289 return null;
293 * Connects to the database.
294 * Must be called before other methods.
295 * @param string $dbhost The database host.
296 * @param string $dbuser The database user to connect as.
297 * @param string $dbpass The password to use when connecting to the database.
298 * @param string $dbname The name of the database being connected to.
299 * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
300 * @param array $dboptions driver specific options
301 * @return bool true
302 * @throws dml_connection_exception if error
304 public abstract function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null);
307 * Store various database settings
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 mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
313 * @param array $dboptions driver specific options
314 * @return void
316 protected function store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null) {
317 $this->dbhost = $dbhost;
318 $this->dbuser = $dbuser;
319 $this->dbpass = $dbpass;
320 $this->dbname = $dbname;
321 $this->prefix = $prefix;
322 $this->dboptions = (array)$dboptions;
326 * Returns a hash for the settings used during connection.
328 * If not already requested it is generated and stored in a private property.
330 * @return string
332 protected function get_settings_hash() {
333 if (empty($this->settingshash)) {
334 $this->settingshash = md5($this->dbhost . $this->dbuser . $this->dbname . $this->prefix);
336 return $this->settingshash;
340 * Handle the creation and caching of the databasemeta information for all databases.
342 * @return cache_application The databasemeta cachestore to complete operations on.
344 protected function get_metacache() {
345 if (!isset($this->metacache)) {
346 $properties = array('dbfamily' => $this->get_dbfamily(), 'settings' => $this->get_settings_hash());
347 $this->metacache = cache::make('core', 'databasemeta', $properties);
349 return $this->metacache;
353 * Handle the creation and caching of the temporary tables.
355 * @return cache_application The temp_tables cachestore to complete operations on.
357 protected function get_temp_tables_cache() {
358 if (!isset($this->metacachetemp)) {
359 // Using connection data to prevent collisions when using the same temp table name with different db connections.
360 $properties = array('dbfamily' => $this->get_dbfamily(), 'settings' => $this->get_settings_hash());
361 $this->metacachetemp = cache::make('core', 'temp_tables', $properties);
363 return $this->metacachetemp;
367 * Attempt to create the database
368 * @param string $dbhost The database host.
369 * @param string $dbuser The database user to connect as.
370 * @param string $dbpass The password to use when connecting to the database.
371 * @param string $dbname The name of the database being connected to.
372 * @param array $dboptions An array of optional database options (eg: dbport)
374 * @return bool success True for successful connection. False otherwise.
376 public function create_database($dbhost, $dbuser, $dbpass, $dbname, array $dboptions=null) {
377 return false;
381 * Returns transaction trace for debugging purposes.
382 * @private to be used by core only
383 * @return array or null if not in transaction.
385 public function get_transaction_start_backtrace() {
386 if (!$this->transactions) {
387 return null;
389 $lowesttransaction = end($this->transactions);
390 return $lowesttransaction->get_backtrace();
394 * Closes the database connection and releases all resources
395 * and memory (especially circular memory references).
396 * Do NOT use connect() again, create a new instance if needed.
397 * @return void
399 public function dispose() {
400 if ($this->disposed) {
401 return;
403 $this->disposed = true;
404 if ($this->transactions) {
405 $this->force_transaction_rollback();
408 if ($this->temptables) {
409 $this->temptables->dispose();
410 $this->temptables = null;
412 if ($this->database_manager) {
413 $this->database_manager->dispose();
414 $this->database_manager = null;
416 $this->tables = null;
420 * This should be called before each db query.
422 * @param string $sql The query string.
423 * @param array|null $params An array of parameters.
424 * @param int $type The type of query ( SQL_QUERY_SELECT | SQL_QUERY_AUX_READONLY | SQL_QUERY_AUX |
425 * SQL_QUERY_INSERT | SQL_QUERY_UPDATE | SQL_QUERY_STRUCTURE ).
426 * @param mixed $extrainfo This is here for any driver specific extra information.
427 * @return void
429 protected function query_start($sql, ?array $params, $type, $extrainfo=null) {
430 if ($this->loggingquery) {
431 return;
433 $this->last_sql = $sql;
434 $this->last_params = $params;
435 $this->last_type = $type;
436 $this->last_extrainfo = $extrainfo;
437 $this->last_time = microtime(true);
439 switch ($type) {
440 case SQL_QUERY_SELECT:
441 case SQL_QUERY_AUX:
442 case SQL_QUERY_AUX_READONLY:
443 $this->reads++;
444 break;
445 case SQL_QUERY_INSERT:
446 case SQL_QUERY_UPDATE:
447 case SQL_QUERY_STRUCTURE:
448 $this->writes++;
449 default:
450 if ((PHPUNIT_TEST) || (defined('BEHAT_TEST') && BEHAT_TEST) ||
451 defined('BEHAT_SITE_RUNNING')) {
453 // Set list of tables that are updated.
454 require_once(__DIR__.'/../testing/classes/util.php');
455 testing_util::set_table_modified_by_sql($sql);
459 $this->print_debug($sql, $params);
463 * This should be called immediately after each db query. It does a clean up of resources.
464 * It also throws exceptions if the sql that ran produced errors.
465 * @param mixed $result The db specific result obtained from running a query.
466 * @throws dml_read_exception | dml_write_exception | ddl_change_structure_exception
467 * @return void
469 protected function query_end($result) {
470 if ($this->loggingquery) {
471 return;
473 if ($result !== false) {
474 $this->query_log();
475 // free memory
476 $this->last_sql = null;
477 $this->last_params = null;
478 $this->print_debug_time();
479 return;
482 // remember current info, log queries may alter it
483 $type = $this->last_type;
484 $sql = $this->last_sql;
485 $params = $this->last_params;
486 $error = $this->get_last_error();
488 $this->query_log($error);
490 switch ($type) {
491 case SQL_QUERY_SELECT:
492 case SQL_QUERY_AUX:
493 case SQL_QUERY_AUX_READONLY:
494 throw new dml_read_exception($error, $sql, $params);
495 case SQL_QUERY_INSERT:
496 case SQL_QUERY_UPDATE:
497 throw new dml_write_exception($error, $sql, $params);
498 case SQL_QUERY_STRUCTURE:
499 $this->get_manager(); // includes ddl exceptions classes ;-)
500 throw new ddl_change_structure_exception($error, $sql);
505 * This logs the last query based on 'logall', 'logslow' and 'logerrors' options configured via $CFG->dboptions .
506 * @param string|bool $error or false if not error
507 * @return void
509 public function query_log($error=false) {
510 // Logging disabled by the driver.
511 if ($this->skiplogging) {
512 return;
515 $logall = !empty($this->dboptions['logall']);
516 $logslow = !empty($this->dboptions['logslow']) ? $this->dboptions['logslow'] : false;
517 $logerrors = !empty($this->dboptions['logerrors']);
518 $iserror = ($error !== false);
520 $time = $this->query_time();
522 // Will be shown or not depending on MDL_PERF values rather than in dboptions['log*].
523 $this->queriestime = $this->queriestime + $time;
525 if ($logall or ($logslow and ($logslow < ($time+0.00001))) or ($iserror and $logerrors)) {
526 $this->loggingquery = true;
527 try {
528 $backtrace = debug_backtrace();
529 if ($backtrace) {
530 //remove query_log()
531 array_shift($backtrace);
533 if ($backtrace) {
534 //remove query_end()
535 array_shift($backtrace);
537 $log = new stdClass();
538 $log->qtype = $this->last_type;
539 $log->sqltext = $this->last_sql;
540 $log->sqlparams = var_export((array)$this->last_params, true);
541 $log->error = (int)$iserror;
542 $log->info = $iserror ? $error : null;
543 $log->backtrace = format_backtrace($backtrace, true);
544 $log->exectime = $time;
545 $log->timelogged = time();
546 $this->insert_record('log_queries', $log);
547 } catch (Exception $ignored) {
549 $this->loggingquery = false;
554 * Disable logging temporarily.
556 protected function query_log_prevent() {
557 $this->skiplogging = true;
561 * Restore old logging behavior.
563 protected function query_log_allow() {
564 $this->skiplogging = false;
568 * Returns the time elapsed since the query started.
569 * @return float Seconds with microseconds
571 protected function query_time() {
572 return microtime(true) - $this->last_time;
576 * Returns database server info array
577 * @return array Array containing 'description' and 'version' at least.
579 public abstract function get_server_info();
582 * Returns supported query parameter types
583 * @return int bitmask of accepted SQL_PARAMS_*
585 protected abstract function allowed_param_types();
588 * Returns the last error reported by the database engine.
589 * @return string The error message.
591 public abstract function get_last_error();
594 * Prints sql debug info
595 * @param string $sql The query which is being debugged.
596 * @param array $params The query parameters. (optional)
597 * @param mixed $obj The library specific object. (optional)
598 * @return void
600 protected function print_debug($sql, array $params=null, $obj=null) {
601 if (!$this->get_debug()) {
602 return;
604 if (CLI_SCRIPT) {
605 $separator = "--------------------------------\n";
606 echo $separator;
607 echo "{$sql}\n";
608 if (!is_null($params)) {
609 echo "[" . var_export($params, true) . "]\n";
611 echo $separator;
612 } else if (AJAX_SCRIPT) {
613 $separator = "--------------------------------";
614 error_log($separator);
615 error_log($sql);
616 if (!is_null($params)) {
617 error_log("[" . var_export($params, true) . "]");
619 error_log($separator);
620 } else {
621 $separator = "<hr />\n";
622 echo $separator;
623 echo s($sql) . "\n";
624 if (!is_null($params)) {
625 echo "[" . s(var_export($params, true)) . "]\n";
627 echo $separator;
632 * Prints the time a query took to run.
633 * @return void
635 protected function print_debug_time() {
636 if (!$this->get_debug()) {
637 return;
639 $time = $this->query_time();
640 $message = "Query took: {$time} seconds.\n";
641 if (CLI_SCRIPT) {
642 echo $message;
643 echo "--------------------------------\n";
644 } else if (AJAX_SCRIPT) {
645 error_log($message);
646 error_log("--------------------------------");
647 } else {
648 echo s($message);
649 echo "<hr />\n";
654 * Returns the SQL WHERE conditions.
655 * @param string $table The table name that these conditions will be validated against.
656 * @param array $conditions The conditions to build the where clause. (must not contain numeric indexes)
657 * @throws dml_exception
658 * @return array An array list containing sql 'where' part and 'params'.
660 protected function where_clause($table, array $conditions=null) {
661 // We accept nulls in conditions
662 $conditions = is_null($conditions) ? array() : $conditions;
664 if (empty($conditions)) {
665 return array('', array());
668 // Some checks performed under debugging only
669 if (debugging()) {
670 $columns = $this->get_columns($table);
671 if (empty($columns)) {
672 // no supported columns means most probably table does not exist
673 throw new dml_exception('ddltablenotexist', $table);
675 foreach ($conditions as $key=>$value) {
676 if (!isset($columns[$key])) {
677 $a = new stdClass();
678 $a->fieldname = $key;
679 $a->tablename = $table;
680 throw new dml_exception('ddlfieldnotexist', $a);
682 $column = $columns[$key];
683 if ($column->meta_type == 'X') {
684 //ok so the column is a text column. sorry no text columns in the where clause conditions
685 throw new dml_exception('textconditionsnotallowed', $conditions);
690 $allowed_types = $this->allowed_param_types();
691 $where = array();
692 $params = array();
694 foreach ($conditions as $key=>$value) {
695 if (is_int($key)) {
696 throw new dml_exception('invalidnumkey');
698 if (is_null($value)) {
699 $where[] = "$key IS NULL";
700 } else {
701 if ($allowed_types & SQL_PARAMS_NAMED) {
702 // Need to verify key names because they can contain, originally,
703 // spaces and other forbidden chars when using sql_xxx() functions and friends.
704 $normkey = trim(preg_replace('/[^a-zA-Z0-9_-]/', '_', $key), '-_');
705 if ($normkey !== $key) {
706 debugging('Invalid key found in the conditions array.');
708 $where[] = "$key = :$normkey";
709 $params[$normkey] = $value;
710 } else {
711 $where[] = "$key = ?";
712 $params[] = $value;
716 $where = implode(" AND ", $where);
717 return array($where, $params);
721 * Returns SQL WHERE conditions for the ..._list group of methods.
723 * @param string $field the name of a field.
724 * @param array $values the values field might take.
725 * @return array An array containing sql 'where' part and 'params'
727 protected function where_clause_list($field, array $values) {
728 if (empty($values)) {
729 return array("1 = 2", array()); // Fake condition, won't return rows ever. MDL-17645
732 // Note: Do not use get_in_or_equal() because it can not deal with bools and nulls.
734 $params = array();
735 $select = "";
736 $values = (array)$values;
737 foreach ($values as $value) {
738 if (is_bool($value)) {
739 $value = (int)$value;
741 if (is_null($value)) {
742 $select = "$field IS NULL";
743 } else {
744 $params[] = $value;
747 if ($params) {
748 if ($select !== "") {
749 $select = "$select OR ";
751 $count = count($params);
752 if ($count == 1) {
753 $select = $select."$field = ?";
754 } else {
755 $qs = str_repeat(',?', $count);
756 $qs = ltrim($qs, ',');
757 $select = $select."$field IN ($qs)";
760 return array($select, $params);
764 * Constructs 'IN()' or '=' sql fragment
765 * @param mixed $items A single value or array of values for the expression.
766 * @param int $type Parameter bounding type : SQL_PARAMS_QM or SQL_PARAMS_NAMED.
767 * @param string $prefix Named parameter placeholder prefix (a unique counter value is appended to each parameter name).
768 * @param bool $equal True means we want to equate to the constructed expression, false means we don't want to equate to it.
769 * @param mixed $onemptyitems This defines the behavior when the array of items provided is empty. Defaults to false,
770 * meaning throw exceptions. Other values will become part of the returned SQL fragment.
771 * @throws coding_exception | dml_exception
772 * @return array A list containing the constructed sql fragment and an array of parameters.
774 public function get_in_or_equal($items, $type=SQL_PARAMS_QM, $prefix='param', $equal=true, $onemptyitems=false) {
776 // default behavior, throw exception on empty array
777 if (is_array($items) and empty($items) and $onemptyitems === false) {
778 throw new coding_exception('moodle_database::get_in_or_equal() does not accept empty arrays');
780 // handle $onemptyitems on empty array of items
781 if (is_array($items) and empty($items)) {
782 if (is_null($onemptyitems)) { // Special case, NULL value
783 $sql = $equal ? ' IS NULL' : ' IS NOT NULL';
784 return (array($sql, array()));
785 } else {
786 $items = array($onemptyitems); // Rest of cases, prepare $items for std processing
790 if ($type == SQL_PARAMS_QM) {
791 if (!is_array($items) or count($items) == 1) {
792 $sql = $equal ? '= ?' : '<> ?';
793 $items = (array)$items;
794 $params = array_values($items);
795 } else {
796 if ($equal) {
797 $sql = 'IN ('.implode(',', array_fill(0, count($items), '?')).')';
798 } else {
799 $sql = 'NOT IN ('.implode(',', array_fill(0, count($items), '?')).')';
801 $params = array_values($items);
804 } else if ($type == SQL_PARAMS_NAMED) {
805 if (empty($prefix)) {
806 $prefix = 'param';
809 if (!is_array($items)){
810 $param = $prefix.$this->inorequaluniqueindex++;
811 $sql = $equal ? "= :$param" : "<> :$param";
812 $params = array($param=>$items);
813 } else if (count($items) == 1) {
814 $param = $prefix.$this->inorequaluniqueindex++;
815 $sql = $equal ? "= :$param" : "<> :$param";
816 $item = reset($items);
817 $params = array($param=>$item);
818 } else {
819 $params = array();
820 $sql = array();
821 foreach ($items as $item) {
822 $param = $prefix.$this->inorequaluniqueindex++;
823 $params[$param] = $item;
824 $sql[] = ':'.$param;
826 if ($equal) {
827 $sql = 'IN ('.implode(',', $sql).')';
828 } else {
829 $sql = 'NOT IN ('.implode(',', $sql).')';
833 } else {
834 throw new dml_exception('typenotimplement');
836 return array($sql, $params);
840 * Converts short table name {tablename} to the real prefixed table name in given sql.
841 * @param string $sql The sql to be operated on.
842 * @return string The sql with tablenames being prefixed with $CFG->prefix
844 protected function fix_table_names($sql) {
845 return preg_replace_callback(
846 '/\{([a-z][a-z0-9_]*)\}/',
847 function($matches) {
848 return $this->fix_table_name($matches[1]);
850 $sql
855 * Adds the prefix to the table name.
857 * @param string $tablename The table name
858 * @return string The prefixed table name
860 protected function fix_table_name($tablename) {
861 return $this->prefix . $tablename;
865 * Internal private utitlity function used to fix parameters.
866 * Used with {@link preg_replace_callback()}
867 * @param array $match Refer to preg_replace_callback usage for description.
868 * @return string
870 private function _fix_sql_params_dollar_callback($match) {
871 $this->fix_sql_params_i++;
872 return "\$".$this->fix_sql_params_i;
876 * Detects object parameters and throws exception if found
877 * @param mixed $value
878 * @return void
879 * @throws coding_exception if object detected
881 protected function detect_objects($value) {
882 if (is_object($value)) {
883 throw new coding_exception('Invalid database query parameter value', 'Objects are are not allowed: '.get_class($value));
888 * Normalizes sql query parameters and verifies parameters.
889 * @param string $sql The query or part of it.
890 * @param array $params The query parameters.
891 * @return array (sql, params, type of params)
893 public function fix_sql_params($sql, array $params=null) {
894 $params = (array)$params; // mke null array if needed
895 $allowed_types = $this->allowed_param_types();
897 // convert table names
898 $sql = $this->fix_table_names($sql);
900 // cast booleans to 1/0 int and detect forbidden objects
901 foreach ($params as $key => $value) {
902 $this->detect_objects($value);
903 $params[$key] = is_bool($value) ? (int)$value : $value;
906 // NICOLAS C: Fixed regexp for negative backwards look-ahead of double colons. Thanks for Sam Marshall's help
907 $named_count = preg_match_all('/(?<!:):[a-z][a-z0-9_]*/', $sql, $named_matches); // :: used in pgsql casts
908 $dollar_count = preg_match_all('/\$[1-9][0-9]*/', $sql, $dollar_matches);
909 $q_count = substr_count($sql, '?');
911 // Optionally add debug trace to sql as a comment.
912 $sql = $this->add_sql_debugging($sql);
914 $count = 0;
916 if ($named_count) {
917 $type = SQL_PARAMS_NAMED;
918 $count = $named_count;
921 if ($dollar_count) {
922 if ($count) {
923 throw new dml_exception('mixedtypesqlparam');
925 $type = SQL_PARAMS_DOLLAR;
926 $count = $dollar_count;
929 if ($q_count) {
930 if ($count) {
931 throw new dml_exception('mixedtypesqlparam');
933 $type = SQL_PARAMS_QM;
934 $count = $q_count;
938 if (!$count) {
939 // ignore params
940 if ($allowed_types & SQL_PARAMS_NAMED) {
941 return array($sql, array(), SQL_PARAMS_NAMED);
942 } else if ($allowed_types & SQL_PARAMS_QM) {
943 return array($sql, array(), SQL_PARAMS_QM);
944 } else {
945 return array($sql, array(), SQL_PARAMS_DOLLAR);
949 if ($count > count($params)) {
950 $a = new stdClass;
951 $a->expected = $count;
952 $a->actual = count($params);
953 throw new dml_exception('invalidqueryparam', $a);
956 $target_type = $allowed_types;
958 if ($type & $allowed_types) { // bitwise AND
959 if ($count == count($params)) {
960 if ($type == SQL_PARAMS_QM) {
961 return array($sql, array_values($params), SQL_PARAMS_QM); // 0-based array required
962 } else {
963 //better do the validation of names below
966 // needs some fixing or validation - there might be more params than needed
967 $target_type = $type;
970 if ($type == SQL_PARAMS_NAMED) {
971 $finalparams = array();
972 foreach ($named_matches[0] as $key) {
973 $key = trim($key, ':');
974 if (!array_key_exists($key, $params)) {
975 throw new dml_exception('missingkeyinsql', $key, '');
977 if (strlen($key) > 30) {
978 throw new coding_exception(
979 "Placeholder names must be 30 characters or shorter. '" .
980 $key . "' is too long.", $sql);
982 $finalparams[$key] = $params[$key];
984 if ($count != count($finalparams)) {
985 throw new dml_exception('duplicateparaminsql');
988 if ($target_type & SQL_PARAMS_QM) {
989 $sql = preg_replace('/(?<!:):[a-z][a-z0-9_]*/', '?', $sql);
990 return array($sql, array_values($finalparams), SQL_PARAMS_QM); // 0-based required
991 } else if ($target_type & SQL_PARAMS_NAMED) {
992 return array($sql, $finalparams, SQL_PARAMS_NAMED);
993 } else { // $type & SQL_PARAMS_DOLLAR
994 //lambda-style functions eat memory - we use globals instead :-(
995 $this->fix_sql_params_i = 0;
996 $sql = preg_replace_callback('/(?<!:):[a-z][a-z0-9_]*/', array($this, '_fix_sql_params_dollar_callback'), $sql);
997 return array($sql, array_values($finalparams), SQL_PARAMS_DOLLAR); // 0-based required
1000 } else if ($type == SQL_PARAMS_DOLLAR) {
1001 if ($target_type & SQL_PARAMS_DOLLAR) {
1002 return array($sql, array_values($params), SQL_PARAMS_DOLLAR); // 0-based required
1003 } else if ($target_type & SQL_PARAMS_QM) {
1004 $sql = preg_replace('/\$[0-9]+/', '?', $sql);
1005 return array($sql, array_values($params), SQL_PARAMS_QM); // 0-based required
1006 } else { //$target_type & SQL_PARAMS_NAMED
1007 $sql = preg_replace('/\$([0-9]+)/', ':param\\1', $sql);
1008 $finalparams = array();
1009 foreach ($params as $key=>$param) {
1010 $key++;
1011 $finalparams['param'.$key] = $param;
1013 return array($sql, $finalparams, SQL_PARAMS_NAMED);
1016 } else { // $type == SQL_PARAMS_QM
1017 if (count($params) != $count) {
1018 $params = array_slice($params, 0, $count);
1021 if ($target_type & SQL_PARAMS_QM) {
1022 return array($sql, array_values($params), SQL_PARAMS_QM); // 0-based required
1023 } else if ($target_type & SQL_PARAMS_NAMED) {
1024 $finalparams = array();
1025 $pname = 'param0';
1026 $parts = explode('?', $sql);
1027 $sql = array_shift($parts);
1028 foreach ($parts as $part) {
1029 $param = array_shift($params);
1030 $pname++;
1031 $sql .= ':'.$pname.$part;
1032 $finalparams[$pname] = $param;
1034 return array($sql, $finalparams, SQL_PARAMS_NAMED);
1035 } else { // $type & SQL_PARAMS_DOLLAR
1036 //lambda-style functions eat memory - we use globals instead :-(
1037 $this->fix_sql_params_i = 0;
1038 $sql = preg_replace_callback('/\?/', array($this, '_fix_sql_params_dollar_callback'), $sql);
1039 return array($sql, array_values($params), SQL_PARAMS_DOLLAR); // 0-based required
1045 * Add an SQL comment to trace all sql calls back to the calling php code
1046 * @param string $sql Original sql
1047 * @return string Instrumented sql
1049 protected function add_sql_debugging(string $sql): string {
1050 global $CFG;
1052 if (!property_exists($CFG, 'debugsqltrace')) {
1053 return $sql;
1056 $level = $CFG->debugsqltrace;
1058 if (empty($level)) {
1059 return $sql;
1062 $callers = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
1064 // Ignore moodle_database internals.
1065 $callers = array_filter($callers, function($caller) {
1066 return empty($caller['class']) || $caller['class'] != 'moodle_database';
1069 $callers = array_slice($callers, 0, $level);
1071 $text = trim(format_backtrace($callers, true));
1073 // Convert all linebreaks to SQL comments, optionally
1074 // also eating any * formatting.
1075 $text = preg_replace("/(^|\n)\*?\s*/", "\n-- ", $text);
1077 // Convert all ? to 'unknown' in the sql coment so these don't get
1078 // caught by fix_sql_params().
1079 $text = str_replace('?', 'unknown', $text);
1081 // Convert tokens like :test to ::test for the same reason.
1082 $text = preg_replace('/(?<!:):[a-z][a-z0-9_]*/', ':\0', $text);
1084 return $sql . $text;
1089 * Ensures that limit params are numeric and positive integers, to be passed to the database.
1090 * We explicitly treat null, '' and -1 as 0 in order to provide compatibility with how limit
1091 * values have been passed historically.
1093 * @param int $limitfrom Where to start results from
1094 * @param int $limitnum How many results to return
1095 * @return array Normalised limit params in array($limitfrom, $limitnum)
1097 protected function normalise_limit_from_num($limitfrom, $limitnum) {
1098 global $CFG;
1100 // We explicilty treat these cases as 0.
1101 if ($limitfrom === null || $limitfrom === '' || $limitfrom === -1) {
1102 $limitfrom = 0;
1104 if ($limitnum === null || $limitnum === '' || $limitnum === -1) {
1105 $limitnum = 0;
1108 if ($CFG->debugdeveloper) {
1109 if (!is_numeric($limitfrom)) {
1110 $strvalue = var_export($limitfrom, true);
1111 debugging("Non-numeric limitfrom parameter detected: $strvalue, did you pass the correct arguments?",
1112 DEBUG_DEVELOPER);
1113 } else if ($limitfrom < 0) {
1114 debugging("Negative limitfrom parameter detected: $limitfrom, did you pass the correct arguments?",
1115 DEBUG_DEVELOPER);
1118 if (!is_numeric($limitnum)) {
1119 $strvalue = var_export($limitnum, true);
1120 debugging("Non-numeric limitnum parameter detected: $strvalue, did you pass the correct arguments?",
1121 DEBUG_DEVELOPER);
1122 } else if ($limitnum < 0) {
1123 debugging("Negative limitnum parameter detected: $limitnum, did you pass the correct arguments?",
1124 DEBUG_DEVELOPER);
1128 $limitfrom = (int)$limitfrom;
1129 $limitnum = (int)$limitnum;
1130 $limitfrom = max(0, $limitfrom);
1131 $limitnum = max(0, $limitnum);
1133 return array($limitfrom, $limitnum);
1137 * Return tables in database WITHOUT current prefix.
1138 * @param bool $usecache if true, returns list of cached tables.
1139 * @return array of table names in lowercase and without prefix
1141 public abstract function get_tables($usecache=true);
1144 * Return table indexes - everything lowercased.
1145 * @param string $table The table we want to get indexes from.
1146 * @return array An associative array of indexes containing 'unique' flag and 'columns' being indexed
1148 public abstract function get_indexes($table);
1151 * Returns detailed information about columns in table. This information is cached internally.
1153 * @param string $table The table's name.
1154 * @param bool $usecache Flag to use internal cacheing. The default is true.
1155 * @return database_column_info[] of database_column_info objects indexed with column names
1157 public function get_columns($table, $usecache = true): array {
1158 if (!$table) { // Table not specified, return empty array directly.
1159 return [];
1162 if ($usecache) {
1163 if ($this->temptables->is_temptable($table)) {
1164 if ($data = $this->get_temp_tables_cache()->get($table)) {
1165 return $data;
1167 } else {
1168 if ($data = $this->get_metacache()->get($table)) {
1169 return $data;
1174 $structure = $this->fetch_columns($table);
1176 if ($usecache) {
1177 if ($this->temptables->is_temptable($table)) {
1178 $this->get_temp_tables_cache()->set($table, $structure);
1179 } else {
1180 $this->get_metacache()->set($table, $structure);
1184 return $structure;
1188 * Returns detailed information about columns in table. This information is cached internally.
1190 * @param string $table The table's name.
1191 * @return database_column_info[] of database_column_info objects indexed with column names
1193 protected abstract function fetch_columns(string $table): array;
1196 * Normalise values based on varying RDBMS's dependencies (booleans, LOBs...)
1198 * @param database_column_info $column column metadata corresponding with the value we are going to normalise
1199 * @param mixed $value value we are going to normalise
1200 * @return mixed the normalised value
1202 protected abstract function normalise_value($column, $value);
1205 * Resets the internal column details cache
1207 * @param array|null $tablenames an array of xmldb table names affected by this request.
1208 * @return void
1210 public function reset_caches($tablenames = null) {
1211 if (!empty($tablenames)) {
1212 $dbmetapurged = false;
1213 foreach ($tablenames as $tablename) {
1214 if ($this->temptables->is_temptable($tablename)) {
1215 $this->get_temp_tables_cache()->delete($tablename);
1216 } else if ($dbmetapurged === false) {
1217 $this->tables = null;
1218 $this->get_metacache()->purge();
1219 $this->metacache = null;
1220 $dbmetapurged = true;
1223 } else {
1224 $this->get_temp_tables_cache()->purge();
1225 $this->tables = null;
1226 // Purge MUC as well.
1227 $this->get_metacache()->purge();
1228 $this->metacache = null;
1233 * Returns the sql generator used for db manipulation.
1234 * Used mostly in upgrade.php scripts.
1235 * @return database_manager The instance used to perform ddl operations.
1236 * @see lib/ddl/database_manager.php
1238 public function get_manager() {
1239 global $CFG;
1241 if (!$this->database_manager) {
1242 require_once($CFG->libdir.'/ddllib.php');
1244 $classname = $this->get_dbfamily().'_sql_generator';
1245 require_once("$CFG->libdir/ddl/$classname.php");
1246 $generator = new $classname($this, $this->temptables);
1248 $this->database_manager = new database_manager($this, $generator);
1250 return $this->database_manager;
1254 * Attempts to change db encoding to UTF-8 encoding if possible.
1255 * @return bool True is successful.
1257 public function change_db_encoding() {
1258 return false;
1262 * Checks to see if the database is in unicode mode?
1263 * @return bool
1265 public function setup_is_unicodedb() {
1266 return true;
1270 * Enable/disable very detailed debugging.
1271 * @param bool $state
1272 * @return void
1274 public function set_debug($state) {
1275 $this->debug = $state;
1279 * Returns debug status
1280 * @return bool $state
1282 public function get_debug() {
1283 return $this->debug;
1287 * Enable/disable detailed sql logging
1289 * @deprecated since Moodle 2.9
1291 public function set_logging($state) {
1292 throw new coding_exception('set_logging() can not be used any more.');
1296 * Do NOT use in code, this is for use by database_manager only!
1297 * @param string|array $sql query or array of queries
1298 * @param array|null $tablenames an array of xmldb table names affected by this request.
1299 * @return bool true
1300 * @throws ddl_change_structure_exception A DDL specific exception is thrown for any errors.
1302 public abstract function change_database_structure($sql, $tablenames = null);
1305 * Executes a general sql query. Should be used only when no other method suitable.
1306 * Do NOT use this to make changes in db structure, use database_manager methods instead!
1307 * @param string $sql query
1308 * @param array $params query parameters
1309 * @return bool true
1310 * @throws dml_exception A DML specific exception is thrown for any errors.
1312 public abstract function execute($sql, array $params=null);
1315 * Get a number of records as a moodle_recordset where all the given conditions met.
1317 * Selects records from the table $table.
1319 * If specified, only records meeting $conditions.
1321 * If specified, the results will be sorted as specified by $sort. This
1322 * is added to the SQL as "ORDER BY $sort". Example values of $sort
1323 * might be "time ASC" or "time DESC".
1325 * If $fields is specified, only those fields are returned.
1327 * Since this method is a little less readable, use of it should be restricted to
1328 * code where it's possible there might be large datasets being returned. For known
1329 * small datasets use get_records - it leads to simpler code.
1331 * If you only want some of the records, specify $limitfrom and $limitnum.
1332 * The query will skip the first $limitfrom records (according to the sort
1333 * order) and then return the next $limitnum records. If either of $limitfrom
1334 * or $limitnum is specified, both must be present.
1336 * The return value is a moodle_recordset
1337 * if the query succeeds. If an error occurs, false is returned.
1339 * @param string $table the table to query.
1340 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1341 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1342 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
1343 * @param int $limitfrom return a subset of records, starting at this point (optional).
1344 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1345 * @return moodle_recordset A moodle_recordset instance
1346 * @throws dml_exception A DML specific exception is thrown for any errors.
1348 public function get_recordset($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1349 list($select, $params) = $this->where_clause($table, $conditions);
1350 return $this->get_recordset_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1354 * Get a number of records as a moodle_recordset where one field match one list of values.
1356 * Only records where $field takes one of the values $values are returned.
1357 * $values must be an array of values.
1359 * Other arguments and the return type are like {@link function get_recordset}.
1361 * @param string $table the table to query.
1362 * @param string $field a field to check (optional).
1363 * @param array $values array of values the field must have
1364 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1365 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
1366 * @param int $limitfrom return a subset of records, starting at this point (optional).
1367 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1368 * @return moodle_recordset A moodle_recordset instance.
1369 * @throws dml_exception A DML specific exception is thrown for any errors.
1371 public function get_recordset_list($table, $field, array $values, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1372 list($select, $params) = $this->where_clause_list($field, $values);
1373 return $this->get_recordset_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1377 * Get a number of records as a moodle_recordset which match a particular WHERE clause.
1379 * If given, $select is used as the SELECT parameter in the SQL query,
1380 * otherwise all records from the table are returned.
1382 * Other arguments and the return type are like {@link function get_recordset}.
1384 * @param string $table the table to query.
1385 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1386 * @param array $params array of sql parameters
1387 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1388 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
1389 * @param int $limitfrom return a subset of records, starting at this point (optional).
1390 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1391 * @return moodle_recordset A moodle_recordset instance.
1392 * @throws dml_exception A DML specific exception is thrown for any errors.
1394 public function get_recordset_select($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1395 $sql = "SELECT $fields FROM {".$table."}";
1396 if ($select) {
1397 $sql .= " WHERE $select";
1399 if ($sort) {
1400 $sql .= " ORDER BY $sort";
1402 return $this->get_recordset_sql($sql, $params, $limitfrom, $limitnum);
1406 * Get a number of records as a moodle_recordset using a SQL statement.
1408 * Since this method is a little less readable, use of it should be restricted to
1409 * code where it's possible there might be large datasets being returned. For known
1410 * small datasets use get_records_sql - it leads to simpler code.
1412 * The return type is like {@link function get_recordset}.
1414 * @param string $sql the SQL select query to execute.
1415 * @param array $params array of sql parameters
1416 * @param int $limitfrom return a subset of records, starting at this point (optional).
1417 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1418 * @return moodle_recordset A moodle_recordset instance.
1419 * @throws dml_exception A DML specific exception is thrown for any errors.
1421 public abstract function get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0);
1424 * Get all records from a table.
1426 * This method works around potential memory problems and may improve performance,
1427 * this method may block access to table until the recordset is closed.
1429 * @param string $table Name of database table.
1430 * @return moodle_recordset A moodle_recordset instance {@link function get_recordset}.
1431 * @throws dml_exception A DML specific exception is thrown for any errors.
1433 public function export_table_recordset($table) {
1434 return $this->get_recordset($table, array());
1438 * Get a number of records as an array of objects where all the given conditions met.
1440 * If the query succeeds and returns at least one record, the
1441 * return value is an array of objects, one object for each
1442 * record found. The array key is the value from the first
1443 * column of the result set. The object associated with that key
1444 * has a member variable for each column of the results.
1446 * @param string $table the table to query.
1447 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1448 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1449 * @param string $fields a comma separated list of fields to return (optional, by default
1450 * all fields are returned). The first field will be used as key for the
1451 * array so must be a unique field such as 'id'.
1452 * @param int $limitfrom return a subset of records, starting at this point (optional).
1453 * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
1454 * @return array An array of Objects indexed by first column.
1455 * @throws dml_exception A DML specific exception is thrown for any errors.
1457 public function get_records($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1458 list($select, $params) = $this->where_clause($table, $conditions);
1459 return $this->get_records_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1463 * Get a number of records as an array of objects where one field match one list of values.
1465 * Return value is like {@link function get_records}.
1467 * @param string $table The database table to be checked against.
1468 * @param string $field The field to search
1469 * @param array $values An array of values
1470 * @param string $sort Sort order (as valid SQL sort parameter)
1471 * @param string $fields A comma separated list of fields to be returned from the chosen table. If specified,
1472 * the first field should be a unique one such as 'id' since it will be used as a key in the associative
1473 * array.
1474 * @param int $limitfrom return a subset of records, starting at this point (optional).
1475 * @param int $limitnum return a subset comprising this many records in total (optional).
1476 * @return array An array of objects indexed by first column
1477 * @throws dml_exception A DML specific exception is thrown for any errors.
1479 public function get_records_list($table, $field, array $values, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1480 list($select, $params) = $this->where_clause_list($field, $values);
1481 return $this->get_records_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1485 * Get a number of records as an array of objects which match a particular WHERE clause.
1487 * Return value is like {@link function get_records}.
1489 * @param string $table The table to query.
1490 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1491 * @param array $params An array of sql parameters
1492 * @param string $sort An order to sort the results in (optional, a valid SQL ORDER BY parameter).
1493 * @param string $fields A comma separated list of fields to return
1494 * (optional, by default all fields are returned). The first field will be used as key for the
1495 * array so must be a unique field such as 'id'.
1496 * @param int $limitfrom return a subset of records, starting at this point (optional).
1497 * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
1498 * @return array of objects indexed by first column
1499 * @throws dml_exception A DML specific exception is thrown for any errors.
1501 public function get_records_select($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1502 if ($select) {
1503 $select = "WHERE $select";
1505 if ($sort) {
1506 $sort = " ORDER BY $sort";
1508 return $this->get_records_sql("SELECT $fields FROM {" . $table . "} $select $sort", $params, $limitfrom, $limitnum);
1512 * Get a number of records as an array of objects using a SQL statement.
1514 * Return value is like {@link function get_records}.
1516 * @param string $sql the SQL select query to execute. The first column of this SELECT statement
1517 * must be a unique value (usually the 'id' field), as it will be used as the key of the
1518 * returned array.
1519 * @param array $params array of sql parameters
1520 * @param int $limitfrom return a subset of records, starting at this point (optional).
1521 * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
1522 * @return array of objects indexed by first column
1523 * @throws dml_exception A DML specific exception is thrown for any errors.
1525 public abstract function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0);
1528 * Get the first two columns from a number of records as an associative array where all the given conditions met.
1530 * Arguments are like {@link function get_recordset}.
1532 * If no errors occur the return value
1533 * is an associative whose keys come from the first field of each record,
1534 * and whose values are the corresponding second fields.
1535 * False is returned if an error occurs.
1537 * @param string $table the table to query.
1538 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1539 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1540 * @param string $fields a comma separated list of fields to return - the number of fields should be 2!
1541 * @param int $limitfrom return a subset of records, starting at this point (optional).
1542 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1543 * @return array an associative array
1544 * @throws dml_exception A DML specific exception is thrown for any errors.
1546 public function get_records_menu($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1547 $menu = array();
1548 if ($records = $this->get_records($table, $conditions, $sort, $fields, $limitfrom, $limitnum)) {
1549 foreach ($records as $record) {
1550 $record = (array)$record;
1551 $key = array_shift($record);
1552 $value = array_shift($record);
1553 $menu[$key] = $value;
1556 return $menu;
1560 * Get the first two columns from a number of records as an associative array which match a particular WHERE clause.
1562 * Arguments are like {@link function get_recordset_select}.
1563 * Return value is like {@link function get_records_menu}.
1565 * @param string $table The database table to be checked against.
1566 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1567 * @param array $params array of sql parameters
1568 * @param string $sort Sort order (optional) - a valid SQL order parameter
1569 * @param string $fields A comma separated list of fields to be returned from the chosen table - the number of fields should be 2!
1570 * @param int $limitfrom return a subset of records, starting at this point (optional).
1571 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1572 * @return array an associative array
1573 * @throws dml_exception A DML specific exception is thrown for any errors.
1575 public function get_records_select_menu($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1576 $menu = array();
1577 if ($records = $this->get_records_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum)) {
1578 foreach ($records as $record) {
1579 $record = (array)$record;
1580 $key = array_shift($record);
1581 $value = array_shift($record);
1582 $menu[$key] = $value;
1585 return $menu;
1589 * Get the first two columns from a number of records as an associative array using a SQL statement.
1591 * Arguments are like {@link function get_recordset_sql}.
1592 * Return value is like {@link function get_records_menu}.
1594 * @param string $sql The SQL string you wish to be executed.
1595 * @param array $params array of sql parameters
1596 * @param int $limitfrom return a subset of records, starting at this point (optional).
1597 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1598 * @return array an associative array
1599 * @throws dml_exception A DML specific exception is thrown for any errors.
1601 public function get_records_sql_menu($sql, array $params=null, $limitfrom=0, $limitnum=0) {
1602 $menu = array();
1603 if ($records = $this->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
1604 foreach ($records as $record) {
1605 $record = (array)$record;
1606 $key = array_shift($record);
1607 $value = array_shift($record);
1608 $menu[$key] = $value;
1611 return $menu;
1615 * Get a single database record as an object where all the given conditions met.
1617 * @param string $table The table to select from.
1618 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1619 * @param string $fields A comma separated list of fields to be returned from the chosen table.
1620 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1621 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1622 * MUST_EXIST means we will throw an exception if no record or multiple records found.
1624 * @todo MDL-30407 MUST_EXIST option should not throw a dml_exception, it should throw a different exception as it's a requested check.
1625 * @return mixed a fieldset object containing the first matching record, false or exception if error not found depending on mode
1626 * @throws dml_exception A DML specific exception is thrown for any errors.
1628 public function get_record($table, array $conditions, $fields='*', $strictness=IGNORE_MISSING) {
1629 list($select, $params) = $this->where_clause($table, $conditions);
1630 return $this->get_record_select($table, $select, $params, $fields, $strictness);
1634 * Get a single database record as an object which match a particular WHERE clause.
1636 * @param string $table The database table to be checked against.
1637 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1638 * @param array $params array of sql parameters
1639 * @param string $fields A comma separated list of fields to be returned from the chosen table.
1640 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1641 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1642 * MUST_EXIST means throw exception if no record or multiple records found
1643 * @return stdClass|false a fieldset object containing the first matching record, false or exception if error not found depending on mode
1644 * @throws dml_exception A DML specific exception is thrown for any errors.
1646 public function get_record_select($table, $select, array $params=null, $fields='*', $strictness=IGNORE_MISSING) {
1647 if ($select) {
1648 $select = "WHERE $select";
1650 try {
1651 return $this->get_record_sql("SELECT $fields FROM {" . $table . "} $select", $params, $strictness);
1652 } catch (dml_missing_record_exception $e) {
1653 // create new exception which will contain correct table name
1654 throw new dml_missing_record_exception($table, $e->sql, $e->params);
1659 * Get a single database record as an object using a SQL statement.
1661 * The SQL statement should normally only return one record.
1662 * It is recommended to use get_records_sql() if more matches possible!
1664 * @param string $sql The SQL string you wish to be executed, should normally only return one record.
1665 * @param array $params array of sql parameters
1666 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1667 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1668 * MUST_EXIST means throw exception if no record or multiple records found
1669 * @return mixed a fieldset object containing the first matching record, false or exception if error not found depending on mode
1670 * @throws dml_exception A DML specific exception is thrown for any errors.
1672 public function get_record_sql($sql, array $params=null, $strictness=IGNORE_MISSING) {
1673 $strictness = (int)$strictness; // we support true/false for BC reasons too
1674 if ($strictness == IGNORE_MULTIPLE) {
1675 $count = 1;
1676 } else {
1677 $count = 0;
1679 if (!$records = $this->get_records_sql($sql, $params, 0, $count)) {
1680 // not found
1681 if ($strictness == MUST_EXIST) {
1682 throw new dml_missing_record_exception('', $sql, $params);
1684 return false;
1687 if (count($records) > 1) {
1688 if ($strictness == MUST_EXIST) {
1689 throw new dml_multiple_records_exception($sql, $params);
1691 debugging('Error: mdb->get_record() found more than one record!');
1694 $return = reset($records);
1695 return $return;
1699 * Get a single field value from a table record where all the given conditions met.
1701 * @param string $table the table to query.
1702 * @param string $return the field to return the value of.
1703 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1704 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1705 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1706 * MUST_EXIST means throw exception if no record or multiple records found
1707 * @return mixed the specified value false if not found
1708 * @throws dml_exception A DML specific exception is thrown for any errors.
1710 public function get_field($table, $return, array $conditions, $strictness=IGNORE_MISSING) {
1711 list($select, $params) = $this->where_clause($table, $conditions);
1712 return $this->get_field_select($table, $return, $select, $params, $strictness);
1716 * Get a single field value from a table record which match a particular WHERE clause.
1718 * @param string $table the table to query.
1719 * @param string $return the field to return the value of.
1720 * @param string $select A fragment of SQL to be used in a where clause returning one row with one column
1721 * @param array $params array of sql parameters
1722 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1723 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1724 * MUST_EXIST means throw exception if no record or multiple records found
1725 * @return mixed the specified value false if not found
1726 * @throws dml_exception A DML specific exception is thrown for any errors.
1728 public function get_field_select($table, $return, $select, array $params=null, $strictness=IGNORE_MISSING) {
1729 if ($select) {
1730 $select = "WHERE $select";
1732 try {
1733 return $this->get_field_sql("SELECT $return FROM {" . $table . "} $select", $params, $strictness);
1734 } catch (dml_missing_record_exception $e) {
1735 // create new exception which will contain correct table name
1736 throw new dml_missing_record_exception($table, $e->sql, $e->params);
1741 * Get a single field value (first field) using a SQL statement.
1743 * @param string $sql The SQL query returning one row with one column
1744 * @param array $params array of sql parameters
1745 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1746 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1747 * MUST_EXIST means throw exception if no record or multiple records found
1748 * @return mixed the specified value false if not found
1749 * @throws dml_exception A DML specific exception is thrown for any errors.
1751 public function get_field_sql($sql, array $params=null, $strictness=IGNORE_MISSING) {
1752 if (!$record = $this->get_record_sql($sql, $params, $strictness)) {
1753 return false;
1756 $record = (array)$record;
1757 return reset($record); // first column
1761 * Selects records and return values of chosen field as an array which match a particular WHERE clause.
1763 * @param string $table the table to query.
1764 * @param string $return the field we are intered in
1765 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1766 * @param array $params array of sql parameters
1767 * @return array of values
1768 * @throws dml_exception A DML specific exception is thrown for any errors.
1770 public function get_fieldset_select($table, $return, $select, array $params=null) {
1771 if ($select) {
1772 $select = "WHERE $select";
1774 return $this->get_fieldset_sql("SELECT $return FROM {" . $table . "} $select", $params);
1778 * Selects records and return values (first field) as an array using a SQL statement.
1780 * @param string $sql The SQL query
1781 * @param array $params array of sql parameters
1782 * @return array of values
1783 * @throws dml_exception A DML specific exception is thrown for any errors.
1785 public abstract function get_fieldset_sql($sql, array $params=null);
1788 * Insert new record into database, as fast as possible, no safety checks, lobs not supported.
1789 * @param string $table name
1790 * @param mixed $params data record as object or array
1791 * @param bool $returnid Returns id of inserted record.
1792 * @param bool $bulk true means repeated inserts expected
1793 * @param bool $customsequence true if 'id' included in $params, disables $returnid
1794 * @return bool|int true or new id
1795 * @throws dml_exception A DML specific exception is thrown for any errors.
1797 public abstract function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false);
1800 * Insert a record into a table and return the "id" field if required.
1802 * Some conversions and safety checks are carried out. Lobs are supported.
1803 * If the return ID isn't required, then this just reports success as true/false.
1804 * $data is an object containing needed data
1805 * @param string $table The database table to be inserted into
1806 * @param object|array $dataobject A data object with values for one or more fields in the record
1807 * @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.
1808 * @param bool $bulk Set to true is multiple inserts are expected
1809 * @return bool|int true or new id
1810 * @throws dml_exception A DML specific exception is thrown for any errors.
1812 public abstract function insert_record($table, $dataobject, $returnid=true, $bulk=false);
1815 * Insert multiple records into database as fast as possible.
1817 * Order of inserts is maintained, but the operation is not atomic,
1818 * use transactions if necessary.
1820 * This method is intended for inserting of large number of small objects,
1821 * do not use for huge objects with text or binary fields.
1823 * @since Moodle 2.7
1825 * @param string $table The database table to be inserted into
1826 * @param array|Traversable $dataobjects list of objects to be inserted, must be compatible with foreach
1827 * @return void does not return new record ids
1829 * @throws coding_exception if data objects have different structure
1830 * @throws dml_exception A DML specific exception is thrown for any errors.
1832 public function insert_records($table, $dataobjects) {
1833 if (!is_array($dataobjects) and !($dataobjects instanceof Traversable)) {
1834 throw new coding_exception('insert_records() passed non-traversable object');
1837 $fields = null;
1838 // Note: override in driver if there is a faster way.
1839 foreach ($dataobjects as $dataobject) {
1840 if (!is_array($dataobject) and !is_object($dataobject)) {
1841 throw new coding_exception('insert_records() passed invalid record object');
1843 $dataobject = (array)$dataobject;
1844 if ($fields === null) {
1845 $fields = array_keys($dataobject);
1846 } else if ($fields !== array_keys($dataobject)) {
1847 throw new coding_exception('All dataobjects in insert_records() must have the same structure!');
1849 $this->insert_record($table, $dataobject, false);
1854 * Import a record into a table, id field is required.
1855 * Safety checks are NOT carried out. Lobs are supported.
1857 * @param string $table name of database table to be inserted into
1858 * @param object $dataobject A data object with values for one or more fields in the record
1859 * @return bool true
1860 * @throws dml_exception A DML specific exception is thrown for any errors.
1862 public abstract function import_record($table, $dataobject);
1865 * Update record in database, as fast as possible, no safety checks, lobs not supported.
1866 * @param string $table name
1867 * @param mixed $params data record as object or array
1868 * @param bool $bulk True means repeated updates expected.
1869 * @return bool true
1870 * @throws dml_exception A DML specific exception is thrown for any errors.
1872 public abstract function update_record_raw($table, $params, $bulk=false);
1875 * Update a record in a table
1877 * $dataobject is an object containing needed data
1878 * Relies on $dataobject having a variable "id" to
1879 * specify the record to update
1881 * @param string $table The database table to be checked against.
1882 * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
1883 * @param bool $bulk True means repeated updates expected.
1884 * @return bool true
1885 * @throws dml_exception A DML specific exception is thrown for any errors.
1887 public abstract function update_record($table, $dataobject, $bulk=false);
1890 * Set a single field in every table record where all the given conditions met.
1892 * @param string $table The database table to be checked against.
1893 * @param string $newfield the field to set.
1894 * @param string $newvalue the value to set the field to.
1895 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1896 * @return bool true
1897 * @throws dml_exception A DML specific exception is thrown for any errors.
1899 public function set_field($table, $newfield, $newvalue, array $conditions=null) {
1900 list($select, $params) = $this->where_clause($table, $conditions);
1901 return $this->set_field_select($table, $newfield, $newvalue, $select, $params);
1905 * Set a single field in every table record which match a particular WHERE clause.
1907 * @param string $table The database table to be checked against.
1908 * @param string $newfield the field to set.
1909 * @param string $newvalue the value to set the field to.
1910 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1911 * @param array $params array of sql parameters
1912 * @return bool true
1913 * @throws dml_exception A DML specific exception is thrown for any errors.
1915 public abstract function set_field_select($table, $newfield, $newvalue, $select, array $params=null);
1919 * Count the records in a table where all the given conditions met.
1921 * @param string $table The table to query.
1922 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1923 * @return int The count of records returned from the specified criteria.
1924 * @throws dml_exception A DML specific exception is thrown for any errors.
1926 public function count_records($table, array $conditions=null) {
1927 list($select, $params) = $this->where_clause($table, $conditions);
1928 return $this->count_records_select($table, $select, $params);
1932 * Count the records in a table which match a particular WHERE clause.
1934 * @param string $table The database table to be checked against.
1935 * @param string $select A fragment of SQL to be used in a WHERE clause in the SQL call.
1936 * @param array $params array of sql parameters
1937 * @param string $countitem The count string to be used in the SQL call. Default is COUNT('x').
1938 * @return int The count of records returned from the specified criteria.
1939 * @throws dml_exception A DML specific exception is thrown for any errors.
1941 public function count_records_select($table, $select, array $params=null, $countitem="COUNT('x')") {
1942 if ($select) {
1943 $select = "WHERE $select";
1945 return $this->count_records_sql("SELECT $countitem FROM {" . $table . "} $select", $params);
1949 * Get the result of a SQL SELECT COUNT(...) query.
1951 * Given a query that counts rows, return that count. (In fact,
1952 * given any query, return the first field of the first record
1953 * returned. However, this method should only be used for the
1954 * intended purpose.) If an error occurs, 0 is returned.
1956 * @param string $sql The SQL string you wish to be executed.
1957 * @param array $params array of sql parameters
1958 * @return int the count
1959 * @throws dml_exception A DML specific exception is thrown for any errors.
1961 public function count_records_sql($sql, array $params=null) {
1962 $count = $this->get_field_sql($sql, $params);
1963 if ($count === false or !is_number($count) or $count < 0) {
1964 throw new coding_exception("count_records_sql() expects the first field to contain non-negative number from COUNT(), '$count' found instead.");
1966 return (int)$count;
1970 * Test whether a record exists in a table where all the given conditions met.
1972 * @param string $table The table to check.
1973 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1974 * @return bool true if a matching record exists, else false.
1975 * @throws dml_exception A DML specific exception is thrown for any errors.
1977 public function record_exists($table, array $conditions) {
1978 list($select, $params) = $this->where_clause($table, $conditions);
1979 return $this->record_exists_select($table, $select, $params);
1983 * Test whether any records exists in a table which match a particular WHERE clause.
1985 * @param string $table The database table to be checked against.
1986 * @param string $select A fragment of SQL to be used in a WHERE clause in the SQL call.
1987 * @param array $params array of sql parameters
1988 * @return bool true if a matching record exists, else false.
1989 * @throws dml_exception A DML specific exception is thrown for any errors.
1991 public function record_exists_select($table, $select, array $params=null) {
1992 if ($select) {
1993 $select = "WHERE $select";
1995 return $this->record_exists_sql("SELECT 'x' FROM {" . $table . "} $select", $params);
1999 * Test whether a SQL SELECT statement returns any records.
2001 * This function returns true if the SQL statement executes
2002 * without any errors and returns at least one record.
2004 * @param string $sql The SQL statement to execute.
2005 * @param array $params array of sql parameters
2006 * @return bool true if the SQL executes without errors and returns at least one record.
2007 * @throws dml_exception A DML specific exception is thrown for any errors.
2009 public function record_exists_sql($sql, array $params=null) {
2010 $mrs = $this->get_recordset_sql($sql, $params, 0, 1);
2011 $return = $mrs->valid();
2012 $mrs->close();
2013 return $return;
2017 * Delete the records from a table where all the given conditions met.
2018 * If conditions not specified, table is truncated.
2020 * @param string $table the table to delete from.
2021 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
2022 * @return bool true.
2023 * @throws dml_exception A DML specific exception is thrown for any errors.
2025 public function delete_records($table, array $conditions=null) {
2026 // truncate is drop/create (DDL), not transactional safe,
2027 // so we don't use the shortcut within them. MDL-29198
2028 if (is_null($conditions) && empty($this->transactions)) {
2029 return $this->execute("TRUNCATE TABLE {".$table."}");
2031 list($select, $params) = $this->where_clause($table, $conditions);
2032 return $this->delete_records_select($table, $select, $params);
2036 * Delete the records from a table where one field match one list of values.
2038 * @param string $table the table to delete from.
2039 * @param string $field The field to search
2040 * @param array $values array of values
2041 * @return bool true.
2042 * @throws dml_exception A DML specific exception is thrown for any errors.
2044 public function delete_records_list($table, $field, array $values) {
2045 list($select, $params) = $this->where_clause_list($field, $values);
2046 return $this->delete_records_select($table, $select, $params);
2050 * Deletes records from a table using a subquery. The subquery should return a list of values
2051 * in a single column, which match one field from the table being deleted.
2053 * The $alias parameter must be set to the name of the single column in your subquery result
2054 * (e.g. if the subquery is 'SELECT id FROM whatever', then it should be 'id'). This is not
2055 * needed on most databases, but MySQL requires it.
2057 * (On database where the subquery is inefficient, it is implemented differently.)
2059 * @param string $table Table to delete from
2060 * @param string $field Field in table to match
2061 * @param string $alias Name of single column in subquery e.g. 'id'
2062 * @param string $subquery Subquery that will return values of the field to delete
2063 * @param array $params Parameters for subquery
2064 * @throws dml_exception If there is any error
2065 * @since Moodle 3.10
2067 public function delete_records_subquery(string $table, string $field, string $alias,
2068 string $subquery, array $params = []): void {
2069 $this->delete_records_select($table, $field . ' IN (' . $subquery . ')', $params);
2073 * Delete one or more records from a table which match a particular WHERE clause.
2075 * @param string $table The database table to be checked against.
2076 * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
2077 * @param array $params array of sql parameters
2078 * @return bool true.
2079 * @throws dml_exception A DML specific exception is thrown for any errors.
2081 public abstract function delete_records_select($table, $select, array $params=null);
2084 * Returns the FROM clause required by some DBs in all SELECT statements.
2086 * To be used in queries not having FROM clause to provide cross_db
2087 * Most DBs don't need it, hence the default is ''
2088 * @return string
2090 public function sql_null_from_clause() {
2091 return '';
2095 * Returns the SQL text to be used in order to perform one bitwise AND operation
2096 * between 2 integers.
2098 * NOTE: The SQL result is a number and can not be used directly in
2099 * SQL condition, please compare it to some number to get a bool!!
2101 * @param int $int1 First integer in the operation.
2102 * @param int $int2 Second integer in the operation.
2103 * @return string The piece of SQL code to be used in your statement.
2105 public function sql_bitand($int1, $int2) {
2106 return '((' . $int1 . ') & (' . $int2 . '))';
2110 * Returns the SQL text to be used in order to perform one bitwise NOT operation
2111 * with 1 integer.
2113 * @param int $int1 The operand integer in the operation.
2114 * @return string The piece of SQL code to be used in your statement.
2116 public function sql_bitnot($int1) {
2117 return '(~(' . $int1 . '))';
2121 * Returns the SQL text to be used in order to perform one bitwise OR operation
2122 * between 2 integers.
2124 * NOTE: The SQL result is a number and can not be used directly in
2125 * SQL condition, please compare it to some number to get a bool!!
2127 * @param int $int1 The first operand integer in the operation.
2128 * @param int $int2 The second operand integer in the operation.
2129 * @return string The piece of SQL code to be used in your statement.
2131 public function sql_bitor($int1, $int2) {
2132 return '((' . $int1 . ') | (' . $int2 . '))';
2136 * Returns the SQL text to be used in order to perform one bitwise XOR operation
2137 * between 2 integers.
2139 * NOTE: The SQL result is a number and can not be used directly in
2140 * SQL condition, please compare it to some number to get a bool!!
2142 * @param int $int1 The first operand integer in the operation.
2143 * @param int $int2 The second operand integer in the operation.
2144 * @return string The piece of SQL code to be used in your statement.
2146 public function sql_bitxor($int1, $int2) {
2147 return '((' . $int1 . ') ^ (' . $int2 . '))';
2151 * Returns the SQL text to be used in order to perform module '%'
2152 * operation - remainder after division
2154 * @param int $int1 The first operand integer in the operation.
2155 * @param int $int2 The second operand integer in the operation.
2156 * @return string The piece of SQL code to be used in your statement.
2158 public function sql_modulo($int1, $int2) {
2159 return '((' . $int1 . ') % (' . $int2 . '))';
2163 * Returns the cross db correct CEIL (ceiling) expression applied to fieldname.
2164 * note: Most DBs use CEIL(), hence it's the default here.
2166 * @param string $fieldname The field (or expression) we are going to ceil.
2167 * @return string The piece of SQL code to be used in your ceiling statement.
2169 public function sql_ceil($fieldname) {
2170 return ' CEIL(' . $fieldname . ')';
2174 * Return SQL for casting to char of given field/expression. Default implementation performs implicit cast using
2175 * concatenation with an empty string
2177 * @param string $field Table field or SQL expression to be cast
2178 * @return string
2180 public function sql_cast_to_char(string $field): string {
2181 return $this->sql_concat("''", $field);
2185 * Returns the SQL to be used in order to CAST one CHAR column to INTEGER.
2187 * Be aware that the CHAR column you're trying to cast contains really
2188 * int values or the RDBMS will throw an error!
2190 * @param string $fieldname The name of the field to be casted.
2191 * @param bool $text Specifies if the original column is one TEXT (CLOB) column (true). Defaults to false.
2192 * @return string The piece of SQL code to be used in your statement.
2194 public function sql_cast_char2int($fieldname, $text=false) {
2195 return ' ' . $fieldname . ' ';
2199 * Returns the SQL to be used in order to CAST one CHAR column to REAL number.
2201 * Be aware that the CHAR column you're trying to cast contains really
2202 * numbers or the RDBMS will throw an error!
2204 * @param string $fieldname The name of the field to be casted.
2205 * @param bool $text Specifies if the original column is one TEXT (CLOB) column (true). Defaults to false.
2206 * @return string The piece of SQL code to be used in your statement.
2208 public function sql_cast_char2real($fieldname, $text=false) {
2209 return ' ' . $fieldname . ' ';
2213 * Returns the SQL to be used in order to an UNSIGNED INTEGER column to SIGNED.
2215 * (Only MySQL needs this. MySQL things that 1 * -1 = 18446744073709551615
2216 * if the 1 comes from an unsigned column).
2218 * @deprecated since 2.3
2219 * @param string $fieldname The name of the field to be cast
2220 * @return string The piece of SQL code to be used in your statement.
2222 public function sql_cast_2signed($fieldname) {
2223 return ' ' . $fieldname . ' ';
2227 * Returns the SQL text to be used to compare one TEXT (clob) column with
2228 * one varchar column, because some RDBMS doesn't support such direct
2229 * comparisons.
2231 * @param string $fieldname The name of the TEXT field we need to order by
2232 * @param int $numchars Number of chars to use for the ordering (defaults to 32).
2233 * @return string The piece of SQL code to be used in your statement.
2235 public function sql_compare_text($fieldname, $numchars=32) {
2236 return $this->sql_order_by_text($fieldname, $numchars);
2240 * Returns an equal (=) or not equal (<>) part of a query.
2242 * Note the use of this method may lead to slower queries (full scans) so
2243 * use it only when needed and against already reduced data sets.
2245 * @since Moodle 3.2
2247 * @param string $fieldname Usually the name of the table column.
2248 * @param string $param Usually the bound query parameter (?, :named).
2249 * @param bool $casesensitive Use case sensitive search when set to true (default).
2250 * @param bool $accentsensitive Use accent sensitive search when set to true (default). (not all databases support accent insensitive)
2251 * @param bool $notequal True means not equal (<>)
2252 * @return string The SQL code fragment.
2254 public function sql_equal($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notequal = false) {
2255 // Note that, by default, it's assumed that the correct sql equal operations are
2256 // case sensitive. Only databases not observing this behavior must override the method.
2257 // Also, accent sensitiveness only will be handled by databases supporting it.
2258 $equalop = $notequal ? '<>' : '=';
2259 if ($casesensitive) {
2260 return "$fieldname $equalop $param";
2261 } else {
2262 return "LOWER($fieldname) $equalop LOWER($param)";
2267 * Returns 'LIKE' part of a query.
2269 * @param string $fieldname Usually the name of the table column.
2270 * @param string $param Usually the bound query parameter (?, :named).
2271 * @param bool $casesensitive Use case sensitive search when set to true (default).
2272 * @param bool $accentsensitive Use accent sensitive search when set to true (default). (not all databases support accent insensitive)
2273 * @param bool $notlike True means "NOT LIKE".
2274 * @param string $escapechar The escape char for '%' and '_'.
2275 * @return string The SQL code fragment.
2277 public function sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = '\\') {
2278 if (strpos($param, '%') !== false) {
2279 debugging('Potential SQL injection detected, sql_like() expects bound parameters (? or :named)');
2281 $LIKE = $notlike ? 'NOT LIKE' : 'LIKE';
2282 // by default ignore any sensitiveness - each database does it in a different way
2283 return "$fieldname $LIKE $param ESCAPE '$escapechar'";
2287 * Escape sql LIKE special characters like '_' or '%'.
2288 * @param string $text The string containing characters needing escaping.
2289 * @param string $escapechar The desired escape character, defaults to '\\'.
2290 * @return string The escaped sql LIKE string.
2292 public function sql_like_escape($text, $escapechar = '\\') {
2293 $text = str_replace('_', $escapechar.'_', $text);
2294 $text = str_replace('%', $escapechar.'%', $text);
2295 return $text;
2299 * Returns the proper SQL to do CONCAT between the elements(fieldnames) passed.
2301 * This function accepts variable number of string parameters.
2302 * All strings/fieldnames will used in the SQL concatenate statement generated.
2304 * @return string The SQL to concatenate strings passed in.
2305 * @uses func_get_args() and thus parameters are unlimited OPTIONAL number of additional field names.
2307 public abstract function sql_concat();
2310 * Returns the proper SQL to do CONCAT between the elements passed
2311 * with a given separator
2313 * @param string $separator The separator desired for the SQL concatenating $elements.
2314 * @param array $elements The array of strings to be concatenated.
2315 * @return string The SQL to concatenate the strings.
2317 public abstract function sql_concat_join($separator="' '", $elements=array());
2320 * Return SQL for performing group concatenation on given field/expression
2322 * @param string $field Table field or SQL expression to be concatenated
2323 * @param string $separator The separator desired between each concatetated field
2324 * @param string $sort Ordering of the concatenated field
2325 * @return string
2327 public abstract function sql_group_concat(string $field, string $separator = ', ', string $sort = ''): string;
2330 * Returns the proper SQL (for the dbms in use) to concatenate $firstname and $lastname
2332 * @todo MDL-31233 This may not be needed here.
2334 * @param string $first User's first name (default:'firstname').
2335 * @param string $last User's last name (default:'lastname').
2336 * @return string The SQL to concatenate strings.
2338 function sql_fullname($first='firstname', $last='lastname') {
2339 return $this->sql_concat($first, "' '", $last);
2343 * Returns the SQL text to be used to order by one TEXT (clob) column, because
2344 * some RDBMS doesn't support direct ordering of such fields.
2346 * Note that the use or queries being ordered by TEXT columns must be minimised,
2347 * because it's really slooooooow.
2349 * @param string $fieldname The name of the TEXT field we need to order by.
2350 * @param int $numchars The number of chars to use for the ordering (defaults to 32).
2351 * @return string The piece of SQL code to be used in your statement.
2353 public function sql_order_by_text($fieldname, $numchars=32) {
2354 return $fieldname;
2358 * Returns the SQL text to be used to order by columns, standardising the return
2359 * pattern of null values across database types to sort nulls first when ascending
2360 * and last when descending.
2362 * @param string $fieldname The name of the field we need to sort by.
2363 * @param int $sort An order to sort the results in.
2364 * @return string The piece of SQL code to be used in your statement.
2366 public function sql_order_by_null(string $fieldname, int $sort = SORT_ASC): string {
2367 return $fieldname . ' ' . ($sort == SORT_ASC ? 'ASC' : 'DESC');
2371 * Returns the SQL text to be used to calculate the length in characters of one expression.
2372 * @param string $fieldname The fieldname/expression to calculate its length in characters.
2373 * @return string the piece of SQL code to be used in the statement.
2375 public function sql_length($fieldname) {
2376 return ' LENGTH(' . $fieldname . ')';
2380 * Returns the proper substr() SQL text used to extract substrings from DB
2381 * NOTE: this was originally returning only function name
2383 * @param string $expr Some string field, no aggregates.
2384 * @param mixed $start Integer or expression evaluating to integer (1 based value; first char has index 1)
2385 * @param mixed $length Optional integer or expression evaluating to integer.
2386 * @return string The sql substring extraction fragment.
2388 public function sql_substr($expr, $start, $length=false) {
2389 if (count(func_get_args()) < 2) {
2390 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.');
2392 if ($length === false) {
2393 return "SUBSTR($expr, $start)";
2394 } else {
2395 return "SUBSTR($expr, $start, $length)";
2400 * Returns the SQL for returning searching one string for the location of another.
2402 * Note, there is no guarantee which order $needle, $haystack will be in
2403 * the resulting SQL so when using this method, and both arguments contain
2404 * placeholders, you should use named placeholders.
2406 * @param string $needle the SQL expression that will be searched for.
2407 * @param string $haystack the SQL expression that will be searched in.
2408 * @return string The required searching SQL part.
2410 public function sql_position($needle, $haystack) {
2411 // Implementation using standard SQL.
2412 return "POSITION(($needle) IN ($haystack))";
2416 * This used to return empty string replacement character.
2418 * @deprecated use bound parameter with empty string instead
2420 * @return string An empty string.
2422 function sql_empty() {
2423 debugging("sql_empty() is deprecated, please use empty string '' as sql parameter value instead", DEBUG_DEVELOPER);
2424 return '';
2428 * Returns the proper SQL to know if one field is empty.
2430 * Note that the function behavior strongly relies on the
2431 * parameters passed describing the field so, please, be accurate
2432 * when specifying them.
2434 * Also, note that this function is not suitable to look for
2435 * fields having NULL contents at all. It's all for empty values!
2437 * This function should be applied in all the places where conditions of
2438 * the type:
2440 * ... AND fieldname = '';
2442 * are being used. Final result for text fields should be:
2444 * ... AND ' . sql_isempty('tablename', 'fieldname', true/false, true);
2446 * and for varchar fields result should be:
2448 * ... AND fieldname = :empty; "; $params['empty'] = '';
2450 * (see parameters description below)
2452 * @param string $tablename Name of the table (without prefix). Not used for now but can be
2453 * necessary in the future if we want to use some introspection using
2454 * meta information against the DB. /// TODO ///
2455 * @param string $fieldname Name of the field we are going to check
2456 * @param bool $nullablefield For specifying if the field is nullable (true) or no (false) in the DB.
2457 * @param bool $textfield For specifying if it is a text (also called clob) field (true) or a varchar one (false)
2458 * @return string the sql code to be added to check for empty values
2460 public function sql_isempty($tablename, $fieldname, $nullablefield, $textfield) {
2461 return " ($fieldname = '') ";
2465 * Returns the proper SQL to know if one field is not empty.
2467 * Note that the function behavior strongly relies on the
2468 * parameters passed describing the field so, please, be accurate
2469 * when specifying them.
2471 * This function should be applied in all the places where conditions of
2472 * the type:
2474 * ... AND fieldname != '';
2476 * are being used. Final result for text fields should be:
2478 * ... AND ' . sql_isnotempty('tablename', 'fieldname', true/false, true/false);
2480 * and for varchar fields result should be:
2482 * ... AND fieldname != :empty; "; $params['empty'] = '';
2484 * (see parameters description below)
2486 * @param string $tablename Name of the table (without prefix). This is not used for now but can be
2487 * necessary in the future if we want to use some introspection using
2488 * meta information against the DB.
2489 * @param string $fieldname The name of the field we are going to check.
2490 * @param bool $nullablefield Specifies if the field is nullable (true) or not (false) in the DB.
2491 * @param bool $textfield Specifies if it is a text (also called clob) field (true) or a varchar one (false).
2492 * @return string The sql code to be added to check for non empty values.
2494 public function sql_isnotempty($tablename, $fieldname, $nullablefield, $textfield) {
2495 return ' ( NOT ' . $this->sql_isempty($tablename, $fieldname, $nullablefield, $textfield) . ') ';
2499 * Returns true if this database driver supports regex syntax when searching.
2500 * @return bool True if supported.
2502 public function sql_regex_supported() {
2503 return false;
2507 * Returns the driver specific syntax (SQL part) for matching regex positively or negatively (inverted matching).
2508 * Eg: 'REGEXP':'NOT REGEXP' or '~*' : '!~*'
2510 * @param bool $positivematch
2511 * @param bool $casesensitive
2512 * @return string or empty if not supported
2514 public function sql_regex($positivematch = true, $casesensitive = false) {
2515 return '';
2519 * Returns the word-beginning boundary marker if this database driver supports regex syntax when searching.
2520 * @return string The word-beginning boundary marker. Otherwise, an empty string.
2522 public function sql_regex_get_word_beginning_boundary_marker() {
2523 if ($this->sql_regex_supported()) {
2524 return '[[:<:]]';
2527 return '';
2531 * Returns the word-end boundary marker if this database driver supports regex syntax when searching.
2532 * @return string The word-end boundary marker. Otherwise, an empty string.
2534 public function sql_regex_get_word_end_boundary_marker() {
2535 if ($this->sql_regex_supported()) {
2536 return '[[:>:]]';
2539 return '';
2543 * Returns the SQL that allows to find intersection of two or more queries
2545 * @since Moodle 2.8
2547 * @param array $selects array of SQL select queries, each of them only returns fields with the names from $fields
2548 * @param string $fields comma-separated list of fields (used only by some DB engines)
2549 * @return string SQL query that will return only values that are present in each of selects
2551 public function sql_intersect($selects, $fields) {
2552 if (!count($selects)) {
2553 throw new coding_exception('sql_intersect() requires at least one element in $selects');
2554 } else if (count($selects) == 1) {
2555 return $selects[0];
2557 static $aliascnt = 0;
2558 $rv = '('.$selects[0].')';
2559 for ($i = 1; $i < count($selects); $i++) {
2560 $rv .= " INTERSECT (".$selects[$i].')';
2562 return $rv;
2566 * Does this driver support tool_replace?
2568 * @since Moodle 2.6.1
2569 * @return bool
2571 public function replace_all_text_supported() {
2572 return false;
2576 * Replace given text in all rows of column.
2578 * @since Moodle 2.6.1
2579 * @param string $table name of the table
2580 * @param database_column_info $column
2581 * @param string $search
2582 * @param string $replace
2584 public function replace_all_text($table, database_column_info $column, $search, $replace) {
2585 if (!$this->replace_all_text_supported()) {
2586 return;
2589 // NOTE: override this methods if following standard compliant SQL
2590 // does not work for your driver.
2592 // Enclose the column name by the proper quotes if it's a reserved word.
2593 $columnname = $this->get_manager()->generator->getEncQuoted($column->name);
2595 $searchsql = $this->sql_like($columnname, '?');
2596 $searchparam = '%'.$this->sql_like_escape($search).'%';
2598 $sql = "UPDATE {".$table."}
2599 SET $columnname = REPLACE($columnname, ?, ?)
2600 WHERE $searchsql";
2602 if ($column->meta_type === 'X') {
2603 $this->execute($sql, array($search, $replace, $searchparam));
2605 } else if ($column->meta_type === 'C') {
2606 if (core_text::strlen($search) < core_text::strlen($replace)) {
2607 $colsize = $column->max_length;
2608 $sql = "UPDATE {".$table."}
2609 SET $columnname = " . $this->sql_substr("REPLACE(" . $columnname . ", ?, ?)", 1, $colsize) . "
2610 WHERE $searchsql";
2612 $this->execute($sql, array($search, $replace, $searchparam));
2617 * Analyze the data in temporary tables to force statistics collection after bulk data loads.
2619 * @return void
2621 public function update_temp_table_stats() {
2622 $this->temptables->update_stats();
2626 * Checks and returns true if transactions are supported.
2628 * It is not responsible to run productions servers
2629 * on databases without transaction support ;-)
2631 * Override in driver if needed.
2633 * @return bool
2635 protected function transactions_supported() {
2636 // protected for now, this might be changed to public if really necessary
2637 return true;
2641 * Returns true if a transaction is in progress.
2642 * @return bool
2644 public function is_transaction_started() {
2645 return !empty($this->transactions);
2649 * This is a test that throws an exception if transaction in progress.
2650 * This test does not force rollback of active transactions.
2651 * @return void
2652 * @throws dml_transaction_exception if stansaction active
2654 public function transactions_forbidden() {
2655 if ($this->is_transaction_started()) {
2656 throw new dml_transaction_exception('This code can not be excecuted in transaction');
2661 * On DBs that support it, switch to transaction mode and begin a transaction
2662 * you'll need to ensure you call allow_commit() on the returned object
2663 * or your changes *will* be lost.
2665 * this is _very_ useful for massive updates
2667 * Delegated database transactions can be nested, but only one actual database
2668 * transaction is used for the outer-most delegated transaction. This method
2669 * returns a transaction object which you should keep until the end of the
2670 * delegated transaction. The actual database transaction will
2671 * only be committed if all the nested delegated transactions commit
2672 * successfully. If any part of the transaction rolls back then the whole
2673 * thing is rolled back.
2675 * @return moodle_transaction
2677 public function start_delegated_transaction() {
2678 $transaction = new moodle_transaction($this);
2679 $this->transactions[] = $transaction;
2680 if (count($this->transactions) == 1) {
2681 $this->begin_transaction();
2683 return $transaction;
2687 * Driver specific start of real database transaction,
2688 * this can not be used directly in code.
2689 * @return void
2691 protected abstract function begin_transaction();
2694 * Indicates delegated transaction finished successfully.
2695 * The real database transaction is committed only if
2696 * all delegated transactions committed.
2697 * @param moodle_transaction $transaction The transaction to commit
2698 * @return void
2699 * @throws dml_transaction_exception Creates and throws transaction related exceptions.
2701 public function commit_delegated_transaction(moodle_transaction $transaction) {
2702 if ($transaction->is_disposed()) {
2703 throw new dml_transaction_exception('Transactions already disposed', $transaction);
2705 // mark as disposed so that it can not be used again
2706 $transaction->dispose();
2708 if (empty($this->transactions)) {
2709 throw new dml_transaction_exception('Transaction not started', $transaction);
2712 if ($this->force_rollback) {
2713 throw new dml_transaction_exception('Tried to commit transaction after lower level rollback', $transaction);
2716 if ($transaction !== $this->transactions[count($this->transactions) - 1]) {
2717 // one incorrect commit at any level rollbacks everything
2718 $this->force_rollback = true;
2719 throw new dml_transaction_exception('Invalid transaction commit attempt', $transaction);
2722 if (count($this->transactions) == 1) {
2723 // only commit the top most level
2724 $this->commit_transaction();
2726 array_pop($this->transactions);
2728 if (empty($this->transactions)) {
2729 \core\event\manager::database_transaction_commited();
2730 \core\message\manager::database_transaction_commited();
2735 * Driver specific commit of real database transaction,
2736 * this can not be used directly in code.
2737 * @return void
2739 protected abstract function commit_transaction();
2742 * Call when delegated transaction failed, this rolls back
2743 * all delegated transactions up to the top most level.
2745 * In many cases you do not need to call this method manually,
2746 * because all open delegated transactions are rolled back
2747 * automatically if exceptions not caught.
2749 * @param moodle_transaction $transaction An instance of a moodle_transaction.
2750 * @param Exception|Throwable $e The related exception/throwable to this transaction rollback.
2751 * @return void This does not return, instead the exception passed in will be rethrown.
2753 public function rollback_delegated_transaction(moodle_transaction $transaction, $e) {
2754 if (!($e instanceof Exception) && !($e instanceof Throwable)) {
2755 // PHP7 - we catch Throwables in phpunit but can't use that as the type hint in PHP5.
2756 $e = new \coding_exception("Must be given an Exception or Throwable object!");
2758 if ($transaction->is_disposed()) {
2759 throw new dml_transaction_exception('Transactions already disposed', $transaction);
2761 // mark as disposed so that it can not be used again
2762 $transaction->dispose();
2764 // one rollback at any level rollbacks everything
2765 $this->force_rollback = true;
2767 if (empty($this->transactions) or $transaction !== $this->transactions[count($this->transactions) - 1]) {
2768 // this may or may not be a coding problem, better just rethrow the exception,
2769 // because we do not want to loose the original $e
2770 throw $e;
2773 if (count($this->transactions) == 1) {
2774 // only rollback the top most level
2775 $this->rollback_transaction();
2777 array_pop($this->transactions);
2778 if (empty($this->transactions)) {
2779 // finally top most level rolled back
2780 $this->force_rollback = false;
2781 \core\event\manager::database_transaction_rolledback();
2782 \core\message\manager::database_transaction_rolledback();
2784 throw $e;
2788 * Driver specific abort of real database transaction,
2789 * this can not be used directly in code.
2790 * @return void
2792 protected abstract function rollback_transaction();
2795 * Force rollback of all delegated transaction.
2796 * Does not throw any exceptions and does not log anything.
2798 * This method should be used only from default exception handlers and other
2799 * core code.
2801 * @return void
2803 public function force_transaction_rollback() {
2804 if ($this->transactions) {
2805 try {
2806 $this->rollback_transaction();
2807 } catch (dml_exception $e) {
2808 // ignore any sql errors here, the connection might be broken
2812 // now enable transactions again
2813 $this->transactions = array();
2814 $this->force_rollback = false;
2816 \core\event\manager::database_transaction_rolledback();
2817 \core\message\manager::database_transaction_rolledback();
2821 * Is session lock supported in this driver?
2822 * @return bool
2824 public function session_lock_supported() {
2825 return false;
2829 * Obtains the session lock.
2830 * @param int $rowid The id of the row with session record.
2831 * @param int $timeout The maximum allowed time to wait for the lock in seconds.
2832 * @return void
2833 * @throws dml_exception A DML specific exception is thrown for any errors.
2835 public function get_session_lock($rowid, $timeout) {
2836 $this->used_for_db_sessions = true;
2840 * Releases the session lock.
2841 * @param int $rowid The id of the row with session record.
2842 * @return void
2843 * @throws dml_exception A DML specific exception is thrown for any errors.
2845 public function release_session_lock($rowid) {
2849 * Returns the number of reads done by this database.
2850 * @return int Number of reads.
2852 public function perf_get_reads() {
2853 return $this->reads;
2857 * Returns whether we want to connect to slave database for read queries.
2858 * @return bool Want read only connection
2860 public function want_read_slave(): bool {
2861 return false;
2865 * Returns the number of reads before first write done by this database.
2866 * @return int Number of reads.
2868 public function perf_get_reads_slave(): int {
2869 return 0;
2873 * Returns the number of writes done by this database.
2874 * @return int Number of writes.
2876 public function perf_get_writes() {
2877 return $this->writes;
2881 * Returns the number of queries done by this database.
2882 * @return int Number of queries.
2884 public function perf_get_queries() {
2885 return $this->writes + $this->reads;
2889 * Time waiting for the database engine to finish running all queries.
2890 * @return float Number of seconds with microseconds
2892 public function perf_get_queries_time() {
2893 return $this->queriestime;
2897 * Whether the database is able to support full-text search or not.
2899 * @return bool
2901 public function is_fulltext_search_supported() {
2902 // No support unless specified.
2903 return false;