2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Abstract database driver class.
21 * @copyright 2008 Petr Skoda (http://skodak.org)
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') || die();
27 require_once(__DIR__.'/database_column_info.php');
28 require_once(__DIR__.'/moodle_recordset.php');
29 require_once(__DIR__.'/moodle_transaction.php');
31 /** SQL_PARAMS_NAMED - Bitmask, indicates :name type parameters are supported by db backend. */
32 define('SQL_PARAMS_NAMED', 1);
34 /** SQL_PARAMS_QM - Bitmask, indicates ? type parameters are supported by db backend. */
35 define('SQL_PARAMS_QM', 2);
37 /** SQL_PARAMS_DOLLAR - Bitmask, indicates $1, $2, ... type parameters are supported by db backend. */
38 define('SQL_PARAMS_DOLLAR', 4);
40 /** SQL_QUERY_SELECT - Normal select query, reading only. */
41 define('SQL_QUERY_SELECT', 1);
43 /** SQL_QUERY_INSERT - Insert select query, writing. */
44 define('SQL_QUERY_INSERT', 2);
46 /** SQL_QUERY_UPDATE - Update select query, writing. */
47 define('SQL_QUERY_UPDATE', 3);
49 /** SQL_QUERY_STRUCTURE - Query changing db structure, writing. */
50 define('SQL_QUERY_STRUCTURE', 4);
52 /** SQL_QUERY_AUX - Auxiliary query done by driver, setting connection config, getting table info, etc. */
53 define('SQL_QUERY_AUX', 5);
56 * Abstract class representing moodle database interface.
57 * @link http://docs.moodle.org/dev/DML_functions
60 * @copyright 2008 Petr Skoda (http://skodak.org)
61 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
63 abstract class moodle_database {
65 /** @var database_manager db manager which allows db structure modifications. */
66 protected $database_manager;
67 /** @var moodle_temptables temptables manager to provide cross-db support for temp tables. */
68 protected $temptables;
69 /** @var array Cache of table info. */
70 protected $tables = null;
72 // db connection options
73 /** @var string db host name. */
75 /** @var string db host user. */
77 /** @var string db host password. */
79 /** @var string db name. */
81 /** @var string Prefix added to table names. */
84 /** @var array Database or driver specific options, such as sockets or TCP/IP db connections. */
87 /** @var bool True means non-moodle external database used.*/
90 /** @var int The database reads (performance counter).*/
92 /** @var int The database writes (performance counter).*/
93 protected $writes = 0;
94 /** @var float Time queries took to finish, seconds with microseconds.*/
95 protected $queriestime = 0;
97 /** @var int Debug level. */
100 /** @var string Last used query 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 */
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() {
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) {
192 $classname = $type.'_'.$library.'_moodle_database';
193 $libfile = "$CFG->libdir/dml/$classname.php";
195 if (!file_exists($libfile)) {
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()
238 public abstract function get_name();
241 * Returns the localised database configuration help.
242 * Note: can be used before connect()
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
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
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;
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() {
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
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
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.
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) {
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) {
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.
395 public function dispose() {
396 if ($this->disposed) {
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.
423 protected function query_start($sql, array $params=null, $type, $extrainfo=null) {
424 if ($this->loggingquery) {
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);
434 case SQL_QUERY_SELECT:
438 case SQL_QUERY_INSERT:
439 case SQL_QUERY_UPDATE:
440 case SQL_QUERY_STRUCTURE:
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
462 protected function query_end($result) {
463 if ($this->loggingquery) {
466 if ($result !== false) {
469 $this->last_sql = null;
470 $this->last_params = null;
471 $this->print_debug_time();
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);
484 case SQL_QUERY_SELECT:
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
501 public function query_log($error=false) {
502 // Logging disabled by the driver.
503 if ($this->skiplogging) {
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;
520 $backtrace = debug_backtrace();
523 array_shift($backtrace);
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)
592 protected function print_debug($sql, array $params=null, $obj=null) {
593 if (!$this->get_debug()) {
597 echo "--------------------------------\n";
599 if (!is_null($params)) {
600 echo "[".var_export($params, true)."]\n";
602 echo "--------------------------------\n";
606 if (!is_null($params)) {
607 echo "[".s(var_export($params, true))."]\n";
614 * Prints the time a query took to run.
617 protected function print_debug_time() {
618 if (!$this->get_debug()) {
621 $time = $this->query_time();
622 $message = "Query took: {$time} seconds.\n";
625 echo "--------------------------------\n";
633 * Returns the SQL WHERE conditions.
634 * @param string $table The table name that these conditions will be validated against.
635 * @param array $conditions The conditions to build the where clause. (must not contain numeric indexes)
636 * @throws dml_exception
637 * @return array An array list containing sql 'where' part and 'params'.
639 protected function where_clause($table, array $conditions=null) {
640 // We accept nulls in conditions
641 $conditions = is_null($conditions) ? array() : $conditions;
643 if (empty($conditions)) {
644 return array('', array());
647 // Some checks performed under debugging only
649 $columns = $this->get_columns($table);
650 if (empty($columns)) {
651 // no supported columns means most probably table does not exist
652 throw new dml_exception('ddltablenotexist', $table);
654 foreach ($conditions as $key=>$value) {
655 if (!isset($columns[$key])) {
657 $a->fieldname = $key;
658 $a->tablename = $table;
659 throw new dml_exception('ddlfieldnotexist', $a);
661 $column = $columns[$key];
662 if ($column->meta_type == 'X') {
663 //ok so the column is a text column. sorry no text columns in the where clause conditions
664 throw new dml_exception('textconditionsnotallowed', $conditions);
669 $allowed_types = $this->allowed_param_types();
673 foreach ($conditions as $key=>$value) {
675 throw new dml_exception('invalidnumkey');
677 if (is_null($value)) {
678 $where[] = "$key IS NULL";
680 if ($allowed_types & SQL_PARAMS_NAMED) {
681 // Need to verify key names because they can contain, originally,
682 // spaces and other forbidden chars when using sql_xxx() functions and friends.
683 $normkey = trim(preg_replace('/[^a-zA-Z0-9_-]/', '_', $key), '-_');
684 if ($normkey !== $key) {
685 debugging('Invalid key found in the conditions array.');
687 $where[] = "$key = :$normkey";
688 $params[$normkey] = $value;
690 $where[] = "$key = ?";
695 $where = implode(" AND ", $where);
696 return array($where, $params);
700 * Returns SQL WHERE conditions for the ..._list group of methods.
702 * @param string $field the name of a field.
703 * @param array $values the values field might take.
704 * @return array An array containing sql 'where' part and 'params'
706 protected function where_clause_list($field, array $values) {
707 if (empty($values)) {
708 return array("1 = 2", array()); // Fake condition, won't return rows ever. MDL-17645
711 // Note: Do not use get_in_or_equal() because it can not deal with bools and nulls.
715 $values = (array)$values;
716 foreach ($values as $value) {
717 if (is_bool($value)) {
718 $value = (int)$value;
720 if (is_null($value)) {
721 $select = "$field IS NULL";
727 if ($select !== "") {
728 $select = "$select OR ";
730 $count = count($params);
732 $select = $select."$field = ?";
734 $qs = str_repeat(',?', $count);
735 $qs = ltrim($qs, ',');
736 $select = $select."$field IN ($qs)";
739 return array($select, $params);
743 * Constructs 'IN()' or '=' sql fragment
744 * @param mixed $items A single value or array of values for the expression.
745 * @param int $type Parameter bounding type : SQL_PARAMS_QM or SQL_PARAMS_NAMED.
746 * @param string $prefix Named parameter placeholder prefix (a unique counter value is appended to each parameter name).
747 * @param bool $equal True means we want to equate to the constructed expression, false means we don't want to equate to it.
748 * @param mixed $onemptyitems This defines the behavior when the array of items provided is empty. Defaults to false,
749 * meaning throw exceptions. Other values will become part of the returned SQL fragment.
750 * @throws coding_exception | dml_exception
751 * @return array A list containing the constructed sql fragment and an array of parameters.
753 public function get_in_or_equal($items, $type=SQL_PARAMS_QM, $prefix='param', $equal=true, $onemptyitems=false) {
755 // default behavior, throw exception on empty array
756 if (is_array($items) and empty($items) and $onemptyitems === false) {
757 throw new coding_exception('moodle_database::get_in_or_equal() does not accept empty arrays');
759 // handle $onemptyitems on empty array of items
760 if (is_array($items) and empty($items)) {
761 if (is_null($onemptyitems)) { // Special case, NULL value
762 $sql = $equal ? ' IS NULL' : ' IS NOT NULL';
763 return (array($sql, array()));
765 $items = array($onemptyitems); // Rest of cases, prepare $items for std processing
769 if ($type == SQL_PARAMS_QM) {
770 if (!is_array($items) or count($items) == 1) {
771 $sql = $equal ? '= ?' : '<> ?';
772 $items = (array)$items;
773 $params = array_values($items);
776 $sql = 'IN ('.implode(',', array_fill(0, count($items), '?')).')';
778 $sql = 'NOT IN ('.implode(',', array_fill(0, count($items), '?')).')';
780 $params = array_values($items);
783 } else if ($type == SQL_PARAMS_NAMED) {
784 if (empty($prefix)) {
788 if (!is_array($items)){
789 $param = $prefix.$this->inorequaluniqueindex++;
790 $sql = $equal ? "= :$param" : "<> :$param";
791 $params = array($param=>$items);
792 } else if (count($items) == 1) {
793 $param = $prefix.$this->inorequaluniqueindex++;
794 $sql = $equal ? "= :$param" : "<> :$param";
795 $item = reset($items);
796 $params = array($param=>$item);
800 foreach ($items as $item) {
801 $param = $prefix.$this->inorequaluniqueindex++;
802 $params[$param] = $item;
806 $sql = 'IN ('.implode(',', $sql).')';
808 $sql = 'NOT IN ('.implode(',', $sql).')';
813 throw new dml_exception('typenotimplement');
815 return array($sql, $params);
819 * Converts short table name {tablename} to the real prefixed table name in given sql.
820 * @param string $sql The sql to be operated on.
821 * @return string The sql with tablenames being prefixed with $CFG->prefix
823 protected function fix_table_names($sql) {
824 return preg_replace('/\{([a-z][a-z0-9_]*)\}/', $this->prefix.'$1', $sql);
828 * Internal private utitlity function used to fix parameters.
829 * Used with {@link preg_replace_callback()}
830 * @param array $match Refer to preg_replace_callback usage for description.
833 private function _fix_sql_params_dollar_callback($match) {
834 $this->fix_sql_params_i++;
835 return "\$".$this->fix_sql_params_i;
839 * Detects object parameters and throws exception if found
840 * @param mixed $value
842 * @throws coding_exception if object detected
844 protected function detect_objects($value) {
845 if (is_object($value)) {
846 throw new coding_exception('Invalid database query parameter value', 'Objects are are not allowed: '.get_class($value));
851 * Normalizes sql query parameters and verifies parameters.
852 * @param string $sql The query or part of it.
853 * @param array $params The query parameters.
854 * @return array (sql, params, type of params)
856 public function fix_sql_params($sql, array $params=null) {
857 $params = (array)$params; // mke null array if needed
858 $allowed_types = $this->allowed_param_types();
860 // convert table names
861 $sql = $this->fix_table_names($sql);
863 // cast booleans to 1/0 int and detect forbidden objects
864 foreach ($params as $key => $value) {
865 $this->detect_objects($value);
866 $params[$key] = is_bool($value) ? (int)$value : $value;
869 // NICOLAS C: Fixed regexp for negative backwards look-ahead of double colons. Thanks for Sam Marshall's help
870 $named_count = preg_match_all('/(?<!:):[a-z][a-z0-9_]*/', $sql, $named_matches); // :: used in pgsql casts
871 $dollar_count = preg_match_all('/\$[1-9][0-9]*/', $sql, $dollar_matches);
872 $q_count = substr_count($sql, '?');
877 $type = SQL_PARAMS_NAMED;
878 $count = $named_count;
883 throw new dml_exception('mixedtypesqlparam');
885 $type = SQL_PARAMS_DOLLAR;
886 $count = $dollar_count;
891 throw new dml_exception('mixedtypesqlparam');
893 $type = SQL_PARAMS_QM;
900 if ($allowed_types & SQL_PARAMS_NAMED) {
901 return array($sql, array(), SQL_PARAMS_NAMED);
902 } else if ($allowed_types & SQL_PARAMS_QM) {
903 return array($sql, array(), SQL_PARAMS_QM);
905 return array($sql, array(), SQL_PARAMS_DOLLAR);
909 if ($count > count($params)) {
911 $a->expected = $count;
912 $a->actual = count($params);
913 throw new dml_exception('invalidqueryparam', $a);
916 $target_type = $allowed_types;
918 if ($type & $allowed_types) { // bitwise AND
919 if ($count == count($params)) {
920 if ($type == SQL_PARAMS_QM) {
921 return array($sql, array_values($params), SQL_PARAMS_QM); // 0-based array required
923 //better do the validation of names below
926 // needs some fixing or validation - there might be more params than needed
927 $target_type = $type;
930 if ($type == SQL_PARAMS_NAMED) {
931 $finalparams = array();
932 foreach ($named_matches[0] as $key) {
933 $key = trim($key, ':');
934 if (!array_key_exists($key, $params)) {
935 throw new dml_exception('missingkeyinsql', $key, '');
937 if (strlen($key) > 30) {
938 throw new coding_exception(
939 "Placeholder names must be 30 characters or shorter. '" .
940 $key . "' is too long.", $sql);
942 $finalparams[$key] = $params[$key];
944 if ($count != count($finalparams)) {
945 throw new dml_exception('duplicateparaminsql');
948 if ($target_type & SQL_PARAMS_QM) {
949 $sql = preg_replace('/(?<!:):[a-z][a-z0-9_]*/', '?', $sql);
950 return array($sql, array_values($finalparams), SQL_PARAMS_QM); // 0-based required
951 } else if ($target_type & SQL_PARAMS_NAMED) {
952 return array($sql, $finalparams, SQL_PARAMS_NAMED);
953 } else { // $type & SQL_PARAMS_DOLLAR
954 //lambda-style functions eat memory - we use globals instead :-(
955 $this->fix_sql_params_i = 0;
956 $sql = preg_replace_callback('/(?<!:):[a-z][a-z0-9_]*/', array($this, '_fix_sql_params_dollar_callback'), $sql);
957 return array($sql, array_values($finalparams), SQL_PARAMS_DOLLAR); // 0-based required
960 } else if ($type == SQL_PARAMS_DOLLAR) {
961 if ($target_type & SQL_PARAMS_DOLLAR) {
962 return array($sql, array_values($params), SQL_PARAMS_DOLLAR); // 0-based required
963 } else if ($target_type & SQL_PARAMS_QM) {
964 $sql = preg_replace('/\$[0-9]+/', '?', $sql);
965 return array($sql, array_values($params), SQL_PARAMS_QM); // 0-based required
966 } else { //$target_type & SQL_PARAMS_NAMED
967 $sql = preg_replace('/\$([0-9]+)/', ':param\\1', $sql);
968 $finalparams = array();
969 foreach ($params as $key=>$param) {
971 $finalparams['param'.$key] = $param;
973 return array($sql, $finalparams, SQL_PARAMS_NAMED);
976 } else { // $type == SQL_PARAMS_QM
977 if (count($params) != $count) {
978 $params = array_slice($params, 0, $count);
981 if ($target_type & SQL_PARAMS_QM) {
982 return array($sql, array_values($params), SQL_PARAMS_QM); // 0-based required
983 } else if ($target_type & SQL_PARAMS_NAMED) {
984 $finalparams = array();
986 $parts = explode('?', $sql);
987 $sql = array_shift($parts);
988 foreach ($parts as $part) {
989 $param = array_shift($params);
991 $sql .= ':'.$pname.$part;
992 $finalparams[$pname] = $param;
994 return array($sql, $finalparams, SQL_PARAMS_NAMED);
995 } else { // $type & SQL_PARAMS_DOLLAR
996 //lambda-style functions eat memory - we use globals instead :-(
997 $this->fix_sql_params_i = 0;
998 $sql = preg_replace_callback('/\?/', array($this, '_fix_sql_params_dollar_callback'), $sql);
999 return array($sql, array_values($params), SQL_PARAMS_DOLLAR); // 0-based required
1005 * Ensures that limit params are numeric and positive integers, to be passed to the database.
1006 * We explicitly treat null, '' and -1 as 0 in order to provide compatibility with how limit
1007 * values have been passed historically.
1009 * @param int $limitfrom Where to start results from
1010 * @param int $limitnum How many results to return
1011 * @return array Normalised limit params in array($limitfrom, $limitnum)
1013 protected function normalise_limit_from_num($limitfrom, $limitnum) {
1016 // We explicilty treat these cases as 0.
1017 if ($limitfrom === null || $limitfrom === '' || $limitfrom === -1) {
1020 if ($limitnum === null || $limitnum === '' || $limitnum === -1) {
1024 if ($CFG->debugdeveloper) {
1025 if (!is_numeric($limitfrom)) {
1026 $strvalue = var_export($limitfrom, true);
1027 debugging("Non-numeric limitfrom parameter detected: $strvalue, did you pass the correct arguments?",
1029 } else if ($limitfrom < 0) {
1030 debugging("Negative limitfrom parameter detected: $limitfrom, did you pass the correct arguments?",
1034 if (!is_numeric($limitnum)) {
1035 $strvalue = var_export($limitnum, true);
1036 debugging("Non-numeric limitnum parameter detected: $strvalue, did you pass the correct arguments?",
1038 } else if ($limitnum < 0) {
1039 debugging("Negative limitnum parameter detected: $limitnum, did you pass the correct arguments?",
1044 $limitfrom = (int)$limitfrom;
1045 $limitnum = (int)$limitnum;
1046 $limitfrom = max(0, $limitfrom);
1047 $limitnum = max(0, $limitnum);
1049 return array($limitfrom, $limitnum);
1053 * Return tables in database WITHOUT current prefix.
1054 * @param bool $usecache if true, returns list of cached tables.
1055 * @return array of table names in lowercase and without prefix
1057 public abstract function get_tables($usecache=true);
1060 * Return table indexes - everything lowercased.
1061 * @param string $table The table we want to get indexes from.
1062 * @return array An associative array of indexes containing 'unique' flag and 'columns' being indexed
1064 public abstract function get_indexes($table);
1067 * Returns detailed information about columns in table. This information is cached internally.
1068 * @param string $table The table's name.
1069 * @param bool $usecache Flag to use internal cacheing. The default is true.
1070 * @return array of database_column_info objects indexed with column names
1072 public abstract function get_columns($table, $usecache=true);
1075 * Normalise values based on varying RDBMS's dependencies (booleans, LOBs...)
1077 * @param database_column_info $column column metadata corresponding with the value we are going to normalise
1078 * @param mixed $value value we are going to normalise
1079 * @return mixed the normalised value
1081 protected abstract function normalise_value($column, $value);
1084 * Resets the internal column details cache
1086 * @param array|null $tablenames an array of xmldb table names affected by this request.
1089 public function reset_caches($tablenames = null) {
1090 if (!empty($tablenames)) {
1091 $dbmetapurged = false;
1092 foreach ($tablenames as $tablename) {
1093 if ($this->temptables->is_temptable($tablename)) {
1094 $this->get_temp_tables_cache()->delete($tablename);
1095 } else if ($dbmetapurged === false) {
1096 $this->tables = null;
1097 $this->get_metacache()->purge();
1098 $this->metacache = null;
1099 $dbmetapurged = true;
1103 $this->get_temp_tables_cache()->purge();
1104 $this->tables = null;
1105 // Purge MUC as well.
1106 $this->get_metacache()->purge();
1107 $this->metacache = null;
1112 * Returns the sql generator used for db manipulation.
1113 * Used mostly in upgrade.php scripts.
1114 * @return database_manager The instance used to perform ddl operations.
1115 * @see lib/ddl/database_manager.php
1117 public function get_manager() {
1120 if (!$this->database_manager) {
1121 require_once($CFG->libdir.'/ddllib.php');
1123 $classname = $this->get_dbfamily().'_sql_generator';
1124 require_once("$CFG->libdir/ddl/$classname.php");
1125 $generator = new $classname($this, $this->temptables);
1127 $this->database_manager = new database_manager($this, $generator);
1129 return $this->database_manager;
1133 * Attempts to change db encoding to UTF-8 encoding if possible.
1134 * @return bool True is successful.
1136 public function change_db_encoding() {
1141 * Checks to see if the database is in unicode mode?
1144 public function setup_is_unicodedb() {
1149 * Enable/disable very detailed debugging.
1150 * @param bool $state
1153 public function set_debug($state) {
1154 $this->debug = $state;
1158 * Returns debug status
1159 * @return bool $state
1161 public function get_debug() {
1162 return $this->debug;
1166 * Enable/disable detailed sql logging
1168 * @deprecated since Moodle 2.9
1170 public function set_logging($state) {
1171 throw new coding_exception('set_logging() can not be used any more.');
1175 * Do NOT use in code, this is for use by database_manager only!
1176 * @param string|array $sql query or array of queries
1177 * @param array|null $tablenames an array of xmldb table names affected by this request.
1179 * @throws ddl_change_structure_exception A DDL specific exception is thrown for any errors.
1181 public abstract function change_database_structure($sql, $tablenames = null);
1184 * Executes a general sql query. Should be used only when no other method suitable.
1185 * Do NOT use this to make changes in db structure, use database_manager methods instead!
1186 * @param string $sql query
1187 * @param array $params query parameters
1189 * @throws dml_exception A DML specific exception is thrown for any errors.
1191 public abstract function execute($sql, array $params=null);
1194 * Get a number of records as a moodle_recordset where all the given conditions met.
1196 * Selects records from the table $table.
1198 * If specified, only records meeting $conditions.
1200 * If specified, the results will be sorted as specified by $sort. This
1201 * is added to the SQL as "ORDER BY $sort". Example values of $sort
1202 * might be "time ASC" or "time DESC".
1204 * If $fields is specified, only those fields are returned.
1206 * Since this method is a little less readable, use of it should be restricted to
1207 * code where it's possible there might be large datasets being returned. For known
1208 * small datasets use get_records - it leads to simpler code.
1210 * If you only want some of the records, specify $limitfrom and $limitnum.
1211 * The query will skip the first $limitfrom records (according to the sort
1212 * order) and then return the next $limitnum records. If either of $limitfrom
1213 * or $limitnum is specified, both must be present.
1215 * The return value is a moodle_recordset
1216 * if the query succeeds. If an error occurs, false is returned.
1218 * @param string $table the table to query.
1219 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1220 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1221 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
1222 * @param int $limitfrom return a subset of records, starting at this point (optional).
1223 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1224 * @return moodle_recordset A moodle_recordset instance
1225 * @throws dml_exception A DML specific exception is thrown for any errors.
1227 public function get_recordset($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1228 list($select, $params) = $this->where_clause($table, $conditions);
1229 return $this->get_recordset_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1233 * Get a number of records as a moodle_recordset where one field match one list of values.
1235 * Only records where $field takes one of the values $values are returned.
1236 * $values must be an array of values.
1238 * Other arguments and the return type are like {@link function get_recordset}.
1240 * @param string $table the table to query.
1241 * @param string $field a field to check (optional).
1242 * @param array $values array of values the field must have
1243 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1244 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
1245 * @param int $limitfrom return a subset of records, starting at this point (optional).
1246 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1247 * @return moodle_recordset A moodle_recordset instance.
1248 * @throws dml_exception A DML specific exception is thrown for any errors.
1250 public function get_recordset_list($table, $field, array $values, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1251 list($select, $params) = $this->where_clause_list($field, $values);
1252 return $this->get_recordset_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1256 * Get a number of records as a moodle_recordset which match a particular WHERE clause.
1258 * If given, $select is used as the SELECT parameter in the SQL query,
1259 * otherwise all records from the table are returned.
1261 * Other arguments and the return type are like {@link function get_recordset}.
1263 * @param string $table the table to query.
1264 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1265 * @param array $params array of sql parameters
1266 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1267 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
1268 * @param int $limitfrom return a subset of records, starting at this point (optional).
1269 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1270 * @return moodle_recordset A moodle_recordset instance.
1271 * @throws dml_exception A DML specific exception is thrown for any errors.
1273 public function get_recordset_select($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1274 $sql = "SELECT $fields FROM {".$table."}";
1276 $sql .= " WHERE $select";
1279 $sql .= " ORDER BY $sort";
1281 return $this->get_recordset_sql($sql, $params, $limitfrom, $limitnum);
1285 * Get a number of records as a moodle_recordset using a SQL statement.
1287 * Since this method is a little less readable, use of it should be restricted to
1288 * code where it's possible there might be large datasets being returned. For known
1289 * small datasets use get_records_sql - it leads to simpler code.
1291 * The return type is like {@link function get_recordset}.
1293 * @param string $sql the SQL select query to execute.
1294 * @param array $params array of sql parameters
1295 * @param int $limitfrom return a subset of records, starting at this point (optional).
1296 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1297 * @return moodle_recordset A moodle_recordset instance.
1298 * @throws dml_exception A DML specific exception is thrown for any errors.
1300 public abstract function get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0);
1303 * Get all records from a table.
1305 * This method works around potential memory problems and may improve performance,
1306 * this method may block access to table until the recordset is closed.
1308 * @param string $table Name of database table.
1309 * @return moodle_recordset A moodle_recordset instance {@link function get_recordset}.
1310 * @throws dml_exception A DML specific exception is thrown for any errors.
1312 public function export_table_recordset($table) {
1313 return $this->get_recordset($table, array());
1317 * Get a number of records as an array of objects where all the given conditions met.
1319 * If the query succeeds and returns at least one record, the
1320 * return value is an array of objects, one object for each
1321 * record found. The array key is the value from the first
1322 * column of the result set. The object associated with that key
1323 * has a member variable for each column of the results.
1325 * @param string $table the table to query.
1326 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1327 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1328 * @param string $fields a comma separated list of fields to return (optional, by default
1329 * all fields are returned). The first field will be used as key for the
1330 * array so must be a unique field such as 'id'.
1331 * @param int $limitfrom return a subset of records, starting at this point (optional).
1332 * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
1333 * @return array An array of Objects indexed by first column.
1334 * @throws dml_exception A DML specific exception is thrown for any errors.
1336 public function get_records($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1337 list($select, $params) = $this->where_clause($table, $conditions);
1338 return $this->get_records_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1342 * Get a number of records as an array of objects where one field match one list of values.
1344 * Return value is like {@link function get_records}.
1346 * @param string $table The database table to be checked against.
1347 * @param string $field The field to search
1348 * @param array $values An array of values
1349 * @param string $sort Sort order (as valid SQL sort parameter)
1350 * @param string $fields A comma separated list of fields to be returned from the chosen table. If specified,
1351 * the first field should be a unique one such as 'id' since it will be used as a key in the associative
1353 * @param int $limitfrom return a subset of records, starting at this point (optional).
1354 * @param int $limitnum return a subset comprising this many records in total (optional).
1355 * @return array An array of objects indexed by first column
1356 * @throws dml_exception A DML specific exception is thrown for any errors.
1358 public function get_records_list($table, $field, array $values, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1359 list($select, $params) = $this->where_clause_list($field, $values);
1360 return $this->get_records_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1364 * Get a number of records as an array of objects which match a particular WHERE clause.
1366 * Return value is like {@link function get_records}.
1368 * @param string $table The table to query.
1369 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1370 * @param array $params An array of sql parameters
1371 * @param string $sort An order to sort the results in (optional, a valid SQL ORDER BY parameter).
1372 * @param string $fields A comma separated list of fields to return
1373 * (optional, by default all fields are returned). The first field will be used as key for the
1374 * array so must be a unique field such as 'id'.
1375 * @param int $limitfrom return a subset of records, starting at this point (optional).
1376 * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
1377 * @return array of objects indexed by first column
1378 * @throws dml_exception A DML specific exception is thrown for any errors.
1380 public function get_records_select($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1382 $select = "WHERE $select";
1385 $sort = " ORDER BY $sort";
1387 return $this->get_records_sql("SELECT $fields FROM {" . $table . "} $select $sort", $params, $limitfrom, $limitnum);
1391 * Get a number of records as an array of objects using a SQL statement.
1393 * Return value is like {@link function get_records}.
1395 * @param string $sql the SQL select query to execute. The first column of this SELECT statement
1396 * must be a unique value (usually the 'id' field), as it will be used as the key of the
1398 * @param array $params array of sql parameters
1399 * @param int $limitfrom return a subset of records, starting at this point (optional).
1400 * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
1401 * @return array of objects indexed by first column
1402 * @throws dml_exception A DML specific exception is thrown for any errors.
1404 public abstract function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0);
1407 * Get the first two columns from a number of records as an associative array where all the given conditions met.
1409 * Arguments are like {@link function get_recordset}.
1411 * If no errors occur the return value
1412 * is an associative whose keys come from the first field of each record,
1413 * and whose values are the corresponding second fields.
1414 * False is returned if an error occurs.
1416 * @param string $table the table to query.
1417 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1418 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1419 * @param string $fields a comma separated list of fields to return - the number of fields should be 2!
1420 * @param int $limitfrom return a subset of records, starting at this point (optional).
1421 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1422 * @return array an associative array
1423 * @throws dml_exception A DML specific exception is thrown for any errors.
1425 public function get_records_menu($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1427 if ($records = $this->get_records($table, $conditions, $sort, $fields, $limitfrom, $limitnum)) {
1428 foreach ($records as $record) {
1429 $record = (array)$record;
1430 $key = array_shift($record);
1431 $value = array_shift($record);
1432 $menu[$key] = $value;
1439 * Get the first two columns from a number of records as an associative array which match a particular WHERE clause.
1441 * Arguments are like {@link function get_recordset_select}.
1442 * Return value is like {@link function get_records_menu}.
1444 * @param string $table The database table to be checked against.
1445 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1446 * @param array $params array of sql parameters
1447 * @param string $sort Sort order (optional) - a valid SQL order parameter
1448 * @param string $fields A comma separated list of fields to be returned from the chosen table - the number of fields should be 2!
1449 * @param int $limitfrom return a subset of records, starting at this point (optional).
1450 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1451 * @return array an associative array
1452 * @throws dml_exception A DML specific exception is thrown for any errors.
1454 public function get_records_select_menu($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1456 if ($records = $this->get_records_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum)) {
1457 foreach ($records as $record) {
1458 $record = (array)$record;
1459 $key = array_shift($record);
1460 $value = array_shift($record);
1461 $menu[$key] = $value;
1468 * Get the first two columns from a number of records as an associative array using a SQL statement.
1470 * Arguments are like {@link function get_recordset_sql}.
1471 * Return value is like {@link function get_records_menu}.
1473 * @param string $sql The SQL string you wish to be executed.
1474 * @param array $params array of sql parameters
1475 * @param int $limitfrom return a subset of records, starting at this point (optional).
1476 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1477 * @return array an associative array
1478 * @throws dml_exception A DML specific exception is thrown for any errors.
1480 public function get_records_sql_menu($sql, array $params=null, $limitfrom=0, $limitnum=0) {
1482 if ($records = $this->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
1483 foreach ($records as $record) {
1484 $record = (array)$record;
1485 $key = array_shift($record);
1486 $value = array_shift($record);
1487 $menu[$key] = $value;
1494 * Get a single database record as an object where all the given conditions met.
1496 * @param string $table The table to select from.
1497 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1498 * @param string $fields A comma separated list of fields to be returned from the chosen table.
1499 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1500 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1501 * MUST_EXIST means we will throw an exception if no record or multiple records found.
1503 * @todo MDL-30407 MUST_EXIST option should not throw a dml_exception, it should throw a different exception as it's a requested check.
1504 * @return mixed a fieldset object containing the first matching record, false or exception if error not found depending on mode
1505 * @throws dml_exception A DML specific exception is thrown for any errors.
1507 public function get_record($table, array $conditions, $fields='*', $strictness=IGNORE_MISSING) {
1508 list($select, $params) = $this->where_clause($table, $conditions);
1509 return $this->get_record_select($table, $select, $params, $fields, $strictness);
1513 * Get a single database record as an object which match a particular WHERE clause.
1515 * @param string $table The database table to be checked against.
1516 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1517 * @param array $params array of sql parameters
1518 * @param string $fields A comma separated list of fields to be returned from the chosen table.
1519 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1520 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1521 * MUST_EXIST means throw exception if no record or multiple records found
1522 * @return stdClass|false a fieldset object containing the first matching record, false or exception if error not found depending on mode
1523 * @throws dml_exception A DML specific exception is thrown for any errors.
1525 public function get_record_select($table, $select, array $params=null, $fields='*', $strictness=IGNORE_MISSING) {
1527 $select = "WHERE $select";
1530 return $this->get_record_sql("SELECT $fields FROM {" . $table . "} $select", $params, $strictness);
1531 } catch (dml_missing_record_exception $e) {
1532 // create new exception which will contain correct table name
1533 throw new dml_missing_record_exception($table, $e->sql, $e->params);
1538 * Get a single database record as an object using a SQL statement.
1540 * The SQL statement should normally only return one record.
1541 * It is recommended to use get_records_sql() if more matches possible!
1543 * @param string $sql The SQL string you wish to be executed, should normally only return one record.
1544 * @param array $params array of sql parameters
1545 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1546 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1547 * MUST_EXIST means throw exception if no record or multiple records found
1548 * @return mixed a fieldset object containing the first matching record, false or exception if error not found depending on mode
1549 * @throws dml_exception A DML specific exception is thrown for any errors.
1551 public function get_record_sql($sql, array $params=null, $strictness=IGNORE_MISSING) {
1552 $strictness = (int)$strictness; // we support true/false for BC reasons too
1553 if ($strictness == IGNORE_MULTIPLE) {
1558 if (!$records = $this->get_records_sql($sql, $params, 0, $count)) {
1560 if ($strictness == MUST_EXIST) {
1561 throw new dml_missing_record_exception('', $sql, $params);
1566 if (count($records) > 1) {
1567 if ($strictness == MUST_EXIST) {
1568 throw new dml_multiple_records_exception($sql, $params);
1570 debugging('Error: mdb->get_record() found more than one record!');
1573 $return = reset($records);
1578 * Get a single field value from a table record where all the given conditions met.
1580 * @param string $table the table to query.
1581 * @param string $return the field to return the value of.
1582 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1583 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1584 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1585 * MUST_EXIST means throw exception if no record or multiple records found
1586 * @return mixed the specified value false if not found
1587 * @throws dml_exception A DML specific exception is thrown for any errors.
1589 public function get_field($table, $return, array $conditions, $strictness=IGNORE_MISSING) {
1590 list($select, $params) = $this->where_clause($table, $conditions);
1591 return $this->get_field_select($table, $return, $select, $params, $strictness);
1595 * Get a single field value from a table record which match a particular WHERE clause.
1597 * @param string $table the table to query.
1598 * @param string $return the field to return the value of.
1599 * @param string $select A fragment of SQL to be used in a where clause returning one row with one column
1600 * @param array $params array of sql parameters
1601 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1602 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1603 * MUST_EXIST means throw exception if no record or multiple records found
1604 * @return mixed the specified value false if not found
1605 * @throws dml_exception A DML specific exception is thrown for any errors.
1607 public function get_field_select($table, $return, $select, array $params=null, $strictness=IGNORE_MISSING) {
1609 $select = "WHERE $select";
1612 return $this->get_field_sql("SELECT $return FROM {" . $table . "} $select", $params, $strictness);
1613 } catch (dml_missing_record_exception $e) {
1614 // create new exception which will contain correct table name
1615 throw new dml_missing_record_exception($table, $e->sql, $e->params);
1620 * Get a single field value (first field) using a SQL statement.
1622 * @param string $sql The SQL query returning one row with one column
1623 * @param array $params array of sql parameters
1624 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1625 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1626 * MUST_EXIST means throw exception if no record or multiple records found
1627 * @return mixed the specified value false if not found
1628 * @throws dml_exception A DML specific exception is thrown for any errors.
1630 public function get_field_sql($sql, array $params=null, $strictness=IGNORE_MISSING) {
1631 if (!$record = $this->get_record_sql($sql, $params, $strictness)) {
1635 $record = (array)$record;
1636 return reset($record); // first column
1640 * Selects records and return values of chosen field as an array which match a particular WHERE clause.
1642 * @param string $table the table to query.
1643 * @param string $return the field we are intered in
1644 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1645 * @param array $params array of sql parameters
1646 * @return array of values
1647 * @throws dml_exception A DML specific exception is thrown for any errors.
1649 public function get_fieldset_select($table, $return, $select, array $params=null) {
1651 $select = "WHERE $select";
1653 return $this->get_fieldset_sql("SELECT $return FROM {" . $table . "} $select", $params);
1657 * Selects records and return values (first field) as an array using a SQL statement.
1659 * @param string $sql The SQL query
1660 * @param array $params array of sql parameters
1661 * @return array of values
1662 * @throws dml_exception A DML specific exception is thrown for any errors.
1664 public abstract function get_fieldset_sql($sql, array $params=null);
1667 * Insert new record into database, as fast as possible, no safety checks, lobs not supported.
1668 * @param string $table name
1669 * @param mixed $params data record as object or array
1670 * @param bool $returnid Returns id of inserted record.
1671 * @param bool $bulk true means repeated inserts expected
1672 * @param bool $customsequence true if 'id' included in $params, disables $returnid
1673 * @return bool|int true or new id
1674 * @throws dml_exception A DML specific exception is thrown for any errors.
1676 public abstract function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false);
1679 * Insert a record into a table and return the "id" field if required.
1681 * Some conversions and safety checks are carried out. Lobs are supported.
1682 * If the return ID isn't required, then this just reports success as true/false.
1683 * $data is an object containing needed data
1684 * @param string $table The database table to be inserted into
1685 * @param object $dataobject A data object with values for one or more fields in the record
1686 * @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.
1687 * @param bool $bulk Set to true is multiple inserts are expected
1688 * @return bool|int true or new id
1689 * @throws dml_exception A DML specific exception is thrown for any errors.
1691 public abstract function insert_record($table, $dataobject, $returnid=true, $bulk=false);
1694 * Insert multiple records into database as fast as possible.
1696 * Order of inserts is maintained, but the operation is not atomic,
1697 * use transactions if necessary.
1699 * This method is intended for inserting of large number of small objects,
1700 * do not use for huge objects with text or binary fields.
1704 * @param string $table The database table to be inserted into
1705 * @param array|Traversable $dataobjects list of objects to be inserted, must be compatible with foreach
1706 * @return void does not return new record ids
1708 * @throws coding_exception if data objects have different structure
1709 * @throws dml_exception A DML specific exception is thrown for any errors.
1711 public function insert_records($table, $dataobjects) {
1712 if (!is_array($dataobjects) and !($dataobjects instanceof Traversable)) {
1713 throw new coding_exception('insert_records() passed non-traversable object');
1717 // Note: override in driver if there is a faster way.
1718 foreach ($dataobjects as $dataobject) {
1719 if (!is_array($dataobject) and !is_object($dataobject)) {
1720 throw new coding_exception('insert_records() passed invalid record object');
1722 $dataobject = (array)$dataobject;
1723 if ($fields === null) {
1724 $fields = array_keys($dataobject);
1725 } else if ($fields !== array_keys($dataobject)) {
1726 throw new coding_exception('All dataobjects in insert_records() must have the same structure!');
1728 $this->insert_record($table, $dataobject, false);
1733 * Import a record into a table, id field is required.
1734 * Safety checks are NOT carried out. Lobs are supported.
1736 * @param string $table name of database table to be inserted into
1737 * @param object $dataobject A data object with values for one or more fields in the record
1739 * @throws dml_exception A DML specific exception is thrown for any errors.
1741 public abstract function import_record($table, $dataobject);
1744 * Update record in database, as fast as possible, no safety checks, lobs not supported.
1745 * @param string $table name
1746 * @param mixed $params data record as object or array
1747 * @param bool $bulk True means repeated updates expected.
1749 * @throws dml_exception A DML specific exception is thrown for any errors.
1751 public abstract function update_record_raw($table, $params, $bulk=false);
1754 * Update a record in a table
1756 * $dataobject is an object containing needed data
1757 * Relies on $dataobject having a variable "id" to
1758 * specify the record to update
1760 * @param string $table The database table to be checked against.
1761 * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
1762 * @param bool $bulk True means repeated updates expected.
1764 * @throws dml_exception A DML specific exception is thrown for any errors.
1766 public abstract function update_record($table, $dataobject, $bulk=false);
1769 * Set a single field in every table record where all the given conditions met.
1771 * @param string $table The database table to be checked against.
1772 * @param string $newfield the field to set.
1773 * @param string $newvalue the value to set the field to.
1774 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1776 * @throws dml_exception A DML specific exception is thrown for any errors.
1778 public function set_field($table, $newfield, $newvalue, array $conditions=null) {
1779 list($select, $params) = $this->where_clause($table, $conditions);
1780 return $this->set_field_select($table, $newfield, $newvalue, $select, $params);
1784 * Set a single field in every table record which match a particular WHERE clause.
1786 * @param string $table The database table to be checked against.
1787 * @param string $newfield the field to set.
1788 * @param string $newvalue the value to set the field to.
1789 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1790 * @param array $params array of sql parameters
1792 * @throws dml_exception A DML specific exception is thrown for any errors.
1794 public abstract function set_field_select($table, $newfield, $newvalue, $select, array $params=null);
1798 * Count the records in a table where all the given conditions met.
1800 * @param string $table The table to query.
1801 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1802 * @return int The count of records returned from the specified criteria.
1803 * @throws dml_exception A DML specific exception is thrown for any errors.
1805 public function count_records($table, array $conditions=null) {
1806 list($select, $params) = $this->where_clause($table, $conditions);
1807 return $this->count_records_select($table, $select, $params);
1811 * Count the records in a table which match a particular WHERE clause.
1813 * @param string $table The database table to be checked against.
1814 * @param string $select A fragment of SQL to be used in a WHERE clause in the SQL call.
1815 * @param array $params array of sql parameters
1816 * @param string $countitem The count string to be used in the SQL call. Default is COUNT('x').
1817 * @return int The count of records returned from the specified criteria.
1818 * @throws dml_exception A DML specific exception is thrown for any errors.
1820 public function count_records_select($table, $select, array $params=null, $countitem="COUNT('x')") {
1822 $select = "WHERE $select";
1824 return $this->count_records_sql("SELECT $countitem FROM {" . $table . "} $select", $params);
1828 * Get the result of a SQL SELECT COUNT(...) query.
1830 * Given a query that counts rows, return that count. (In fact,
1831 * given any query, return the first field of the first record
1832 * returned. However, this method should only be used for the
1833 * intended purpose.) If an error occurs, 0 is returned.
1835 * @param string $sql The SQL string you wish to be executed.
1836 * @param array $params array of sql parameters
1837 * @return int the count
1838 * @throws dml_exception A DML specific exception is thrown for any errors.
1840 public function count_records_sql($sql, array $params=null) {
1841 $count = $this->get_field_sql($sql, $params);
1842 if ($count === false or !is_number($count) or $count < 0) {
1843 throw new coding_exception("count_records_sql() expects the first field to contain non-negative number from COUNT(), '$count' found instead.");
1849 * Test whether a record exists in a table where all the given conditions met.
1851 * @param string $table The table to check.
1852 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1853 * @return bool true if a matching record exists, else false.
1854 * @throws dml_exception A DML specific exception is thrown for any errors.
1856 public function record_exists($table, array $conditions) {
1857 list($select, $params) = $this->where_clause($table, $conditions);
1858 return $this->record_exists_select($table, $select, $params);
1862 * Test whether any records exists in a table which match a particular WHERE clause.
1864 * @param string $table The database table to be checked against.
1865 * @param string $select A fragment of SQL to be used in a WHERE clause in the SQL call.
1866 * @param array $params array of sql parameters
1867 * @return bool true if a matching record exists, else false.
1868 * @throws dml_exception A DML specific exception is thrown for any errors.
1870 public function record_exists_select($table, $select, array $params=null) {
1872 $select = "WHERE $select";
1874 return $this->record_exists_sql("SELECT 'x' FROM {" . $table . "} $select", $params);
1878 * Test whether a SQL SELECT statement returns any records.
1880 * This function returns true if the SQL statement executes
1881 * without any errors and returns at least one record.
1883 * @param string $sql The SQL statement to execute.
1884 * @param array $params array of sql parameters
1885 * @return bool true if the SQL executes without errors and returns at least one record.
1886 * @throws dml_exception A DML specific exception is thrown for any errors.
1888 public function record_exists_sql($sql, array $params=null) {
1889 $mrs = $this->get_recordset_sql($sql, $params, 0, 1);
1890 $return = $mrs->valid();
1896 * Delete the records from a table where all the given conditions met.
1897 * If conditions not specified, table is truncated.
1899 * @param string $table the table to delete from.
1900 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1901 * @return bool true.
1902 * @throws dml_exception A DML specific exception is thrown for any errors.
1904 public function delete_records($table, array $conditions=null) {
1905 // truncate is drop/create (DDL), not transactional safe,
1906 // so we don't use the shortcut within them. MDL-29198
1907 if (is_null($conditions) && empty($this->transactions)) {
1908 return $this->execute("TRUNCATE TABLE {".$table."}");
1910 list($select, $params) = $this->where_clause($table, $conditions);
1911 return $this->delete_records_select($table, $select, $params);
1915 * Delete the records from a table where one field match one list of values.
1917 * @param string $table the table to delete from.
1918 * @param string $field The field to search
1919 * @param array $values array of values
1920 * @return bool true.
1921 * @throws dml_exception A DML specific exception is thrown for any errors.
1923 public function delete_records_list($table, $field, array $values) {
1924 list($select, $params) = $this->where_clause_list($field, $values);
1925 return $this->delete_records_select($table, $select, $params);
1929 * Delete one or more records from a table which match a particular WHERE clause.
1931 * @param string $table The database table to be checked against.
1932 * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
1933 * @param array $params array of sql parameters
1934 * @return bool true.
1935 * @throws dml_exception A DML specific exception is thrown for any errors.
1937 public abstract function delete_records_select($table, $select, array $params=null);
1940 * Returns the FROM clause required by some DBs in all SELECT statements.
1942 * To be used in queries not having FROM clause to provide cross_db
1943 * Most DBs don't need it, hence the default is ''
1946 public function sql_null_from_clause() {
1951 * Returns the SQL text to be used in order to perform one bitwise AND operation
1952 * between 2 integers.
1954 * NOTE: The SQL result is a number and can not be used directly in
1955 * SQL condition, please compare it to some number to get a bool!!
1957 * @param int $int1 First integer in the operation.
1958 * @param int $int2 Second integer in the operation.
1959 * @return string The piece of SQL code to be used in your statement.
1961 public function sql_bitand($int1, $int2) {
1962 return '((' . $int1 . ') & (' . $int2 . '))';
1966 * Returns the SQL text to be used in order to perform one bitwise NOT operation
1969 * @param int $int1 The operand integer in the operation.
1970 * @return string The piece of SQL code to be used in your statement.
1972 public function sql_bitnot($int1) {
1973 return '(~(' . $int1 . '))';
1977 * Returns the SQL text to be used in order to perform one bitwise OR operation
1978 * between 2 integers.
1980 * NOTE: The SQL result is a number and can not be used directly in
1981 * SQL condition, please compare it to some number to get a bool!!
1983 * @param int $int1 The first operand integer in the operation.
1984 * @param int $int2 The second operand integer in the operation.
1985 * @return string The piece of SQL code to be used in your statement.
1987 public function sql_bitor($int1, $int2) {
1988 return '((' . $int1 . ') | (' . $int2 . '))';
1992 * Returns the SQL text to be used in order to perform one bitwise XOR operation
1993 * between 2 integers.
1995 * NOTE: The SQL result is a number and can not be used directly in
1996 * SQL condition, please compare it to some number to get a bool!!
1998 * @param int $int1 The first operand integer in the operation.
1999 * @param int $int2 The second operand integer in the operation.
2000 * @return string The piece of SQL code to be used in your statement.
2002 public function sql_bitxor($int1, $int2) {
2003 return '((' . $int1 . ') ^ (' . $int2 . '))';
2007 * Returns the SQL text to be used in order to perform module '%'
2008 * operation - remainder after division
2010 * @param int $int1 The first operand integer in the operation.
2011 * @param int $int2 The second operand integer in the operation.
2012 * @return string The piece of SQL code to be used in your statement.
2014 public function sql_modulo($int1, $int2) {
2015 return '((' . $int1 . ') % (' . $int2 . '))';
2019 * Returns the cross db correct CEIL (ceiling) expression applied to fieldname.
2020 * note: Most DBs use CEIL(), hence it's the default here.
2022 * @param string $fieldname The field (or expression) we are going to ceil.
2023 * @return string The piece of SQL code to be used in your ceiling statement.
2025 public function sql_ceil($fieldname) {
2026 return ' CEIL(' . $fieldname . ')';
2030 * Returns the SQL to be used in order to CAST one CHAR column to INTEGER.
2032 * Be aware that the CHAR column you're trying to cast contains really
2033 * int values or the RDBMS will throw an error!
2035 * @param string $fieldname The name of the field to be casted.
2036 * @param bool $text Specifies if the original column is one TEXT (CLOB) column (true). Defaults to false.
2037 * @return string The piece of SQL code to be used in your statement.
2039 public function sql_cast_char2int($fieldname, $text=false) {
2040 return ' ' . $fieldname . ' ';
2044 * Returns the SQL to be used in order to CAST one CHAR column to REAL number.
2046 * Be aware that the CHAR column you're trying to cast contains really
2047 * numbers or the RDBMS will throw an error!
2049 * @param string $fieldname The name of the field to be casted.
2050 * @param bool $text Specifies if the original column is one TEXT (CLOB) column (true). Defaults to false.
2051 * @return string The piece of SQL code to be used in your statement.
2053 public function sql_cast_char2real($fieldname, $text=false) {
2054 return ' ' . $fieldname . ' ';
2058 * Returns the SQL to be used in order to an UNSIGNED INTEGER column to SIGNED.
2060 * (Only MySQL needs this. MySQL things that 1 * -1 = 18446744073709551615
2061 * if the 1 comes from an unsigned column).
2063 * @deprecated since 2.3
2064 * @param string $fieldname The name of the field to be cast
2065 * @return string The piece of SQL code to be used in your statement.
2067 public function sql_cast_2signed($fieldname) {
2068 return ' ' . $fieldname . ' ';
2072 * Returns the SQL text to be used to compare one TEXT (clob) column with
2073 * one varchar column, because some RDBMS doesn't support such direct
2076 * @param string $fieldname The name of the TEXT field we need to order by
2077 * @param int $numchars Number of chars to use for the ordering (defaults to 32).
2078 * @return string The piece of SQL code to be used in your statement.
2080 public function sql_compare_text($fieldname, $numchars=32) {
2081 return $this->sql_order_by_text($fieldname, $numchars);
2085 * Returns an equal (=) or not equal (<>) part of a query.
2087 * Note the use of this method may lead to slower queries (full scans) so
2088 * use it only when needed and against already reduced data sets.
2092 * @param string $fieldname Usually the name of the table column.
2093 * @param string $param Usually the bound query parameter (?, :named).
2094 * @param bool $casesensitive Use case sensitive search when set to true (default).
2095 * @param bool $accentsensitive Use accent sensitive search when set to true (default). (not all databases support accent insensitive)
2096 * @param bool $notequal True means not equal (<>)
2097 * @return string The SQL code fragment.
2099 public function sql_equal($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notequal = false) {
2100 // Note that, by default, it's assumed that the correct sql equal operations are
2101 // case sensitive. Only databases not observing this behavior must override the method.
2102 // Also, accent sensitiveness only will be handled by databases supporting it.
2103 $equalop = $notequal ? '<>' : '=';
2104 if ($casesensitive) {
2105 return "$fieldname $equalop $param";
2107 return "LOWER($fieldname) $equalop LOWER($param)";
2112 * Returns 'LIKE' part of a query.
2114 * @param string $fieldname Usually the name of the table column.
2115 * @param string $param Usually the bound query parameter (?, :named).
2116 * @param bool $casesensitive Use case sensitive search when set to true (default).
2117 * @param bool $accentsensitive Use accent sensitive search when set to true (default). (not all databases support accent insensitive)
2118 * @param bool $notlike True means "NOT LIKE".
2119 * @param string $escapechar The escape char for '%' and '_'.
2120 * @return string The SQL code fragment.
2122 public function sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = '\\') {
2123 if (strpos($param, '%') !== false) {
2124 debugging('Potential SQL injection detected, sql_like() expects bound parameters (? or :named)');
2126 $LIKE = $notlike ? 'NOT LIKE' : 'LIKE';
2127 // by default ignore any sensitiveness - each database does it in a different way
2128 return "$fieldname $LIKE $param ESCAPE '$escapechar'";
2132 * Escape sql LIKE special characters like '_' or '%'.
2133 * @param string $text The string containing characters needing escaping.
2134 * @param string $escapechar The desired escape character, defaults to '\\'.
2135 * @return string The escaped sql LIKE string.
2137 public function sql_like_escape($text, $escapechar = '\\') {
2138 $text = str_replace('_', $escapechar.'_', $text);
2139 $text = str_replace('%', $escapechar.'%', $text);
2144 * Returns the proper SQL to do CONCAT between the elements(fieldnames) passed.
2146 * This function accepts variable number of string parameters.
2147 * All strings/fieldnames will used in the SQL concatenate statement generated.
2149 * @return string The SQL to concatenate strings passed in.
2150 * @uses func_get_args() and thus parameters are unlimited OPTIONAL number of additional field names.
2152 public abstract function sql_concat();
2155 * Returns the proper SQL to do CONCAT between the elements passed
2156 * with a given separator
2158 * @param string $separator The separator desired for the SQL concatenating $elements.
2159 * @param array $elements The array of strings to be concatenated.
2160 * @return string The SQL to concatenate the strings.
2162 public abstract function sql_concat_join($separator="' '", $elements=array());
2165 * Returns the proper SQL (for the dbms in use) to concatenate $firstname and $lastname
2167 * @todo MDL-31233 This may not be needed here.
2169 * @param string $first User's first name (default:'firstname').
2170 * @param string $last User's last name (default:'lastname').
2171 * @return string The SQL to concatenate strings.
2173 function sql_fullname($first='firstname', $last='lastname') {
2174 return $this->sql_concat($first, "' '", $last);
2178 * Returns the SQL text to be used to order by one TEXT (clob) column, because
2179 * some RDBMS doesn't support direct ordering of such fields.
2181 * Note that the use or queries being ordered by TEXT columns must be minimised,
2182 * because it's really slooooooow.
2184 * @param string $fieldname The name of the TEXT field we need to order by.
2185 * @param int $numchars The number of chars to use for the ordering (defaults to 32).
2186 * @return string The piece of SQL code to be used in your statement.
2188 public function sql_order_by_text($fieldname, $numchars=32) {
2193 * Returns the SQL text to be used to calculate the length in characters of one expression.
2194 * @param string $fieldname The fieldname/expression to calculate its length in characters.
2195 * @return string the piece of SQL code to be used in the statement.
2197 public function sql_length($fieldname) {
2198 return ' LENGTH(' . $fieldname . ')';
2202 * Returns the proper substr() SQL text used to extract substrings from DB
2203 * NOTE: this was originally returning only function name
2205 * @param string $expr Some string field, no aggregates.
2206 * @param mixed $start Integer or expression evaluating to integer (1 based value; first char has index 1)
2207 * @param mixed $length Optional integer or expression evaluating to integer.
2208 * @return string The sql substring extraction fragment.
2210 public function sql_substr($expr, $start, $length=false) {
2211 if (count(func_get_args()) < 2) {
2212 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.');
2214 if ($length === false) {
2215 return "SUBSTR($expr, $start)";
2217 return "SUBSTR($expr, $start, $length)";
2222 * Returns the SQL for returning searching one string for the location of another.
2224 * Note, there is no guarantee which order $needle, $haystack will be in
2225 * the resulting SQL so when using this method, and both arguments contain
2226 * placeholders, you should use named placeholders.
2228 * @param string $needle the SQL expression that will be searched for.
2229 * @param string $haystack the SQL expression that will be searched in.
2230 * @return string The required searching SQL part.
2232 public function sql_position($needle, $haystack) {
2233 // Implementation using standard SQL.
2234 return "POSITION(($needle) IN ($haystack))";
2238 * This used to return empty string replacement character.
2240 * @deprecated use bound parameter with empty string instead
2242 * @return string An empty string.
2244 function sql_empty() {
2245 debugging("sql_empty() is deprecated, please use empty string '' as sql parameter value instead", DEBUG_DEVELOPER);
2250 * Returns the proper SQL to know if one field is empty.
2252 * Note that the function behavior strongly relies on the
2253 * parameters passed describing the field so, please, be accurate
2254 * when specifying them.
2256 * Also, note that this function is not suitable to look for
2257 * fields having NULL contents at all. It's all for empty values!
2259 * This function should be applied in all the places where conditions of
2262 * ... AND fieldname = '';
2264 * are being used. Final result for text fields should be:
2266 * ... AND ' . sql_isempty('tablename', 'fieldname', true/false, true);
2268 * and for varchar fields result should be:
2270 * ... AND fieldname = :empty; "; $params['empty'] = '';
2272 * (see parameters description below)
2274 * @param string $tablename Name of the table (without prefix). Not used for now but can be
2275 * necessary in the future if we want to use some introspection using
2276 * meta information against the DB. /// TODO ///
2277 * @param string $fieldname Name of the field we are going to check
2278 * @param bool $nullablefield For specifying if the field is nullable (true) or no (false) in the DB.
2279 * @param bool $textfield For specifying if it is a text (also called clob) field (true) or a varchar one (false)
2280 * @return string the sql code to be added to check for empty values
2282 public function sql_isempty($tablename, $fieldname, $nullablefield, $textfield) {
2283 return " ($fieldname = '') ";
2287 * Returns the proper SQL to know if one field is not empty.
2289 * Note that the function behavior strongly relies on the
2290 * parameters passed describing the field so, please, be accurate
2291 * when specifying them.
2293 * This function should be applied in all the places where conditions of
2296 * ... AND fieldname != '';
2298 * are being used. Final result for text fields should be:
2300 * ... AND ' . sql_isnotempty('tablename', 'fieldname', true/false, true/false);
2302 * and for varchar fields result should be:
2304 * ... AND fieldname != :empty; "; $params['empty'] = '';
2306 * (see parameters description below)
2308 * @param string $tablename Name of the table (without prefix). This is not used for now but can be
2309 * necessary in the future if we want to use some introspection using
2310 * meta information against the DB.
2311 * @param string $fieldname The name of the field we are going to check.
2312 * @param bool $nullablefield Specifies if the field is nullable (true) or not (false) in the DB.
2313 * @param bool $textfield Specifies if it is a text (also called clob) field (true) or a varchar one (false).
2314 * @return string The sql code to be added to check for non empty values.
2316 public function sql_isnotempty($tablename, $fieldname, $nullablefield, $textfield) {
2317 return ' ( NOT ' . $this->sql_isempty($tablename, $fieldname, $nullablefield, $textfield) . ') ';
2321 * Returns true if this database driver supports regex syntax when searching.
2322 * @return bool True if supported.
2324 public function sql_regex_supported() {
2329 * Returns the driver specific syntax (SQL part) for matching regex positively or negatively (inverted matching).
2330 * Eg: 'REGEXP':'NOT REGEXP' or '~*' : '!~*'
2331 * @param bool $positivematch
2332 * @return string or empty if not supported
2334 public function sql_regex($positivematch=true) {
2339 * Returns the SQL that allows to find intersection of two or more queries
2343 * @param array $selects array of SQL select queries, each of them only returns fields with the names from $fields
2344 * @param string $fields comma-separated list of fields (used only by some DB engines)
2345 * @return string SQL query that will return only values that are present in each of selects
2347 public function sql_intersect($selects, $fields) {
2348 if (!count($selects)) {
2349 throw new coding_exception('sql_intersect() requires at least one element in $selects');
2350 } else if (count($selects) == 1) {
2353 static $aliascnt = 0;
2354 $rv = '('.$selects[0].')';
2355 for ($i = 1; $i < count($selects); $i++) {
2356 $rv .= " INTERSECT (".$selects[$i].')';
2362 * Does this driver support tool_replace?
2364 * @since Moodle 2.6.1
2367 public function replace_all_text_supported() {
2372 * Replace given text in all rows of column.
2374 * @since Moodle 2.6.1
2375 * @param string $table name of the table
2376 * @param database_column_info $column
2377 * @param string $search
2378 * @param string $replace
2380 public function replace_all_text($table, database_column_info $column, $search, $replace) {
2381 if (!$this->replace_all_text_supported()) {
2385 // NOTE: override this methods if following standard compliant SQL
2386 // does not work for your driver.
2388 $columnname = $column->name;
2389 $sql = "UPDATE {".$table."}
2390 SET $columnname = REPLACE($columnname, ?, ?)
2391 WHERE $columnname IS NOT NULL";
2393 if ($column->meta_type === 'X') {
2394 $this->execute($sql, array($search, $replace));
2396 } else if ($column->meta_type === 'C') {
2397 if (core_text::strlen($search) < core_text::strlen($replace)) {
2398 $colsize = $column->max_length;
2399 $sql = "UPDATE {".$table."}
2400 SET $columnname = " . $this->sql_substr("REPLACE(" . $columnname . ", ?, ?)", 1, $colsize) . "
2401 WHERE $columnname IS NOT NULL";
2403 $this->execute($sql, array($search, $replace));
2408 * Analyze the data in temporary tables to force statistics collection after bulk data loads.
2412 public function update_temp_table_stats() {
2413 $this->temptables->update_stats();
2417 * Checks and returns true if transactions are supported.
2419 * It is not responsible to run productions servers
2420 * on databases without transaction support ;-)
2422 * Override in driver if needed.
2426 protected function transactions_supported() {
2427 // protected for now, this might be changed to public if really necessary
2432 * Returns true if a transaction is in progress.
2435 public function is_transaction_started() {
2436 return !empty($this->transactions);
2440 * This is a test that throws an exception if transaction in progress.
2441 * This test does not force rollback of active transactions.
2443 * @throws dml_transaction_exception if stansaction active
2445 public function transactions_forbidden() {
2446 if ($this->is_transaction_started()) {
2447 throw new dml_transaction_exception('This code can not be excecuted in transaction');
2452 * On DBs that support it, switch to transaction mode and begin a transaction
2453 * you'll need to ensure you call allow_commit() on the returned object
2454 * or your changes *will* be lost.
2456 * this is _very_ useful for massive updates
2458 * Delegated database transactions can be nested, but only one actual database
2459 * transaction is used for the outer-most delegated transaction. This method
2460 * returns a transaction object which you should keep until the end of the
2461 * delegated transaction. The actual database transaction will
2462 * only be committed if all the nested delegated transactions commit
2463 * successfully. If any part of the transaction rolls back then the whole
2464 * thing is rolled back.
2466 * @return moodle_transaction
2468 public function start_delegated_transaction() {
2469 $transaction = new moodle_transaction($this);
2470 $this->transactions[] = $transaction;
2471 if (count($this->transactions) == 1) {
2472 $this->begin_transaction();
2474 return $transaction;
2478 * Driver specific start of real database transaction,
2479 * this can not be used directly in code.
2482 protected abstract function begin_transaction();
2485 * Indicates delegated transaction finished successfully.
2486 * The real database transaction is committed only if
2487 * all delegated transactions committed.
2488 * @param moodle_transaction $transaction The transaction to commit
2490 * @throws dml_transaction_exception Creates and throws transaction related exceptions.
2492 public function commit_delegated_transaction(moodle_transaction $transaction) {
2493 if ($transaction->is_disposed()) {
2494 throw new dml_transaction_exception('Transactions already disposed', $transaction);
2496 // mark as disposed so that it can not be used again
2497 $transaction->dispose();
2499 if (empty($this->transactions)) {
2500 throw new dml_transaction_exception('Transaction not started', $transaction);
2503 if ($this->force_rollback) {
2504 throw new dml_transaction_exception('Tried to commit transaction after lower level rollback', $transaction);
2507 if ($transaction !== $this->transactions[count($this->transactions) - 1]) {
2508 // one incorrect commit at any level rollbacks everything
2509 $this->force_rollback = true;
2510 throw new dml_transaction_exception('Invalid transaction commit attempt', $transaction);
2513 if (count($this->transactions) == 1) {
2514 // only commit the top most level
2515 $this->commit_transaction();
2517 array_pop($this->transactions);
2519 if (empty($this->transactions)) {
2520 \core\event\manager::database_transaction_commited();
2521 \core\message\manager::database_transaction_commited();
2526 * Driver specific commit of real database transaction,
2527 * this can not be used directly in code.
2530 protected abstract function commit_transaction();
2533 * Call when delegated transaction failed, this rolls back
2534 * all delegated transactions up to the top most level.
2536 * In many cases you do not need to call this method manually,
2537 * because all open delegated transactions are rolled back
2538 * automatically if exceptions not caught.
2540 * @param moodle_transaction $transaction An instance of a moodle_transaction.
2541 * @param Exception|Throwable $e The related exception/throwable to this transaction rollback.
2542 * @return void This does not return, instead the exception passed in will be rethrown.
2544 public function rollback_delegated_transaction(moodle_transaction $transaction, $e) {
2545 if (!($e instanceof Exception) && !($e instanceof Throwable)) {
2546 // PHP7 - we catch Throwables in phpunit but can't use that as the type hint in PHP5.
2547 $e = new \coding_exception("Must be given an Exception or Throwable object!");
2549 if ($transaction->is_disposed()) {
2550 throw new dml_transaction_exception('Transactions already disposed', $transaction);
2552 // mark as disposed so that it can not be used again
2553 $transaction->dispose();
2555 // one rollback at any level rollbacks everything
2556 $this->force_rollback = true;
2558 if (empty($this->transactions) or $transaction !== $this->transactions[count($this->transactions) - 1]) {
2559 // this may or may not be a coding problem, better just rethrow the exception,
2560 // because we do not want to loose the original $e
2564 if (count($this->transactions) == 1) {
2565 // only rollback the top most level
2566 $this->rollback_transaction();
2568 array_pop($this->transactions);
2569 if (empty($this->transactions)) {
2570 // finally top most level rolled back
2571 $this->force_rollback = false;
2572 \core\event\manager::database_transaction_rolledback();
2573 \core\message\manager::database_transaction_rolledback();
2579 * Driver specific abort of real database transaction,
2580 * this can not be used directly in code.
2583 protected abstract function rollback_transaction();
2586 * Force rollback of all delegated transaction.
2587 * Does not throw any exceptions and does not log anything.
2589 * This method should be used only from default exception handlers and other
2594 public function force_transaction_rollback() {
2595 if ($this->transactions) {
2597 $this->rollback_transaction();
2598 } catch (dml_exception $e) {
2599 // ignore any sql errors here, the connection might be broken
2603 // now enable transactions again
2604 $this->transactions = array();
2605 $this->force_rollback = false;
2607 \core\event\manager::database_transaction_rolledback();
2608 \core\message\manager::database_transaction_rolledback();
2612 * Is session lock supported in this driver?
2615 public function session_lock_supported() {
2620 * Obtains the session lock.
2621 * @param int $rowid The id of the row with session record.
2622 * @param int $timeout The maximum allowed time to wait for the lock in seconds.
2624 * @throws dml_exception A DML specific exception is thrown for any errors.
2626 public function get_session_lock($rowid, $timeout) {
2627 $this->used_for_db_sessions = true;
2631 * Releases the session lock.
2632 * @param int $rowid The id of the row with session record.
2634 * @throws dml_exception A DML specific exception is thrown for any errors.
2636 public function release_session_lock($rowid) {
2640 * Returns the number of reads done by this database.
2641 * @return int Number of reads.
2643 public function perf_get_reads() {
2644 return $this->reads;
2648 * Returns the number of writes done by this database.
2649 * @return int Number of writes.
2651 public function perf_get_writes() {
2652 return $this->writes;
2656 * Returns the number of queries done by this database.
2657 * @return int Number of queries.
2659 public function perf_get_queries() {
2660 return $this->writes + $this->reads;
2664 * Time waiting for the database engine to finish running all queries.
2665 * @return float Number of seconds with microseconds
2667 public function perf_get_queries_time() {
2668 return $this->queriestime;