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