3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
20 * Abstract database driver class.
24 * @copyright 2008 Petr Skoda (http://skodak.org)
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') || die();
30 require_once($CFG->libdir.'/dml/database_column_info.php');
31 require_once($CFG->libdir.'/dml/moodle_recordset.php');
32 require_once($CFG->libdir.'/dml/moodle_transaction.php');
34 /// GLOBAL CONSTANTS /////////////////////////////////////////////////////////
36 /** Bitmask, indicates :name type parameters are supported by db backend. */
37 define('SQL_PARAMS_NAMED', 1);
39 /** Bitmask, indicates ? type parameters are supported by db backend. */
40 define('SQL_PARAMS_QM', 2);
42 /** Bitmask, indicates $1, $2, ... type parameters are supported by db backend. */
43 define('SQL_PARAMS_DOLLAR', 4);
46 /** Normal select query, reading only */
47 define('SQL_QUERY_SELECT', 1);
49 /** Insert select query, writing */
50 define('SQL_QUERY_INSERT', 2);
52 /** Update select query, writing */
53 define('SQL_QUERY_UPDATE', 3);
55 /** Query changing db structure, writing */
56 define('SQL_QUERY_STRUCTURE', 4);
58 /** Auxiliary query done by driver, setting connection config, getting table info, etc. */
59 define('SQL_QUERY_AUX', 5);
62 * Abstract class representing moodle database interface.
64 abstract class moodle_database {
66 /** @var database_manager db manager which allows db structure modifications */
67 protected $database_manager;
68 /** @var moodle_temptables temptables manager to provide cross-db support for temp tables */
69 protected $temptables;
70 /** @var array cache of column info */
71 protected $columns = array(); // I wish we had a shared memory cache for this :-(
72 /** @var array cache of table info */
73 protected $tables = null;
75 // db connection options
76 /** @var string db host name */
78 /** @var string db host user */
80 /** @var string db host password */
82 /** @var string db name */
84 /** @var string table prefix */
87 /** @var array Database or driver specific options, such as sockets or TCPIP db connections */
90 /** @var bool true means non-moodle external database used.*/
93 /** @var int The database reads (performance counter).*/
95 /** @var int The database writes (performance counter).*/
96 protected $writes = 0;
98 /** @var int Debug level */
101 /** @var string last query sql */
103 /** @var array last query parameters */
104 protected $last_params;
105 /** @var int last query type */
106 protected $last_type;
107 /** @var string last extra info */
108 protected $last_extrainfo;
109 /** @var float last time in seconds with millisecond precision */
110 protected $last_time;
111 /** @var bool flag indicating logging of query in progress, prevents infinite loops */
112 private $loggingquery = false;
114 /** @var bool true if db used for db sessions */
115 protected $used_for_db_sessions = false;
117 /** @var array open transactions */
118 private $transactions = array();
119 /** @var bool force rollback of all current transactions */
120 private $force_rollback = false;
122 /** @var int internal temporary variable */
123 private $fix_sql_params_i;
124 /** @var int internal temporary variable used by {@link get_in_or_equal()}. */
125 private $inorequaluniqueindex = 1; // guarantees unique parameters in each request
128 * Constructor - instantiates the database, specifying if it's external (connect to other systems) or no (Moodle DB)
129 * note this has effect to decide if prefix checks must be performed or no
130 * @param bool true means external database used
132 public function __construct($external=false) {
133 $this->external = $external;
137 * Destructor - cleans up and flushes everything needed.
139 public function __destruct() {
144 * Detects if all needed PHP stuff installed.
145 * Note: can be used before connect()
146 * @return mixed true if ok, string if something
148 public abstract function driver_installed();
151 * Returns database table prefix
152 * Note: can be used before connect()
153 * @return string database table prefix
155 public function get_prefix() {
156 return $this->prefix;
160 * Loads and returns a database instance with the specified type and library.
161 * @param string $type database type of the driver (mysqli, pgsql, mssql, sqldrv, oci, etc.)
162 * @param string $library database library of the driver (native, pdo, etc.)
163 * @param boolean $external true if this is an external database
164 * @return moodle_database driver object or null if error
166 public static function get_driver_instance($type, $library, $external = false) {
169 $classname = $type.'_'.$library.'_moodle_database';
170 $libfile = "$CFG->libdir/dml/$classname.php";
172 if (!file_exists($libfile)) {
176 require_once($libfile);
177 return new $classname($external);
181 * Returns database family type - describes SQL dialect
182 * Note: can be used before connect()
183 * @return string db family name (mysql, postgres, mssql, oracle, etc.)
185 public abstract function get_dbfamily();
188 * Returns more specific database driver type
189 * Note: can be used before connect()
190 * @return string db type mysqli, pgsql, oci, mssql, sqlsrv
192 protected abstract function get_dbtype();
195 * Returns general database library name
196 * Note: can be used before connect()
197 * @return string db type pdo, native
199 protected abstract function get_dblibrary();
202 * Returns localised database type name
203 * Note: can be used before connect()
206 public abstract function get_name();
209 * Returns localised database configuration help.
210 * Note: can be used before connect()
213 public abstract function get_configuration_help();
216 * Returns localised database description
217 * Note: can be used before connect()
220 public abstract function get_configuration_hints();
223 * Returns db related part of config.php
226 public function export_dbconfig() {
227 $cfg = new stdClass();
228 $cfg->dbtype = $this->get_dbtype();
229 $cfg->dblibrary = $this->get_dblibrary();
230 $cfg->dbhost = $this->dbhost;
231 $cfg->dbname = $this->dbname;
232 $cfg->dbuser = $this->dbuser;
233 $cfg->dbpass = $this->dbpass;
234 $cfg->prefix = $this->prefix;
235 if ($this->dboptions) {
236 $cfg->dboptions = $this->dboptions;
243 * Diagnose database and tables, this function is used
244 * to verify database and driver settings, db engine types, etc.
246 * @return string null means everything ok, string means problem found.
248 public function diagnose() {
254 * Must be called before other methods.
255 * @param string $dbhost
256 * @param string $dbuser
257 * @param string $dbpass
258 * @param string $dbname
259 * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
260 * @param array $dboptions driver specific options
262 * @throws dml_connection_exception if error
264 public abstract function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null);
267 * Store various database settings
268 * @param string $dbhost
269 * @param string $dbuser
270 * @param string $dbpass
271 * @param string $dbname
272 * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
273 * @param array $dboptions driver specific options
276 protected function store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null) {
277 $this->dbhost = $dbhost;
278 $this->dbuser = $dbuser;
279 $this->dbpass = $dbpass;
280 $this->dbname = $dbname;
281 $this->prefix = $prefix;
282 $this->dboptions = (array)$dboptions;
286 * Attempt to create the database
287 * @param string $dbhost
288 * @param string $dbuser
289 * @param string $dbpass
290 * @param string $dbname
292 * @return bool success
294 public function create_database($dbhost, $dbuser, $dbpass, $dbname, array $dboptions=null) {
299 * Close database connection and release all resources
300 * and memory (especially circular memory references).
301 * Do NOT use connect() again, create a new instance if needed.
304 public function dispose() {
305 if ($this->transactions) {
306 // this should not happen, it usually indicates wrong catching of exceptions,
307 // because all transactions should be finished manually or in default exception handler.
308 // unfortunately we can not access global $CFG any more and can not print debug,
309 // the diagnostic info should be printed in footer instead
310 $lowesttransaction = end($this->transactions);
311 $backtrace = $lowesttransaction->get_backtrace();
313 error_log('Potential coding error - active database transaction detected when disposing database:'."\n".format_backtrace($backtrace, true));
314 $this->force_transaction_rollback();
316 if ($this->used_for_db_sessions) {
317 // this is needed because we need to save session to db before closing it
318 session_get_instance()->write_close();
319 $this->used_for_db_sessions = false;
321 if ($this->temptables) {
322 $this->temptables->dispose();
323 $this->temptables = null;
325 if ($this->database_manager) {
326 $this->database_manager->dispose();
327 $this->database_manager = null;
329 $this->columns = array();
330 $this->tables = null;
334 * Called before each db query.
336 * @param array array of parameters
337 * @param int $type type of query
338 * @param mixed $extrainfo driver specific extra information
341 protected function query_start($sql, array $params=null, $type, $extrainfo=null) {
342 if ($this->loggingquery) {
345 $this->last_sql = $sql;
346 $this->last_params = $params;
347 $this->last_type = $type;
348 $this->last_extrainfo = $extrainfo;
349 $this->last_time = microtime(true);
352 case SQL_QUERY_SELECT:
356 case SQL_QUERY_INSERT:
357 case SQL_QUERY_UPDATE:
358 case SQL_QUERY_STRUCTURE:
362 $this->print_debug($sql, $params);
366 * Called immediately after each db query.
367 * @param mixed db specific result
370 protected function query_end($result) {
371 if ($this->loggingquery) {
374 if ($result !== false) {
377 $this->last_sql = null;
378 $this->last_params = null;
382 // remember current info, log queries may alter it
383 $type = $this->last_type;
384 $sql = $this->last_sql;
385 $params = $this->last_params;
386 $time = microtime(true) - $this->last_time;
387 $error = $this->get_last_error();
389 $this->query_log($error);
392 case SQL_QUERY_SELECT:
394 throw new dml_read_exception($error, $sql, $params);
395 case SQL_QUERY_INSERT:
396 case SQL_QUERY_UPDATE:
397 throw new dml_write_exception($error, $sql, $params);
398 case SQL_QUERY_STRUCTURE:
399 $this->get_manager(); // includes ddl exceptions classes ;-)
400 throw new ddl_change_structure_exception($error, $sql);
405 * Log last database query if requested
406 * @param mixed string error or false if not error
409 public function query_log($error=false) {
410 $logall = !empty($this->dboptions['logall']);
411 $logslow = !empty($this->dboptions['logslow']) ? $this->dboptions['logslow'] : false;
412 $logerrors = !empty($this->dboptions['logerrors']);
413 $iserror = ($error !== false);
415 $time = microtime(true) - $this->last_time;
417 if ($logall or ($logslow and ($logslow < ($time+0.00001))) or ($iserror and $logerrors)) {
418 $this->loggingquery = true;
420 $backtrace = debug_backtrace();
423 array_shift($backtrace);
427 array_shift($backtrace);
429 $log = new stdClass();
430 $log->qtype = $this->last_type;
431 $log->sqltext = $this->last_sql;
432 $log->sqlparams = var_export((array)$this->last_params, true);
433 $log->error = (int)$iserror;
434 $log->info = $iserror ? $error : null;
435 $log->backtrace = format_backtrace($backtrace, true);
436 $log->exectime = $time;
437 $log->timelogged = time();
438 $this->insert_record('log_queries', $log);
439 } catch (Exception $ignored) {
441 $this->loggingquery = false;
446 * Returns database server info array
449 public abstract function get_server_info();
452 * Returns supported query parameter types
453 * @return int bitmask
455 protected abstract function allowed_param_types();
458 * Returns last error reported by database engine.
459 * @return string error message
461 public abstract function get_last_error();
464 * Print sql debug info
465 * @param string $sql query which caused problems
466 * @param array $params optional query parameters
467 * @param mixed $obj optional library specific object
470 protected function print_debug($sql, array $params=null, $obj=null) {
471 if (!$this->get_debug()) {
475 echo "--------------------------------\n";
477 if (!is_null($params)) {
478 echo "[".var_export($params, true)."]\n";
480 echo "--------------------------------\n";
484 if (!is_null($params)) {
485 echo "[".s(var_export($params, true))."]\n";
492 * Returns SQL WHERE conditions.
493 * @param string $table - the table name that these conditions will be validated against.
494 * @param array conditions - must not contain numeric indexes
495 * @return array sql part and params
497 protected function where_clause($table, array $conditions=null) {
498 $allowed_types = $this->allowed_param_types();
499 if (empty($conditions)) {
500 return array('', array());
505 $columns = $this->get_columns($table);
506 foreach ($conditions as $key=>$value) {
507 if (!isset($columns[$key])) {
509 $a->fieldname = $key;
510 $a->tablename = $table;
511 throw new dml_exception('ddlfieldnotexist', $a);
513 $column = $columns[$key];
514 if ($column->meta_type == 'X') {
515 //ok so the column is a text column. sorry no text columns in the where clause conditions
516 throw new dml_exception('textconditionsnotallowed', $conditions);
519 throw new dml_exception('invalidnumkey');
521 if (is_null($value)) {
522 $where[] = "$key IS NULL";
524 if ($allowed_types & SQL_PARAMS_NAMED) {
525 // Need to verify key names because they can contain, originally,
526 // spaces and other forbidden chars when using sql_xxx() functions and friends.
527 $normkey = trim(preg_replace('/[^a-zA-Z0-9_-]/', '_', $key), '-_');
528 if ($normkey !== $key) {
529 debugging('Invalid key found in the conditions array.');
531 $where[] = "$key = :$normkey";
532 $params[$normkey] = $value;
534 $where[] = "$key = ?";
539 $where = implode(" AND ", $where);
540 return array($where, $params);
544 * Returns SQL WHERE conditions for the ..._list methods.
546 * @param string $field the name of a field.
547 * @param array $values the values field might take.
548 * @return array sql part and params
550 protected function where_clause_list($field, array $values) {
553 $values = (array)$values;
554 foreach ($values as $value) {
555 if (is_bool($value)) {
556 $value = (int)$value;
558 if (is_null($value)) {
559 $select[] = "$field IS NULL";
561 $select[] = "$field = ?";
565 $select = implode(" OR ", $select);
566 return array($select, $params);
570 * Constructs IN() or = sql fragment
571 * @param mixed $items single or array of values
572 * @param int $type bound param type SQL_PARAMS_QM or SQL_PARAMS_NAMED
573 * @param string $prefix named parameter placeholder prefix (unique counter value is appended to each parameter name)
574 * @param bool $equal true means equal, false not equal
575 * @param mixed $onemptyitems defines the behavior when the array of items is empty. Defaults to false,
576 * meaning throw exceptions. Other values will become part of the returned SQL fragment.
577 * @return array - $sql and $params
579 public function get_in_or_equal($items, $type=SQL_PARAMS_QM, $prefix='param', $equal=true, $onemptyitems=false) {
581 // default behavior, throw exception on empty array
582 if (is_array($items) and empty($items) and $onemptyitems === false) {
583 throw new coding_exception('moodle_database::get_in_or_equal() does not accept empty arrays');
585 // handle $onemptyitems on empty array of items
586 if (is_array($items) and empty($items)) {
587 if (is_null($onemptyitems)) { // Special case, NULL value
588 $sql = $equal ? ' IS NULL' : ' IS NOT NULL';
589 return (array($sql, array()));
591 $items = array($onemptyitems); // Rest of cases, prepare $items for std processing
595 if ($type == SQL_PARAMS_QM) {
596 if (!is_array($items) or count($items) == 1) {
597 $sql = $equal ? '= ?' : '<> ?';
598 $items = (array)$items;
599 $params = array_values($items);
602 $sql = 'IN ('.implode(',', array_fill(0, count($items), '?')).')';
604 $sql = 'NOT IN ('.implode(',', array_fill(0, count($items), '?')).')';
606 $params = array_values($items);
609 } else if ($type == SQL_PARAMS_NAMED) {
610 if (empty($prefix)) {
614 if (!is_array($items)){
615 $param = $prefix.$this->inorequaluniqueindex++;
616 $sql = $equal ? "= :$param" : "<> :$param";
617 $params = array($param=>$items);
618 } else if (count($items) == 1) {
619 $param = $prefix.$this->inorequaluniqueindex++;
620 $sql = $equal ? "= :$param" : "<> :$param";
621 $item = reset($items);
622 $params = array($param=>$item);
626 foreach ($items as $item) {
627 $param = $prefix.$this->inorequaluniqueindex++;
628 $params[$param] = $item;
632 $sql = 'IN ('.implode(',', $sql).')';
634 $sql = 'NOT IN ('.implode(',', $sql).')';
639 throw new dml_exception('typenotimplement');
641 return array($sql, $params);
645 * Converts short table name {tablename} to real table name
649 protected function fix_table_names($sql) {
650 return preg_replace('/\{([a-z][a-z0-9_]*)\}/', $this->prefix.'$1', $sql);
653 /** Internal function */
654 private function _fix_sql_params_dollar_callback($match) {
655 $this->fix_sql_params_i++;
656 return "\$".$this->fix_sql_params_i;
660 * Normalizes sql query parameters and verifies parameters.
661 * @param string $sql query or part of it
662 * @param array $params query parameters
663 * @return array (sql, params, type of params)
665 public function fix_sql_params($sql, array $params=null) {
666 $params = (array)$params; // mke null array if needed
667 $allowed_types = $this->allowed_param_types();
669 // convert table names
670 $sql = $this->fix_table_names($sql);
672 // cast booleans to 1/0 int
673 foreach ($params as $key => $value) {
674 $params[$key] = is_bool($value) ? (int)$value : $value;
677 // NICOLAS C: Fixed regexp for negative backwards lookahead of double colons. Thanks for Sam Marshall's help
678 $named_count = preg_match_all('/(?<!:):[a-z][a-z0-9_]*/', $sql, $named_matches); // :: used in pgsql casts
679 $dollar_count = preg_match_all('/\$[1-9][0-9]*/', $sql, $dollar_matches);
680 $q_count = substr_count($sql, '?');
685 $type = SQL_PARAMS_NAMED;
686 $count = $named_count;
691 throw new dml_exception('mixedtypesqlparam');
693 $type = SQL_PARAMS_DOLLAR;
694 $count = $dollar_count;
699 throw new dml_exception('mixedtypesqlparam');
701 $type = SQL_PARAMS_QM;
708 if ($allowed_types & SQL_PARAMS_NAMED) {
709 return array($sql, array(), SQL_PARAMS_NAMED);
710 } else if ($allowed_types & SQL_PARAMS_QM) {
711 return array($sql, array(), SQL_PARAMS_QM);
713 return array($sql, array(), SQL_PARAMS_DOLLAR);
717 if ($count > count($params)) {
719 $a->expected = $count;
720 $a->actual = count($params);
721 throw new dml_exception('invalidqueryparam', $a);
724 $target_type = $allowed_types;
726 if ($type & $allowed_types) { // bitwise AND
727 if ($count == count($params)) {
728 if ($type == SQL_PARAMS_QM) {
729 return array($sql, array_values($params), SQL_PARAMS_QM); // 0-based array required
731 //better do the validation of names below
734 // needs some fixing or validation - there might be more params than needed
735 $target_type = $type;
738 if ($type == SQL_PARAMS_NAMED) {
739 $finalparams = array();
740 foreach ($named_matches[0] as $key) {
741 $key = trim($key, ':');
742 if (!array_key_exists($key, $params)) {
743 throw new dml_exception('missingkeyinsql', $key, '');
745 $finalparams[$key] = $params[$key];
747 if ($count != count($finalparams)) {
748 throw new dml_exception('duplicateparaminsql');
751 if ($target_type & SQL_PARAMS_QM) {
752 $sql = preg_replace('/(?<!:):[a-z][a-z0-9_]*/', '?', $sql);
753 return array($sql, array_values($finalparams), SQL_PARAMS_QM); // 0-based required
754 } else if ($target_type & SQL_PARAMS_NAMED) {
755 return array($sql, $finalparams, SQL_PARAMS_NAMED);
756 } else { // $type & SQL_PARAMS_DOLLAR
757 //lambda-style functions eat memory - we use globals instead :-(
758 $this->fix_sql_params_i = 0;
759 $sql = preg_replace_callback('/(?<!:):[a-z][a-z0-9_]*/', array($this, '_fix_sql_params_dollar_callback'), $sql);
760 return array($sql, array_values($finalparams), SQL_PARAMS_DOLLAR); // 0-based required
763 } else if ($type == SQL_PARAMS_DOLLAR) {
764 if ($target_type & SQL_PARAMS_DOLLAR) {
765 return array($sql, array_values($params), SQL_PARAMS_DOLLAR); // 0-based required
766 } else if ($target_type & SQL_PARAMS_QM) {
767 $sql = preg_replace('/\$[0-9]+/', '?', $sql);
768 return array($sql, array_values($params), SQL_PARAMS_QM); // 0-based required
769 } else { //$target_type & SQL_PARAMS_NAMED
770 $sql = preg_replace('/\$([0-9]+)/', ':param\\1', $sql);
771 $finalparams = array();
772 foreach ($params as $key=>$param) {
774 $finalparams['param'.$key] = $param;
776 return array($sql, $finalparams, SQL_PARAMS_NAMED);
779 } else { // $type == SQL_PARAMS_QM
780 if (count($params) != $count) {
781 $params = array_slice($params, 0, $count);
784 if ($target_type & SQL_PARAMS_QM) {
785 return array($sql, array_values($params), SQL_PARAMS_QM); // 0-based required
786 } else if ($target_type & SQL_PARAMS_NAMED) {
787 $finalparams = array();
789 $parts = explode('?', $sql);
790 $sql = array_shift($parts);
791 foreach ($parts as $part) {
792 $param = array_shift($params);
794 $sql .= ':'.$pname.$part;
795 $finalparams[$pname] = $param;
797 return array($sql, $finalparams, SQL_PARAMS_NAMED);
798 } else { // $type & SQL_PARAMS_DOLLAR
799 //lambda-style functions eat memory - we use globals instead :-(
800 $this->fix_sql_params_i = 0;
801 $sql = preg_replace_callback('/\?/', array($this, '_fix_sql_params_dollar_callback'), $sql);
802 return array($sql, array_values($params), SQL_PARAMS_DOLLAR); // 0-based required
808 * Return tables in database WITHOUT current prefix
809 * @return array of table names in lowercase and without prefix
811 public abstract function get_tables($usecache=true);
814 * Return table indexes - everything lowercased
815 * @return array of arrays
817 public abstract function get_indexes($table);
820 * Returns detailed information about columns in table. This information is cached internally.
821 * @param string $table name
822 * @param bool $usecache
823 * @return array of database_column_info objects indexed with column names
825 public abstract function get_columns($table, $usecache=true);
828 * Normalise values based in RDBMS dependencies (booleans, LOBs...)
830 * @param database_column_info $column column metadata corresponding with the value we are going to normalise
831 * @param mixed $value value we are going to normalise
832 * @return mixed the normalised value
834 protected abstract function normalise_value($column, $value);
837 * Reset internal column details cache
838 * @param string $table - empty means all, or one if name of table given
841 public function reset_caches() {
842 $this->columns = array();
843 $this->tables = null;
847 * Returns sql generator used for db manipulation.
848 * Used mostly in upgrade.php scripts.
849 * @return database_manager instance
851 public function get_manager() {
854 if (!$this->database_manager) {
855 require_once($CFG->libdir.'/ddllib.php');
857 $classname = $this->get_dbfamily().'_sql_generator';
858 require_once("$CFG->libdir/ddl/$classname.php");
859 $generator = new $classname($this, $this->temptables);
861 $this->database_manager = new database_manager($this, $generator);
863 return $this->database_manager;
867 * Attempt to change db encoding toUTF-8 if possible
868 * @return bool success
870 public function change_db_encoding() {
875 * Is db in unicode mode?
878 public function setup_is_unicodedb() {
883 * Enable/disable very detailed debugging
887 public function set_debug($state) {
888 $this->debug = $state;
892 * Returns debug status
893 * @return bool $state
895 public function get_debug() {
900 * Enable/disable detailed sql logging
903 public function set_logging($state) {
904 // adodb sql logging shares one table without prefix per db - this is no longer acceptable :-(
905 // we must create one table shared by all drivers
909 * Do NOT use in code, to be used by database_manager only!
910 * @param string $sql query
912 * @throws dml_exception if error
914 public abstract function change_database_structure($sql);
917 * Execute general sql query. Should be used only when no other method suitable.
918 * Do NOT use this to make changes in db structure, use database_manager::execute_sql() instead!
919 * @param string $sql query
920 * @param array $params query parameters
922 * @throws dml_exception if error
924 public abstract function execute($sql, array $params=null);
927 * Get a number of records as a moodle_recordset where all the given conditions met.
929 * Selects records from the table $table.
931 * If specified, only records meeting $conditions.
933 * If specified, the results will be sorted as specified by $sort. This
934 * is added to the SQL as "ORDER BY $sort". Example values of $sort
935 * might be "time ASC" or "time DESC".
937 * If $fields is specified, only those fields are returned.
939 * Since this method is a little less readable, use of it should be restricted to
940 * code where it's possible there might be large datasets being returned. For known
941 * small datasets use get_records - it leads to simpler code.
943 * If you only want some of the records, specify $limitfrom and $limitnum.
944 * The query will skip the first $limitfrom records (according to the sort
945 * order) and then return the next $limitnum records. If either of $limitfrom
946 * or $limitnum is specified, both must be present.
948 * The return value is a moodle_recordset
949 * if the query succeeds. If an error occurs, false is returned.
951 * @param string $table the table to query.
952 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
953 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
954 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
955 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
956 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
957 * @return moodle_recordset instance
958 * @throws dml_exception if error
960 public function get_recordset($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
961 list($select, $params) = $this->where_clause($table, $conditions);
962 return $this->get_recordset_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
966 * Get a number of records as a moodle_recordset where one field match one list of values.
968 * Only records where $field takes one of the values $values are returned.
969 * $values must be an array of values.
971 * Other arguments and the return type as for @see function get_recordset.
973 * @param string $table the table to query.
974 * @param string $field a field to check (optional).
975 * @param array $values array of values the field must have
976 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
977 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
978 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
979 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
980 * @return moodle_recordset instance
981 * @throws dml_exception if error
983 public function get_recordset_list($table, $field, array $values, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
984 list($select, $params) = $this->where_clause_list($field, $values);
985 if (empty($select)) {
986 $select = '1 = 2'; /// Fake condition, won't return rows ever. MDL-17645
989 return $this->get_recordset_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
993 * Get a number of records as a moodle_recordset which match a particular WHERE clause.
995 * If given, $select is used as the SELECT parameter in the SQL query,
996 * otherwise all records from the table are returned.
998 * Other arguments and the return type as for @see function get_recordset.
1000 * @param string $table the table to query.
1001 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1002 * @param array $params array of sql parameters
1003 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1004 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
1005 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
1006 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1007 * @return moodle_recordset instance
1008 * @throws dml_exception if error
1010 public function get_recordset_select($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1011 $sql = "SELECT $fields FROM {".$table."}";
1013 $sql .= " WHERE $select";
1016 $sql .= " ORDER BY $sort";
1018 return $this->get_recordset_sql($sql, $params, $limitfrom, $limitnum);
1022 * Get a number of records as a moodle_recordset using a SQL statement.
1024 * Since this method is a little less readable, use of it should be restricted to
1025 * code where it's possible there might be large datasets being returned. For known
1026 * small datasets use get_records_sql - it leads to simpler code.
1028 * The return type is as for @see function get_recordset.
1030 * @param string $sql the SQL select query to execute.
1031 * @param array $params array of sql parameters
1032 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
1033 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1034 * @return moodle_recordset instance
1035 * @throws dml_exception if error
1037 public abstract function get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0);
1040 * Get a number of records as an array of objects where all the given conditions met.
1042 * If the query succeeds and returns at least one record, the
1043 * return value is an array of objects, one object for each
1044 * record found. The array key is the value from the first
1045 * column of the result set. The object associated with that key
1046 * has a member variable for each column of the results.
1048 * @param string $table the table to query.
1049 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1050 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1051 * @param string $fields a comma separated list of fields to return (optional, by default
1052 * all fields are returned). The first field will be used as key for the
1053 * array so must be a unique field such as 'id'.
1054 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
1055 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1056 * @return array of objects indexed by first column
1057 * @throws dml_exception if error
1059 public function get_records($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1060 list($select, $params) = $this->where_clause($table, $conditions);
1061 return $this->get_records_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1065 * Get a number of records as an array of objects where one field match one list of values.
1067 * Return value as for @see function get_records.
1069 * @param string $table The database table to be checked against.
1070 * @param string $field The field to search
1071 * @param string $values array of values
1072 * @param string $sort Sort order (as valid SQL sort parameter)
1073 * @param string $fields A comma separated list of fields to be returned from the chosen table. If specified,
1074 * the first field should be a unique one such as 'id' since it will be used as a key in the associative
1076 * @return array of objects indexed by first column
1077 * @throws dml_exception if error
1079 public function get_records_list($table, $field, array $values, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1080 list($select, $params) = $this->where_clause_list($field, $values);
1081 if (empty($select)) {
1082 // nothing to return
1085 return $this->get_records_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1089 * Get a number of records as an array of objects which match a particular WHERE clause.
1091 * Return value as for @see function get_records.
1093 * @param string $table the table to query.
1094 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1095 * @param array $params array of sql parameters
1096 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1097 * @param string $fields a comma separated list of fields to return
1098 * (optional, by default all fields are returned). The first field will be used as key for the
1099 * array so must be a unique field such as 'id'.
1100 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
1101 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1102 * @return array of objects indexed by first column
1103 * @throws dml_exception if error
1105 public function get_records_select($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1107 $select = "WHERE $select";
1110 $sort = " ORDER BY $sort";
1112 return $this->get_records_sql("SELECT $fields FROM {" . $table . "} $select $sort", $params, $limitfrom, $limitnum);
1116 * Get a number of records as an array of objects using a SQL statement.
1118 * Return value as for @see function get_records.
1120 * @param string $sql the SQL select query to execute. The first column of this SELECT statement
1121 * must be a unique value (usually the 'id' field), as it will be used as the key of the
1123 * @param array $params array of sql parameters
1124 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
1125 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1126 * @return array of objects indexed by first column
1127 * @throws dml_exception if error
1129 public abstract function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0);
1132 * Get the first two columns from a number of records as an associative array where all the given conditions met.
1134 * Arguments as for @see function get_recordset.
1136 * If no errors occur the return value
1137 * is an associative whose keys come from the first field of each record,
1138 * and whose values are the corresponding second fields.
1139 * False is returned if an error occurs.
1141 * @param string $table the table to query.
1142 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1143 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1144 * @param string $fields a comma separated list of fields to return - the number of fields should be 2!
1145 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
1146 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1147 * @return array an associative array
1148 * @throws dml_exception if error
1150 public function get_records_menu($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1152 if ($records = $this->get_records($table, $conditions, $sort, $fields, $limitfrom, $limitnum)) {
1153 foreach ($records as $record) {
1154 $record = (array)$record;
1155 $key = array_shift($record);
1156 $value = array_shift($record);
1157 $menu[$key] = $value;
1164 * Get the first two columns from a number of records as an associative array which match a particular WHERE clause.
1166 * Arguments as for @see function get_recordset_select.
1167 * Return value as for @see function get_records_menu.
1169 * @param string $table The database table to be checked against.
1170 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1171 * @param array $params array of sql parameters
1172 * @param string $sort Sort order (optional) - a valid SQL order parameter
1173 * @param string $fields A comma separated list of fields to be returned from the chosen table - the number of fields should be 2!
1174 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
1175 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1176 * @return array an associative array
1177 * @throws dml_exception if error
1179 public function get_records_select_menu($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1181 if ($records = $this->get_records_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum)) {
1182 foreach ($records as $record) {
1183 $record = (array)$record;
1184 $key = array_shift($record);
1185 $value = array_shift($record);
1186 $menu[$key] = $value;
1193 * Get the first two columns from a number of records as an associative array using a SQL statement.
1195 * Arguments as for @see function get_recordset_sql.
1196 * Return value as for @see function get_records_menu.
1198 * @param string $sql The SQL string you wish to be executed.
1199 * @param array $params array of sql parameters
1200 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
1201 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1202 * @return array an associative array
1203 * @throws dml_exception if error
1205 public function get_records_sql_menu($sql, array $params=null, $limitfrom=0, $limitnum=0) {
1207 if ($records = $this->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
1208 foreach ($records as $record) {
1209 $record = (array)$record;
1210 $key = array_shift($record);
1211 $value = array_shift($record);
1212 $menu[$key] = $value;
1219 * Get a single database record as an object where all the given conditions met.
1221 * @param string $table The table to select from.
1222 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1223 * @param string $fields A comma separated list of fields to be returned from the chosen table.
1224 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1225 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1226 * MUST_EXIST means throw exception if no record or multiple records found
1227 * @return mixed a fieldset object containing the first matching record, false or exception if error not found depending on mode
1228 * @throws dml_exception if error
1230 public function get_record($table, array $conditions, $fields='*', $strictness=IGNORE_MISSING) {
1231 list($select, $params) = $this->where_clause($table, $conditions);
1232 return $this->get_record_select($table, $select, $params, $fields, $strictness);
1236 * Get a single database record as an object which match a particular WHERE clause.
1238 * @param string $table The database table to be checked against.
1239 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1240 * @param array $params array of sql parameters
1241 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1242 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1243 * MUST_EXIST means throw exception if no record or multiple records found
1244 * @return mixed a fieldset object containing the first matching record, false or exception if error not found depending on mode
1245 * @throws dml_exception if error
1247 public function get_record_select($table, $select, array $params=null, $fields='*', $strictness=IGNORE_MISSING) {
1249 $select = "WHERE $select";
1252 return $this->get_record_sql("SELECT $fields FROM {" . $table . "} $select", $params, $strictness);
1253 } catch (dml_missing_record_exception $e) {
1254 // create new exception which will contain correct table name
1255 throw new dml_missing_record_exception($table, $e->sql, $e->params);
1260 * Get a single database record as an object using a SQL statement.
1262 * The SQL statement should normally only return one record.
1263 * It is recommended to use get_records_sql() if more matches possible!
1265 * @param string $sql The SQL string you wish to be executed, should normally only return one record.
1266 * @param array $params array of sql parameters
1267 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1268 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1269 * MUST_EXIST means throw exception if no record or multiple records found
1270 * @return mixed a fieldset object containing the first matching record, false or exception if error not found depending on mode
1271 * @throws dml_exception if error
1273 public function get_record_sql($sql, array $params=null, $strictness=IGNORE_MISSING) {
1274 $strictness = (int)$strictness; // we support true/false for BC reasons too
1275 if ($strictness == IGNORE_MULTIPLE) {
1280 if (!$records = $this->get_records_sql($sql, $params, 0, $count)) {
1282 if ($strictness == MUST_EXIST) {
1283 throw new dml_missing_record_exception('', $sql, $params);
1288 if (count($records) > 1) {
1289 if ($strictness == MUST_EXIST) {
1290 throw new dml_multiple_records_exception($sql, $params);
1292 debugging('Error: mdb->get_record() found more than one record!');
1295 $return = reset($records);
1300 * Get a single field value from a table record where all the given conditions met.
1302 * @param string $table the table to query.
1303 * @param string $return the field to return the value of.
1304 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1305 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1306 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1307 * MUST_EXIST means throw exception if no record or multiple records found
1308 * @return mixed the specified value false if not found
1309 * @throws dml_exception if error
1311 public function get_field($table, $return, array $conditions, $strictness=IGNORE_MISSING) {
1312 list($select, $params) = $this->where_clause($table, $conditions);
1313 return $this->get_field_select($table, $return, $select, $params, $strictness);
1317 * Get a single field value from a table record which match a particular WHERE clause.
1319 * @param string $table the table to query.
1320 * @param string $return the field to return the value of.
1321 * @param string $select A fragment of SQL to be used in a where clause returning one row with one column
1322 * @param array $params array of sql parameters
1323 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1324 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1325 * MUST_EXIST means throw exception if no record or multiple records found
1326 * @return mixed the specified value false if not found
1327 * @throws dml_exception if error
1329 public function get_field_select($table, $return, $select, array $params=null, $strictness=IGNORE_MISSING) {
1331 $select = "WHERE $select";
1334 return $this->get_field_sql("SELECT $return FROM {" . $table . "} $select", $params, $strictness);
1335 } catch (dml_missing_record_exception $e) {
1336 // create new exception which will contain correct table name
1337 throw new dml_missing_record_exception($table, $e->sql, $e->params);
1342 * Get a single field value (first field) using a SQL statement.
1344 * @param string $table the table to query.
1345 * @param string $return the field to return the value of.
1346 * @param string $sql The SQL query returning one row with one column
1347 * @param array $params array of sql parameters
1348 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1349 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1350 * MUST_EXIST means throw exception if no record or multiple records found
1351 * @return mixed the specified value false if not found
1352 * @throws dml_exception if error
1354 public function get_field_sql($sql, array $params=null, $strictness=IGNORE_MISSING) {
1355 if (!$record = $this->get_record_sql($sql, $params, $strictness)) {
1359 $record = (array)$record;
1360 return reset($record); // first column
1364 * Selects records and return values of chosen field as an array which match a particular WHERE clause.
1366 * @param string $table the table to query.
1367 * @param string $return the field we are intered in
1368 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1369 * @param array $params array of sql parameters
1370 * @return array of values
1371 * @throws dml_exception if error
1373 public function get_fieldset_select($table, $return, $select, array $params=null) {
1375 $select = "WHERE $select";
1377 return $this->get_fieldset_sql("SELECT $return FROM {" . $table . "} $select", $params);
1381 * Selects records and return values (first field) as an array using a SQL statement.
1383 * @param string $sql The SQL query
1384 * @param array $params array of sql parameters
1385 * @return array of values
1386 * @throws dml_exception if error
1388 public abstract function get_fieldset_sql($sql, array $params=null);
1391 * Insert new record into database, as fast as possible, no safety checks, lobs not supported.
1392 * @param string $table name
1393 * @param mixed $params data record as object or array
1394 * @param bool $returnit return it of inserted record
1395 * @param bool $bulk true means repeated inserts expected
1396 * @param bool $customsequence true if 'id' included in $params, disables $returnid
1397 * @return bool|int true or new id
1398 * @throws dml_exception if error
1400 public abstract function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false);
1403 * Insert a record into a table and return the "id" field if required.
1405 * Some conversions and safety checks are carried out. Lobs are supported.
1406 * If the return ID isn't required, then this just reports success as true/false.
1407 * $data is an object containing needed data
1408 * @param string $table The database table to be inserted into
1409 * @param object $data A data object with values for one or more fields in the record
1410 * @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.
1411 * @return bool|int true or new id
1412 * @throws dml_exception if error
1414 public abstract function insert_record($table, $dataobject, $returnid=true, $bulk=false);
1417 * Import a record into a table, id field is required.
1418 * Safety checks are NOT carried out. Lobs are supported.
1420 * @param string $table name of database table to be inserted into
1421 * @param object $dataobject A data object with values for one or more fields in the record
1423 * @throws dml_exception if error
1425 public abstract function import_record($table, $dataobject);
1428 * Update record in database, as fast as possible, no safety checks, lobs not supported.
1429 * @param string $table name
1430 * @param mixed $params data record as object or array
1431 * @param bool true means repeated updates expected
1433 * @throws dml_exception if error
1435 public abstract function update_record_raw($table, $params, $bulk=false);
1438 * Update a record in a table
1440 * $dataobject is an object containing needed data
1441 * Relies on $dataobject having a variable "id" to
1442 * specify the record to update
1444 * @param string $table The database table to be checked against.
1445 * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
1446 * @param bool true means repeated updates expected
1448 * @throws dml_exception if error
1450 public abstract function update_record($table, $dataobject, $bulk=false);
1454 * Set a single field in every table record where all the given conditions met.
1456 * @param string $table The database table to be checked against.
1457 * @param string $newfield the field to set.
1458 * @param string $newvalue the value to set the field to.
1459 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1461 * @throws dml_exception if error
1463 public function set_field($table, $newfield, $newvalue, array $conditions=null) {
1464 list($select, $params) = $this->where_clause($table, $conditions);
1465 return $this->set_field_select($table, $newfield, $newvalue, $select, $params);
1469 * Set a single field in every table record which match a particular WHERE clause.
1471 * @param string $table The database table to be checked against.
1472 * @param string $newfield the field to set.
1473 * @param string $newvalue the value to set the field to.
1474 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1475 * @param array $params array of sql parameters
1477 * @throws dml_exception if error
1479 public abstract function set_field_select($table, $newfield, $newvalue, $select, array $params=null);
1483 * Count the records in a table where all the given conditions met.
1485 * @param string $table The table to query.
1486 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1487 * @return int The count of records returned from the specified criteria.
1488 * @throws dml_exception if error
1490 public function count_records($table, array $conditions=null) {
1491 list($select, $params) = $this->where_clause($table, $conditions);
1492 return $this->count_records_select($table, $select, $params);
1496 * Count the records in a table which match a particular WHERE clause.
1498 * @param string $table The database table to be checked against.
1499 * @param string $select A fragment of SQL to be used in a WHERE clause in the SQL call.
1500 * @param array $params array of sql parameters
1501 * @param string $countitem The count string to be used in the SQL call. Default is COUNT('x').
1502 * @return int The count of records returned from the specified criteria.
1503 * @throws dml_exception if error
1505 public function count_records_select($table, $select, array $params=null, $countitem="COUNT('x')") {
1507 $select = "WHERE $select";
1509 return $this->count_records_sql("SELECT $countitem FROM {" . $table . "} $select", $params);
1513 * Get the result of a SQL SELECT COUNT(...) query.
1515 * Given a query that counts rows, return that count. (In fact,
1516 * given any query, return the first field of the first record
1517 * returned. However, this method should only be used for the
1518 * intended purpose.) If an error occurs, 0 is returned.
1520 * @param string $sql The SQL string you wish to be executed.
1521 * @param array $params array of sql parameters
1522 * @return int the count
1523 * @throws dml_exception if error
1525 public function count_records_sql($sql, array $params=null) {
1526 if ($count = $this->get_field_sql($sql, $params)) {
1534 * Test whether a record exists in a table where all the given conditions met.
1536 * The record to test is specified by giving up to three fields that must
1537 * equal the corresponding values.
1539 * @param string $table The table to check.
1540 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1541 * @return bool true if a matching record exists, else false.
1542 * @throws dml_exception if error
1544 public function record_exists($table, array $conditions) {
1545 list($select, $params) = $this->where_clause($table, $conditions);
1546 return $this->record_exists_select($table, $select, $params);
1550 * Test whether any records exists in a table which match a particular WHERE clause.
1552 * @param string $table The database table to be checked against.
1553 * @param string $select A fragment of SQL to be used in a WHERE clause in the SQL call.
1554 * @param array $params array of sql parameters
1555 * @return bool true if a matching record exists, else false.
1556 * @throws dml_exception if error
1558 public function record_exists_select($table, $select, array $params=null) {
1560 $select = "WHERE $select";
1562 return $this->record_exists_sql("SELECT 'x' FROM {" . $table . "} $select", $params);
1566 * Test whether a SQL SELECT statement returns any records.
1568 * This function returns true if the SQL statement executes
1569 * without any errors and returns at least one record.
1571 * @param string $sql The SQL statement to execute.
1572 * @param array $params array of sql parameters
1573 * @return bool true if the SQL executes without errors and returns at least one record.
1574 * @throws dml_exception if error
1576 public function record_exists_sql($sql, array $params=null) {
1577 $mrs = $this->get_recordset_sql($sql, $params, 0, 1);
1578 $return = $mrs->valid();
1584 * Delete the records from a table where all the given conditions met.
1585 * If conditions not specified, table is truncated.
1587 * @param string $table the table to delete from.
1588 * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1589 * @return bool true.
1590 * @throws dml_exception if error
1592 public function delete_records($table, array $conditions=null) {
1593 if (is_null($conditions)) {
1594 return $this->execute("TRUNCATE TABLE {".$table."}");
1596 list($select, $params) = $this->where_clause($table, $conditions);
1597 return $this->delete_records_select($table, $select, $params);
1601 * Delete the records from a table where one field match one list of values.
1603 * @param string $table the table to delete from.
1604 * @param string $field The field to search
1605 * @param array $values array of values
1606 * @return bool true.
1607 * @throws dml_exception if error
1609 public function delete_records_list($table, $field, array $values) {
1610 list($select, $params) = $this->where_clause_list($field, $values);
1611 if (empty($select)) {
1612 // nothing to delete
1615 return $this->delete_records_select($table, $select, $params);
1619 * Delete one or more records from a table which match a particular WHERE clause.
1621 * @param string $table The database table to be checked against.
1622 * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
1623 * @param array $params array of sql parameters
1624 * @return bool true.
1625 * @throws dml_exception if error
1627 public abstract function delete_records_select($table, $select, array $params=null);
1633 * Returns the FROM clause required by some DBs in all SELECT statements.
1635 * To be used in queries not having FROM clause to provide cross_db
1636 * Most DBs don't need it, hence the default is ''
1639 public function sql_null_from_clause() {
1644 * Returns the SQL text to be used in order to perform one bitwise AND operation
1645 * between 2 integers.
1647 * NOTE: The SQL result is a number and can not be used directly in
1648 * SQL condition, please compare it to some number to get a bool!!
1650 * @param int $int1 first integer in the operation
1651 * @param int $int2 second integer in the operation
1652 * @return string the piece of SQL code to be used in your statement
1654 public function sql_bitand($int1, $int2) {
1655 return '((' . $int1 . ') & (' . $int2 . '))';
1659 * Returns the SQL text to be used in order to perform one bitwise NOT operation
1662 * @param int $int1 integer in the operation
1663 * @return string the piece of SQL code to be used in your statement.
1665 public function sql_bitnot($int1) {
1666 return '(~(' . $int1 . '))';
1670 * Returns the SQL text to be used in order to perform one bitwise OR operation
1671 * between 2 integers.
1673 * NOTE: The SQL result is a number and can not be used directly in
1674 * SQL condition, please compare it to some number to get a bool!!
1676 * @param int $int1 first integer in the operation
1677 * @param int $int2 second integer in the operation
1678 * @return string the piece of SQL code to be used in your statement.
1680 public function sql_bitor($int1, $int2) {
1681 return '((' . $int1 . ') | (' . $int2 . '))';
1685 * Returns the SQL text to be used in order to perform one bitwise XOR operation
1686 * between 2 integers.
1688 * NOTE: The SQL result is a number and can not be used directly in
1689 * SQL condition, please compare it to some number to get a bool!!
1691 * @param int $int1 first integer in the operation
1692 * @param int $int2 second integer in the operation
1693 * @return string the piece of SQL code to be used in your statement.
1695 public function sql_bitxor($int1, $int2) {
1696 return '((' . $int1 . ') ^ (' . $int2 . '))';
1700 * Returns the SQL text to be used in order to perform module '%'
1701 * operation - remainder after division
1703 * @param int $int1 first integer in the operation
1704 * @param int $int2 second integer in the operation
1705 * @return string the piece of SQL code to be used in your statement.
1707 public function sql_modulo($int1, $int2) {
1708 return '((' . $int1 . ') % (' . $int2 . '))';
1712 * Returns the correct CEIL expression applied to fieldname.
1714 * @param string $fieldname the field (or expression) we are going to ceil
1715 * @return string the piece of SQL code to be used in your ceiling statement
1716 * Most DB use CEIL(), hence it's the default.
1718 public function sql_ceil($fieldname) {
1719 return ' CEIL(' . $fieldname . ')';
1723 * Returns the SQL to be used in order to CAST one CHAR column to INTEGER.
1725 * Be aware that the CHAR column you're trying to cast contains really
1726 * int values or the RDBMS will throw an error!
1728 * @param string $fieldname the name of the field to be casted
1729 * @param bool $text to specify if the original column is one TEXT (CLOB) column (true). Defaults to false.
1730 * @return string the piece of SQL code to be used in your statement.
1732 public function sql_cast_char2int($fieldname, $text=false) {
1733 return ' ' . $fieldname . ' ';
1737 * Returns the SQL to be used in order to CAST one CHAR column to REAL number.
1739 * Be aware that the CHAR column you're trying to cast contains really
1740 * numbers or the RDBMS will throw an error!
1742 * @param string $fieldname the name of the field to be casted
1743 * @param bool $text to specify if the original column is one TEXT (CLOB) column (true). Defaults to false.
1744 * @return string the piece of SQL code to be used in your statement.
1746 public function sql_cast_char2real($fieldname, $text=false) {
1747 return ' ' . $fieldname . ' ';
1751 * Returns the SQL to be used in order to an UNSIGNED INTEGER column to SIGNED.
1753 * (Only MySQL needs this. MySQL things that 1 * -1 = 18446744073709551615
1754 * if the 1 comes from an unsigned column).
1756 * @param string $fieldname the name of the field to be cast
1757 * @return string the piece of SQL code to be used in your statement.
1759 public function sql_cast_2signed($fieldname) {
1760 return ' ' . $fieldname . ' ';
1764 * Returns the SQL text to be used to compare one TEXT (clob) column with
1765 * one varchar column, because some RDBMS doesn't support such direct
1768 * @param string $fieldname the name of the TEXT field we need to order by
1769 * @param int $numchars of chars to use for the ordering (defaults to 32)
1770 * @return string the piece of SQL code to be used in your statement.
1772 public function sql_compare_text($fieldname, $numchars=32) {
1773 return $this->sql_order_by_text($fieldname, $numchars);
1777 * Returns 'LIKE' part of a query.
1779 * @param string $fieldname usually name of the table column
1780 * @param string $param usually bound query parameter (?, :named)
1781 * @param bool $casesensitive use case sensitive search
1782 * @param bool $accensensitive use accent sensitive search (not all databases support accent insensitive)
1783 * @param bool $notlike true means "NOT LIKE"
1784 * @param string $escapechar escape char for '%' and '_'
1785 * @return string SQL code fragment
1787 public function sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = '\\') {
1788 if (strpos($param, '%') !== false) {
1789 debugging('Potential SQL injection detected, sql_like() expects bound parameters (? or :named)');
1791 $LIKE = $notlike ? 'NOT LIKE' : 'LIKE';
1792 // by default ignore any sensitiveness - each database does it in a different way
1793 return "$fieldname $LIKE $param ESCAPE '$escapechar'";
1797 * Escape sql LIKE special characters.
1798 * @param string $text
1799 * @param string $escapechar
1802 public function sql_like_escape($text, $escapechar = '\\') {
1803 $text = str_replace('_', $escapechar.'_', $text);
1804 $text = str_replace('%', $escapechar.'%', $text);
1809 * Returns the proper SQL to do LIKE in a case-insensitive way.
1811 * Note the LIKE are case sensitive for Oracle. Oracle 10g is required to use
1812 * the case insensitive search using regexp_like() or NLS_COMP=LINGUISTIC :-(
1813 * See http://docs.moodle.org/en/XMLDB_Problems#Case-insensitive_searches
1818 public function sql_ilike() {
1819 debugging('sql_ilike() is deprecated, please use sql_like() instead');
1824 * Returns the proper SQL to do CONCAT between the elements passed
1825 * Can take many parameters
1827 * This function accepts variable number of string parameters.
1831 public abstract function sql_concat();
1834 * Returns the proper SQL to do CONCAT between the elements passed
1835 * with a given separator
1837 * @param string $separator
1838 * @param array $elements
1841 public abstract function sql_concat_join($separator="' '", $elements=array());
1844 * Returns the proper SQL (for the dbms in use) to concatenate $firstname and $lastname
1845 * TODO: Does this really need to be here? Eloy 20070727.
1846 * TODO: we definitely do not! (skodak)
1848 * @param string $first User's first name
1849 * @param string $last User's last name
1852 function sql_fullname($first='firstname', $last='lastname') {
1853 return $this->sql_concat($first, "' '", $last);
1857 * Returns the SQL text to be used to order by one TEXT (clob) column, because
1858 * some RDBMS doesn't support direct ordering of such fields.
1860 * Note that the use or queries being ordered by TEXT columns must be minimised,
1861 * because it's really slooooooow.
1863 * @param string $fieldname the name of the TEXT field we need to order by
1864 * @param string $numchars of chars to use for the ordering (defaults to 32)
1865 * @return string the piece of SQL code to be used in your statement.
1867 public function sql_order_by_text($fieldname, $numchars=32) {
1872 * Returns the SQL text to be used to calculate the length in characters of one expression.
1873 * @param string $fieldname or expression to calculate its length in characters.
1874 * @return string the piece of SQL code to be used in the statement.
1876 public function sql_length($fieldname) {
1877 return ' LENGTH(' . $fieldname . ')';
1881 * Returns the proper substr() SQL text used to extract substrings from DB
1882 * NOTE: this was originally returning only function name
1884 * @param string $expr some string field, no aggregates
1885 * @param mixed $start integer or expression evaluating to int (1 based value; first char has index 1)
1886 * @param mixed $length optional integer or expression evaluating to int
1887 * @return string sql fragment
1889 public function sql_substr($expr, $start, $length=false) {
1890 if (count(func_get_args()) < 2) {
1891 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.');
1893 if ($length === false) {
1894 return "SUBSTR($expr, $start)";
1896 return "SUBSTR($expr, $start, $length)";
1901 * Returns the SQL for returning searching one string for the location of another.
1902 * Note, there is no guarantee which order $needle, $haystack will be in
1903 * the resulting SQL, so when using this method, and both arguments contain
1904 * placeholders, you should use named placeholders.
1905 * @param string $needle the SQL expression that will be searched for.
1906 * @param string $haystack the SQL expression that will be searched in.
1907 * @return string the required SQL
1909 public function sql_position($needle, $haystack) {
1910 // Implementation using standard SQL.
1911 return "POSITION(($needle) IN ($haystack))";
1915 * Returns the empty string char used by every supported DB. To be used when
1916 * we are searching for that values in our queries. Only Oracle uses this
1917 * for now (will be out, once we migrate to proper NULLs if that days arrives)
1920 function sql_empty() {
1925 * Returns the proper SQL to know if one field is empty.
1927 * Note that the function behavior strongly relies on the
1928 * parameters passed describing the field so, please, be accurate
1929 * when specifying them.
1931 * Also, note that this function is not suitable to look for
1932 * fields having NULL contents at all. It's all for empty values!
1934 * This function should be applied in all the places where conditions of
1937 * ... AND fieldname = '';
1939 * are being used. Final result should be:
1941 * ... AND ' . sql_isempty('tablename', 'fieldname', true/false, true/false);
1943 * (see parameters description below)
1945 * @param string $tablename name of the table (without prefix). Not used for now but can be
1946 * necessary in the future if we want to use some introspection using
1947 * meta information against the DB. /// TODO ///
1948 * @param string $fieldname name of the field we are going to check
1949 * @param boolean $nullablefield to specify if the field us nullable (true) or no (false) in the DB
1950 * @param boolean $textfield to specify if it is a text (also called clob) field (true) or a varchar one (false)
1951 * @return string the sql code to be added to check for empty values
1953 public function sql_isempty($tablename, $fieldname, $nullablefield, $textfield) {
1954 return " ($fieldname = '') ";
1958 * Returns the proper SQL to know if one field is not empty.
1960 * Note that the function behavior strongly relies on the
1961 * parameters passed describing the field so, please, be accurate
1962 * when specifying them.
1964 * This function should be applied in all the places where conditions of
1967 * ... AND fieldname != '';
1969 * are being used. Final result should be:
1971 * ... AND ' . sql_isnotempty('tablename', 'fieldname', true/false, true/false);
1973 * (see parameters description below)
1975 * @param string $tablename name of the table (without prefix). Not used for now but can be
1976 * necessary in the future if we want to use some introspection using
1977 * meta information against the DB. /// TODO ///
1978 * @param string $fieldname name of the field we are going to check
1979 * @param boolean $nullablefield to specify if the field us nullable (true) or no (false) in the DB
1980 * @param boolean $textfield to specify if it is a text (also called clob) field (true) or a varchar one (false)
1981 * @return string the sql code to be added to check for non empty values
1983 public function sql_isnotempty($tablename, $fieldname, $nullablefield, $textfield) {
1984 return ' ( NOT ' . $this->sql_isempty($tablename, $fieldname, $nullablefield, $textfield) . ') ';
1988 * Does this driver suppoer regex syntax when searching
1991 public function sql_regex_supported() {
1996 * Return regex positive or negative match sql
1997 * @param bool $positivematch
1998 * @return string or empty if not supported
2000 public function sql_regex($positivematch=true) {
2007 * Are transactions supported?
2008 * It is not responsible to run productions servers
2009 * on databases without transaction support ;-)
2011 * Override in driver if needed.
2015 protected function transactions_supported() {
2016 // protected for now, this might be changed to public if really necessary
2021 * Returns true if transaction in progress
2024 public function is_transaction_started() {
2025 return !empty($this->transactions);
2029 * Throws exception if transaction in progress.
2030 * This test does not force rollback of active transactions.
2033 public function transactions_forbidden() {
2034 if ($this->is_transaction_started()) {
2035 throw new dml_transaction_exception('This code can not be excecuted in transaction');
2040 * On DBs that support it, switch to transaction mode and begin a transaction
2041 * you'll need to ensure you call allow_commit() on the returned object
2042 * or your changes *will* be lost.
2044 * this is _very_ useful for massive updates
2046 * Delegated database transactions can be nested, but only one actual database
2047 * transaction is used for the outer-most delegated transaction. This method
2048 * returns a transaction object which you should keep until the end of the
2049 * delegated transaction. The actual database transaction will
2050 * only be committed if all the nested delegated transactions commit
2051 * successfully. If any part of the transaction rolls back then the whole
2052 * thing is rolled back.
2054 * @return moodle_transaction
2056 public function start_delegated_transaction() {
2057 $transaction = new moodle_transaction($this);
2058 $this->transactions[] = $transaction;
2059 if (count($this->transactions) == 1) {
2060 $this->begin_transaction();
2062 return $transaction;
2066 * Driver specific start of real database transaction,
2067 * this can not be used directly in code.
2070 protected abstract function begin_transaction();
2073 * Indicates delegated transaction finished successfully.
2074 * The real database transaction is committed only if
2075 * all delegated transactions committed.
2078 public function commit_delegated_transaction(moodle_transaction $transaction) {
2079 if ($transaction->is_disposed()) {
2080 throw new dml_transaction_exception('Transactions already disposed', $transaction);
2082 // mark as disposed so that it can not be used again
2083 $transaction->dispose();
2085 if (empty($this->transactions)) {
2086 throw new dml_transaction_exception('Transaction not started', $transaction);
2089 if ($this->force_rollback) {
2090 throw new dml_transaction_exception('Tried to commit transaction after lower level rollback', $transaction);
2093 if ($transaction !== $this->transactions[count($this->transactions) - 1]) {
2094 // one incorrect commit at any level rollbacks everything
2095 $this->force_rollback = true;
2096 throw new dml_transaction_exception('Invalid transaction commit attempt', $transaction);
2099 if (count($this->transactions) == 1) {
2100 // only commit the top most level
2101 $this->commit_transaction();
2103 array_pop($this->transactions);
2107 * Driver specific commit of real database transaction,
2108 * this can not be used directly in code.
2111 protected abstract function commit_transaction();
2114 * Call when delegated transaction failed, this rolls back
2115 * all delegated transactions up to the top most level.
2117 * In many cases you do not need to call this method manually,
2118 * because all open delegated transactions are rolled back
2119 * automatically if exceptions not caught.
2121 * @param moodle_transaction $transaction
2122 * @param Exception $e exception that caused the problem
2123 * @return void - does not return, exception is rethrown
2125 public function rollback_delegated_transaction(moodle_transaction $transaction, Exception $e) {
2126 if ($transaction->is_disposed()) {
2127 throw new dml_transaction_exception('Transactions already disposed', $transaction);
2129 // mark as disposed so that it can not be used again
2130 $transaction->dispose();
2132 // one rollback at any level rollbacks everything
2133 $this->force_rollback = true;
2135 if (empty($this->transactions) or $transaction !== $this->transactions[count($this->transactions) - 1]) {
2136 // this may or may not be a coding problem, better just rethrow the exception,
2137 // because we do not want to loose the original $e
2141 if (count($this->transactions) == 1) {
2142 // only rollback the top most level
2143 $this->rollback_transaction();
2145 array_pop($this->transactions);
2146 if (empty($this->transactions)) {
2147 // finally top most level rolled back
2148 $this->force_rollback = false;
2154 * Driver specific abort of real database transaction,
2155 * this can not be used directly in code.
2158 protected abstract function rollback_transaction();
2161 * Force rollback of all delegated transaction.
2162 * Does not trow any exceptions and does not log anything.
2164 * This method should be used only from default exception handlers and other
2169 public function force_transaction_rollback() {
2170 if ($this->transactions) {
2172 $this->rollback_transaction();
2173 } catch (dml_exception $e) {
2174 // ignore any sql errors here, the connection might be broken
2178 // now enable transactions again
2179 $this->transactions = array(); // unfortunately all unfinished exceptions are kept in memory
2180 $this->force_rollback = false;
2185 * Is session lock supported in this driver?
2188 public function session_lock_supported() {
2193 * Obtain session lock
2194 * @param int $rowid id of the row with session record
2195 * @return bool success
2197 public function get_session_lock($rowid) {
2198 $this->used_for_db_sessions = true;
2202 * Release session lock
2203 * @param int $rowid id of the row with session record
2204 * @return bool success
2206 public function release_session_lock($rowid) {
2209 /// performance and logging
2211 * Returns number of reads done by this database
2214 public function perf_get_reads() {
2215 return $this->reads;
2219 * Returns number of writes done by this database
2222 public function perf_get_writes() {
2223 return $this->writes;
2227 * Returns number of queries done by this database
2230 public function perf_get_queries() {
2231 return $this->writes + $this->reads;