Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 3.9.x will end* 10 May 2021 (12 months).
  • Bug fixes for security issues in 3.9.x will end* 8 May 2023 (36 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

Differences Between: [Versions 39 and 310] [Versions 39 and 311] [Versions 39 and 400] [Versions 39 and 401] [Versions 39 and 402] [Versions 39 and 403]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  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/>.
  16  
  17  /**
  18   * Abstract database driver class.
  19   *
  20   * @package    core_dml
  21   * @copyright  2008 Petr Skoda (http://skodak.org)
  22   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  defined('MOODLE_INTERNAL') || die();
  26  
  27  require_once (__DIR__.'/database_column_info.php');
  28  require_once (__DIR__.'/moodle_recordset.php');
  29  require_once (__DIR__.'/moodle_transaction.php');
  30  
  31  /** SQL_PARAMS_NAMED - Bitmask, indicates :name type parameters are supported by db backend. */
  32  define('SQL_PARAMS_NAMED', 1);
  33  
  34  /** SQL_PARAMS_QM - Bitmask, indicates ? type parameters are supported by db backend. */
  35  define('SQL_PARAMS_QM', 2);
  36  
  37  /** SQL_PARAMS_DOLLAR - Bitmask, indicates $1, $2, ... type parameters are supported by db backend. */
  38  define('SQL_PARAMS_DOLLAR', 4);
  39  
  40  /** SQL_QUERY_SELECT - Normal select query, reading only. */
  41  define('SQL_QUERY_SELECT', 1);
  42  
  43  /** SQL_QUERY_INSERT - Insert select query, writing. */
  44  define('SQL_QUERY_INSERT', 2);
  45  
  46  /** SQL_QUERY_UPDATE - Update select query, writing. */
  47  define('SQL_QUERY_UPDATE', 3);
  48  
  49  /** SQL_QUERY_STRUCTURE - Query changing db structure, writing. */
  50  define('SQL_QUERY_STRUCTURE', 4);
  51  
  52  /** SQL_QUERY_AUX - Auxiliary query done by driver, setting connection config, getting table info, etc. */
  53  define('SQL_QUERY_AUX', 5);
  54  
  55  /**
  56   * Abstract class representing moodle database interface.
  57   * @link http://docs.moodle.org/dev/DML_functions
  58   *
  59   * @package    core_dml
  60   * @copyright  2008 Petr Skoda (http://skodak.org)
  61   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  62   */
  63  abstract class moodle_database {
  64  
  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;
  71  
  72      // db connection options
  73      /** @var string db host name. */
  74      protected $dbhost;
  75      /** @var string db host user. */
  76      protected $dbuser;
  77      /** @var string db host password. */
  78      protected $dbpass;
  79      /** @var string db name. */
  80      protected $dbname;
  81      /** @var string Prefix added to table names. */
  82      protected $prefix;
  83  
  84      /** @var array Database or driver specific options, such as sockets or TCP/IP db connections. */
  85      protected $dboptions;
  86  
  87      /** @var bool True means non-moodle external database used.*/
  88      protected $external;
  89  
  90      /** @var int The database reads (performance counter).*/
  91      protected $reads = 0;
  92      /** @var int The database writes (performance counter).*/
  93      protected $writes = 0;
  94      /** @var float Time queries took to finish, seconds with microseconds.*/
  95      protected $queriestime = 0;
  96  
  97      /** @var int Debug level. */
  98      protected $debug  = 0;
  99  
 100      /** @var string Last used query sql. */
 101      protected $last_sql;
 102      /** @var array Last query parameters. */
 103      protected $last_params;
 104      /** @var int Last query type. */
 105      protected $last_type;
 106      /** @var string Last extra info. */
 107      protected $last_extrainfo;
 108      /** @var float Last time in seconds with millisecond precision. */
 109      protected $last_time;
 110      /** @var bool Flag indicating logging of query in progress. This helps prevent infinite loops. */
 111      protected $loggingquery = false;
 112  
 113      /** @var bool True if the db is used for db sessions. */
 114      protected $used_for_db_sessions = false;
 115  
 116      /** @var array Array containing open transactions. */
 117      protected $transactions = array();
 118      /** @var bool Flag used to force rollback of all current transactions. */
 119      private $force_rollback = false;
 120  
 121      /** @var string MD5 of settings used for connection. Used by MUC as an identifier. */
 122      private $settingshash;
 123  
 124      /** @var cache_application for column info */
 125      protected $metacache;
 126  
 127      /** @var cache_request for column info on temp tables */
 128      protected $metacachetemp;
 129  
 130      /** @var bool flag marking database instance as disposed */
 131      protected $disposed;
 132  
 133      /**
 134       * @var int internal temporary variable used to fix params. Its used by {@link _fix_sql_params_dollar_callback()}.
 135       */
 136      private $fix_sql_params_i;
 137      /**
 138       * @var int internal temporary variable used to guarantee unique parameters in each request. Its used by {@link get_in_or_equal()}.
 139       */
 140      private $inorequaluniqueindex = 1;
 141  
 142      /**
 143       * @var boolean variable use to temporarily disable logging.
 144       */
 145      protected $skiplogging = false;
 146  
 147      /**
 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.
 151       */
 152      public function __construct($external=false) {
 153          $this->external  = $external;
 154      }
 155  
 156      /**
 157       * Destructor - cleans up and flushes everything needed.
 158       */
 159      public function __destruct() {
 160          $this->dispose();
 161      }
 162  
 163      /**
 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.
 167       */
 168      public abstract function driver_installed();
 169  
 170      /**
 171       * Returns database table prefix
 172       * Note: can be used before connect()
 173       * @return string The prefix used in the database.
 174       */
 175      public function get_prefix() {
 176          return $this->prefix;
 177      }
 178  
 179      /**
 180       * Loads and returns a database instance with the specified type and library.
 181       *
 182       * The loaded class is within lib/dml directory and of the form: $type.'_'.$library.'_moodle_database'
 183       *
 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}
 188       */
 189      public static function get_driver_instance($type, $library, $external = false) {
 190          global $CFG;
 191  
 192          $classname = $type.'_'.$library.'_moodle_database';
 193          $libfile   = "$CFG->libdir/dml/$classname.php";
 194  
 195          if (!file_exists($libfile)) {
 196              return null;
 197          }
 198  
 199          require_once($libfile);
 200          return new $classname($external);
 201      }
 202  
 203      /**
 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.
 207       */
 208      public function get_dbvendor() {
 209          return $this->get_dbfamily();
 210      }
 211  
 212      /**
 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.)
 216       */
 217      public abstract function get_dbfamily();
 218  
 219      /**
 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
 223       */
 224      protected abstract function get_dbtype();
 225  
 226      /**
 227       * Returns the general database library name
 228       * Note: can be used before connect()
 229       * @return string The db library type -  pdo, native etc.
 230       */
 231      protected abstract function get_dblibrary();
 232  
 233      /**
 234       * Returns the localised database type name
 235       * Note: can be used before connect()
 236       * @return string
 237       */
 238      public abstract function get_name();
 239  
 240      /**
 241       * Returns the localised database configuration help.
 242       * Note: can be used before connect()
 243       * @return string
 244       */
 245      public abstract function get_configuration_help();
 246  
 247      /**
 248       * Returns the localised database description
 249       * Note: can be used before connect()
 250       * @deprecated since 2.6
 251       * @return string
 252       */
 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();
 256      }
 257  
 258      /**
 259       * Returns the db related part of config.php
 260       * @return stdClass
 261       */
 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;
 273          }
 274  
 275          return $cfg;
 276      }
 277  
 278      /**
 279       * Diagnose database and tables, this function is used
 280       * to verify database and driver settings, db engine types, etc.
 281       *
 282       * @return string null means everything ok, string means problem found.
 283       */
 284      public function diagnose() {
 285          return null;
 286      }
 287  
 288      /**
 289       * Connects to the database.
 290       * Must be called before other methods.
 291       * @param string $dbhost The database host.
 292       * @param string $dbuser The database user to connect as.
 293       * @param string $dbpass The password to use when connecting to the database.
 294       * @param string $dbname The name of the database being connected to.
 295       * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
 296       * @param array $dboptions driver specific options
 297       * @return bool true
 298       * @throws dml_connection_exception if error
 299       */
 300      public abstract function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null);
 301  
 302      /**
 303       * Store various database settings
 304       * @param string $dbhost The database host.
 305       * @param string $dbuser The database user to connect as.
 306       * @param string $dbpass The password to use when connecting to the database.
 307       * @param string $dbname The name of the database being connected to.
 308       * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
 309       * @param array $dboptions driver specific options
 310       * @return void
 311       */
 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;
 319      }
 320  
 321      /**
 322       * Returns a hash for the settings used during connection.
 323       *
 324       * If not already requested it is generated and stored in a private property.
 325       *
 326       * @return string
 327       */
 328      protected function get_settings_hash() {
 329          if (empty($this->settingshash)) {
 330              $this->settingshash = md5($this->dbhost . $this->dbuser . $this->dbname . $this->prefix);
 331          }
 332          return $this->settingshash;
 333      }
 334  
 335      /**
 336       * Handle the creation and caching of the databasemeta information for all databases.
 337       *
 338       * @return cache_application The databasemeta cachestore to complete operations on.
 339       */
 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);
 344          }
 345          return $this->metacache;
 346      }
 347  
 348      /**
 349       * Handle the creation and caching of the temporary tables.
 350       *
 351       * @return cache_application The temp_tables cachestore to complete operations on.
 352       */
 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);
 358          }
 359          return $this->metacachetemp;
 360      }
 361  
 362      /**
 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)
 369       *
 370       * @return bool success True for successful connection. False otherwise.
 371       */
 372      public function create_database($dbhost, $dbuser, $dbpass, $dbname, array $dboptions=null) {
 373          return false;
 374      }
 375  
 376      /**
 377       * Returns transaction trace for debugging purposes.
 378       * @private to be used by core only
 379       * @return array or null if not in transaction.
 380       */
 381      public function get_transaction_start_backtrace() {
 382          if (!$this->transactions) {
 383              return null;
 384          }
 385          $lowesttransaction = end($this->transactions);
 386          return $lowesttransaction->get_backtrace();
 387      }
 388  
 389      /**
 390       * Closes the database connection and releases all resources
 391       * and memory (especially circular memory references).
 392       * Do NOT use connect() again, create a new instance if needed.
 393       * @return void
 394       */
 395      public function dispose() {
 396          if ($this->disposed) {
 397              return;
 398          }
 399          $this->disposed = true;
 400          if ($this->transactions) {
 401              $this->force_transaction_rollback();
 402          }
 403  
 404          if ($this->temptables) {
 405              $this->temptables->dispose();
 406              $this->temptables = null;
 407          }
 408          if ($this->database_manager) {
 409              $this->database_manager->dispose();
 410              $this->database_manager = null;
 411          }
 412          $this->tables  = null;
 413      }
 414  
 415      /**
 416       * This should be called before each db query.
 417       * @param string $sql The query string.
 418       * @param array $params An array of parameters.
 419       * @param int $type The type of query. ( SQL_QUERY_SELECT | SQL_QUERY_AUX | SQL_QUERY_INSERT | SQL_QUERY_UPDATE | SQL_QUERY_STRUCTURE )
 420       * @param mixed $extrainfo This is here for any driver specific extra information.
 421       * @return void
 422       */
 423      protected function query_start($sql, array $params=null, $type, $extrainfo=null) {
 424          if ($this->loggingquery) {
 425              return;
 426          }
 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);
 432  
 433          switch ($type) {
 434              case SQL_QUERY_SELECT:
 435              case SQL_QUERY_AUX:
 436                  $this->reads++;
 437                  break;
 438              case SQL_QUERY_INSERT:
 439              case SQL_QUERY_UPDATE:
 440              case SQL_QUERY_STRUCTURE:
 441                  $this->writes++;
 442              default:
 443                  if ((PHPUNIT_TEST) || (defined('BEHAT_TEST') && BEHAT_TEST) ||
 444                      defined('BEHAT_SITE_RUNNING')) {
 445  
 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);
 449                  }
 450          }
 451  
 452          $this->print_debug($sql, $params);
 453      }
 454  
 455      /**
 456       * This should be called immediately after each db query. It does a clean up of resources.
 457       * It also throws exceptions if the sql that ran produced errors.
 458       * @param mixed $result The db specific result obtained from running a query.
 459       * @throws dml_read_exception | dml_write_exception | ddl_change_structure_exception
 460       * @return void
 461       */
 462      protected function query_end($result) {
 463          if ($this->loggingquery) {
 464              return;
 465          }
 466          if ($result !== false) {
 467              $this->query_log();
 468              // free memory
 469              $this->last_sql    = null;
 470              $this->last_params = null;
 471              $this->print_debug_time();
 472              return;
 473          }
 474  
 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();
 480  
 481          $this->query_log($error);
 482  
 483          switch ($type) {
 484              case SQL_QUERY_SELECT:
 485              case SQL_QUERY_AUX:
 486                  throw new dml_read_exception($error, $sql, $params);
 487              case SQL_QUERY_INSERT:
 488              case SQL_QUERY_UPDATE:
 489                  throw new dml_write_exception($error, $sql, $params);
 490              case SQL_QUERY_STRUCTURE:
 491                  $this->get_manager(); // includes ddl exceptions classes ;-)
 492                  throw new ddl_change_structure_exception($error, $sql);
 493          }
 494      }
 495  
 496      /**
 497       * This logs the last query based on 'logall', 'logslow' and 'logerrors' options configured via $CFG->dboptions .
 498       * @param string|bool $error or false if not error
 499       * @return void
 500       */
 501      public function query_log($error=false) {
 502          // Logging disabled by the driver.
 503          if ($this->skiplogging) {
 504              return;
 505          }
 506  
 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);
 511  
 512          $time = $this->query_time();
 513  
 514          // Will be shown or not depending on MDL_PERF values rather than in dboptions['log*].
 515          $this->queriestime = $this->queriestime + $time;
 516  
 517          if ($logall or ($logslow and ($logslow < ($time+0.00001))) or ($iserror and $logerrors)) {
 518              $this->loggingquery = true;
 519              try {
 520                  $backtrace = debug_backtrace();
 521                  if ($backtrace) {
 522                      //remove query_log()
 523                      array_shift($backtrace);
 524                  }
 525                  if ($backtrace) {
 526                      //remove query_end()
 527                      array_shift($backtrace);
 528                  }
 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) {
 540              }
 541              $this->loggingquery = false;
 542          }
 543      }
 544  
 545      /**
 546       * Disable logging temporarily.
 547       */
 548      protected function query_log_prevent() {
 549          $this->skiplogging = true;
 550      }
 551  
 552      /**
 553       * Restore old logging behavior.
 554       */
 555      protected function query_log_allow() {
 556          $this->skiplogging = false;
 557      }
 558  
 559      /**
 560       * Returns the time elapsed since the query started.
 561       * @return float Seconds with microseconds
 562       */
 563      protected function query_time() {
 564          return microtime(true) - $this->last_time;
 565      }
 566  
 567      /**
 568       * Returns database server info array
 569       * @return array Array containing 'description' and 'version' at least.
 570       */
 571      public abstract function get_server_info();
 572  
 573      /**
 574       * Returns supported query parameter types
 575       * @return int bitmask of accepted SQL_PARAMS_*
 576       */
 577      protected abstract function allowed_param_types();
 578  
 579      /**
 580       * Returns the last error reported by the database engine.
 581       * @return string The error message.
 582       */
 583      public abstract function get_last_error();
 584  
 585      /**
 586       * Prints sql debug info
 587       * @param string $sql The query which is being debugged.
 588       * @param array $params The query parameters. (optional)
 589       * @param mixed $obj The library specific object. (optional)
 590       * @return void
 591       */
 592      protected function print_debug($sql, array $params=null, $obj=null) {
 593          if (!$this->get_debug()) {
 594              return;
 595          }
 596          if (CLI_SCRIPT) {
 597              $separator = "--------------------------------\n";
 598              echo $separator;
 599              echo "{$sql}\n";
 600              if (!is_null($params)) {
 601                  echo "[" . var_export($params, true) . "]\n";
 602              }
 603              echo $separator;
 604          } else if (AJAX_SCRIPT) {
 605              $separator = "--------------------------------";
 606              error_log($separator);
 607              error_log($sql);
 608              if (!is_null($params)) {
 609                  error_log("[" . var_export($params, true) . "]");
 610              }
 611              error_log($separator);
 612          } else {
 613              $separator = "<hr />\n";
 614              echo $separator;
 615              echo s($sql) . "\n";
 616              if (!is_null($params)) {
 617                  echo "[" . s(var_export($params, true)) . "]\n";
 618              }
 619              echo $separator;
 620          }
 621      }
 622  
 623      /**
 624       * Prints the time a query took to run.
 625       * @return void
 626       */
 627      protected function print_debug_time() {
 628          if (!$this->get_debug()) {
 629              return;
 630          }
 631          $time = $this->query_time();
 632          $message = "Query took: {$time} seconds.\n";
 633          if (CLI_SCRIPT) {
 634              echo $message;
 635              echo "--------------------------------\n";
 636          } else if (AJAX_SCRIPT) {
 637              error_log($message);
 638              error_log("--------------------------------");
 639          } else {
 640              echo s($message);
 641              echo "<hr />\n";
 642          }
 643      }
 644  
 645      /**
 646       * Returns the SQL WHERE conditions.
 647       * @param string $table The table name that these conditions will be validated against.
 648       * @param array $conditions The conditions to build the where clause. (must not contain numeric indexes)
 649       * @throws dml_exception
 650       * @return array An array list containing sql 'where' part and 'params'.
 651       */
 652      protected function where_clause($table, array $conditions=null) {
 653          // We accept nulls in conditions
 654          $conditions = is_null($conditions) ? array() : $conditions;
 655  
 656          if (empty($conditions)) {
 657              return array('', array());
 658          }
 659  
 660          // Some checks performed under debugging only
 661          if (debugging()) {
 662              $columns = $this->get_columns($table);
 663              if (empty($columns)) {
 664                  // no supported columns means most probably table does not exist
 665                  throw new dml_exception('ddltablenotexist', $table);
 666              }
 667              foreach ($conditions as $key=>$value) {
 668                  if (!isset($columns[$key])) {
 669                      $a = new stdClass();
 670                      $a->fieldname = $key;
 671                      $a->tablename = $table;
 672                      throw new dml_exception('ddlfieldnotexist', $a);
 673                  }
 674                  $column = $columns[$key];
 675                  if ($column->meta_type == 'X') {
 676                      //ok so the column is a text column. sorry no text columns in the where clause conditions
 677                      throw new dml_exception('textconditionsnotallowed', $conditions);
 678                  }
 679              }
 680          }
 681  
 682          $allowed_types = $this->allowed_param_types();
 683          $where = array();
 684          $params = array();
 685  
 686          foreach ($conditions as $key=>$value) {
 687              if (is_int($key)) {
 688                  throw new dml_exception('invalidnumkey');
 689              }
 690              if (is_null($value)) {
 691                  $where[] = "$key IS NULL";
 692              } else {
 693                  if ($allowed_types & SQL_PARAMS_NAMED) {
 694                      // Need to verify key names because they can contain, originally,
 695                      // spaces and other forbidden chars when using sql_xxx() functions and friends.
 696                      $normkey = trim(preg_replace('/[^a-zA-Z0-9_-]/', '_', $key), '-_');
 697                      if ($normkey !== $key) {
 698                          debugging('Invalid key found in the conditions array.');
 699                      }
 700                      $where[] = "$key = :$normkey";
 701                      $params[$normkey] = $value;
 702                  } else {
 703                      $where[] = "$key = ?";
 704                      $params[] = $value;
 705                  }
 706              }
 707          }
 708          $where = implode(" AND ", $where);
 709          return array($where, $params);
 710      }
 711  
 712      /**
 713       * Returns SQL WHERE conditions for the ..._list group of methods.
 714       *
 715       * @param string $field the name of a field.
 716       * @param array $values the values field might take.
 717       * @return array An array containing sql 'where' part and 'params'
 718       */
 719      protected function where_clause_list($field, array $values) {
 720          if (empty($values)) {
 721              return array("1 = 2", array()); // Fake condition, won't return rows ever. MDL-17645
 722          }
 723  
 724          // Note: Do not use get_in_or_equal() because it can not deal with bools and nulls.
 725  
 726          $params = array();
 727          $select = "";
 728          $values = (array)$values;
 729          foreach ($values as $value) {
 730              if (is_bool($value)) {
 731                  $value = (int)$value;
 732              }
 733              if (is_null($value)) {
 734                  $select = "$field IS NULL";
 735              } else {
 736                  $params[] = $value;
 737              }
 738          }
 739          if ($params) {
 740              if ($select !== "") {
 741                  $select = "$select OR ";
 742              }
 743              $count = count($params);
 744              if ($count == 1) {
 745                  $select = $select."$field = ?";
 746              } else {
 747                  $qs = str_repeat(',?', $count);
 748                  $qs = ltrim($qs, ',');
 749                  $select = $select."$field IN ($qs)";
 750              }
 751          }
 752          return array($select, $params);
 753      }
 754  
 755      /**
 756       * Constructs 'IN()' or '=' sql fragment
 757       * @param mixed $items A single value or array of values for the expression.
 758       * @param int $type Parameter bounding type : SQL_PARAMS_QM or SQL_PARAMS_NAMED.
 759       * @param string $prefix Named parameter placeholder prefix (a unique counter value is appended to each parameter name).
 760       * @param bool $equal True means we want to equate to the constructed expression, false means we don't want to equate to it.
 761       * @param mixed $onemptyitems This defines the behavior when the array of items provided is empty. Defaults to false,
 762       *              meaning throw exceptions. Other values will become part of the returned SQL fragment.
 763       * @throws coding_exception | dml_exception
 764       * @return array A list containing the constructed sql fragment and an array of parameters.
 765       */
 766      public function get_in_or_equal($items, $type=SQL_PARAMS_QM, $prefix='param', $equal=true, $onemptyitems=false) {
 767  
 768          // default behavior, throw exception on empty array
 769          if (is_array($items) and empty($items) and $onemptyitems === false) {
 770              throw new coding_exception('moodle_database::get_in_or_equal() does not accept empty arrays');
 771          }
 772          // handle $onemptyitems on empty array of items
 773          if (is_array($items) and empty($items)) {
 774              if (is_null($onemptyitems)) {             // Special case, NULL value
 775                  $sql = $equal ? ' IS NULL' : ' IS NOT NULL';
 776                  return (array($sql, array()));
 777              } else {
 778                  $items = array($onemptyitems);        // Rest of cases, prepare $items for std processing
 779              }
 780          }
 781  
 782          if ($type == SQL_PARAMS_QM) {
 783              if (!is_array($items) or count($items) == 1) {
 784                  $sql = $equal ? '= ?' : '<> ?';
 785                  $items = (array)$items;
 786                  $params = array_values($items);
 787              } else {
 788                  if ($equal) {
 789                      $sql = 'IN ('.implode(',', array_fill(0, count($items), '?')).')';
 790                  } else {
 791                      $sql = 'NOT IN ('.implode(',', array_fill(0, count($items), '?')).')';
 792                  }
 793                  $params = array_values($items);
 794              }
 795  
 796          } else if ($type == SQL_PARAMS_NAMED) {
 797              if (empty($prefix)) {
 798                  $prefix = 'param';
 799              }
 800  
 801              if (!is_array($items)){
 802                  $param = $prefix.$this->inorequaluniqueindex++;
 803                  $sql = $equal ? "= :$param" : "<> :$param";
 804                  $params = array($param=>$items);
 805              } else if (count($items) == 1) {
 806                  $param = $prefix.$this->inorequaluniqueindex++;
 807                  $sql = $equal ? "= :$param" : "<> :$param";
 808                  $item = reset($items);
 809                  $params = array($param=>$item);
 810              } else {
 811                  $params = array();
 812                  $sql = array();
 813                  foreach ($items as $item) {
 814                      $param = $prefix.$this->inorequaluniqueindex++;
 815                      $params[$param] = $item;
 816                      $sql[] = ':'.$param;
 817                  }
 818                  if ($equal) {
 819                      $sql = 'IN ('.implode(',', $sql).')';
 820                  } else {
 821                      $sql = 'NOT IN ('.implode(',', $sql).')';
 822                  }
 823              }
 824  
 825          } else {
 826              throw new dml_exception('typenotimplement');
 827          }
 828          return array($sql, $params);
 829      }
 830  
 831      /**
 832       * Converts short table name {tablename} to the real prefixed table name in given sql.
 833       * @param string $sql The sql to be operated on.
 834       * @return string The sql with tablenames being prefixed with $CFG->prefix
 835       */
 836      protected function fix_table_names($sql) {
 837          return preg_replace_callback(
 838              '/\{([a-z][a-z0-9_]*)\}/',
 839              function($matches) {
 840                  return $this->fix_table_name($matches[1]);
 841              },
 842              $sql
 843          );
 844      }
 845  
 846      /**
 847       * Adds the prefix to the table name.
 848       *
 849       * @param string $tablename The table name
 850       * @return string The prefixed table name
 851       */
 852      protected function fix_table_name($tablename) {
 853          return $this->prefix . $tablename;
 854      }
 855  
 856      /**
 857       * Internal private utitlity function used to fix parameters.
 858       * Used with {@link preg_replace_callback()}
 859       * @param array $match Refer to preg_replace_callback usage for description.
 860       * @return string
 861       */
 862      private function _fix_sql_params_dollar_callback($match) {
 863          $this->fix_sql_params_i++;
 864          return "\$".$this->fix_sql_params_i;
 865      }
 866  
 867      /**
 868       * Detects object parameters and throws exception if found
 869       * @param mixed $value
 870       * @return void
 871       * @throws coding_exception if object detected
 872       */
 873      protected function detect_objects($value) {
 874          if (is_object($value)) {
 875              throw new coding_exception('Invalid database query parameter value', 'Objects are are not allowed: '.get_class($value));
 876          }
 877      }
 878  
 879      /**
 880       * Normalizes sql query parameters and verifies parameters.
 881       * @param string $sql The query or part of it.
 882       * @param array $params The query parameters.
 883       * @return array (sql, params, type of params)
 884       */
 885      public function fix_sql_params($sql, array $params=null) {
 886          $params = (array)$params; // mke null array if needed
 887          $allowed_types = $this->allowed_param_types();
 888  
 889          // convert table names
 890          $sql = $this->fix_table_names($sql);
 891  
 892          // cast booleans to 1/0 int and detect forbidden objects
 893          foreach ($params as $key => $value) {
 894              $this->detect_objects($value);
 895              $params[$key] = is_bool($value) ? (int)$value : $value;
 896          }
 897  
 898          // NICOLAS C: Fixed regexp for negative backwards look-ahead of double colons. Thanks for Sam Marshall's help
 899          $named_count = preg_match_all('/(?<!:):[a-z][a-z0-9_]*/', $sql, $named_matches); // :: used in pgsql casts
 900          $dollar_count = preg_match_all('/\$[1-9][0-9]*/', $sql, $dollar_matches);
 901          $q_count     = substr_count($sql, '?');
 902  
 903          $count = 0;
 904  
 905          if ($named_count) {
 906              $type = SQL_PARAMS_NAMED;
 907              $count = $named_count;
 908  
 909          }
 910          if ($dollar_count) {
 911              if ($count) {
 912                  throw new dml_exception('mixedtypesqlparam');
 913              }
 914              $type = SQL_PARAMS_DOLLAR;
 915              $count = $dollar_count;
 916  
 917          }
 918          if ($q_count) {
 919              if ($count) {
 920                  throw new dml_exception('mixedtypesqlparam');
 921              }
 922              $type = SQL_PARAMS_QM;
 923              $count = $q_count;
 924  
 925          }
 926  
 927          if (!$count) {
 928               // ignore params
 929              if ($allowed_types & SQL_PARAMS_NAMED) {
 930                  return array($sql, array(), SQL_PARAMS_NAMED);
 931              } else if ($allowed_types & SQL_PARAMS_QM) {
 932                  return array($sql, array(), SQL_PARAMS_QM);
 933              } else {
 934                  return array($sql, array(), SQL_PARAMS_DOLLAR);
 935              }
 936          }
 937  
 938          if ($count > count($params)) {
 939              $a = new stdClass;
 940              $a->expected = $count;
 941              $a->actual = count($params);
 942              throw new dml_exception('invalidqueryparam', $a);
 943          }
 944  
 945          $target_type = $allowed_types;
 946  
 947          if ($type & $allowed_types) { // bitwise AND
 948              if ($count == count($params)) {
 949                  if ($type == SQL_PARAMS_QM) {
 950                      return array($sql, array_values($params), SQL_PARAMS_QM); // 0-based array required
 951                  } else {
 952                      //better do the validation of names below
 953                  }
 954              }
 955              // needs some fixing or validation - there might be more params than needed
 956              $target_type = $type;
 957          }
 958  
 959          if ($type == SQL_PARAMS_NAMED) {
 960              $finalparams = array();
 961              foreach ($named_matches[0] as $key) {
 962                  $key = trim($key, ':');
 963                  if (!array_key_exists($key, $params)) {
 964                      throw new dml_exception('missingkeyinsql', $key, '');
 965                  }
 966                  if (strlen($key) > 30) {
 967                      throw new coding_exception(
 968                              "Placeholder names must be 30 characters or shorter. '" .
 969                              $key . "' is too long.", $sql);
 970                  }
 971                  $finalparams[$key] = $params[$key];
 972              }
 973              if ($count != count($finalparams)) {
 974                  throw new dml_exception('duplicateparaminsql');
 975              }
 976  
 977              if ($target_type & SQL_PARAMS_QM) {
 978                  $sql = preg_replace('/(?<!:):[a-z][a-z0-9_]*/', '?', $sql);
 979                  return array($sql, array_values($finalparams), SQL_PARAMS_QM); // 0-based required
 980              } else if ($target_type & SQL_PARAMS_NAMED) {
 981                  return array($sql, $finalparams, SQL_PARAMS_NAMED);
 982              } else {  // $type & SQL_PARAMS_DOLLAR
 983                  //lambda-style functions eat memory - we use globals instead :-(
 984                  $this->fix_sql_params_i = 0;
 985                  $sql = preg_replace_callback('/(?<!:):[a-z][a-z0-9_]*/', array($this, '_fix_sql_params_dollar_callback'), $sql);
 986                  return array($sql, array_values($finalparams), SQL_PARAMS_DOLLAR); // 0-based required
 987              }
 988  
 989          } else if ($type == SQL_PARAMS_DOLLAR) {
 990              if ($target_type & SQL_PARAMS_DOLLAR) {
 991                  return array($sql, array_values($params), SQL_PARAMS_DOLLAR); // 0-based required
 992              } else if ($target_type & SQL_PARAMS_QM) {
 993                  $sql = preg_replace('/\$[0-9]+/', '?', $sql);
 994                  return array($sql, array_values($params), SQL_PARAMS_QM); // 0-based required
 995              } else { //$target_type & SQL_PARAMS_NAMED
 996                  $sql = preg_replace('/\$([0-9]+)/', ':param\\1', $sql);
 997                  $finalparams = array();
 998                  foreach ($params as $key=>$param) {
 999                      $key++;
1000                      $finalparams['param'.$key] = $param;
1001                  }
1002                  return array($sql, $finalparams, SQL_PARAMS_NAMED);
1003              }
1004  
1005          } else { // $type == SQL_PARAMS_QM
1006              if (count($params) != $count) {
1007                  $params = array_slice($params, 0, $count);
1008              }
1009  
1010              if ($target_type & SQL_PARAMS_QM) {
1011                  return array($sql, array_values($params), SQL_PARAMS_QM); // 0-based required
1012              } else if ($target_type & SQL_PARAMS_NAMED) {
1013                  $finalparams = array();
1014                  $pname = 'param0';
1015                  $parts = explode('?', $sql);
1016                  $sql = array_shift($parts);
1017                  foreach ($parts as $part) {
1018                      $param = array_shift($params);
1019                      $pname++;
1020                      $sql .= ':'.$pname.$part;
1021                      $finalparams[$pname] = $param;
1022                  }
1023                  return array($sql, $finalparams, SQL_PARAMS_NAMED);
1024              } else {  // $type & SQL_PARAMS_DOLLAR
1025                  //lambda-style functions eat memory - we use globals instead :-(
1026                  $this->fix_sql_params_i = 0;
1027                  $sql = preg_replace_callback('/\?/', array($this, '_fix_sql_params_dollar_callback'), $sql);
1028                  return array($sql, array_values($params), SQL_PARAMS_DOLLAR); // 0-based required
1029              }
1030          }
1031      }
1032  
1033      /**
1034       * Ensures that limit params are numeric and positive integers, to be passed to the database.
1035       * We explicitly treat null, '' and -1 as 0 in order to provide compatibility with how limit
1036       * values have been passed historically.
1037       *
1038       * @param int $limitfrom Where to start results from
1039       * @param int $limitnum How many results to return
1040       * @return array Normalised limit params in array($limitfrom, $limitnum)
1041       */
1042      protected function normalise_limit_from_num($limitfrom, $limitnum) {
1043          global $CFG;
1044  
1045          // We explicilty treat these cases as 0.
1046          if ($limitfrom === null || $limitfrom === '' || $limitfrom === -1) {
1047              $limitfrom = 0;
1048          }
1049          if ($limitnum === null || $limitnum === '' || $limitnum === -1) {
1050              $limitnum = 0;
1051          }
1052  
1053          if ($CFG->debugdeveloper) {
1054              if (!is_numeric($limitfrom)) {
1055                  $strvalue = var_export($limitfrom, true);
1056                  debugging("Non-numeric limitfrom parameter detected: $strvalue, did you pass the correct arguments?",
1057                      DEBUG_DEVELOPER);
1058              } else if ($limitfrom < 0) {
1059                  debugging("Negative limitfrom parameter detected: $limitfrom, did you pass the correct arguments?",
1060                      DEBUG_DEVELOPER);
1061              }
1062  
1063              if (!is_numeric($limitnum)) {
1064                  $strvalue = var_export($limitnum, true);
1065                  debugging("Non-numeric limitnum parameter detected: $strvalue, did you pass the correct arguments?",
1066                      DEBUG_DEVELOPER);
1067              } else if ($limitnum < 0) {
1068                  debugging("Negative limitnum parameter detected: $limitnum, did you pass the correct arguments?",
1069                      DEBUG_DEVELOPER);
1070              }
1071          }
1072  
1073          $limitfrom = (int)$limitfrom;
1074          $limitnum  = (int)$limitnum;
1075          $limitfrom = max(0, $limitfrom);
1076          $limitnum  = max(0, $limitnum);
1077  
1078          return array($limitfrom, $limitnum);
1079      }
1080  
1081      /**
1082       * Return tables in database WITHOUT current prefix.
1083       * @param bool $usecache if true, returns list of cached tables.
1084       * @return array of table names in lowercase and without prefix
1085       */
1086      public abstract function get_tables($usecache=true);
1087  
1088      /**
1089       * Return table indexes - everything lowercased.
1090       * @param string $table The table we want to get indexes from.
1091       * @return array An associative array of indexes containing 'unique' flag and 'columns' being indexed
1092       */
1093      public abstract function get_indexes($table);
1094  
1095      /**
1096       * Returns detailed information about columns in table. This information is cached internally.
1097       *
1098       * @param string $table The table's name.
1099       * @param bool $usecache Flag to use internal cacheing. The default is true.
1100       * @return database_column_info[] of database_column_info objects indexed with column names
1101       */
1102      public function get_columns($table, $usecache = true): array {
1103          if (!$table) { // Table not specified, return empty array directly.
1104              return [];
1105          }
1106  
1107          if ($usecache) {
1108              if ($this->temptables->is_temptable($table)) {
1109                  if ($data = $this->get_temp_tables_cache()->get($table)) {
1110                      return $data;
1111                  }
1112              } else {
1113                  if ($data = $this->get_metacache()->get($table)) {
1114                      return $data;
1115                  }
1116              }
1117          }
1118  
1119          $structure = $this->fetch_columns($table);
1120  
1121          if ($usecache) {
1122              if ($this->temptables->is_temptable($table)) {
1123                  $this->get_temp_tables_cache()->set($table, $structure);
1124              } else {
1125                  $this->get_metacache()->set($table, $structure);
1126              }
1127          }
1128  
1129          return $structure;
1130      }
1131  
1132      /**
1133       * Returns detailed information about columns in table. This information is cached internally.
1134       *
1135       * @param string $table The table's name.
1136       * @return database_column_info[] of database_column_info objects indexed with column names
1137       */
1138      protected abstract function fetch_columns(string $table): array;
1139  
1140      /**
1141       * Normalise values based on varying RDBMS's dependencies (booleans, LOBs...)
1142       *
1143       * @param database_column_info $column column metadata corresponding with the value we are going to normalise
1144       * @param mixed $value value we are going to normalise
1145       * @return mixed the normalised value
1146       */
1147      protected abstract function normalise_value($column, $value);
1148  
1149      /**
1150       * Resets the internal column details cache
1151       *
1152       * @param array|null $tablenames an array of xmldb table names affected by this request.
1153       * @return void
1154       */
1155      public function reset_caches($tablenames = null) {
1156          if (!empty($tablenames)) {
1157              $dbmetapurged = false;
1158              foreach ($tablenames as $tablename) {
1159                  if ($this->temptables->is_temptable($tablename)) {
1160                      $this->get_temp_tables_cache()->delete($tablename);
1161                  } else if ($dbmetapurged === false) {
1162                      $this->tables = null;
1163                      $this->get_metacache()->purge();
1164                      $this->metacache = null;
1165                      $dbmetapurged = true;
1166                  }
1167              }
1168          } else {
1169              $this->get_temp_tables_cache()->purge();
1170              $this->tables = null;
1171              // Purge MUC as well.
1172              $this->get_metacache()->purge();
1173              $this->metacache = null;
1174          }
1175      }
1176  
1177      /**
1178       * Returns the sql generator used for db manipulation.
1179       * Used mostly in upgrade.php scripts.
1180       * @return database_manager The instance used to perform ddl operations.
1181       * @see lib/ddl/database_manager.php
1182       */
1183      public function get_manager() {
1184          global $CFG;
1185  
1186          if (!$this->database_manager) {
1187              require_once($CFG->libdir.'/ddllib.php');
1188  
1189              $classname = $this->get_dbfamily().'_sql_generator';
1190              require_once("$CFG->libdir/ddl/$classname.php");
1191              $generator = new $classname($this, $this->temptables);
1192  
1193              $this->database_manager = new database_manager($this, $generator);
1194          }
1195          return $this->database_manager;
1196      }
1197  
1198      /**
1199       * Attempts to change db encoding to UTF-8 encoding if possible.
1200       * @return bool True is successful.
1201       */
1202      public function change_db_encoding() {
1203          return false;
1204      }
1205  
1206      /**
1207       * Checks to see if the database is in unicode mode?
1208       * @return bool
1209       */
1210      public function setup_is_unicodedb() {
1211          return true;
1212      }
1213  
1214      /**
1215       * Enable/disable very detailed debugging.
1216       * @param bool $state
1217       * @return void
1218       */
1219      public function set_debug($state) {
1220          $this->debug = $state;
1221      }
1222  
1223      /**
1224       * Returns debug status
1225       * @return bool $state
1226       */
1227      public function get_debug() {
1228          return $this->debug;
1229      }
1230  
1231      /**
1232       * Enable/disable detailed sql logging
1233       *
1234       * @deprecated since Moodle 2.9
1235       */
1236      public function set_logging($state) {
1237          throw new coding_exception('set_logging() can not be used any more.');
1238      }
1239  
1240      /**
1241       * Do NOT use in code, this is for use by database_manager only!
1242       * @param string|array $sql query or array of queries
1243       * @param array|null $tablenames an array of xmldb table names affected by this request.
1244       * @return bool true
1245       * @throws ddl_change_structure_exception A DDL specific exception is thrown for any errors.
1246       */
1247      public abstract function change_database_structure($sql, $tablenames = null);
1248  
1249      /**
1250       * Executes a general sql query. Should be used only when no other method suitable.
1251       * Do NOT use this to make changes in db structure, use database_manager methods instead!
1252       * @param string $sql query
1253       * @param array $params query parameters
1254       * @return bool true
1255       * @throws dml_exception A DML specific exception is thrown for any errors.
1256       */
1257      public abstract function execute($sql, array $params=null);
1258  
1259      /**
1260       * Get a number of records as a moodle_recordset where all the given conditions met.
1261       *
1262       * Selects records from the table $table.
1263       *
1264       * If specified, only records meeting $conditions.
1265       *
1266       * If specified, the results will be sorted as specified by $sort. This
1267       * is added to the SQL as "ORDER BY $sort". Example values of $sort
1268       * might be "time ASC" or "time DESC".
1269       *
1270       * If $fields is specified, only those fields are returned.
1271       *
1272       * Since this method is a little less readable, use of it should be restricted to
1273       * code where it's possible there might be large datasets being returned.  For known
1274       * small datasets use get_records - it leads to simpler code.
1275       *
1276       * If you only want some of the records, specify $limitfrom and $limitnum.
1277       * The query will skip the first $limitfrom records (according to the sort
1278       * order) and then return the next $limitnum records. If either of $limitfrom
1279       * or $limitnum is specified, both must be present.
1280       *
1281       * The return value is a moodle_recordset
1282       * if the query succeeds. If an error occurs, false is returned.
1283       *
1284       * @param string $table the table to query.
1285       * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1286       * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1287       * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
1288       * @param int $limitfrom return a subset of records, starting at this point (optional).
1289       * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1290       * @return moodle_recordset A moodle_recordset instance
1291       * @throws dml_exception A DML specific exception is thrown for any errors.
1292       */
1293      public function get_recordset($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1294          list($select, $params) = $this->where_clause($table, $conditions);
1295          return $this->get_recordset_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1296      }
1297  
1298      /**
1299       * Get a number of records as a moodle_recordset where one field match one list of values.
1300       *
1301       * Only records where $field takes one of the values $values are returned.
1302       * $values must be an array of values.
1303       *
1304       * Other arguments and the return type are like {@link function get_recordset}.
1305       *
1306       * @param string $table the table to query.
1307       * @param string $field a field to check (optional).
1308       * @param array $values array of values the field must have
1309       * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1310       * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
1311       * @param int $limitfrom return a subset of records, starting at this point (optional).
1312       * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1313       * @return moodle_recordset A moodle_recordset instance.
1314       * @throws dml_exception A DML specific exception is thrown for any errors.
1315       */
1316      public function get_recordset_list($table, $field, array $values, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1317          list($select, $params) = $this->where_clause_list($field, $values);
1318          return $this->get_recordset_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1319      }
1320  
1321      /**
1322       * Get a number of records as a moodle_recordset which match a particular WHERE clause.
1323       *
1324       * If given, $select is used as the SELECT parameter in the SQL query,
1325       * otherwise all records from the table are returned.
1326       *
1327       * Other arguments and the return type are like {@link function get_recordset}.
1328       *
1329       * @param string $table the table to query.
1330       * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1331       * @param array $params array of sql parameters
1332       * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1333       * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
1334       * @param int $limitfrom return a subset of records, starting at this point (optional).
1335       * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1336       * @return moodle_recordset A moodle_recordset instance.
1337       * @throws dml_exception A DML specific exception is thrown for any errors.
1338       */
1339      public function get_recordset_select($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1340          $sql = "SELECT $fields FROM {".$table."}";
1341          if ($select) {
1342              $sql .= " WHERE $select";
1343          }
1344          if ($sort) {
1345              $sql .= " ORDER BY $sort";
1346          }
1347          return $this->get_recordset_sql($sql, $params, $limitfrom, $limitnum);
1348      }
1349  
1350      /**
1351       * Get a number of records as a moodle_recordset using a SQL statement.
1352       *
1353       * Since this method is a little less readable, use of it should be restricted to
1354       * code where it's possible there might be large datasets being returned.  For known
1355       * small datasets use get_records_sql - it leads to simpler code.
1356       *
1357       * The return type is like {@link function get_recordset}.
1358       *
1359       * @param string $sql the SQL select query to execute.
1360       * @param array $params array of sql parameters
1361       * @param int $limitfrom return a subset of records, starting at this point (optional).
1362       * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1363       * @return moodle_recordset A moodle_recordset instance.
1364       * @throws dml_exception A DML specific exception is thrown for any errors.
1365       */
1366      public abstract function get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0);
1367  
1368      /**
1369       * Get all records from a table.
1370       *
1371       * This method works around potential memory problems and may improve performance,
1372       * this method may block access to table until the recordset is closed.
1373       *
1374       * @param string $table Name of database table.
1375       * @return moodle_recordset A moodle_recordset instance {@link function get_recordset}.
1376       * @throws dml_exception A DML specific exception is thrown for any errors.
1377       */
1378      public function export_table_recordset($table) {
1379          return $this->get_recordset($table, array());
1380      }
1381  
1382      /**
1383       * Get a number of records as an array of objects where all the given conditions met.
1384       *
1385       * If the query succeeds and returns at least one record, the
1386       * return value is an array of objects, one object for each
1387       * record found. The array key is the value from the first
1388       * column of the result set. The object associated with that key
1389       * has a member variable for each column of the results.
1390       *
1391       * @param string $table the table to query.
1392       * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1393       * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1394       * @param string $fields a comma separated list of fields to return (optional, by default
1395       *   all fields are returned). The first field will be used as key for the
1396       *   array so must be a unique field such as 'id'.
1397       * @param int $limitfrom return a subset of records, starting at this point (optional).
1398       * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
1399       * @return array An array of Objects indexed by first column.
1400       * @throws dml_exception A DML specific exception is thrown for any errors.
1401       */
1402      public function get_records($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1403          list($select, $params) = $this->where_clause($table, $conditions);
1404          return $this->get_records_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1405      }
1406  
1407      /**
1408       * Get a number of records as an array of objects where one field match one list of values.
1409       *
1410       * Return value is like {@link function get_records}.
1411       *
1412       * @param string $table The database table to be checked against.
1413       * @param string $field The field to search
1414       * @param array $values An array of values
1415       * @param string $sort Sort order (as valid SQL sort parameter)
1416       * @param string $fields A comma separated list of fields to be returned from the chosen table. If specified,
1417       *   the first field should be a unique one such as 'id' since it will be used as a key in the associative
1418       *   array.
1419       * @param int $limitfrom return a subset of records, starting at this point (optional).
1420       * @param int $limitnum return a subset comprising this many records in total (optional).
1421       * @return array An array of objects indexed by first column
1422       * @throws dml_exception A DML specific exception is thrown for any errors.
1423       */
1424      public function get_records_list($table, $field, array $values, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1425          list($select, $params) = $this->where_clause_list($field, $values);
1426          return $this->get_records_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum);
1427      }
1428  
1429      /**
1430       * Get a number of records as an array of objects which match a particular WHERE clause.
1431       *
1432       * Return value is like {@link function get_records}.
1433       *
1434       * @param string $table The table to query.
1435       * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1436       * @param array $params An array of sql parameters
1437       * @param string $sort An order to sort the results in (optional, a valid SQL ORDER BY parameter).
1438       * @param string $fields A comma separated list of fields to return
1439       *   (optional, by default all fields are returned). The first field will be used as key for the
1440       *   array so must be a unique field such as 'id'.
1441       * @param int $limitfrom return a subset of records, starting at this point (optional).
1442       * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
1443       * @return array of objects indexed by first column
1444       * @throws dml_exception A DML specific exception is thrown for any errors.
1445       */
1446      public function get_records_select($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1447          if ($select) {
1448              $select = "WHERE $select";
1449          }
1450          if ($sort) {
1451              $sort = " ORDER BY $sort";
1452          }
1453          return $this->get_records_sql("SELECT $fields FROM {" . $table . "} $select $sort", $params, $limitfrom, $limitnum);
1454      }
1455  
1456      /**
1457       * Get a number of records as an array of objects using a SQL statement.
1458       *
1459       * Return value is like {@link function get_records}.
1460       *
1461       * @param string $sql the SQL select query to execute. The first column of this SELECT statement
1462       *   must be a unique value (usually the 'id' field), as it will be used as the key of the
1463       *   returned array.
1464       * @param array $params array of sql parameters
1465       * @param int $limitfrom return a subset of records, starting at this point (optional).
1466       * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
1467       * @return array of objects indexed by first column
1468       * @throws dml_exception A DML specific exception is thrown for any errors.
1469       */
1470      public abstract function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0);
1471  
1472      /**
1473       * Get the first two columns from a number of records as an associative array where all the given conditions met.
1474       *
1475       * Arguments are like {@link function get_recordset}.
1476       *
1477       * If no errors occur the return value
1478       * is an associative whose keys come from the first field of each record,
1479       * and whose values are the corresponding second fields.
1480       * False is returned if an error occurs.
1481       *
1482       * @param string $table the table to query.
1483       * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1484       * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
1485       * @param string $fields a comma separated list of fields to return - the number of fields should be 2!
1486       * @param int $limitfrom return a subset of records, starting at this point (optional).
1487       * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1488       * @return array an associative array
1489       * @throws dml_exception A DML specific exception is thrown for any errors.
1490       */
1491      public function get_records_menu($table, array $conditions=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1492          $menu = array();
1493          if ($records = $this->get_records($table, $conditions, $sort, $fields, $limitfrom, $limitnum)) {
1494              foreach ($records as $record) {
1495                  $record = (array)$record;
1496                  $key   = array_shift($record);
1497                  $value = array_shift($record);
1498                  $menu[$key] = $value;
1499              }
1500          }
1501          return $menu;
1502      }
1503  
1504      /**
1505       * Get the first two columns from a number of records as an associative array which match a particular WHERE clause.
1506       *
1507       * Arguments are like {@link function get_recordset_select}.
1508       * Return value is like {@link function get_records_menu}.
1509       *
1510       * @param string $table The database table to be checked against.
1511       * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1512       * @param array $params array of sql parameters
1513       * @param string $sort Sort order (optional) - a valid SQL order parameter
1514       * @param string $fields A comma separated list of fields to be returned from the chosen table - the number of fields should be 2!
1515       * @param int $limitfrom return a subset of records, starting at this point (optional).
1516       * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1517       * @return array an associative array
1518       * @throws dml_exception A DML specific exception is thrown for any errors.
1519       */
1520      public function get_records_select_menu($table, $select, array $params=null, $sort='', $fields='*', $limitfrom=0, $limitnum=0) {
1521          $menu = array();
1522          if ($records = $this->get_records_select($table, $select, $params, $sort, $fields, $limitfrom, $limitnum)) {
1523              foreach ($records as $record) {
1524                  $record = (array)$record;
1525                  $key   = array_shift($record);
1526                  $value = array_shift($record);
1527                  $menu[$key] = $value;
1528              }
1529          }
1530          return $menu;
1531      }
1532  
1533      /**
1534       * Get the first two columns from a number of records as an associative array using a SQL statement.
1535       *
1536       * Arguments are like {@link function get_recordset_sql}.
1537       * Return value is like {@link function get_records_menu}.
1538       *
1539       * @param string $sql The SQL string you wish to be executed.
1540       * @param array $params array of sql parameters
1541       * @param int $limitfrom return a subset of records, starting at this point (optional).
1542       * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1543       * @return array an associative array
1544       * @throws dml_exception A DML specific exception is thrown for any errors.
1545       */
1546      public function get_records_sql_menu($sql, array $params=null, $limitfrom=0, $limitnum=0) {
1547          $menu = array();
1548          if ($records = $this->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
1549              foreach ($records as $record) {
1550                  $record = (array)$record;
1551                  $key   = array_shift($record);
1552                  $value = array_shift($record);
1553                  $menu[$key] = $value;
1554              }
1555          }
1556          return $menu;
1557      }
1558  
1559      /**
1560       * Get a single database record as an object where all the given conditions met.
1561       *
1562       * @param string $table The table to select from.
1563       * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1564       * @param string $fields A comma separated list of fields to be returned from the chosen table.
1565       * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1566       *                        IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1567       *                        MUST_EXIST means we will throw an exception if no record or multiple records found.
1568       *
1569       * @todo MDL-30407 MUST_EXIST option should not throw a dml_exception, it should throw a different exception as it's a requested check.
1570       * @return mixed a fieldset object containing the first matching record, false or exception if error not found depending on mode
1571       * @throws dml_exception A DML specific exception is thrown for any errors.
1572       */
1573      public function get_record($table, array $conditions, $fields='*', $strictness=IGNORE_MISSING) {
1574          list($select, $params) = $this->where_clause($table, $conditions);
1575          return $this->get_record_select($table, $select, $params, $fields, $strictness);
1576      }
1577  
1578      /**
1579       * Get a single database record as an object which match a particular WHERE clause.
1580       *
1581       * @param string $table The database table to be checked against.
1582       * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1583       * @param array $params array of sql parameters
1584       * @param string $fields A comma separated list of fields to be returned from the chosen table.
1585       * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1586       *                        IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1587       *                        MUST_EXIST means throw exception if no record or multiple records found
1588       * @return stdClass|false a fieldset object containing the first matching record, false or exception if error not found depending on mode
1589       * @throws dml_exception A DML specific exception is thrown for any errors.
1590       */
1591      public function get_record_select($table, $select, array $params=null, $fields='*', $strictness=IGNORE_MISSING) {
1592          if ($select) {
1593              $select = "WHERE $select";
1594          }
1595          try {
1596              return $this->get_record_sql("SELECT $fields FROM {" . $table . "} $select", $params, $strictness);
1597          } catch (dml_missing_record_exception $e) {
1598              // create new exception which will contain correct table name
1599              throw new dml_missing_record_exception($table, $e->sql, $e->params);
1600          }
1601      }
1602  
1603      /**
1604       * Get a single database record as an object using a SQL statement.
1605       *
1606       * The SQL statement should normally only return one record.
1607       * It is recommended to use get_records_sql() if more matches possible!
1608       *
1609       * @param string $sql The SQL string you wish to be executed, should normally only return one record.
1610       * @param array $params array of sql parameters
1611       * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1612       *                        IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1613       *                        MUST_EXIST means throw exception if no record or multiple records found
1614       * @return mixed a fieldset object containing the first matching record, false or exception if error not found depending on mode
1615       * @throws dml_exception A DML specific exception is thrown for any errors.
1616       */
1617      public function get_record_sql($sql, array $params=null, $strictness=IGNORE_MISSING) {
1618          $strictness = (int)$strictness; // we support true/false for BC reasons too
1619          if ($strictness == IGNORE_MULTIPLE) {
1620              $count = 1;
1621          } else {
1622              $count = 0;
1623          }
1624          if (!$records = $this->get_records_sql($sql, $params, 0, $count)) {
1625              // not found
1626              if ($strictness == MUST_EXIST) {
1627                  throw new dml_missing_record_exception('', $sql, $params);
1628              }
1629              return false;
1630          }
1631  
1632          if (count($records) > 1) {
1633              if ($strictness == MUST_EXIST) {
1634                  throw new dml_multiple_records_exception($sql, $params);
1635              }
1636              debugging('Error: mdb->get_record() found more than one record!');
1637          }
1638  
1639          $return = reset($records);
1640          return $return;
1641      }
1642  
1643      /**
1644       * Get a single field value from a table record where all the given conditions met.
1645       *
1646       * @param string $table the table to query.
1647       * @param string $return the field to return the value of.
1648       * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1649       * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1650       *                        IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1651       *                        MUST_EXIST means throw exception if no record or multiple records found
1652       * @return mixed the specified value false if not found
1653       * @throws dml_exception A DML specific exception is thrown for any errors.
1654       */
1655      public function get_field($table, $return, array $conditions, $strictness=IGNORE_MISSING) {
1656          list($select, $params) = $this->where_clause($table, $conditions);
1657          return $this->get_field_select($table, $return, $select, $params, $strictness);
1658      }
1659  
1660      /**
1661       * Get a single field value from a table record which match a particular WHERE clause.
1662       *
1663       * @param string $table the table to query.
1664       * @param string $return the field to return the value of.
1665       * @param string $select A fragment of SQL to be used in a where clause returning one row with one column
1666       * @param array $params array of sql parameters
1667       * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1668       *                        IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1669       *                        MUST_EXIST means throw exception if no record or multiple records found
1670       * @return mixed the specified value false if not found
1671       * @throws dml_exception A DML specific exception is thrown for any errors.
1672       */
1673      public function get_field_select($table, $return, $select, array $params=null, $strictness=IGNORE_MISSING) {
1674          if ($select) {
1675              $select = "WHERE $select";
1676          }
1677          try {
1678              return $this->get_field_sql("SELECT $return FROM {" . $table . "} $select", $params, $strictness);
1679          } catch (dml_missing_record_exception $e) {
1680              // create new exception which will contain correct table name
1681              throw new dml_missing_record_exception($table, $e->sql, $e->params);
1682          }
1683      }
1684  
1685      /**
1686       * Get a single field value (first field) using a SQL statement.
1687       *
1688       * @param string $sql The SQL query returning one row with one column
1689       * @param array $params array of sql parameters
1690       * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1691       *                        IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1692       *                        MUST_EXIST means throw exception if no record or multiple records found
1693       * @return mixed the specified value false if not found
1694       * @throws dml_exception A DML specific exception is thrown for any errors.
1695       */
1696      public function get_field_sql($sql, array $params=null, $strictness=IGNORE_MISSING) {
1697          if (!$record = $this->get_record_sql($sql, $params, $strictness)) {
1698              return false;
1699          }
1700  
1701          $record = (array)$record;
1702          return reset($record); // first column
1703      }
1704  
1705      /**
1706       * Selects records and return values of chosen field as an array which match a particular WHERE clause.
1707       *
1708       * @param string $table the table to query.
1709       * @param string $return the field we are intered in
1710       * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1711       * @param array $params array of sql parameters
1712       * @return array of values
1713       * @throws dml_exception A DML specific exception is thrown for any errors.
1714       */
1715      public function get_fieldset_select($table, $return, $select, array $params=null) {
1716          if ($select) {
1717              $select = "WHERE $select";
1718          }
1719          return $this->get_fieldset_sql("SELECT $return FROM {" . $table . "} $select", $params);
1720      }
1721  
1722      /**
1723       * Selects records and return values (first field) as an array using a SQL statement.
1724       *
1725       * @param string $sql The SQL query
1726       * @param array $params array of sql parameters
1727       * @return array of values
1728       * @throws dml_exception A DML specific exception is thrown for any errors.
1729       */
1730      public abstract function get_fieldset_sql($sql, array $params=null);
1731  
1732      /**
1733       * Insert new record into database, as fast as possible, no safety checks, lobs not supported.
1734       * @param string $table name
1735       * @param mixed $params data record as object or array
1736       * @param bool $returnid Returns id of inserted record.
1737       * @param bool $bulk true means repeated inserts expected
1738       * @param bool $customsequence true if 'id' included in $params, disables $returnid
1739       * @return bool|int true or new id
1740       * @throws dml_exception A DML specific exception is thrown for any errors.
1741       */
1742      public abstract function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false);
1743  
1744      /**
1745       * Insert a record into a table and return the "id" field if required.
1746       *
1747       * Some conversions and safety checks are carried out. Lobs are supported.
1748       * If the return ID isn't required, then this just reports success as true/false.
1749       * $data is an object containing needed data
1750       * @param string $table The database table to be inserted into
1751       * @param object|array $dataobject A data object with values for one or more fields in the record
1752       * @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.
1753       * @param bool $bulk Set to true is multiple inserts are expected
1754       * @return bool|int true or new id
1755       * @throws dml_exception A DML specific exception is thrown for any errors.
1756       */
1757      public abstract function insert_record($table, $dataobject, $returnid=true, $bulk=false);
1758  
1759      /**
1760       * Insert multiple records into database as fast as possible.
1761       *
1762       * Order of inserts is maintained, but the operation is not atomic,
1763       * use transactions if necessary.
1764       *
1765       * This method is intended for inserting of large number of small objects,
1766       * do not use for huge objects with text or binary fields.
1767       *
1768       * @since Moodle 2.7
1769       *
1770       * @param string $table  The database table to be inserted into
1771       * @param array|Traversable $dataobjects list of objects to be inserted, must be compatible with foreach
1772       * @return void does not return new record ids
1773       *
1774       * @throws coding_exception if data objects have different structure
1775       * @throws dml_exception A DML specific exception is thrown for any errors.
1776       */
1777      public function insert_records($table, $dataobjects) {
1778          if (!is_array($dataobjects) and !($dataobjects instanceof Traversable)) {
1779              throw new coding_exception('insert_records() passed non-traversable object');
1780          }
1781  
1782          $fields = null;
1783          // Note: override in driver if there is a faster way.
1784          foreach ($dataobjects as $dataobject) {
1785              if (!is_array($dataobject) and !is_object($dataobject)) {
1786                  throw new coding_exception('insert_records() passed invalid record object');
1787              }
1788              $dataobject = (array)$dataobject;
1789              if ($fields === null) {
1790                  $fields = array_keys($dataobject);
1791              } else if ($fields !== array_keys($dataobject)) {
1792                  throw new coding_exception('All dataobjects in insert_records() must have the same structure!');
1793              }
1794              $this->insert_record($table, $dataobject, false);
1795          }
1796      }
1797  
1798      /**
1799       * Import a record into a table, id field is required.
1800       * Safety checks are NOT carried out. Lobs are supported.
1801       *
1802       * @param string $table name of database table to be inserted into
1803       * @param object $dataobject A data object with values for one or more fields in the record
1804       * @return bool true
1805       * @throws dml_exception A DML specific exception is thrown for any errors.
1806       */
1807      public abstract function import_record($table, $dataobject);
1808  
1809      /**
1810       * Update record in database, as fast as possible, no safety checks, lobs not supported.
1811       * @param string $table name
1812       * @param mixed $params data record as object or array
1813       * @param bool $bulk True means repeated updates expected.
1814       * @return bool true
1815       * @throws dml_exception A DML specific exception is thrown for any errors.
1816       */
1817      public abstract function update_record_raw($table, $params, $bulk=false);
1818  
1819      /**
1820       * Update a record in a table
1821       *
1822       * $dataobject is an object containing needed data
1823       * Relies on $dataobject having a variable "id" to
1824       * specify the record to update
1825       *
1826       * @param string $table The database table to be checked against.
1827       * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
1828       * @param bool $bulk True means repeated updates expected.
1829       * @return bool true
1830       * @throws dml_exception A DML specific exception is thrown for any errors.
1831       */
1832      public abstract function update_record($table, $dataobject, $bulk=false);
1833  
1834      /**
1835       * Set a single field in every table record where all the given conditions met.
1836       *
1837       * @param string $table The database table to be checked against.
1838       * @param string $newfield the field to set.
1839       * @param string $newvalue the value to set the field to.
1840       * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1841       * @return bool true
1842       * @throws dml_exception A DML specific exception is thrown for any errors.
1843       */
1844      public function set_field($table, $newfield, $newvalue, array $conditions=null) {
1845          list($select, $params) = $this->where_clause($table, $conditions);
1846          return $this->set_field_select($table, $newfield, $newvalue, $select, $params);
1847      }
1848  
1849      /**
1850       * Set a single field in every table record which match a particular WHERE clause.
1851       *
1852       * @param string $table The database table to be checked against.
1853       * @param string $newfield the field to set.
1854       * @param string $newvalue the value to set the field to.
1855       * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1856       * @param array $params array of sql parameters
1857       * @return bool true
1858       * @throws dml_exception A DML specific exception is thrown for any errors.
1859       */
1860      public abstract function set_field_select($table, $newfield, $newvalue, $select, array $params=null);
1861  
1862  
1863      /**
1864       * Count the records in a table where all the given conditions met.
1865       *
1866       * @param string $table The table to query.
1867       * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1868       * @return int The count of records returned from the specified criteria.
1869       * @throws dml_exception A DML specific exception is thrown for any errors.
1870       */
1871      public function count_records($table, array $conditions=null) {
1872          list($select, $params) = $this->where_clause($table, $conditions);
1873          return $this->count_records_select($table, $select, $params);
1874      }
1875  
1876      /**
1877       * Count the records in a table which match a particular WHERE clause.
1878       *
1879       * @param string $table The database table to be checked against.
1880       * @param string $select A fragment of SQL to be used in a WHERE clause in the SQL call.
1881       * @param array $params array of sql parameters
1882       * @param string $countitem The count string to be used in the SQL call. Default is COUNT('x').
1883       * @return int The count of records returned from the specified criteria.
1884       * @throws dml_exception A DML specific exception is thrown for any errors.
1885       */
1886      public function count_records_select($table, $select, array $params=null, $countitem="COUNT('x')") {
1887          if ($select) {
1888              $select = "WHERE $select";
1889          }
1890          return $this->count_records_sql("SELECT $countitem FROM {" . $table . "} $select", $params);
1891      }
1892  
1893      /**
1894       * Get the result of a SQL SELECT COUNT(...) query.
1895       *
1896       * Given a query that counts rows, return that count. (In fact,
1897       * given any query, return the first field of the first record
1898       * returned. However, this method should only be used for the
1899       * intended purpose.) If an error occurs, 0 is returned.
1900       *
1901       * @param string $sql The SQL string you wish to be executed.
1902       * @param array $params array of sql parameters
1903       * @return int the count
1904       * @throws dml_exception A DML specific exception is thrown for any errors.
1905       */
1906      public function count_records_sql($sql, array $params=null) {
1907          $count = $this->get_field_sql($sql, $params);
1908          if ($count === false or !is_number($count) or $count < 0) {
1909              throw new coding_exception("count_records_sql() expects the first field to contain non-negative number from COUNT(), '$count' found instead.");
1910          }
1911          return (int)$count;
1912      }
1913  
1914      /**
1915       * Test whether a record exists in a table where all the given conditions met.
1916       *
1917       * @param string $table The table to check.
1918       * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1919       * @return bool true if a matching record exists, else false.
1920       * @throws dml_exception A DML specific exception is thrown for any errors.
1921       */
1922      public function record_exists($table, array $conditions) {
1923          list($select, $params) = $this->where_clause($table, $conditions);
1924          return $this->record_exists_select($table, $select, $params);
1925      }
1926  
1927      /**
1928       * Test whether any records exists in a table which match a particular WHERE clause.
1929       *
1930       * @param string $table The database table to be checked against.
1931       * @param string $select A fragment of SQL to be used in a WHERE clause in the SQL call.
1932       * @param array $params array of sql parameters
1933       * @return bool true if a matching record exists, else false.
1934       * @throws dml_exception A DML specific exception is thrown for any errors.
1935       */
1936      public function record_exists_select($table, $select, array $params=null) {
1937          if ($select) {
1938              $select = "WHERE $select";
1939          }
1940          return $this->record_exists_sql("SELECT 'x' FROM {" . $table . "} $select", $params);
1941      }
1942  
1943      /**
1944       * Test whether a SQL SELECT statement returns any records.
1945       *
1946       * This function returns true if the SQL statement executes
1947       * without any errors and returns at least one record.
1948       *
1949       * @param string $sql The SQL statement to execute.
1950       * @param array $params array of sql parameters
1951       * @return bool true if the SQL executes without errors and returns at least one record.
1952       * @throws dml_exception A DML specific exception is thrown for any errors.
1953       */
1954      public function record_exists_sql($sql, array $params=null) {
1955          $mrs = $this->get_recordset_sql($sql, $params, 0, 1);
1956          $return = $mrs->valid();
1957          $mrs->close();
1958          return $return;
1959      }
1960  
1961      /**
1962       * Delete the records from a table where all the given conditions met.
1963       * If conditions not specified, table is truncated.
1964       *
1965       * @param string $table the table to delete from.
1966       * @param array $conditions optional array $fieldname=>requestedvalue with AND in between
1967       * @return bool true.
1968       * @throws dml_exception A DML specific exception is thrown for any errors.
1969       */
1970      public function delete_records($table, array $conditions=null) {
1971          // truncate is drop/create (DDL), not transactional safe,
1972          // so we don't use the shortcut within them. MDL-29198
1973          if (is_null($conditions) && empty($this->transactions)) {
1974              return $this->execute("TRUNCATE TABLE {".$table."}");
1975          }
1976          list($select, $params) = $this->where_clause($table, $conditions);
1977          return $this->delete_records_select($table, $select, $params);
1978      }
1979  
1980      /**
1981       * Delete the records from a table where one field match one list of values.
1982       *
1983       * @param string $table the table to delete from.
1984       * @param string $field The field to search
1985       * @param array $values array of values
1986       * @return bool true.
1987       * @throws dml_exception A DML specific exception is thrown for any errors.
1988       */
1989      public function delete_records_list($table, $field, array $values) {
1990          list($select, $params) = $this->where_clause_list($field, $values);
1991          return $this->delete_records_select($table, $select, $params);
1992      }
1993  
1994      /**
1995       * Deletes records from a table using a subquery. The subquery should return a list of values
1996       * in a single column, which match one field from the table being deleted.
1997       *
1998       * The $alias parameter must be set to the name of the single column in your subquery result
1999       * (e.g. if the subquery is 'SELECT id FROM whatever', then it should be 'id'). This is not
2000       * needed on most databases, but MySQL requires it.
2001       *
2002       * (On database where the subquery is inefficient, it is implemented differently.)
2003       *
2004       * @param string $table Table to delete from
2005       * @param string $field Field in table to match
2006       * @param string $alias Name of single column in subquery e.g. 'id'
2007       * @param string $subquery Subquery that will return values of the field to delete
2008       * @param array $params Parameters for subquery
2009       * @throws dml_exception If there is any error
2010       * @since Moodle 3.9.3
2011       */
2012      public function delete_records_subquery(string $table, string $field, string $alias,
2013              string $subquery, array $params = []): void {
2014          $this->delete_records_select($table, $field . ' IN (' . $subquery . ')', $params);
2015      }
2016  
2017      /**
2018       * Delete one or more records from a table which match a particular WHERE clause.
2019       *
2020       * @param string $table The database table to be checked against.
2021       * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
2022       * @param array $params array of sql parameters
2023       * @return bool true.
2024       * @throws dml_exception A DML specific exception is thrown for any errors.
2025       */
2026      public abstract function delete_records_select($table, $select, array $params=null);
2027  
2028      /**
2029       * Returns the FROM clause required by some DBs in all SELECT statements.
2030       *
2031       * To be used in queries not having FROM clause to provide cross_db
2032       * Most DBs don't need it, hence the default is ''
2033       * @return string
2034       */
2035      public function sql_null_from_clause() {
2036          return '';
2037      }
2038  
2039      /**
2040       * Returns the SQL text to be used in order to perform one bitwise AND operation
2041       * between 2 integers.
2042       *
2043       * NOTE: The SQL result is a number and can not be used directly in
2044       *       SQL condition, please compare it to some number to get a bool!!
2045       *
2046       * @param int $int1 First integer in the operation.
2047       * @param int $int2 Second integer in the operation.
2048       * @return string The piece of SQL code to be used in your statement.
2049       */
2050      public function sql_bitand($int1, $int2) {
2051          return '((' . $int1 . ') & (' . $int2 . '))';
2052      }
2053  
2054      /**
2055       * Returns the SQL text to be used in order to perform one bitwise NOT operation
2056       * with 1 integer.
2057       *
2058       * @param int $int1 The operand integer in the operation.
2059       * @return string The piece of SQL code to be used in your statement.
2060       */
2061      public function sql_bitnot($int1) {
2062          return '(~(' . $int1 . '))';
2063      }
2064  
2065      /**
2066       * Returns the SQL text to be used in order to perform one bitwise OR operation
2067       * between 2 integers.
2068       *
2069       * NOTE: The SQL result is a number and can not be used directly in
2070       *       SQL condition, please compare it to some number to get a bool!!
2071       *
2072       * @param int $int1 The first operand integer in the operation.
2073       * @param int $int2 The second operand integer in the operation.
2074       * @return string The piece of SQL code to be used in your statement.
2075       */
2076      public function sql_bitor($int1, $int2) {
2077          return '((' . $int1 . ') | (' . $int2 . '))';
2078      }
2079  
2080      /**
2081       * Returns the SQL text to be used in order to perform one bitwise XOR operation
2082       * between 2 integers.
2083       *
2084       * NOTE: The SQL result is a number and can not be used directly in
2085       *       SQL condition, please compare it to some number to get a bool!!
2086       *
2087       * @param int $int1 The first operand integer in the operation.
2088       * @param int $int2 The second operand integer in the operation.
2089       * @return string The piece of SQL code to be used in your statement.
2090       */
2091      public function sql_bitxor($int1, $int2) {
2092          return '((' . $int1 . ') ^ (' . $int2 . '))';
2093      }
2094  
2095      /**
2096       * Returns the SQL text to be used in order to perform module '%'
2097       * operation - remainder after division
2098       *
2099       * @param int $int1 The first operand integer in the operation.
2100       * @param int $int2 The second operand integer in the operation.
2101       * @return string The piece of SQL code to be used in your statement.
2102       */
2103      public function sql_modulo($int1, $int2) {
2104          return '((' . $int1 . ') % (' . $int2 . '))';
2105      }
2106  
2107      /**
2108       * Returns the cross db correct CEIL (ceiling) expression applied to fieldname.
2109       * note: Most DBs use CEIL(), hence it's the default here.
2110       *
2111       * @param string $fieldname The field (or expression) we are going to ceil.
2112       * @return string The piece of SQL code to be used in your ceiling statement.
2113       */
2114      public function sql_ceil($fieldname) {
2115          return ' CEIL(' . $fieldname . ')';
2116      }
2117  
2118      /**
2119       * Returns the SQL to be used in order to CAST one CHAR column to INTEGER.
2120       *
2121       * Be aware that the CHAR column you're trying to cast contains really
2122       * int values or the RDBMS will throw an error!
2123       *
2124       * @param string $fieldname The name of the field to be casted.
2125       * @param bool $text Specifies if the original column is one TEXT (CLOB) column (true). Defaults to false.
2126       * @return string The piece of SQL code to be used in your statement.
2127       */
2128      public function sql_cast_char2int($fieldname, $text=false) {
2129          return ' ' . $fieldname . ' ';
2130      }
2131  
2132      /**
2133       * Returns the SQL to be used in order to CAST one CHAR column to REAL number.
2134       *
2135       * Be aware that the CHAR column you're trying to cast contains really
2136       * numbers or the RDBMS will throw an error!
2137       *
2138       * @param string $fieldname The name of the field to be casted.
2139       * @param bool $text Specifies if the original column is one TEXT (CLOB) column (true). Defaults to false.
2140       * @return string The piece of SQL code to be used in your statement.
2141       */
2142      public function sql_cast_char2real($fieldname, $text=false) {
2143          return ' ' . $fieldname . ' ';
2144      }
2145  
2146      /**
2147       * Returns the SQL to be used in order to an UNSIGNED INTEGER column to SIGNED.
2148       *
2149       * (Only MySQL needs this. MySQL things that 1 * -1 = 18446744073709551615
2150       * if the 1 comes from an unsigned column).
2151       *
2152       * @deprecated since 2.3
2153       * @param string $fieldname The name of the field to be cast
2154       * @return string The piece of SQL code to be used in your statement.
2155       */
2156      public function sql_cast_2signed($fieldname) {
2157          return ' ' . $fieldname . ' ';
2158      }
2159  
2160      /**
2161       * Returns the SQL text to be used to compare one TEXT (clob) column with
2162       * one varchar column, because some RDBMS doesn't support such direct
2163       * comparisons.
2164       *
2165       * @param string $fieldname The name of the TEXT field we need to order by
2166       * @param int $numchars Number of chars to use for the ordering (defaults to 32).
2167       * @return string The piece of SQL code to be used in your statement.
2168       */
2169      public function sql_compare_text($fieldname, $numchars=32) {
2170          return $this->sql_order_by_text($fieldname, $numchars);
2171      }
2172  
2173      /**
2174       * Returns an equal (=) or not equal (<>) part of a query.
2175       *
2176       * Note the use of this method may lead to slower queries (full scans) so
2177       * use it only when needed and against already reduced data sets.
2178       *
2179       * @since Moodle 3.2
2180       *
2181       * @param string $fieldname Usually the name of the table column.
2182       * @param string $param Usually the bound query parameter (?, :named).
2183       * @param bool $casesensitive Use case sensitive search when set to true (default).
2184       * @param bool $accentsensitive Use accent sensitive search when set to true (default). (not all databases support accent insensitive)
2185       * @param bool $notequal True means not equal (<>)
2186       * @return string The SQL code fragment.
2187       */
2188      public function sql_equal($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notequal = false) {
2189          // Note that, by default, it's assumed that the correct sql equal operations are
2190          // case sensitive. Only databases not observing this behavior must override the method.
2191          // Also, accent sensitiveness only will be handled by databases supporting it.
2192          $equalop = $notequal ? '<>' : '=';
2193          if ($casesensitive) {
2194              return "$fieldname $equalop $param";
2195          } else {
2196              return "LOWER($fieldname) $equalop LOWER($param)";
2197          }
2198      }
2199  
2200      /**
2201       * Returns 'LIKE' part of a query.
2202       *
2203       * @param string $fieldname Usually the name of the table column.
2204       * @param string $param Usually the bound query parameter (?, :named).
2205       * @param bool $casesensitive Use case sensitive search when set to true (default).
2206       * @param bool $accentsensitive Use accent sensitive search when set to true (default). (not all databases support accent insensitive)
2207       * @param bool $notlike True means "NOT LIKE".
2208       * @param string $escapechar The escape char for '%' and '_'.
2209       * @return string The SQL code fragment.
2210       */
2211      public function sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = '\\') {
2212          if (strpos($param, '%') !== false) {
2213              debugging('Potential SQL injection detected, sql_like() expects bound parameters (? or :named)');
2214          }
2215          $LIKE = $notlike ? 'NOT LIKE' : 'LIKE';
2216          // by default ignore any sensitiveness - each database does it in a different way
2217          return "$fieldname $LIKE $param ESCAPE '$escapechar'";
2218      }
2219  
2220      /**
2221       * Escape sql LIKE special characters like '_' or '%'.
2222       * @param string $text The string containing characters needing escaping.
2223       * @param string $escapechar The desired escape character, defaults to '\\'.
2224       * @return string The escaped sql LIKE string.
2225       */
2226      public function sql_like_escape($text, $escapechar = '\\') {
2227          $text = str_replace('_', $escapechar.'_', $text);
2228          $text = str_replace('%', $escapechar.'%', $text);
2229          return $text;
2230      }
2231  
2232      /**
2233       * Returns the proper SQL to do CONCAT between the elements(fieldnames) passed.
2234       *
2235       * This function accepts variable number of string parameters.
2236       * All strings/fieldnames will used in the SQL concatenate statement generated.
2237       *
2238       * @return string The SQL to concatenate strings passed in.
2239       * @uses func_get_args()  and thus parameters are unlimited OPTIONAL number of additional field names.
2240       */
2241      public abstract function sql_concat();
2242  
2243      /**
2244       * Returns the proper SQL to do CONCAT between the elements passed
2245       * with a given separator
2246       *
2247       * @param string $separator The separator desired for the SQL concatenating $elements.
2248       * @param array  $elements The array of strings to be concatenated.
2249       * @return string The SQL to concatenate the strings.
2250       */
2251      public abstract function sql_concat_join($separator="' '", $elements=array());
2252  
2253      /**
2254       * Returns the proper SQL (for the dbms in use) to concatenate $firstname and $lastname
2255       *
2256       * @todo MDL-31233 This may not be needed here.
2257       *
2258       * @param string $first User's first name (default:'firstname').
2259       * @param string $last User's last name (default:'lastname').
2260       * @return string The SQL to concatenate strings.
2261       */
2262      function sql_fullname($first='firstname', $last='lastname') {
2263          return $this->sql_concat($first, "' '", $last);
2264      }
2265  
2266      /**
2267       * Returns the SQL text to be used to order by one TEXT (clob) column, because
2268       * some RDBMS doesn't support direct ordering of such fields.
2269       *
2270       * Note that the use or queries being ordered by TEXT columns must be minimised,
2271       * because it's really slooooooow.
2272       *
2273       * @param string $fieldname The name of the TEXT field we need to order by.
2274       * @param int $numchars The number of chars to use for the ordering (defaults to 32).
2275       * @return string The piece of SQL code to be used in your statement.
2276       */
2277      public function sql_order_by_text($fieldname, $numchars=32) {
2278          return $fieldname;
2279      }
2280  
2281      /**
2282       * Returns the SQL text to be used to calculate the length in characters of one expression.
2283       * @param string $fieldname The fieldname/expression to calculate its length in characters.
2284       * @return string the piece of SQL code to be used in the statement.
2285       */
2286      public function sql_length($fieldname) {
2287          return ' LENGTH(' . $fieldname . ')';
2288      }
2289  
2290      /**
2291       * Returns the proper substr() SQL text used to extract substrings from DB
2292       * NOTE: this was originally returning only function name
2293       *
2294       * @param string $expr Some string field, no aggregates.
2295       * @param mixed $start Integer or expression evaluating to integer (1 based value; first char has index 1)
2296       * @param mixed $length Optional integer or expression evaluating to integer.
2297       * @return string The sql substring extraction fragment.
2298       */
2299      public function sql_substr($expr, $start, $length=false) {
2300          if (count(func_get_args()) < 2) {
2301              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.');
2302          }
2303          if ($length === false) {
2304              return "SUBSTR($expr, $start)";
2305          } else {
2306              return "SUBSTR($expr, $start, $length)";
2307          }
2308      }
2309  
2310      /**
2311       * Returns the SQL for returning searching one string for the location of another.
2312       *
2313       * Note, there is no guarantee which order $needle, $haystack will be in
2314       * the resulting SQL so when using this method, and both arguments contain
2315       * placeholders, you should use named placeholders.
2316       *
2317       * @param string $needle the SQL expression that will be searched for.
2318       * @param string $haystack the SQL expression that will be searched in.
2319       * @return string The required searching SQL part.
2320       */
2321      public function sql_position($needle, $haystack) {
2322          // Implementation using standard SQL.
2323          return "POSITION(($needle) IN ($haystack))";
2324      }
2325  
2326      /**
2327       * This used to return empty string replacement character.
2328       *
2329       * @deprecated use bound parameter with empty string instead
2330       *
2331       * @return string An empty string.
2332       */
2333      function sql_empty() {
2334          debugging("sql_empty() is deprecated, please use empty string '' as sql parameter value instead", DEBUG_DEVELOPER);
2335          return '';
2336      }
2337  
2338      /**
2339       * Returns the proper SQL to know if one field is empty.
2340       *
2341       * Note that the function behavior strongly relies on the
2342       * parameters passed describing the field so, please,  be accurate
2343       * when specifying them.
2344       *
2345       * Also, note that this function is not suitable to look for
2346       * fields having NULL contents at all. It's all for empty values!
2347       *
2348       * This function should be applied in all the places where conditions of
2349       * the type:
2350       *
2351       *     ... AND fieldname = '';
2352       *
2353       * are being used. Final result for text fields should be:
2354       *
2355       *     ... AND ' . sql_isempty('tablename', 'fieldname', true/false, true);
2356       *
2357       * and for varchar fields result should be:
2358       *
2359       *    ... AND fieldname = :empty; "; $params['empty'] = '';
2360       *
2361       * (see parameters description below)
2362       *
2363       * @param string $tablename Name of the table (without prefix). Not used for now but can be
2364       *                          necessary in the future if we want to use some introspection using
2365       *                          meta information against the DB. /// TODO ///
2366       * @param string $fieldname Name of the field we are going to check
2367       * @param bool $nullablefield For specifying if the field is nullable (true) or no (false) in the DB.
2368       * @param bool $textfield For specifying if it is a text (also called clob) field (true) or a varchar one (false)
2369       * @return string the sql code to be added to check for empty values
2370       */
2371      public function sql_isempty($tablename, $fieldname, $nullablefield, $textfield) {
2372          return " ($fieldname = '') ";
2373      }
2374  
2375      /**
2376       * Returns the proper SQL to know if one field is not empty.
2377       *
2378       * Note that the function behavior strongly relies on the
2379       * parameters passed describing the field so, please,  be accurate
2380       * when specifying them.
2381       *
2382       * This function should be applied in all the places where conditions of
2383       * the type:
2384       *
2385       *     ... AND fieldname != '';
2386       *
2387       * are being used. Final result for text fields should be:
2388       *
2389       *     ... AND ' . sql_isnotempty('tablename', 'fieldname', true/false, true/false);
2390       *
2391       * and for varchar fields result should be:
2392       *
2393       *    ... AND fieldname != :empty; "; $params['empty'] = '';
2394       *
2395       * (see parameters description below)
2396       *
2397       * @param string $tablename Name of the table (without prefix). This is not used for now but can be
2398       *                          necessary in the future if we want to use some introspection using
2399       *                          meta information against the DB.
2400       * @param string $fieldname The name of the field we are going to check.
2401       * @param bool $nullablefield Specifies if the field is nullable (true) or not (false) in the DB.
2402       * @param bool $textfield Specifies if it is a text (also called clob) field (true) or a varchar one (false).
2403       * @return string The sql code to be added to check for non empty values.
2404       */
2405      public function sql_isnotempty($tablename, $fieldname, $nullablefield, $textfield) {
2406          return ' ( NOT ' . $this->sql_isempty($tablename, $fieldname, $nullablefield, $textfield) . ') ';
2407      }
2408  
2409      /**
2410       * Returns true if this database driver supports regex syntax when searching.
2411       * @return bool True if supported.
2412       */
2413      public function sql_regex_supported() {
2414          return false;
2415      }
2416  
2417      /**
2418       * Returns the driver specific syntax (SQL part) for matching regex positively or negatively (inverted matching).
2419       * Eg: 'REGEXP':'NOT REGEXP' or '~*' : '!~*'
2420       *
2421       * @param bool $positivematch
2422       * @param bool $casesensitive
2423       * @return string or empty if not supported
2424       */
2425      public function sql_regex($positivematch = true, $casesensitive = false) {
2426          return '';
2427      }
2428  
2429      /**
2430       * Returns the SQL that allows to find intersection of two or more queries
2431       *
2432       * @since Moodle 2.8
2433       *
2434       * @param array $selects array of SQL select queries, each of them only returns fields with the names from $fields
2435       * @param string $fields comma-separated list of fields (used only by some DB engines)
2436       * @return string SQL query that will return only values that are present in each of selects
2437       */
2438      public function sql_intersect($selects, $fields) {
2439          if (!count($selects)) {
2440              throw new coding_exception('sql_intersect() requires at least one element in $selects');
2441          } else if (count($selects) == 1) {
2442              return $selects[0];
2443          }
2444          static $aliascnt = 0;
2445          $rv = '('.$selects[0].')';
2446          for ($i = 1; $i < count($selects); $i++) {
2447              $rv .= " INTERSECT (".$selects[$i].')';
2448          }
2449          return $rv;
2450      }
2451  
2452      /**
2453       * Does this driver support tool_replace?
2454       *
2455       * @since Moodle 2.6.1
2456       * @return bool
2457       */
2458      public function replace_all_text_supported() {
2459          return false;
2460      }
2461  
2462      /**
2463       * Replace given text in all rows of column.
2464       *
2465       * @since Moodle 2.6.1
2466       * @param string $table name of the table
2467       * @param database_column_info $column
2468       * @param string $search
2469       * @param string $replace
2470       */
2471      public function replace_all_text($table, database_column_info $column, $search, $replace) {
2472          if (!$this->replace_all_text_supported()) {
2473              return;
2474          }
2475  
2476          // NOTE: override this methods if following standard compliant SQL
2477          //       does not work for your driver.
2478  
2479          // Enclose the column name by the proper quotes if it's a reserved word.
2480          $columnname = $this->get_manager()->generator->getEncQuoted($column->name);
2481  
2482          $searchsql = $this->sql_like($columnname, '?');
2483          $searchparam = '%'.$this->sql_like_escape($search).'%';
2484  
2485          $sql = "UPDATE {".$table."}
2486                         SET $columnname = REPLACE($columnname, ?, ?)
2487                       WHERE $searchsql";
2488  
2489          if ($column->meta_type === 'X') {
2490              $this->execute($sql, array($search, $replace, $searchparam));
2491  
2492          } else if ($column->meta_type === 'C') {
2493              if (core_text::strlen($search) < core_text::strlen($replace)) {
2494                  $colsize = $column->max_length;
2495                  $sql = "UPDATE {".$table."}
2496                         SET $columnname = " . $this->sql_substr("REPLACE(" . $columnname . ", ?, ?)", 1, $colsize) . "
2497                       WHERE $searchsql";
2498              }
2499              $this->execute($sql, array($search, $replace, $searchparam));
2500          }
2501      }
2502  
2503      /**
2504       * Analyze the data in temporary tables to force statistics collection after bulk data loads.
2505       *
2506       * @return void
2507       */
2508      public function update_temp_table_stats() {
2509          $this->temptables->update_stats();
2510      }
2511  
2512      /**
2513       * Checks and returns true if transactions are supported.
2514       *
2515       * It is not responsible to run productions servers
2516       * on databases without transaction support ;-)
2517       *
2518       * Override in driver if needed.
2519       *
2520       * @return bool
2521       */
2522      protected function transactions_supported() {
2523          // protected for now, this might be changed to public if really necessary
2524          return true;
2525      }
2526  
2527      /**
2528       * Returns true if a transaction is in progress.
2529       * @return bool
2530       */
2531      public function is_transaction_started() {
2532          return !empty($this->transactions);
2533      }
2534  
2535      /**
2536       * This is a test that throws an exception if transaction in progress.
2537       * This test does not force rollback of active transactions.
2538       * @return void
2539       * @throws dml_transaction_exception if stansaction active
2540       */
2541      public function transactions_forbidden() {
2542          if ($this->is_transaction_started()) {
2543              throw new dml_transaction_exception('This code can not be excecuted in transaction');
2544          }
2545      }
2546  
2547      /**
2548       * On DBs that support it, switch to transaction mode and begin a transaction
2549       * you'll need to ensure you call allow_commit() on the returned object
2550       * or your changes *will* be lost.
2551       *
2552       * this is _very_ useful for massive updates
2553       *
2554       * Delegated database transactions can be nested, but only one actual database
2555       * transaction is used for the outer-most delegated transaction. This method
2556       * returns a transaction object which you should keep until the end of the
2557       * delegated transaction. The actual database transaction will
2558       * only be committed if all the nested delegated transactions commit
2559       * successfully. If any part of the transaction rolls back then the whole
2560       * thing is rolled back.
2561       *
2562       * @return moodle_transaction
2563       */
2564      public function start_delegated_transaction() {
2565          $transaction = new moodle_transaction($this);
2566          $this->transactions[] = $transaction;
2567          if (count($this->transactions) == 1) {
2568              $this->begin_transaction();
2569          }
2570          return $transaction;
2571      }
2572  
2573      /**
2574       * Driver specific start of real database transaction,
2575       * this can not be used directly in code.
2576       * @return void
2577       */
2578      protected abstract function begin_transaction();
2579  
2580      /**
2581       * Indicates delegated transaction finished successfully.
2582       * The real database transaction is committed only if
2583       * all delegated transactions committed.
2584       * @param moodle_transaction $transaction The transaction to commit
2585       * @return void
2586       * @throws dml_transaction_exception Creates and throws transaction related exceptions.
2587       */
2588      public function commit_delegated_transaction(moodle_transaction $transaction) {
2589          if ($transaction->is_disposed()) {
2590              throw new dml_transaction_exception('Transactions already disposed', $transaction);
2591          }
2592          // mark as disposed so that it can not be used again
2593          $transaction->dispose();
2594  
2595          if (empty($this->transactions)) {
2596              throw new dml_transaction_exception('Transaction not started', $transaction);
2597          }
2598  
2599          if ($this->force_rollback) {
2600              throw new dml_transaction_exception('Tried to commit transaction after lower level rollback', $transaction);
2601          }
2602  
2603          if ($transaction !== $this->transactions[count($this->transactions) - 1]) {
2604              // one incorrect commit at any level rollbacks everything
2605              $this->force_rollback = true;
2606              throw new dml_transaction_exception('Invalid transaction commit attempt', $transaction);
2607          }
2608  
2609          if (count($this->transactions) == 1) {
2610              // only commit the top most level
2611              $this->commit_transaction();
2612          }
2613          array_pop($this->transactions);
2614  
2615          if (empty($this->transactions)) {
2616              \core\event\manager::database_transaction_commited();
2617              \core\message\manager::database_transaction_commited();
2618          }
2619      }
2620  
2621      /**
2622       * Driver specific commit of real database transaction,
2623       * this can not be used directly in code.
2624       * @return void
2625       */
2626      protected abstract function commit_transaction();
2627  
2628      /**
2629       * Call when delegated transaction failed, this rolls back
2630       * all delegated transactions up to the top most level.
2631       *
2632       * In many cases you do not need to call this method manually,
2633       * because all open delegated transactions are rolled back
2634       * automatically if exceptions not caught.
2635       *
2636       * @param moodle_transaction $transaction An instance of a moodle_transaction.
2637       * @param Exception|Throwable $e The related exception/throwable to this transaction rollback.
2638       * @return void This does not return, instead the exception passed in will be rethrown.
2639       */
2640      public function rollback_delegated_transaction(moodle_transaction $transaction, $e) {
2641          if (!($e instanceof Exception) && !($e instanceof Throwable)) {
2642              // PHP7 - we catch Throwables in phpunit but can't use that as the type hint in PHP5.
2643              $e = new \coding_exception("Must be given an Exception or Throwable object!");
2644          }
2645          if ($transaction->is_disposed()) {
2646              throw new dml_transaction_exception('Transactions already disposed', $transaction);
2647          }
2648          // mark as disposed so that it can not be used again
2649          $transaction->dispose();
2650  
2651          // one rollback at any level rollbacks everything
2652          $this->force_rollback = true;
2653  
2654          if (empty($this->transactions) or $transaction !== $this->transactions[count($this->transactions) - 1]) {
2655              // this may or may not be a coding problem, better just rethrow the exception,
2656              // because we do not want to loose the original $e
2657              throw $e;
2658          }
2659  
2660          if (count($this->transactions) == 1) {
2661              // only rollback the top most level
2662              $this->rollback_transaction();
2663          }
2664          array_pop($this->transactions);
2665          if (empty($this->transactions)) {
2666              // finally top most level rolled back
2667              $this->force_rollback = false;
2668              \core\event\manager::database_transaction_rolledback();
2669              \core\message\manager::database_transaction_rolledback();
2670          }
2671          throw $e;
2672      }
2673  
2674      /**
2675       * Driver specific abort of real database transaction,
2676       * this can not be used directly in code.
2677       * @return void
2678       */
2679      protected abstract function rollback_transaction();
2680  
2681      /**
2682       * Force rollback of all delegated transaction.
2683       * Does not throw any exceptions and does not log anything.
2684       *
2685       * This method should be used only from default exception handlers and other
2686       * core code.
2687       *
2688       * @return void
2689       */
2690      public function force_transaction_rollback() {
2691          if ($this->transactions) {
2692              try {
2693                  $this->rollback_transaction();
2694              } catch (dml_exception $e) {
2695                  // ignore any sql errors here, the connection might be broken
2696              }
2697          }
2698  
2699          // now enable transactions again
2700          $this->transactions = array();
2701          $this->force_rollback = false;
2702  
2703          \core\event\manager::database_transaction_rolledback();
2704          \core\message\manager::database_transaction_rolledback();
2705      }
2706  
2707      /**
2708       * Is session lock supported in this driver?
2709       * @return bool
2710       */
2711      public function session_lock_supported() {
2712          return false;
2713      }
2714  
2715      /**
2716       * Obtains the session lock.
2717       * @param int $rowid The id of the row with session record.
2718       * @param int $timeout The maximum allowed time to wait for the lock in seconds.
2719       * @return void
2720       * @throws dml_exception A DML specific exception is thrown for any errors.
2721       */
2722      public function get_session_lock($rowid, $timeout) {
2723          $this->used_for_db_sessions = true;
2724      }
2725  
2726      /**
2727       * Releases the session lock.
2728       * @param int $rowid The id of the row with session record.
2729       * @return void
2730       * @throws dml_exception A DML specific exception is thrown for any errors.
2731       */
2732      public function release_session_lock($rowid) {
2733      }
2734  
2735      /**
2736       * Returns the number of reads done by this database.
2737       * @return int Number of reads.
2738       */
2739      public function perf_get_reads() {
2740          return $this->reads;
2741      }
2742  
2743      /**
2744       * Returns whether we want to connect to slave database for read queries.
2745       * @return bool Want read only connection
2746       */
2747      public function want_read_slave(): bool {
2748          return false;
2749      }
2750  
2751      /**
2752       * Returns the number of reads before first write done by this database.
2753       * @return int Number of reads.
2754       */
2755      public function perf_get_reads_slave(): int {
2756          return 0;
2757      }
2758  
2759      /**
2760       * Returns the number of writes done by this database.
2761       * @return int Number of writes.
2762       */
2763      public function perf_get_writes() {
2764          return $this->writes;
2765      }
2766  
2767      /**
2768       * Returns the number of queries done by this database.
2769       * @return int Number of queries.
2770       */
2771      public function perf_get_queries() {
2772          return $this->writes + $this->reads;
2773      }
2774  
2775      /**
2776       * Time waiting for the database engine to finish running all queries.
2777       * @return float Number of seconds with microseconds
2778       */
2779      public function perf_get_queries_time() {
2780          return $this->queriestime;
2781      }
2782  
2783      /**
2784       * Whether the database is able to support full-text search or not.
2785       *
2786       * @return bool
2787       */
2788      public function is_fulltext_search_supported() {
2789          // No support unless specified.
2790          return false;
2791      }
2792  }