Merge branch 'MDL-64012' of https://github.com/timhunt/moodle
[moodle.git] / lib / dml / moodle_database.php
blob9e781cd8952099397acc7302be7619e455774435
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 /**
56 * Abstract class representing moodle database interface.
57 * @link http://docs.moodle.org/dev/DML_functions
59 * @package core_dml
60 * @copyright 2008 Petr Skoda (http://skodak.org)
61 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
63 abstract class moodle_database {
65 /** @var database_manager db manager which allows db structure modifications. */
66 protected $database_manager;
67 /** @var moodle_temptables temptables manager to provide cross-db support for temp tables. */
68 protected $temptables;
69 /** @var array Cache of table info. */
70 protected $tables = null;
72 // db connection options
73 /** @var string db host name. */
74 protected $dbhost;
75 /** @var string db host user. */
76 protected $dbuser;
77 /** @var string db host password. */
78 protected $dbpass;
79 /** @var string db name. */
80 protected $dbname;
81 /** @var string Prefix added to table names. */
82 protected $prefix;
84 /** @var array Database or driver specific options, such as sockets or TCP/IP db connections. */
85 protected $dboptions;
87 /** @var bool True means non-moodle external database used.*/
88 protected $external;
90 /** @var int The database reads (performance counter).*/
91 protected $reads = 0;
92 /** @var int The database writes (performance counter).*/
93 protected $writes = 0;
94 /** @var float Time queries took to finish, seconds with microseconds.*/
95 protected $queriestime = 0;
97 /** @var int Debug level. */
98 protected $debug = 0;
100 /** @var string Last used query sql. */
101 protected $last_sql;
102 /** @var array Last query parameters. */
103 protected $last_params;
104 /** @var int Last query type. */
105 protected $last_type;
106 /** @var string Last extra info. */
107 protected $last_extrainfo;
108 /** @var float Last time in seconds with millisecond precision. */
109 protected $last_time;
110 /** @var bool Flag indicating logging of query in progress. This helps prevent infinite loops. */
111 private $loggingquery = false;
113 /** @var bool True if the db is used for db sessions. */
114 protected $used_for_db_sessions = false;
116 /** @var array Array containing open transactions. */
117 private $transactions = array();
118 /** @var bool Flag used to force rollback of all current transactions. */
119 private $force_rollback = false;
121 /** @var string MD5 of settings used for connection. Used by MUC as an identifier. */
122 private $settingshash;
124 /** @var cache_application for column info */
125 protected $metacache;
127 /** @var cache_request for column info on temp tables */
128 protected $metacachetemp;
130 /** @var bool flag marking database instance as disposed */
131 protected $disposed;
134 * @var int internal temporary variable used to fix params. Its used by {@link _fix_sql_params_dollar_callback()}.
136 private $fix_sql_params_i;
138 * @var int internal temporary variable used to guarantee unique parameters in each request. Its used by {@link get_in_or_equal()}.
140 private $inorequaluniqueindex = 1;
143 * @var boolean variable use to temporarily disable logging.
145 protected $skiplogging = false;
148 * Constructor - Instantiates the database, specifying if it's external (connect to other systems) or not (Moodle DB).
149 * Note that this affects the decision of whether prefix checks must be performed or not.
150 * @param bool $external True means that an external database is used.
152 public function __construct($external=false) {
153 $this->external = $external;
157 * Destructor - cleans up and flushes everything needed.
159 public function __destruct() {
160 $this->dispose();
164 * Detects if all needed PHP stuff are installed for DB connectivity.
165 * Note: can be used before connect()
166 * @return mixed True if requirements are met, otherwise a string if something isn't installed.
168 public abstract function driver_installed();
171 * Returns database table prefix
172 * Note: can be used before connect()
173 * @return string The prefix used in the database.
175 public function get_prefix() {
176 return $this->prefix;
180 * Loads and returns a database instance with the specified type and library.
182 * The loaded class is within lib/dml directory and of the form: $type.'_'.$library.'_moodle_database'
184 * @param string $type Database driver's type. (eg: mysqli, pgsql, mssql, sqldrv, oci, etc.)
185 * @param string $library Database driver's library (native, pdo, etc.)
186 * @param bool $external True if this is an external database.
187 * @return moodle_database driver object or null if error, for example of driver object see {@link mysqli_native_moodle_database}
189 public static function get_driver_instance($type, $library, $external = false) {
190 global $CFG;
192 $classname = $type.'_'.$library.'_moodle_database';
193 $libfile = "$CFG->libdir/dml/$classname.php";
195 if (!file_exists($libfile)) {
196 return null;
199 require_once($libfile);
200 return new $classname($external);
204 * Returns the database vendor.
205 * Note: can be used before connect()
206 * @return string The db vendor name, usually the same as db family name.
208 public function get_dbvendor() {
209 return $this->get_dbfamily();
213 * Returns the database family type. (This sort of describes the SQL 'dialect')
214 * Note: can be used before connect()
215 * @return string The db family name (mysql, postgres, mssql, oracle, etc.)
217 public abstract function get_dbfamily();
220 * Returns a more specific database driver type
221 * Note: can be used before connect()
222 * @return string The db type mysqli, pgsql, oci, mssql, sqlsrv
224 protected abstract function get_dbtype();
227 * Returns the general database library name
228 * Note: can be used before connect()
229 * @return string The db library type - pdo, native etc.
231 protected abstract function get_dblibrary();
234 * Returns the localised database type name
235 * Note: can be used before connect()
236 * @return string
238 public abstract function get_name();
241 * Returns the localised database configuration help.
242 * Note: can be used before connect()
243 * @return string
245 public abstract function get_configuration_help();
248 * Returns the localised database description
249 * Note: can be used before connect()
250 * @deprecated since 2.6
251 * @return string
253 public function get_configuration_hints() {
254 debugging('$DB->get_configuration_hints() method is deprecated, use $DB->get_configuration_help() instead');
255 return $this->get_configuration_help();
259 * Returns the db related part of config.php
260 * @return stdClass
262 public function export_dbconfig() {
263 $cfg = new stdClass();
264 $cfg->dbtype = $this->get_dbtype();
265 $cfg->dblibrary = $this->get_dblibrary();
266 $cfg->dbhost = $this->dbhost;
267 $cfg->dbname = $this->dbname;
268 $cfg->dbuser = $this->dbuser;
269 $cfg->dbpass = $this->dbpass;
270 $cfg->prefix = $this->prefix;
271 if ($this->dboptions) {
272 $cfg->dboptions = $this->dboptions;
275 return $cfg;
279 * Diagnose database and tables, this function is used
280 * to verify database and driver settings, db engine types, etc.
282 * @return string null means everything ok, string means problem found.
284 public function diagnose() {
285 return null;
289 * Connects to the database.
290 * Must be called before other methods.
291 * @param string $dbhost The database host.
292 * @param string $dbuser The database user to connect as.
293 * @param string $dbpass The password to use when connecting to the database.
294 * @param string $dbname The name of the database being connected to.
295 * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
296 * @param array $dboptions driver specific options
297 * @return bool true
298 * @throws dml_connection_exception if error
300 public abstract function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null);
303 * Store various database settings
304 * @param string $dbhost The database host.
305 * @param string $dbuser The database user to connect as.
306 * @param string $dbpass The password to use when connecting to the database.
307 * @param string $dbname The name of the database being connected to.
308 * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
309 * @param array $dboptions driver specific options
310 * @return void
312 protected function store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null) {
313 $this->dbhost = $dbhost;
314 $this->dbuser = $dbuser;
315 $this->dbpass = $dbpass;
316 $this->dbname = $dbname;
317 $this->prefix = $prefix;
318 $this->dboptions = (array)$dboptions;
322 * Returns a hash for the settings used during connection.
324 * If not already requested it is generated and stored in a private property.
326 * @return string
328 protected function get_settings_hash() {
329 if (empty($this->settingshash)) {
330 $this->settingshash = md5($this->dbhost . $this->dbuser . $this->dbname . $this->prefix);
332 return $this->settingshash;
336 * Handle the creation and caching of the databasemeta information for all databases.
338 * @return cache_application The databasemeta cachestore to complete operations on.
340 protected function get_metacache() {
341 if (!isset($this->metacache)) {
342 $properties = array('dbfamily' => $this->get_dbfamily(), 'settings' => $this->get_settings_hash());
343 $this->metacache = cache::make('core', 'databasemeta', $properties);
345 return $this->metacache;
349 * Handle the creation and caching of the temporary tables.
351 * @return cache_application The temp_tables cachestore to complete operations on.
353 protected function get_temp_tables_cache() {
354 if (!isset($this->metacachetemp)) {
355 // Using connection data to prevent collisions when using the same temp table name with different db connections.
356 $properties = array('dbfamily' => $this->get_dbfamily(), 'settings' => $this->get_settings_hash());
357 $this->metacachetemp = cache::make('core', 'temp_tables', $properties);
359 return $this->metacachetemp;
363 * Attempt to create the database
364 * @param string $dbhost The database host.
365 * @param string $dbuser The database user to connect as.
366 * @param string $dbpass The password to use when connecting to the database.
367 * @param string $dbname The name of the database being connected to.
368 * @param array $dboptions An array of optional database options (eg: dbport)
370 * @return bool success True for successful connection. False otherwise.
372 public function create_database($dbhost, $dbuser, $dbpass, $dbname, array $dboptions=null) {
373 return false;
377 * Returns transaction trace for debugging purposes.
378 * @private to be used by core only
379 * @return array or null if not in transaction.
381 public function get_transaction_start_backtrace() {
382 if (!$this->transactions) {
383 return null;
385 $lowesttransaction = end($this->transactions);
386 return $lowesttransaction->get_backtrace();
390 * Closes the database connection and releases all resources
391 * and memory (especially circular memory references).
392 * Do NOT use connect() again, create a new instance if needed.
393 * @return void
395 public function dispose() {
396 if ($this->disposed) {
397 return;
399 $this->disposed = true;
400 if ($this->transactions) {
401 $this->force_transaction_rollback();
404 if ($this->temptables) {
405 $this->temptables->dispose();
406 $this->temptables = null;
408 if ($this->database_manager) {
409 $this->database_manager->dispose();
410 $this->database_manager = null;
412 $this->tables = null;
416 * This should be called before each db query.
417 * @param string $sql The query string.
418 * @param array $params An array of parameters.
419 * @param int $type The type of query. ( SQL_QUERY_SELECT | SQL_QUERY_AUX | SQL_QUERY_INSERT | SQL_QUERY_UPDATE | SQL_QUERY_STRUCTURE )
420 * @param mixed $extrainfo This is here for any driver specific extra information.
421 * @return void
423 protected function query_start($sql, array $params=null, $type, $extrainfo=null) {
424 if ($this->loggingquery) {
425 return;
427 $this->last_sql = $sql;
428 $this->last_params = $params;
429 $this->last_type = $type;
430 $this->last_extrainfo = $extrainfo;
431 $this->last_time = microtime(true);
433 switch ($type) {
434 case SQL_QUERY_SELECT:
435 case SQL_QUERY_AUX:
436 $this->reads++;
437 break;
438 case SQL_QUERY_INSERT:
439 case SQL_QUERY_UPDATE:
440 case SQL_QUERY_STRUCTURE:
441 $this->writes++;
442 default:
443 if ((PHPUNIT_TEST) || (defined('BEHAT_TEST') && BEHAT_TEST) ||
444 defined('BEHAT_SITE_RUNNING')) {
446 // Set list of tables that are updated.
447 require_once(__DIR__.'/../testing/classes/util.php');
448 testing_util::set_table_modified_by_sql($sql);
452 $this->print_debug($sql, $params);
456 * This should be called immediately after each db query. It does a clean up of resources.
457 * It also throws exceptions if the sql that ran produced errors.
458 * @param mixed $result The db specific result obtained from running a query.
459 * @throws dml_read_exception | dml_write_exception | ddl_change_structure_exception
460 * @return void
462 protected function query_end($result) {
463 if ($this->loggingquery) {
464 return;
466 if ($result !== false) {
467 $this->query_log();
468 // free memory
469 $this->last_sql = null;
470 $this->last_params = null;
471 $this->print_debug_time();
472 return;
475 // remember current info, log queries may alter it
476 $type = $this->last_type;
477 $sql = $this->last_sql;
478 $params = $this->last_params;
479 $error = $this->get_last_error();
481 $this->query_log($error);
483 switch ($type) {
484 case SQL_QUERY_SELECT:
485 case SQL_QUERY_AUX:
486 throw new dml_read_exception($error, $sql, $params);
487 case SQL_QUERY_INSERT:
488 case SQL_QUERY_UPDATE:
489 throw new dml_write_exception($error, $sql, $params);
490 case SQL_QUERY_STRUCTURE:
491 $this->get_manager(); // includes ddl exceptions classes ;-)
492 throw new ddl_change_structure_exception($error, $sql);
497 * This logs the last query based on 'logall', 'logslow' and 'logerrors' options configured via $CFG->dboptions .
498 * @param string|bool $error or false if not error
499 * @return void
501 public function query_log($error=false) {
502 // Logging disabled by the driver.
503 if ($this->skiplogging) {
504 return;
507 $logall = !empty($this->dboptions['logall']);
508 $logslow = !empty($this->dboptions['logslow']) ? $this->dboptions['logslow'] : false;
509 $logerrors = !empty($this->dboptions['logerrors']);
510 $iserror = ($error !== false);
512 $time = $this->query_time();
514 // Will be shown or not depending on MDL_PERF values rather than in dboptions['log*].
515 $this->queriestime = $this->queriestime + $time;
517 if ($logall or ($logslow and ($logslow < ($time+0.00001))) or ($iserror and $logerrors)) {
518 $this->loggingquery = true;
519 try {
520 $backtrace = debug_backtrace();
521 if ($backtrace) {
522 //remove query_log()
523 array_shift($backtrace);
525 if ($backtrace) {
526 //remove query_end()
527 array_shift($backtrace);
529 $log = new stdClass();
530 $log->qtype = $this->last_type;
531 $log->sqltext = $this->last_sql;
532 $log->sqlparams = var_export((array)$this->last_params, true);
533 $log->error = (int)$iserror;
534 $log->info = $iserror ? $error : null;
535 $log->backtrace = format_backtrace($backtrace, true);
536 $log->exectime = $time;
537 $log->timelogged = time();
538 $this->insert_record('log_queries', $log);
539 } catch (Exception $ignored) {
541 $this->loggingquery = false;
546 * Disable logging temporarily.
548 protected function query_log_prevent() {
549 $this->skiplogging = true;
553 * Restore old logging behavior.
555 protected function query_log_allow() {
556 $this->skiplogging = false;
560 * Returns the time elapsed since the query started.
561 * @return float Seconds with microseconds
563 protected function query_time() {
564 return microtime(true) - $this->last_time;
568 * Returns database server info array
569 * @return array Array containing 'description' and 'version' at least.
571 public abstract function get_server_info();
574 * Returns supported query parameter types
575 * @return int bitmask of accepted SQL_PARAMS_*
577 protected abstract function allowed_param_types();
580 * Returns the last error reported by the database engine.
581 * @return string The error message.
583 public abstract function get_last_error();
586 * Prints sql debug info
587 * @param string $sql The query which is being debugged.
588 * @param array $params The query parameters. (optional)
589 * @param mixed $obj The library specific object. (optional)
590 * @return void
592 protected function print_debug($sql, array $params=null, $obj=null) {
593 if (!$this->get_debug()) {
594 return;
596 if (CLI_SCRIPT) {
597 $separator = "--------------------------------\n";
598 echo $separator;
599 echo "{$sql}\n";
600 if (!is_null($params)) {
601 echo "[" . var_export($params, true) . "]\n";
603 echo $separator;
604 } else if (AJAX_SCRIPT) {
605 $separator = "--------------------------------";
606 error_log($separator);
607 error_log($sql);
608 if (!is_null($params)) {
609 error_log("[" . var_export($params, true) . "]");
611 error_log($separator);
612 } else {
613 $separator = "<hr />\n";
614 echo $separator;
615 echo s($sql) . "\n";
616 if (!is_null($params)) {
617 echo "[" . s(var_export($params, true)) . "]\n";
619 echo $separator;
624 * Prints the time a query took to run.
625 * @return void
627 protected function print_debug_time() {
628 if (!$this->get_debug()) {
629 return;
631 $time = $this->query_time();
632 $message = "Query took: {$time} seconds.\n";
633 if (CLI_SCRIPT) {
634 echo $message;
635 echo "--------------------------------\n";
636 } else if (AJAX_SCRIPT) {
637 error_log($message);
638 error_log("--------------------------------");
639 } else {
640 echo s($message);
641 echo "<hr />\n";
646 * Returns the SQL WHERE conditions.
647 * @param string $table The table name that these conditions will be validated against.
648 * @param array $conditions The conditions to build the where clause. (must not contain numeric indexes)
649 * @throws dml_exception
650 * @return array An array list containing sql 'where' part and 'params'.
652 protected function where_clause($table, array $conditions=null) {
653 // We accept nulls in conditions
654 $conditions = is_null($conditions) ? array() : $conditions;
656 if (empty($conditions)) {
657 return array('', array());
660 // Some checks performed under debugging only
661 if (debugging()) {
662 $columns = $this->get_columns($table);
663 if (empty($columns)) {
664 // no supported columns means most probably table does not exist
665 throw new dml_exception('ddltablenotexist', $table);
667 foreach ($conditions as $key=>$value) {
668 if (!isset($columns[$key])) {
669 $a = new stdClass();
670 $a->fieldname = $key;
671 $a->tablename = $table;
672 throw new dml_exception('ddlfieldnotexist', $a);
674 $column = $columns[$key];
675 if ($column->meta_type == 'X') {
676 //ok so the column is a text column. sorry no text columns in the where clause conditions
677 throw new dml_exception('textconditionsnotallowed', $conditions);
682 $allowed_types = $this->allowed_param_types();
683 $where = array();
684 $params = array();
686 foreach ($conditions as $key=>$value) {
687 if (is_int($key)) {
688 throw new dml_exception('invalidnumkey');
690 if (is_null($value)) {
691 $where[] = "$key IS NULL";
692 } else {
693 if ($allowed_types & SQL_PARAMS_NAMED) {
694 // Need to verify key names because they can contain, originally,
695 // spaces and other forbidden chars when using sql_xxx() functions and friends.
696 $normkey = trim(preg_replace('/[^a-zA-Z0-9_-]/', '_', $key), '-_');
697 if ($normkey !== $key) {
698 debugging('Invalid key found in the conditions array.');
700 $where[] = "$key = :$normkey";
701 $params[$normkey] = $value;
702 } else {
703 $where[] = "$key = ?";
704 $params[] = $value;
708 $where = implode(" AND ", $where);
709 return array($where, $params);
713 * Returns SQL WHERE conditions for the ..._list group of methods.
715 * @param string $field the name of a field.
716 * @param array $values the values field might take.
717 * @return array An array containing sql 'where' part and 'params'
719 protected function where_clause_list($field, array $values) {
720 if (empty($values)) {
721 return array("1 = 2", array()); // Fake condition, won't return rows ever. MDL-17645
724 // Note: Do not use get_in_or_equal() because it can not deal with bools and nulls.
726 $params = array();
727 $select = "";
728 $values = (array)$values;
729 foreach ($values as $value) {
730 if (is_bool($value)) {
731 $value = (int)$value;
733 if (is_null($value)) {
734 $select = "$field IS NULL";
735 } else {
736 $params[] = $value;
739 if ($params) {
740 if ($select !== "") {
741 $select = "$select OR ";
743 $count = count($params);
744 if ($count == 1) {
745 $select = $select."$field = ?";
746 } else {
747 $qs = str_repeat(',?', $count);
748 $qs = ltrim($qs, ',');
749 $select = $select."$field IN ($qs)";
752 return array($select, $params);
756 * Constructs 'IN()' or '=' sql fragment
757 * @param mixed $items A single value or array of values for the expression.
758 * @param int $type Parameter bounding type : SQL_PARAMS_QM or SQL_PARAMS_NAMED.
759 * @param string $prefix Named parameter placeholder prefix (a unique counter value is appended to each parameter name).
760 * @param bool $equal True means we want to equate to the constructed expression, false means we don't want to equate to it.
761 * @param mixed $onemptyitems This defines the behavior when the array of items provided is empty. Defaults to false,
762 * meaning throw exceptions. Other values will become part of the returned SQL fragment.
763 * @throws coding_exception | dml_exception
764 * @return array A list containing the constructed sql fragment and an array of parameters.
766 public function get_in_or_equal($items, $type=SQL_PARAMS_QM, $prefix='param', $equal=true, $onemptyitems=false) {
768 // default behavior, throw exception on empty array
769 if (is_array($items) and empty($items) and $onemptyitems === false) {
770 throw new coding_exception('moodle_database::get_in_or_equal() does not accept empty arrays');
772 // handle $onemptyitems on empty array of items
773 if (is_array($items) and empty($items)) {
774 if (is_null($onemptyitems)) { // Special case, NULL value
775 $sql = $equal ? ' IS NULL' : ' IS NOT NULL';
776 return (array($sql, array()));
777 } else {
778 $items = array($onemptyitems); // Rest of cases, prepare $items for std processing
782 if ($type == SQL_PARAMS_QM) {
783 if (!is_array($items) or count($items) == 1) {
784 $sql = $equal ? '= ?' : '<> ?';
785 $items = (array)$items;
786 $params = array_values($items);
787 } else {
788 if ($equal) {
789 $sql = 'IN ('.implode(',', array_fill(0, count($items), '?')).')';
790 } else {
791 $sql = 'NOT IN ('.implode(',', array_fill(0, count($items), '?')).')';
793 $params = array_values($items);
796 } else if ($type == SQL_PARAMS_NAMED) {
797 if (empty($prefix)) {
798 $prefix = 'param';
801 if (!is_array($items)){
802 $param = $prefix.$this->inorequaluniqueindex++;
803 $sql = $equal ? "= :$param" : "<> :$param";
804 $params = array($param=>$items);
805 } else if (count($items) == 1) {
806 $param = $prefix.$this->inorequaluniqueindex++;
807 $sql = $equal ? "= :$param" : "<> :$param";
808 $item = reset($items);
809 $params = array($param=>$item);
810 } else {
811 $params = array();
812 $sql = array();
813 foreach ($items as $item) {
814 $param = $prefix.$this->inorequaluniqueindex++;
815 $params[$param] = $item;
816 $sql[] = ':'.$param;
818 if ($equal) {
819 $sql = 'IN ('.implode(',', $sql).')';
820 } else {
821 $sql = 'NOT IN ('.implode(',', $sql).')';
825 } else {
826 throw new dml_exception('typenotimplement');
828 return array($sql, $params);
832 * Converts short table name {tablename} to the real prefixed table name in given sql.
833 * @param string $sql The sql to be operated on.
834 * @return string The sql with tablenames being prefixed with $CFG->prefix
836 protected function fix_table_names($sql) {
837 return preg_replace('/\{([a-z][a-z0-9_]*)\}/', $this->prefix.'$1', $sql);
841 * Internal private utitlity function used to fix parameters.
842 * Used with {@link preg_replace_callback()}
843 * @param array $match Refer to preg_replace_callback usage for description.
844 * @return string
846 private function _fix_sql_params_dollar_callback($match) {
847 $this->fix_sql_params_i++;
848 return "\$".$this->fix_sql_params_i;
852 * Detects object parameters and throws exception if found
853 * @param mixed $value
854 * @return void
855 * @throws coding_exception if object detected
857 protected function detect_objects($value) {
858 if (is_object($value)) {
859 throw new coding_exception('Invalid database query parameter value', 'Objects are are not allowed: '.get_class($value));
864 * Normalizes sql query parameters and verifies parameters.
865 * @param string $sql The query or part of it.
866 * @param array $params The query parameters.
867 * @return array (sql, params, type of params)
869 public function fix_sql_params($sql, array $params=null) {
870 $params = (array)$params; // mke null array if needed
871 $allowed_types = $this->allowed_param_types();
873 // convert table names
874 $sql = $this->fix_table_names($sql);
876 // cast booleans to 1/0 int and detect forbidden objects
877 foreach ($params as $key => $value) {
878 $this->detect_objects($value);
879 $params[$key] = is_bool($value) ? (int)$value : $value;
882 // NICOLAS C: Fixed regexp for negative backwards look-ahead of double colons. Thanks for Sam Marshall's help
883 $named_count = preg_match_all('/(?<!:):[a-z][a-z0-9_]*/', $sql, $named_matches); // :: used in pgsql casts
884 $dollar_count = preg_match_all('/\$[1-9][0-9]*/', $sql, $dollar_matches);
885 $q_count = substr_count($sql, '?');
887 $count = 0;
889 if ($named_count) {
890 $type = SQL_PARAMS_NAMED;
891 $count = $named_count;
894 if ($dollar_count) {
895 if ($count) {
896 throw new dml_exception('mixedtypesqlparam');
898 $type = SQL_PARAMS_DOLLAR;
899 $count = $dollar_count;
902 if ($q_count) {
903 if ($count) {
904 throw new dml_exception('mixedtypesqlparam');
906 $type = SQL_PARAMS_QM;
907 $count = $q_count;
911 if (!$count) {
912 // ignore params
913 if ($allowed_types & SQL_PARAMS_NAMED) {
914 return array($sql, array(), SQL_PARAMS_NAMED);
915 } else if ($allowed_types & SQL_PARAMS_QM) {
916 return array($sql, array(), SQL_PARAMS_QM);
917 } else {
918 return array($sql, array(), SQL_PARAMS_DOLLAR);
922 if ($count > count($params)) {
923 $a = new stdClass;
924 $a->expected = $count;
925 $a->actual = count($params);
926 throw new dml_exception('invalidqueryparam', $a);
929 $target_type = $allowed_types;
931 if ($type & $allowed_types) { // bitwise AND
932 if ($count == count($params)) {
933 if ($type == SQL_PARAMS_QM) {
934 return array($sql, array_values($params), SQL_PARAMS_QM); // 0-based array required
935 } else {
936 //better do the validation of names below
939 // needs some fixing or validation - there might be more params than needed
940 $target_type = $type;
943 if ($type == SQL_PARAMS_NAMED) {
944 $finalparams = array();
945 foreach ($named_matches[0] as $key) {
946 $key = trim($key, ':');
947 if (!array_key_exists($key, $params)) {
948 throw new dml_exception('missingkeyinsql', $key, '');
950 if (strlen($key) > 30) {
951 throw new coding_exception(
952 "Placeholder names must be 30 characters or shorter. '" .
953 $key . "' is too long.", $sql);
955 $finalparams[$key] = $params[$key];
957 if ($count != count($finalparams)) {
958 throw new dml_exception('duplicateparaminsql');
961 if ($target_type & SQL_PARAMS_QM) {
962 $sql = preg_replace('/(?<!:):[a-z][a-z0-9_]*/', '?', $sql);
963 return array($sql, array_values($finalparams), SQL_PARAMS_QM); // 0-based required
964 } else if ($target_type & SQL_PARAMS_NAMED) {
965 return array($sql, $finalparams, SQL_PARAMS_NAMED);
966 } else { // $type & SQL_PARAMS_DOLLAR
967 //lambda-style functions eat memory - we use globals instead :-(
968 $this->fix_sql_params_i = 0;
969 $sql = preg_replace_callback('/(?<!:):[a-z][a-z0-9_]*/', array($this, '_fix_sql_params_dollar_callback'), $sql);
970 return array($sql, array_values($finalparams), SQL_PARAMS_DOLLAR); // 0-based required
973 } else if ($type == SQL_PARAMS_DOLLAR) {
974 if ($target_type & SQL_PARAMS_DOLLAR) {
975 return array($sql, array_values($params), SQL_PARAMS_DOLLAR); // 0-based required
976 } else if ($target_type & SQL_PARAMS_QM) {
977 $sql = preg_replace('/\$[0-9]+/', '?', $sql);
978 return array($sql, array_values($params), SQL_PARAMS_QM); // 0-based required
979 } else { //$target_type & SQL_PARAMS_NAMED
980 $sql = preg_replace('/\$([0-9]+)/', ':param\\1', $sql);
981 $finalparams = array();
982 foreach ($params as $key=>$param) {
983 $key++;
984 $finalparams['param'.$key] = $param;
986 return array($sql, $finalparams, SQL_PARAMS_NAMED);
989 } else { // $type == SQL_PARAMS_QM
990 if (count($params) != $count) {
991 $params = array_slice($params, 0, $count);
994 if ($target_type & SQL_PARAMS_QM) {
995 return array($sql, array_values($params), SQL_PARAMS_QM); // 0-based required
996 } else if ($target_type & SQL_PARAMS_NAMED) {
997 $finalparams = array();
998 $pname = 'param0';
999 $parts = explode('?', $sql);
1000 $sql = array_shift($parts);
1001 foreach ($parts as $part) {
1002 $param = array_shift($params);
1003 $pname++;
1004 $sql .= ':'.$pname.$part;
1005 $finalparams[$pname] = $param;
1007 return array($sql, $finalparams, SQL_PARAMS_NAMED);
1008 } else { // $type & SQL_PARAMS_DOLLAR
1009 //lambda-style functions eat memory - we use globals instead :-(
1010 $this->fix_sql_params_i = 0;
1011 $sql = preg_replace_callback('/\?/', array($this, '_fix_sql_params_dollar_callback'), $sql);
1012 return array($sql, array_values($params), SQL_PARAMS_DOLLAR); // 0-based required
1018 * Ensures that limit params are numeric and positive integers, to be passed to the database.
1019 * We explicitly treat null, '' and -1 as 0 in order to provide compatibility with how limit
1020 * values have been passed historically.
1022 * @param int $limitfrom Where to start results from
1023 * @param int $limitnum How many results to return
1024 * @return array Normalised limit params in array($limitfrom, $limitnum)
1026 protected function normalise_limit_from_num($limitfrom, $limitnum) {
1027 global $CFG;
1029 // We explicilty treat these cases as 0.
1030 if ($limitfrom === null || $limitfrom === '' || $limitfrom === -1) {
1031 $limitfrom = 0;
1033 if ($limitnum === null || $limitnum === '' || $limitnum === -1) {
1034 $limitnum = 0;
1037 if ($CFG->debugdeveloper) {
1038 if (!is_numeric($limitfrom)) {
1039 $strvalue = var_export($limitfrom, true);
1040 debugging("Non-numeric limitfrom parameter detected: $strvalue, did you pass the correct arguments?",
1041 DEBUG_DEVELOPER);
1042 } else if ($limitfrom < 0) {
1043 debugging("Negative limitfrom parameter detected: $limitfrom, did you pass the correct arguments?",
1044 DEBUG_DEVELOPER);
1047 if (!is_numeric($limitnum)) {
1048 $strvalue = var_export($limitnum, true);
1049 debugging("Non-numeric limitnum parameter detected: $strvalue, did you pass the correct arguments?",
1050 DEBUG_DEVELOPER);
1051 } else if ($limitnum < 0) {
1052 debugging("Negative limitnum parameter detected: $limitnum, did you pass the correct arguments?",
1053 DEBUG_DEVELOPER);
1057 $limitfrom = (int)$limitfrom;
1058 $limitnum = (int)$limitnum;
1059 $limitfrom = max(0, $limitfrom);
1060 $limitnum = max(0, $limitnum);
1062 return array($limitfrom, $limitnum);
1066 * Return tables in database WITHOUT current prefix.
1067 * @param bool $usecache if true, returns list of cached tables.
1068 * @return array of table names in lowercase and without prefix
1070 public abstract function get_tables($usecache=true);
1073 * Return table indexes - everything lowercased.
1074 * @param string $table The table we want to get indexes from.
1075 * @return array An associative array of indexes containing 'unique' flag and 'columns' being indexed
1077 public abstract function get_indexes($table);
1080 * Returns detailed information about columns in table. This information is cached internally.
1081 * @param string $table The table's name.
1082 * @param bool $usecache Flag to use internal cacheing. The default is true.
1083 * @return database_column_info[] of database_column_info objects indexed with column names
1085 public abstract function get_columns($table, $usecache=true);
1088 * Normalise values based on varying RDBMS's dependencies (booleans, LOBs...)
1090 * @param database_column_info $column column metadata corresponding with the value we are going to normalise
1091 * @param mixed $value value we are going to normalise
1092 * @return mixed the normalised value
1094 protected abstract function normalise_value($column, $value);
1097 * Resets the internal column details cache
1099 * @param array|null $tablenames an array of xmldb table names affected by this request.
1100 * @return void
1102 public function reset_caches($tablenames = null) {
1103 if (!empty($tablenames)) {
1104 $dbmetapurged = false;
1105 foreach ($tablenames as $tablename) {
1106 if ($this->temptables->is_temptable($tablename)) {
1107 $this->get_temp_tables_cache()->delete($tablename);
1108 } else if ($dbmetapurged === false) {
1109 $this->tables = null;
1110 $this->get_metacache()->purge();
1111 $this->metacache = null;
1112 $dbmetapurged = true;
1115 } else {
1116 $this->get_temp_tables_cache()->purge();
1117 $this->tables = null;
1118 // Purge MUC as well.
1119 $this->get_metacache()->purge();
1120 $this->metacache = null;
1125 * Returns the sql generator used for db manipulation.
1126 * Used mostly in upgrade.php scripts.
1127 * @return database_manager The instance used to perform ddl operations.
1128 * @see lib/ddl/database_manager.php
1130 public function get_manager() {
1131 global $CFG;
1133 if (!$this->database_manager) {
1134 require_once($CFG->libdir.'/ddllib.php');
1136 $classname = $this->get_dbfamily().'_sql_generator';
1137 require_once("$CFG->libdir/ddl/$classname.php");
1138 $generator = new $classname($this, $this->temptables);
1140 $this->database_manager = new database_manager($this, $generator);
1142 return $this->database_manager;
1146 * Attempts to change db encoding to UTF-8 encoding if possible.
1147 * @return bool True is successful.
1149 public function change_db_encoding() {
1150 return false;
1154 * Checks to see if the database is in unicode mode?
1155 * @return bool
1157 public function setup_is_unicodedb() {
1158 return true;
1162 * Enable/disable very detailed debugging.
1163 * @param bool $state
1164 * @return void
1166 public function set_debug($state) {
1167 $this->debug = $state;
1171 * Returns debug status
1172 * @return bool $state
1174 public function get_debug() {
1175 return $this->debug;
1179 * Enable/disable detailed sql logging
1181 * @deprecated since Moodle 2.9
1183 public function set_logging($state) {
1184 throw new coding_exception('set_logging() can not be used any more.');
1188 * Do NOT use in code, this is for use by database_manager only!
1189 * @param string|array $sql query or array of queries
1190 * @param array|null $tablenames an array of xmldb table names affected by this request.
1191 * @return bool true
1192 * @throws ddl_change_structure_exception A DDL specific exception is thrown for any errors.
1194 public abstract function change_database_structure($sql, $tablenames = null);
1197 * Executes a general sql query. Should be used only when no other method suitable.
1198 * Do NOT use this to make changes in db structure, use database_manager methods instead!
1199 * @param string $sql query
1200 * @param array $params query parameters
1201 * @return bool true
1202 * @throws dml_exception A DML specific exception is thrown for any errors.
1204 public abstract function execute($sql, array $params=null);
1207 * Get a number of records as a moodle_recordset where all the given conditions met.
1209 * Selects records from the table $table.
1211 * If specified, only records meeting $conditions.
1213 * If specified, the results will be sorted as specified by $sort. This
1214 * is added to the SQL as "ORDER BY $sort". Example values of $sort
1215 * might be "time ASC" or "time DESC".
1217 * If $fields is specified, only those fields are returned.
1219 * Since this method is a little less readable, use of it should be restricted to
1220 * code where it's possible there might be large datasets being returned. For known
1221 * small datasets use get_records - it leads to simpler code.
1223 * If you only want some of the records, specify $limitfrom and $limitnum.
1224 * The query will skip the first $limitfrom records (according to the sort
1225 * order) and then return the next $limitnum records. If either of $limitfrom
1226 * or $limitnum is specified, both must be present.
1228 * The return value is a moodle_recordset
1229 * if the query succeeds. If an error occurs, false is returned.
1231 * @param string $table the table to query.
1232 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1233 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1234 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
1235 * @param int $limitfrom return a subset of records, starting at this point (optional).
1236 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1237 * @return moodle_recordset A moodle_recordset instance
1238 * @throws dml_exception A DML specific exception is thrown for any errors.
1240 public function get_recordset($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1241 list($select, $params) = $this->where_clause($table, $conditions);
1242 return $this->get_recordset_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1246 * Get a number of records as a moodle_recordset where one field match one list of values.
1248 * Only records where $field takes one of the values $values are returned.
1249 * $values must be an array of values.
1251 * Other arguments and the return type are like {@link function get_recordset}.
1253 * @param string $table the table to query.
1254 * @param string $field a field to check (optional).
1255 * @param array $values array of values the field must have
1256 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1257 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
1258 * @param int $limitfrom return a subset of records, starting at this point (optional).
1259 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1260 * @return moodle_recordset A moodle_recordset instance.
1261 * @throws dml_exception A DML specific exception is thrown for any errors.
1263 public function get_recordset_list($table, $field, array $values, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1264 list($select, $params) = $this->where_clause_list($field, $values);
1265 return $this->get_recordset_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1269 * Get a number of records as a moodle_recordset which match a particular WHERE clause.
1271 * If given, $select is used as the SELECT parameter in the SQL query,
1272 * otherwise all records from the table are returned.
1274 * Other arguments and the return type are like {@link function get_recordset}.
1276 * @param string $table the table to query.
1277 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1278 * @param array $params array of sql parameters
1279 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1280 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
1281 * @param int $limitfrom return a subset of records, starting at this point (optional).
1282 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1283 * @return moodle_recordset A moodle_recordset instance.
1284 * @throws dml_exception A DML specific exception is thrown for any errors.
1286 public function get_recordset_select($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1287 $sql = "SELECT $fields FROM {".$table."}";
1288 if ($select) {
1289 $sql .= " WHERE $select";
1291 if ($sort) {
1292 $sql .= " ORDER BY $sort";
1294 return $this->get_recordset_sql($sql, $params, $limitfrom, $limitnum);
1298 * Get a number of records as a moodle_recordset using a SQL statement.
1300 * Since this method is a little less readable, use of it should be restricted to
1301 * code where it's possible there might be large datasets being returned. For known
1302 * small datasets use get_records_sql - it leads to simpler code.
1304 * The return type is like {@link function get_recordset}.
1306 * @param string $sql the SQL select query to execute.
1307 * @param array $params array of sql parameters
1308 * @param int $limitfrom return a subset of records, starting at this point (optional).
1309 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1310 * @return moodle_recordset A moodle_recordset instance.
1311 * @throws dml_exception A DML specific exception is thrown for any errors.
1313 public abstract function get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0);
1316 * Get all records from a table.
1318 * This method works around potential memory problems and may improve performance,
1319 * this method may block access to table until the recordset is closed.
1321 * @param string $table Name of database table.
1322 * @return moodle_recordset A moodle_recordset instance {@link function get_recordset}.
1323 * @throws dml_exception A DML specific exception is thrown for any errors.
1325 public function export_table_recordset($table) {
1326 return $this->get_recordset($table, array());
1330 * Get a number of records as an array of objects where all the given conditions met.
1332 * If the query succeeds and returns at least one record, the
1333 * return value is an array of objects, one object for each
1334 * record found. The array key is the value from the first
1335 * column of the result set. The object associated with that key
1336 * has a member variable for each column of the results.
1338 * @param string $table the table to query.
1339 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1340 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1341 * @param string $fields a comma separated list of fields to return (optional, by default
1342 * all fields are returned). The first field will be used as key for the
1343 * array so must be a unique field such as 'id'.
1344 * @param int $limitfrom return a subset of records, starting at this point (optional).
1345 * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
1346 * @return array An array of Objects indexed by first column.
1347 * @throws dml_exception A DML specific exception is thrown for any errors.
1349 public function get_records($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1350 list($select, $params) = $this->where_clause($table, $conditions);
1351 return $this->get_records_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1355 * Get a number of records as an array of objects where one field match one list of values.
1357 * Return value is like {@link function get_records}.
1359 * @param string $table The database table to be checked against.
1360 * @param string $field The field to search
1361 * @param array $values An array of values
1362 * @param string $sort Sort order (as valid SQL sort parameter)
1363 * @param string $fields A comma separated list of fields to be returned from the chosen table. If specified,
1364 * the first field should be a unique one such as 'id' since it will be used as a key in the associative
1365 * array.
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 in total (optional).
1368 * @return array An array of objects indexed by first column
1369 * @throws dml_exception A DML specific exception is thrown for any errors.
1371 public function get_records_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_records_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1377 * Get a number of records as an array of objects which match a particular WHERE clause.
1379 * Return value is like {@link function get_records}.
1381 * @param string $table The table to query.
1382 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1383 * @param array $params An array of sql parameters
1384 * @param string $sort An order to sort the results in (optional, a valid SQL ORDER BY parameter).
1385 * @param string $fields A comma separated list of fields to return
1386 * (optional, by default all fields are returned). The first field will be used as key for the
1387 * array so must be a unique field such as 'id'.
1388 * @param int $limitfrom return a subset of records, starting at this point (optional).
1389 * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
1390 * @return array of objects indexed by first column
1391 * @throws dml_exception A DML specific exception is thrown for any errors.
1393 public function get_records_select($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1394 if ($select) {
1395 $select = "WHERE $select";
1397 if ($sort) {
1398 $sort = " ORDER BY $sort";
1400 return $this->get_records_sql("SELECT $fields FROM {" . $table . "} $select $sort", $params, $limitfrom, $limitnum);
1404 * Get a number of records as an array of objects using a SQL statement.
1406 * Return value is like {@link function get_records}.
1408 * @param string $sql the SQL select query to execute. The first column of this SELECT statement
1409 * must be a unique value (usually the 'id' field), as it will be used as the key of the
1410 * returned array.
1411 * @param array $params array of sql parameters
1412 * @param int $limitfrom return a subset of records, starting at this point (optional).
1413 * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
1414 * @return array of objects indexed by first column
1415 * @throws dml_exception A DML specific exception is thrown for any errors.
1417 public abstract function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0);
1420 * Get the first two columns from a number of records as an associative array where all the given conditions met.
1422 * Arguments are like {@link function get_recordset}.
1424 * If no errors occur the return value
1425 * is an associative whose keys come from the first field of each record,
1426 * and whose values are the corresponding second fields.
1427 * False is returned if an error occurs.
1429 * @param string $table the table to query.
1430 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1431 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1432 * @param string $fields a comma separated list of fields to return - the number of fields should be 2!
1433 * @param int $limitfrom return a subset of records, starting at this point (optional).
1434 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1435 * @return array an associative array
1436 * @throws dml_exception A DML specific exception is thrown for any errors.
1438 public function get_records_menu($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1439 $menu = array();
1440 if ($records = $this->get_records($table, $conditions, $sort, $fields, $limitfrom, $limitnum)) {
1441 foreach ($records as $record) {
1442 $record = (array)$record;
1443 $key = array_shift($record);
1444 $value = array_shift($record);
1445 $menu[$key] = $value;
1448 return $menu;
1452 * Get the first two columns from a number of records as an associative array which match a particular WHERE clause.
1454 * Arguments are like {@link function get_recordset_select}.
1455 * Return value is like {@link function get_records_menu}.
1457 * @param string $table The database table to be checked against.
1458 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1459 * @param array $params array of sql parameters
1460 * @param string $sort Sort order (optional) - a valid SQL order parameter
1461 * @param string $fields A comma separated list of fields to be returned from the chosen table - the number of fields should be 2!
1462 * @param int $limitfrom return a subset of records, starting at this point (optional).
1463 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1464 * @return array an associative array
1465 * @throws dml_exception A DML specific exception is thrown for any errors.
1467 public function get_records_select_menu($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1468 $menu = array();
1469 if ($records = $this->get_records_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum)) {
1470 foreach ($records as $record) {
1471 $record = (array)$record;
1472 $key = array_shift($record);
1473 $value = array_shift($record);
1474 $menu[$key] = $value;
1477 return $menu;
1481 * Get the first two columns from a number of records as an associative array using a SQL statement.
1483 * Arguments are like {@link function get_recordset_sql}.
1484 * Return value is like {@link function get_records_menu}.
1486 * @param string $sql The SQL string you wish to be executed.
1487 * @param array $params array of sql parameters
1488 * @param int $limitfrom return a subset of records, starting at this point (optional).
1489 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1490 * @return array an associative array
1491 * @throws dml_exception A DML specific exception is thrown for any errors.
1493 public function get_records_sql_menu($sql, array $params=null, $limitfrom=0, $limitnum=0) {
1494 $menu = array();
1495 if ($records = $this->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
1496 foreach ($records as $record) {
1497 $record = (array)$record;
1498 $key = array_shift($record);
1499 $value = array_shift($record);
1500 $menu[$key] = $value;
1503 return $menu;
1507 * Get a single database record as an object where all the given conditions met.
1509 * @param string $table The table to select from.
1510 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1511 * @param string $fields A comma separated list of fields to be returned from the chosen table.
1512 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1513 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1514 * MUST_EXIST means we will throw an exception if no record or multiple records found.
1516 * @todo MDL-30407 MUST_EXIST option should not throw a dml_exception, it should throw a different exception as it's a requested check.
1517 * @return mixed a fieldset object containing the first matching record, false or exception if error not found depending on mode
1518 * @throws dml_exception A DML specific exception is thrown for any errors.
1520 public function get_record($table, array $conditions, $fields='*', $strictness=IGNORE_MISSING) {
1521 list($select, $params) = $this->where_clause($table, $conditions);
1522 return $this->get_record_select($table, $select, $params, $fields, $strictness);
1526 * Get a single database record as an object which match a particular WHERE clause.
1528 * @param string $table The database table to be checked against.
1529 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1530 * @param array $params array of sql parameters
1531 * @param string $fields A comma separated list of fields to be returned from the chosen table.
1532 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1533 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1534 * MUST_EXIST means throw exception if no record or multiple records found
1535 * @return stdClass|false a fieldset object containing the first matching record, false or exception if error not found depending on mode
1536 * @throws dml_exception A DML specific exception is thrown for any errors.
1538 public function get_record_select($table, $select, array $params=null, $fields='*', $strictness=IGNORE_MISSING) {
1539 if ($select) {
1540 $select = "WHERE $select";
1542 try {
1543 return $this->get_record_sql("SELECT $fields FROM {" . $table . "} $select", $params, $strictness);
1544 } catch (dml_missing_record_exception $e) {
1545 // create new exception which will contain correct table name
1546 throw new dml_missing_record_exception($table, $e->sql, $e->params);
1551 * Get a single database record as an object using a SQL statement.
1553 * The SQL statement should normally only return one record.
1554 * It is recommended to use get_records_sql() if more matches possible!
1556 * @param string $sql The SQL string you wish to be executed, should normally only return one record.
1557 * @param array $params array of sql parameters
1558 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1559 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1560 * MUST_EXIST means throw exception if no record or multiple records found
1561 * @return mixed a fieldset object containing the first matching record, false or exception if error not found depending on mode
1562 * @throws dml_exception A DML specific exception is thrown for any errors.
1564 public function get_record_sql($sql, array $params=null, $strictness=IGNORE_MISSING) {
1565 $strictness = (int)$strictness; // we support true/false for BC reasons too
1566 if ($strictness == IGNORE_MULTIPLE) {
1567 $count = 1;
1568 } else {
1569 $count = 0;
1571 if (!$records = $this->get_records_sql($sql, $params, 0, $count)) {
1572 // not found
1573 if ($strictness == MUST_EXIST) {
1574 throw new dml_missing_record_exception('', $sql, $params);
1576 return false;
1579 if (count($records) > 1) {
1580 if ($strictness == MUST_EXIST) {
1581 throw new dml_multiple_records_exception($sql, $params);
1583 debugging('Error: mdb->get_record() found more than one record!');
1586 $return = reset($records);
1587 return $return;
1591 * Get a single field value from a table record where all the given conditions met.
1593 * @param string $table the table to query.
1594 * @param string $return the field to return the value of.
1595 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1596 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1597 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1598 * MUST_EXIST means throw exception if no record or multiple records found
1599 * @return mixed the specified value false if not found
1600 * @throws dml_exception A DML specific exception is thrown for any errors.
1602 public function get_field($table, $return, array $conditions, $strictness=IGNORE_MISSING) {
1603 list($select, $params) = $this->where_clause($table, $conditions);
1604 return $this->get_field_select($table, $return, $select, $params, $strictness);
1608 * Get a single field value from a table record which match a particular WHERE clause.
1610 * @param string $table the table to query.
1611 * @param string $return the field to return the value of.
1612 * @param string $select A fragment of SQL to be used in a where clause returning one row with one column
1613 * @param array $params array of sql parameters
1614 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1615 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1616 * MUST_EXIST means throw exception if no record or multiple records found
1617 * @return mixed the specified value false if not found
1618 * @throws dml_exception A DML specific exception is thrown for any errors.
1620 public function get_field_select($table, $return, $select, array $params=null, $strictness=IGNORE_MISSING) {
1621 if ($select) {
1622 $select = "WHERE $select";
1624 try {
1625 return $this->get_field_sql("SELECT $return FROM {" . $table . "} $select", $params, $strictness);
1626 } catch (dml_missing_record_exception $e) {
1627 // create new exception which will contain correct table name
1628 throw new dml_missing_record_exception($table, $e->sql, $e->params);
1633 * Get a single field value (first field) using a SQL statement.
1635 * @param string $sql The SQL query returning one row with one column
1636 * @param array $params array of sql parameters
1637 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1638 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1639 * MUST_EXIST means throw exception if no record or multiple records found
1640 * @return mixed the specified value false if not found
1641 * @throws dml_exception A DML specific exception is thrown for any errors.
1643 public function get_field_sql($sql, array $params=null, $strictness=IGNORE_MISSING) {
1644 if (!$record = $this->get_record_sql($sql, $params, $strictness)) {
1645 return false;
1648 $record = (array)$record;
1649 return reset($record); // first column
1653 * Selects records and return values of chosen field as an array which match a particular WHERE clause.
1655 * @param string $table the table to query.
1656 * @param string $return the field we are intered in
1657 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1658 * @param array $params array of sql parameters
1659 * @return array of values
1660 * @throws dml_exception A DML specific exception is thrown for any errors.
1662 public function get_fieldset_select($table, $return, $select, array $params=null) {
1663 if ($select) {
1664 $select = "WHERE $select";
1666 return $this->get_fieldset_sql("SELECT $return FROM {" . $table . "} $select", $params);
1670 * Selects records and return values (first field) as an array using a SQL statement.
1672 * @param string $sql The SQL query
1673 * @param array $params array of sql parameters
1674 * @return array of values
1675 * @throws dml_exception A DML specific exception is thrown for any errors.
1677 public abstract function get_fieldset_sql($sql, array $params=null);
1680 * Insert new record into database, as fast as possible, no safety checks, lobs not supported.
1681 * @param string $table name
1682 * @param mixed $params data record as object or array
1683 * @param bool $returnid Returns id of inserted record.
1684 * @param bool $bulk true means repeated inserts expected
1685 * @param bool $customsequence true if 'id' included in $params, disables $returnid
1686 * @return bool|int true or new id
1687 * @throws dml_exception A DML specific exception is thrown for any errors.
1689 public abstract function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false);
1692 * Insert a record into a table and return the "id" field if required.
1694 * Some conversions and safety checks are carried out. Lobs are supported.
1695 * If the return ID isn't required, then this just reports success as true/false.
1696 * $data is an object containing needed data
1697 * @param string $table The database table to be inserted into
1698 * @param object $dataobject A data object with values for one or more fields in the record
1699 * @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.
1700 * @param bool $bulk Set to true is multiple inserts are expected
1701 * @return bool|int true or new id
1702 * @throws dml_exception A DML specific exception is thrown for any errors.
1704 public abstract function insert_record($table, $dataobject, $returnid=true, $bulk=false);
1707 * Insert multiple records into database as fast as possible.
1709 * Order of inserts is maintained, but the operation is not atomic,
1710 * use transactions if necessary.
1712 * This method is intended for inserting of large number of small objects,
1713 * do not use for huge objects with text or binary fields.
1715 * @since Moodle 2.7
1717 * @param string $table The database table to be inserted into
1718 * @param array|Traversable $dataobjects list of objects to be inserted, must be compatible with foreach
1719 * @return void does not return new record ids
1721 * @throws coding_exception if data objects have different structure
1722 * @throws dml_exception A DML specific exception is thrown for any errors.
1724 public function insert_records($table, $dataobjects) {
1725 if (!is_array($dataobjects) and !($dataobjects instanceof Traversable)) {
1726 throw new coding_exception('insert_records() passed non-traversable object');
1729 $fields = null;
1730 // Note: override in driver if there is a faster way.
1731 foreach ($dataobjects as $dataobject) {
1732 if (!is_array($dataobject) and !is_object($dataobject)) {
1733 throw new coding_exception('insert_records() passed invalid record object');
1735 $dataobject = (array)$dataobject;
1736 if ($fields === null) {
1737 $fields = array_keys($dataobject);
1738 } else if ($fields !== array_keys($dataobject)) {
1739 throw new coding_exception('All dataobjects in insert_records() must have the same structure!');
1741 $this->insert_record($table, $dataobject, false);
1746 * Import a record into a table, id field is required.
1747 * Safety checks are NOT carried out. Lobs are supported.
1749 * @param string $table name of database table to be inserted into
1750 * @param object $dataobject A data object with values for one or more fields in the record
1751 * @return bool true
1752 * @throws dml_exception A DML specific exception is thrown for any errors.
1754 public abstract function import_record($table, $dataobject);
1757 * Update record in database, as fast as possible, no safety checks, lobs not supported.
1758 * @param string $table name
1759 * @param mixed $params data record as object or array
1760 * @param bool $bulk True means repeated updates expected.
1761 * @return bool true
1762 * @throws dml_exception A DML specific exception is thrown for any errors.
1764 public abstract function update_record_raw($table, $params, $bulk=false);
1767 * Update a record in a table
1769 * $dataobject is an object containing needed data
1770 * Relies on $dataobject having a variable "id" to
1771 * specify the record to update
1773 * @param string $table The database table to be checked against.
1774 * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
1775 * @param bool $bulk True means repeated updates expected.
1776 * @return bool true
1777 * @throws dml_exception A DML specific exception is thrown for any errors.
1779 public abstract function update_record($table, $dataobject, $bulk=false);
1782 * Set a single field in every table record where all the given conditions met.
1784 * @param string $table The database table to be checked against.
1785 * @param string $newfield the field to set.
1786 * @param string $newvalue the value to set the field to.
1787 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1788 * @return bool true
1789 * @throws dml_exception A DML specific exception is thrown for any errors.
1791 public function set_field($table, $newfield, $newvalue, array $conditions=null) {
1792 list($select, $params) = $this->where_clause($table, $conditions);
1793 return $this->set_field_select($table, $newfield, $newvalue, $select, $params);
1797 * Set a single field in every table record which match a particular WHERE clause.
1799 * @param string $table The database table to be checked against.
1800 * @param string $newfield the field to set.
1801 * @param string $newvalue the value to set the field to.
1802 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1803 * @param array $params array of sql parameters
1804 * @return bool true
1805 * @throws dml_exception A DML specific exception is thrown for any errors.
1807 public abstract function set_field_select($table, $newfield, $newvalue, $select, array $params=null);
1811 * Count the records in a table where all the given conditions met.
1813 * @param string $table The table to query.
1814 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1815 * @return int The count of records returned from the specified criteria.
1816 * @throws dml_exception A DML specific exception is thrown for any errors.
1818 public function count_records($table, array $conditions=null) {
1819 list($select, $params) = $this->where_clause($table, $conditions);
1820 return $this->count_records_select($table, $select, $params);
1824 * Count the records in a table which match a particular WHERE clause.
1826 * @param string $table The database table to be checked against.
1827 * @param string $select A fragment of SQL to be used in a WHERE clause in the SQL call.
1828 * @param array $params array of sql parameters
1829 * @param string $countitem The count string to be used in the SQL call. Default is COUNT('x').
1830 * @return int The count of records returned from the specified criteria.
1831 * @throws dml_exception A DML specific exception is thrown for any errors.
1833 public function count_records_select($table, $select, array $params=null, $countitem="COUNT('x')") {
1834 if ($select) {
1835 $select = "WHERE $select";
1837 return $this->count_records_sql("SELECT $countitem FROM {" . $table . "} $select", $params);
1841 * Get the result of a SQL SELECT COUNT(...) query.
1843 * Given a query that counts rows, return that count. (In fact,
1844 * given any query, return the first field of the first record
1845 * returned. However, this method should only be used for the
1846 * intended purpose.) If an error occurs, 0 is returned.
1848 * @param string $sql The SQL string you wish to be executed.
1849 * @param array $params array of sql parameters
1850 * @return int the count
1851 * @throws dml_exception A DML specific exception is thrown for any errors.
1853 public function count_records_sql($sql, array $params=null) {
1854 $count = $this->get_field_sql($sql, $params);
1855 if ($count === false or !is_number($count) or $count < 0) {
1856 throw new coding_exception("count_records_sql() expects the first field to contain non-negative number from COUNT(), '$count' found instead.");
1858 return (int)$count;
1862 * Test whether a record exists in a table where all the given conditions met.
1864 * @param string $table The table to check.
1865 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1866 * @return bool true if a matching record exists, else false.
1867 * @throws dml_exception A DML specific exception is thrown for any errors.
1869 public function record_exists($table, array $conditions) {
1870 list($select, $params) = $this->where_clause($table, $conditions);
1871 return $this->record_exists_select($table, $select, $params);
1875 * Test whether any records exists in a table which match a particular WHERE clause.
1877 * @param string $table The database table to be checked against.
1878 * @param string $select A fragment of SQL to be used in a WHERE clause in the SQL call.
1879 * @param array $params array of sql parameters
1880 * @return bool true if a matching record exists, else false.
1881 * @throws dml_exception A DML specific exception is thrown for any errors.
1883 public function record_exists_select($table, $select, array $params=null) {
1884 if ($select) {
1885 $select = "WHERE $select";
1887 return $this->record_exists_sql("SELECT 'x' FROM {" . $table . "} $select", $params);
1891 * Test whether a SQL SELECT statement returns any records.
1893 * This function returns true if the SQL statement executes
1894 * without any errors and returns at least one record.
1896 * @param string $sql The SQL statement to execute.
1897 * @param array $params array of sql parameters
1898 * @return bool true if the SQL executes without errors and returns at least one record.
1899 * @throws dml_exception A DML specific exception is thrown for any errors.
1901 public function record_exists_sql($sql, array $params=null) {
1902 $mrs = $this->get_recordset_sql($sql, $params, 0, 1);
1903 $return = $mrs->valid();
1904 $mrs->close();
1905 return $return;
1909 * Delete the records from a table where all the given conditions met.
1910 * If conditions not specified, table is truncated.
1912 * @param string $table the table to delete from.
1913 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1914 * @return bool true.
1915 * @throws dml_exception A DML specific exception is thrown for any errors.
1917 public function delete_records($table, array $conditions=null) {
1918 // truncate is drop/create (DDL), not transactional safe,
1919 // so we don't use the shortcut within them. MDL-29198
1920 if (is_null($conditions) && empty($this->transactions)) {
1921 return $this->execute("TRUNCATE TABLE {".$table."}");
1923 list($select, $params) = $this->where_clause($table, $conditions);
1924 return $this->delete_records_select($table, $select, $params);
1928 * Delete the records from a table where one field match one list of values.
1930 * @param string $table the table to delete from.
1931 * @param string $field The field to search
1932 * @param array $values array of values
1933 * @return bool true.
1934 * @throws dml_exception A DML specific exception is thrown for any errors.
1936 public function delete_records_list($table, $field, array $values) {
1937 list($select, $params) = $this->where_clause_list($field, $values);
1938 return $this->delete_records_select($table, $select, $params);
1942 * Delete one or more records from a table which match a particular WHERE clause.
1944 * @param string $table The database table to be checked against.
1945 * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
1946 * @param array $params array of sql parameters
1947 * @return bool true.
1948 * @throws dml_exception A DML specific exception is thrown for any errors.
1950 public abstract function delete_records_select($table, $select, array $params=null);
1953 * Returns the FROM clause required by some DBs in all SELECT statements.
1955 * To be used in queries not having FROM clause to provide cross_db
1956 * Most DBs don't need it, hence the default is ''
1957 * @return string
1959 public function sql_null_from_clause() {
1960 return '';
1964 * Returns the SQL text to be used in order to perform one bitwise AND operation
1965 * between 2 integers.
1967 * NOTE: The SQL result is a number and can not be used directly in
1968 * SQL condition, please compare it to some number to get a bool!!
1970 * @param int $int1 First integer in the operation.
1971 * @param int $int2 Second integer in the operation.
1972 * @return string The piece of SQL code to be used in your statement.
1974 public function sql_bitand($int1, $int2) {
1975 return '((' . $int1 . ') & (' . $int2 . '))';
1979 * Returns the SQL text to be used in order to perform one bitwise NOT operation
1980 * with 1 integer.
1982 * @param int $int1 The operand integer in the operation.
1983 * @return string The piece of SQL code to be used in your statement.
1985 public function sql_bitnot($int1) {
1986 return '(~(' . $int1 . '))';
1990 * Returns the SQL text to be used in order to perform one bitwise OR operation
1991 * between 2 integers.
1993 * NOTE: The SQL result is a number and can not be used directly in
1994 * SQL condition, please compare it to some number to get a bool!!
1996 * @param int $int1 The first operand integer in the operation.
1997 * @param int $int2 The second operand integer in the operation.
1998 * @return string The piece of SQL code to be used in your statement.
2000 public function sql_bitor($int1, $int2) {
2001 return '((' . $int1 . ') | (' . $int2 . '))';
2005 * Returns the SQL text to be used in order to perform one bitwise XOR operation
2006 * between 2 integers.
2008 * NOTE: The SQL result is a number and can not be used directly in
2009 * SQL condition, please compare it to some number to get a bool!!
2011 * @param int $int1 The first operand integer in the operation.
2012 * @param int $int2 The second operand integer in the operation.
2013 * @return string The piece of SQL code to be used in your statement.
2015 public function sql_bitxor($int1, $int2) {
2016 return '((' . $int1 . ') ^ (' . $int2 . '))';
2020 * Returns the SQL text to be used in order to perform module '%'
2021 * operation - remainder after division
2023 * @param int $int1 The first operand integer in the operation.
2024 * @param int $int2 The second operand integer in the operation.
2025 * @return string The piece of SQL code to be used in your statement.
2027 public function sql_modulo($int1, $int2) {
2028 return '((' . $int1 . ') % (' . $int2 . '))';
2032 * Returns the cross db correct CEIL (ceiling) expression applied to fieldname.
2033 * note: Most DBs use CEIL(), hence it's the default here.
2035 * @param string $fieldname The field (or expression) we are going to ceil.
2036 * @return string The piece of SQL code to be used in your ceiling statement.
2038 public function sql_ceil($fieldname) {
2039 return ' CEIL(' . $fieldname . ')';
2043 * Returns the SQL to be used in order to CAST one CHAR column to INTEGER.
2045 * Be aware that the CHAR column you're trying to cast contains really
2046 * int values or the RDBMS will throw an error!
2048 * @param string $fieldname The name of the field to be casted.
2049 * @param bool $text Specifies if the original column is one TEXT (CLOB) column (true). Defaults to false.
2050 * @return string The piece of SQL code to be used in your statement.
2052 public function sql_cast_char2int($fieldname, $text=false) {
2053 return ' ' . $fieldname . ' ';
2057 * Returns the SQL to be used in order to CAST one CHAR column to REAL number.
2059 * Be aware that the CHAR column you're trying to cast contains really
2060 * numbers or the RDBMS will throw an error!
2062 * @param string $fieldname The name of the field to be casted.
2063 * @param bool $text Specifies if the original column is one TEXT (CLOB) column (true). Defaults to false.
2064 * @return string The piece of SQL code to be used in your statement.
2066 public function sql_cast_char2real($fieldname, $text=false) {
2067 return ' ' . $fieldname . ' ';
2071 * Returns the SQL to be used in order to an UNSIGNED INTEGER column to SIGNED.
2073 * (Only MySQL needs this. MySQL things that 1 * -1 = 18446744073709551615
2074 * if the 1 comes from an unsigned column).
2076 * @deprecated since 2.3
2077 * @param string $fieldname The name of the field to be cast
2078 * @return string The piece of SQL code to be used in your statement.
2080 public function sql_cast_2signed($fieldname) {
2081 return ' ' . $fieldname . ' ';
2085 * Returns the SQL text to be used to compare one TEXT (clob) column with
2086 * one varchar column, because some RDBMS doesn't support such direct
2087 * comparisons.
2089 * @param string $fieldname The name of the TEXT field we need to order by
2090 * @param int $numchars Number of chars to use for the ordering (defaults to 32).
2091 * @return string The piece of SQL code to be used in your statement.
2093 public function sql_compare_text($fieldname, $numchars=32) {
2094 return $this->sql_order_by_text($fieldname, $numchars);
2098 * Returns an equal (=) or not equal (<>) part of a query.
2100 * Note the use of this method may lead to slower queries (full scans) so
2101 * use it only when needed and against already reduced data sets.
2103 * @since Moodle 3.2
2105 * @param string $fieldname Usually the name of the table column.
2106 * @param string $param Usually the bound query parameter (?, :named).
2107 * @param bool $casesensitive Use case sensitive search when set to true (default).
2108 * @param bool $accentsensitive Use accent sensitive search when set to true (default). (not all databases support accent insensitive)
2109 * @param bool $notequal True means not equal (<>)
2110 * @return string The SQL code fragment.
2112 public function sql_equal($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notequal = false) {
2113 // Note that, by default, it's assumed that the correct sql equal operations are
2114 // case sensitive. Only databases not observing this behavior must override the method.
2115 // Also, accent sensitiveness only will be handled by databases supporting it.
2116 $equalop = $notequal ? '<>' : '=';
2117 if ($casesensitive) {
2118 return "$fieldname $equalop $param";
2119 } else {
2120 return "LOWER($fieldname) $equalop LOWER($param)";
2125 * Returns 'LIKE' part of a query.
2127 * @param string $fieldname Usually the name of the table column.
2128 * @param string $param Usually the bound query parameter (?, :named).
2129 * @param bool $casesensitive Use case sensitive search when set to true (default).
2130 * @param bool $accentsensitive Use accent sensitive search when set to true (default). (not all databases support accent insensitive)
2131 * @param bool $notlike True means "NOT LIKE".
2132 * @param string $escapechar The escape char for '%' and '_'.
2133 * @return string The SQL code fragment.
2135 public function sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = '\\') {
2136 if (strpos($param, '%') !== false) {
2137 debugging('Potential SQL injection detected, sql_like() expects bound parameters (? or :named)');
2139 $LIKE = $notlike ? 'NOT LIKE' : 'LIKE';
2140 // by default ignore any sensitiveness - each database does it in a different way
2141 return "$fieldname $LIKE $param ESCAPE '$escapechar'";
2145 * Escape sql LIKE special characters like '_' or '%'.
2146 * @param string $text The string containing characters needing escaping.
2147 * @param string $escapechar The desired escape character, defaults to '\\'.
2148 * @return string The escaped sql LIKE string.
2150 public function sql_like_escape($text, $escapechar = '\\') {
2151 $text = str_replace('_', $escapechar.'_', $text);
2152 $text = str_replace('%', $escapechar.'%', $text);
2153 return $text;
2157 * Returns the proper SQL to do CONCAT between the elements(fieldnames) passed.
2159 * This function accepts variable number of string parameters.
2160 * All strings/fieldnames will used in the SQL concatenate statement generated.
2162 * @return string The SQL to concatenate strings passed in.
2163 * @uses func_get_args() and thus parameters are unlimited OPTIONAL number of additional field names.
2165 public abstract function sql_concat();
2168 * Returns the proper SQL to do CONCAT between the elements passed
2169 * with a given separator
2171 * @param string $separator The separator desired for the SQL concatenating $elements.
2172 * @param array $elements The array of strings to be concatenated.
2173 * @return string The SQL to concatenate the strings.
2175 public abstract function sql_concat_join($separator="' '", $elements=array());
2178 * Returns the proper SQL (for the dbms in use) to concatenate $firstname and $lastname
2180 * @todo MDL-31233 This may not be needed here.
2182 * @param string $first User's first name (default:'firstname').
2183 * @param string $last User's last name (default:'lastname').
2184 * @return string The SQL to concatenate strings.
2186 function sql_fullname($first='firstname', $last='lastname') {
2187 return $this->sql_concat($first, "' '", $last);
2191 * Returns the SQL text to be used to order by one TEXT (clob) column, because
2192 * some RDBMS doesn't support direct ordering of such fields.
2194 * Note that the use or queries being ordered by TEXT columns must be minimised,
2195 * because it's really slooooooow.
2197 * @param string $fieldname The name of the TEXT field we need to order by.
2198 * @param int $numchars The number of chars to use for the ordering (defaults to 32).
2199 * @return string The piece of SQL code to be used in your statement.
2201 public function sql_order_by_text($fieldname, $numchars=32) {
2202 return $fieldname;
2206 * Returns the SQL text to be used to calculate the length in characters of one expression.
2207 * @param string $fieldname The fieldname/expression to calculate its length in characters.
2208 * @return string the piece of SQL code to be used in the statement.
2210 public function sql_length($fieldname) {
2211 return ' LENGTH(' . $fieldname . ')';
2215 * Returns the proper substr() SQL text used to extract substrings from DB
2216 * NOTE: this was originally returning only function name
2218 * @param string $expr Some string field, no aggregates.
2219 * @param mixed $start Integer or expression evaluating to integer (1 based value; first char has index 1)
2220 * @param mixed $length Optional integer or expression evaluating to integer.
2221 * @return string The sql substring extraction fragment.
2223 public function sql_substr($expr, $start, $length=false) {
2224 if (count(func_get_args()) < 2) {
2225 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.');
2227 if ($length === false) {
2228 return "SUBSTR($expr, $start)";
2229 } else {
2230 return "SUBSTR($expr, $start, $length)";
2235 * Returns the SQL for returning searching one string for the location of another.
2237 * Note, there is no guarantee which order $needle, $haystack will be in
2238 * the resulting SQL so when using this method, and both arguments contain
2239 * placeholders, you should use named placeholders.
2241 * @param string $needle the SQL expression that will be searched for.
2242 * @param string $haystack the SQL expression that will be searched in.
2243 * @return string The required searching SQL part.
2245 public function sql_position($needle, $haystack) {
2246 // Implementation using standard SQL.
2247 return "POSITION(($needle) IN ($haystack))";
2251 * This used to return empty string replacement character.
2253 * @deprecated use bound parameter with empty string instead
2255 * @return string An empty string.
2257 function sql_empty() {
2258 debugging("sql_empty() is deprecated, please use empty string '' as sql parameter value instead", DEBUG_DEVELOPER);
2259 return '';
2263 * Returns the proper SQL to know if one field is empty.
2265 * Note that the function behavior strongly relies on the
2266 * parameters passed describing the field so, please, be accurate
2267 * when specifying them.
2269 * Also, note that this function is not suitable to look for
2270 * fields having NULL contents at all. It's all for empty values!
2272 * This function should be applied in all the places where conditions of
2273 * the type:
2275 * ... AND fieldname = '';
2277 * are being used. Final result for text fields should be:
2279 * ... AND ' . sql_isempty('tablename', 'fieldname', true/false, true);
2281 * and for varchar fields result should be:
2283 * ... AND fieldname = :empty; "; $params['empty'] = '';
2285 * (see parameters description below)
2287 * @param string $tablename Name of the table (without prefix). Not used for now but can be
2288 * necessary in the future if we want to use some introspection using
2289 * meta information against the DB. /// TODO ///
2290 * @param string $fieldname Name of the field we are going to check
2291 * @param bool $nullablefield For specifying if the field is nullable (true) or no (false) in the DB.
2292 * @param bool $textfield For specifying if it is a text (also called clob) field (true) or a varchar one (false)
2293 * @return string the sql code to be added to check for empty values
2295 public function sql_isempty($tablename, $fieldname, $nullablefield, $textfield) {
2296 return " ($fieldname = '') ";
2300 * Returns the proper SQL to know if one field is not empty.
2302 * Note that the function behavior strongly relies on the
2303 * parameters passed describing the field so, please, be accurate
2304 * when specifying them.
2306 * This function should be applied in all the places where conditions of
2307 * the type:
2309 * ... AND fieldname != '';
2311 * are being used. Final result for text fields should be:
2313 * ... AND ' . sql_isnotempty('tablename', 'fieldname', true/false, true/false);
2315 * and for varchar fields result should be:
2317 * ... AND fieldname != :empty; "; $params['empty'] = '';
2319 * (see parameters description below)
2321 * @param string $tablename Name of the table (without prefix). This is not used for now but can be
2322 * necessary in the future if we want to use some introspection using
2323 * meta information against the DB.
2324 * @param string $fieldname The name of the field we are going to check.
2325 * @param bool $nullablefield Specifies if the field is nullable (true) or not (false) in the DB.
2326 * @param bool $textfield Specifies if it is a text (also called clob) field (true) or a varchar one (false).
2327 * @return string The sql code to be added to check for non empty values.
2329 public function sql_isnotempty($tablename, $fieldname, $nullablefield, $textfield) {
2330 return ' ( NOT ' . $this->sql_isempty($tablename, $fieldname, $nullablefield, $textfield) . ') ';
2334 * Returns true if this database driver supports regex syntax when searching.
2335 * @return bool True if supported.
2337 public function sql_regex_supported() {
2338 return false;
2342 * Returns the driver specific syntax (SQL part) for matching regex positively or negatively (inverted matching).
2343 * Eg: 'REGEXP':'NOT REGEXP' or '~*' : '!~*'
2345 * @param bool $positivematch
2346 * @param bool $casesensitive
2347 * @return string or empty if not supported
2349 public function sql_regex($positivematch = true, $casesensitive = false) {
2350 return '';
2354 * Returns the SQL that allows to find intersection of two or more queries
2356 * @since Moodle 2.8
2358 * @param array $selects array of SQL select queries, each of them only returns fields with the names from $fields
2359 * @param string $fields comma-separated list of fields (used only by some DB engines)
2360 * @return string SQL query that will return only values that are present in each of selects
2362 public function sql_intersect($selects, $fields) {
2363 if (!count($selects)) {
2364 throw new coding_exception('sql_intersect() requires at least one element in $selects');
2365 } else if (count($selects) == 1) {
2366 return $selects[0];
2368 static $aliascnt = 0;
2369 $rv = '('.$selects[0].')';
2370 for ($i = 1; $i < count($selects); $i++) {
2371 $rv .= " INTERSECT (".$selects[$i].')';
2373 return $rv;
2377 * Does this driver support tool_replace?
2379 * @since Moodle 2.6.1
2380 * @return bool
2382 public function replace_all_text_supported() {
2383 return false;
2387 * Replace given text in all rows of column.
2389 * @since Moodle 2.6.1
2390 * @param string $table name of the table
2391 * @param database_column_info $column
2392 * @param string $search
2393 * @param string $replace
2395 public function replace_all_text($table, database_column_info $column, $search, $replace) {
2396 if (!$this->replace_all_text_supported()) {
2397 return;
2400 // NOTE: override this methods if following standard compliant SQL
2401 // does not work for your driver.
2403 // Enclose the column name by the proper quotes if it's a reserved word.
2404 $columnname = $this->get_manager()->generator->getEncQuoted($column->name);
2406 $searchsql = $this->sql_like($columnname, '?');
2407 $searchparam = '%'.$this->sql_like_escape($search).'%';
2409 $sql = "UPDATE {".$table."}
2410 SET $columnname = REPLACE($columnname, ?, ?)
2411 WHERE $searchsql";
2413 if ($column->meta_type === 'X') {
2414 $this->execute($sql, array($search, $replace, $searchparam));
2416 } else if ($column->meta_type === 'C') {
2417 if (core_text::strlen($search) < core_text::strlen($replace)) {
2418 $colsize = $column->max_length;
2419 $sql = "UPDATE {".$table."}
2420 SET $columnname = " . $this->sql_substr("REPLACE(" . $columnname . ", ?, ?)", 1, $colsize) . "
2421 WHERE $searchsql";
2423 $this->execute($sql, array($search, $replace, $searchparam));
2428 * Analyze the data in temporary tables to force statistics collection after bulk data loads.
2430 * @return void
2432 public function update_temp_table_stats() {
2433 $this->temptables->update_stats();
2437 * Checks and returns true if transactions are supported.
2439 * It is not responsible to run productions servers
2440 * on databases without transaction support ;-)
2442 * Override in driver if needed.
2444 * @return bool
2446 protected function transactions_supported() {
2447 // protected for now, this might be changed to public if really necessary
2448 return true;
2452 * Returns true if a transaction is in progress.
2453 * @return bool
2455 public function is_transaction_started() {
2456 return !empty($this->transactions);
2460 * This is a test that throws an exception if transaction in progress.
2461 * This test does not force rollback of active transactions.
2462 * @return void
2463 * @throws dml_transaction_exception if stansaction active
2465 public function transactions_forbidden() {
2466 if ($this->is_transaction_started()) {
2467 throw new dml_transaction_exception('This code can not be excecuted in transaction');
2472 * On DBs that support it, switch to transaction mode and begin a transaction
2473 * you'll need to ensure you call allow_commit() on the returned object
2474 * or your changes *will* be lost.
2476 * this is _very_ useful for massive updates
2478 * Delegated database transactions can be nested, but only one actual database
2479 * transaction is used for the outer-most delegated transaction. This method
2480 * returns a transaction object which you should keep until the end of the
2481 * delegated transaction. The actual database transaction will
2482 * only be committed if all the nested delegated transactions commit
2483 * successfully. If any part of the transaction rolls back then the whole
2484 * thing is rolled back.
2486 * @return moodle_transaction
2488 public function start_delegated_transaction() {
2489 $transaction = new moodle_transaction($this);
2490 $this->transactions[] = $transaction;
2491 if (count($this->transactions) == 1) {
2492 $this->begin_transaction();
2494 return $transaction;
2498 * Driver specific start of real database transaction,
2499 * this can not be used directly in code.
2500 * @return void
2502 protected abstract function begin_transaction();
2505 * Indicates delegated transaction finished successfully.
2506 * The real database transaction is committed only if
2507 * all delegated transactions committed.
2508 * @param moodle_transaction $transaction The transaction to commit
2509 * @return void
2510 * @throws dml_transaction_exception Creates and throws transaction related exceptions.
2512 public function commit_delegated_transaction(moodle_transaction $transaction) {
2513 if ($transaction->is_disposed()) {
2514 throw new dml_transaction_exception('Transactions already disposed', $transaction);
2516 // mark as disposed so that it can not be used again
2517 $transaction->dispose();
2519 if (empty($this->transactions)) {
2520 throw new dml_transaction_exception('Transaction not started', $transaction);
2523 if ($this->force_rollback) {
2524 throw new dml_transaction_exception('Tried to commit transaction after lower level rollback', $transaction);
2527 if ($transaction !== $this->transactions[count($this->transactions) - 1]) {
2528 // one incorrect commit at any level rollbacks everything
2529 $this->force_rollback = true;
2530 throw new dml_transaction_exception('Invalid transaction commit attempt', $transaction);
2533 if (count($this->transactions) == 1) {
2534 // only commit the top most level
2535 $this->commit_transaction();
2537 array_pop($this->transactions);
2539 if (empty($this->transactions)) {
2540 \core\event\manager::database_transaction_commited();
2541 \core\message\manager::database_transaction_commited();
2546 * Driver specific commit of real database transaction,
2547 * this can not be used directly in code.
2548 * @return void
2550 protected abstract function commit_transaction();
2553 * Call when delegated transaction failed, this rolls back
2554 * all delegated transactions up to the top most level.
2556 * In many cases you do not need to call this method manually,
2557 * because all open delegated transactions are rolled back
2558 * automatically if exceptions not caught.
2560 * @param moodle_transaction $transaction An instance of a moodle_transaction.
2561 * @param Exception|Throwable $e The related exception/throwable to this transaction rollback.
2562 * @return void This does not return, instead the exception passed in will be rethrown.
2564 public function rollback_delegated_transaction(moodle_transaction $transaction, $e) {
2565 if (!($e instanceof Exception) && !($e instanceof Throwable)) {
2566 // PHP7 - we catch Throwables in phpunit but can't use that as the type hint in PHP5.
2567 $e = new \coding_exception("Must be given an Exception or Throwable object!");
2569 if ($transaction->is_disposed()) {
2570 throw new dml_transaction_exception('Transactions already disposed', $transaction);
2572 // mark as disposed so that it can not be used again
2573 $transaction->dispose();
2575 // one rollback at any level rollbacks everything
2576 $this->force_rollback = true;
2578 if (empty($this->transactions) or $transaction !== $this->transactions[count($this->transactions) - 1]) {
2579 // this may or may not be a coding problem, better just rethrow the exception,
2580 // because we do not want to loose the original $e
2581 throw $e;
2584 if (count($this->transactions) == 1) {
2585 // only rollback the top most level
2586 $this->rollback_transaction();
2588 array_pop($this->transactions);
2589 if (empty($this->transactions)) {
2590 // finally top most level rolled back
2591 $this->force_rollback = false;
2592 \core\event\manager::database_transaction_rolledback();
2593 \core\message\manager::database_transaction_rolledback();
2595 throw $e;
2599 * Driver specific abort of real database transaction,
2600 * this can not be used directly in code.
2601 * @return void
2603 protected abstract function rollback_transaction();
2606 * Force rollback of all delegated transaction.
2607 * Does not throw any exceptions and does not log anything.
2609 * This method should be used only from default exception handlers and other
2610 * core code.
2612 * @return void
2614 public function force_transaction_rollback() {
2615 if ($this->transactions) {
2616 try {
2617 $this->rollback_transaction();
2618 } catch (dml_exception $e) {
2619 // ignore any sql errors here, the connection might be broken
2623 // now enable transactions again
2624 $this->transactions = array();
2625 $this->force_rollback = false;
2627 \core\event\manager::database_transaction_rolledback();
2628 \core\message\manager::database_transaction_rolledback();
2632 * Is session lock supported in this driver?
2633 * @return bool
2635 public function session_lock_supported() {
2636 return false;
2640 * Obtains the session lock.
2641 * @param int $rowid The id of the row with session record.
2642 * @param int $timeout The maximum allowed time to wait for the lock in seconds.
2643 * @return void
2644 * @throws dml_exception A DML specific exception is thrown for any errors.
2646 public function get_session_lock($rowid, $timeout) {
2647 $this->used_for_db_sessions = true;
2651 * Releases the session lock.
2652 * @param int $rowid The id of the row with session record.
2653 * @return void
2654 * @throws dml_exception A DML specific exception is thrown for any errors.
2656 public function release_session_lock($rowid) {
2660 * Returns the number of reads done by this database.
2661 * @return int Number of reads.
2663 public function perf_get_reads() {
2664 return $this->reads;
2668 * Returns the number of writes done by this database.
2669 * @return int Number of writes.
2671 public function perf_get_writes() {
2672 return $this->writes;
2676 * Returns the number of queries done by this database.
2677 * @return int Number of queries.
2679 public function perf_get_queries() {
2680 return $this->writes + $this->reads;
2684 * Time waiting for the database engine to finish running all queries.
2685 * @return float Number of seconds with microseconds
2687 public function perf_get_queries_time() {
2688 return $this->queriestime;
2692 * Whether the database is able to support full-text search or not.
2694 * @return bool
2696 public function is_fulltext_search_supported() {
2697 // No support unless specified.
2698 return false;