3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
20 * Native mysqli class representing moodle database interface.
24 * @copyright 2008 Petr Skoda (http://skodak.org)
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') || die();
30 require_once($CFG->libdir.'/dml/moodle_database.php');
31 require_once($CFG->libdir.'/dml/mysqli_native_moodle_recordset.php');
32 require_once($CFG->libdir.'/dml/mysqli_native_moodle_temptables.php');
35 * Native mysqli class representing moodle database interface.
37 class mysqli_native_moodle_database extends moodle_database {
39 protected $mysqli = null;
41 private $transactions_supported = null;
44 * Attempt to create the database
45 * @param string $dbhost
46 * @param string $dbuser
47 * @param string $dbpass
48 * @param string $dbname
49 * @return bool success
50 * @throws dml_exception if error
52 public function create_database($dbhost, $dbuser, $dbpass, $dbname, array $dboptions=null) {
53 $driverstatus = $this->driver_installed();
55 if ($driverstatus !== true) {
56 throw new dml_exception('dbdriverproblem', $driverstatus);
59 if (!empty($dboptions['dbsocket'])
60 and (strpos($dboptions['dbsocket'], '/') !== false or strpos($dboptions['dbsocket'], '\\') !== false)) {
61 $dbsocket = $dboptions['dbsocket'];
63 $dbsocket = ini_get('mysqli.default_socket');
65 if (empty($dboptions['dbport'])) {
66 $dbport = (int)ini_get('mysqli.default_port');
68 $dbport = (int)$dboptions['dbport'];
70 // verify ini.get does not return nonsense
75 $conn = new mysqli($dbhost, $dbuser, $dbpass, '', $dbport, $dbsocket); /// Connect without db
76 $dberr = ob_get_contents();
78 $errorno = @$conn->connect_errno;
81 throw new dml_connection_exception($dberr);
84 $result = $conn->query("CREATE DATABASE $dbname DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci");
89 throw new dml_exception('cannotcreatedb');
96 * Detects if all needed PHP stuff installed.
97 * Note: can be used before connect()
98 * @return mixed true if ok, string if something
100 public function driver_installed() {
101 if (!extension_loaded('mysqli')) {
102 return get_string('mysqliextensionisnotpresentinphp', 'install');
108 * Returns database family type - describes SQL dialect
109 * Note: can be used before connect()
110 * @return string db family name (mysql, postgres, mssql, oracle, etc.)
112 public function get_dbfamily() {
117 * Returns more specific database driver type
118 * Note: can be used before connect()
119 * @return string db type mysqli, pgsql, oci, mssql, sqlsrv
121 protected function get_dbtype() {
126 * Returns general database library name
127 * Note: can be used before connect()
128 * @return string db type pdo, native
130 protected function get_dblibrary() {
135 * Returns the current MySQL db engine.
137 * This is an ugly workaround for MySQL default engine problems,
138 * Moodle is designed to work best on ACID compliant databases
139 * with full transaction support. Do not use MyISAM.
141 * @return string or null MySQL engine name
143 public function get_dbengine() {
144 if (isset($this->dboptions['dbengine'])) {
145 return $this->dboptions['dbengine'];
150 if (!$this->external) {
151 // look for current engine of our config table (the first table that gets created),
152 // so that we create all tables with the same engine
153 $sql = "SELECT engine FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = DATABASE() AND table_name = '{$this->prefix}config'";
154 $this->query_start($sql, NULL, SQL_QUERY_AUX);
155 $result = $this->mysqli->query($sql);
156 $this->query_end($result);
157 if ($rec = $result->fetch_assoc()) {
158 $engine = $rec['engine'];
167 // get the default database engine
168 $sql = "SELECT @@storage_engine";
169 $this->query_start($sql, NULL, SQL_QUERY_AUX);
170 $result = $this->mysqli->query($sql);
171 $this->query_end($result);
172 if ($rec = $result->fetch_assoc()) {
173 $engine = $rec['@@storage_engine'];
177 if (!$this->external and $engine === 'MyISAM') {
178 // we really do not want MyISAM for Moodle, InnoDB or XtraDB is a reasonable defaults if supported
179 $sql = "SHOW STORAGE ENGINES";
180 $this->query_start($sql, NULL, SQL_QUERY_AUX);
181 $result = $this->mysqli->query($sql);
182 $this->query_end($result);
184 while ($res = $result->fetch_assoc()) {
185 if ($res['Support'] === 'YES' or $res['Support'] === 'DEFAULT') {
186 $engines[$res['Engine']] = true;
190 if (isset($engines['InnoDB'])) {
193 if (isset($engines['XtraDB'])) {
202 * Returns localised database type name
203 * Note: can be used before connect()
206 public function get_name() {
207 return get_string('nativemysqli', 'install');
211 * Returns localised database configuration help.
212 * Note: can be used before connect()
215 public function get_configuration_help() {
216 return get_string('nativemysqlihelp', 'install');
220 * Returns localised database description
221 * Note: can be used before connect()
224 public function get_configuration_hints() {
225 return get_string('databasesettingssub_mysqli', 'install');
229 * Diagnose database and tables, this function is used
230 * to verify database and driver settings, db engine types, etc.
232 * @return string null means everything ok, string means problem found.
234 public function diagnose() {
235 $sloppymyisamfound = false;
236 $prefix = str_replace('_', '\\_', $this->prefix);
237 $sql = "SHOW TABLE STATUS WHERE Name LIKE BINARY '$prefix%'";
238 $this->query_start($sql, null, SQL_QUERY_AUX);
239 $result = $this->mysqli->query($sql);
240 $this->query_end($result);
242 while ($arr = $result->fetch_assoc()) {
243 if ($arr['Engine'] === 'MyISAM') {
244 $sloppymyisamfound = true;
251 if ($sloppymyisamfound) {
252 return get_string('myisamproblem', 'error');
260 * Must be called before other methods.
261 * @param string $dbhost
262 * @param string $dbuser
263 * @param string $dbpass
264 * @param string $dbname
265 * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
266 * @param array $dboptions driver specific options
267 * @return bool success
269 public function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null) {
270 $driverstatus = $this->driver_installed();
272 if ($driverstatus !== true) {
273 throw new dml_exception('dbdriverproblem', $driverstatus);
276 $this->store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions);
278 // dbsocket is used ONLY if host is NULL or 'localhost',
279 // you can not disable it because it is always tried if dbhost is 'localhost'
280 if (!empty($this->dboptions['dbsocket'])
281 and (strpos($this->dboptions['dbsocket'], '/') !== false or strpos($this->dboptions['dbsocket'], '\\') !== false)) {
282 $dbsocket = $this->dboptions['dbsocket'];
284 $dbsocket = ini_get('mysqli.default_socket');
286 if (empty($this->dboptions['dbport'])) {
287 $dbport = (int)ini_get('mysqli.default_port');
289 $dbport = (int)$this->dboptions['dbport'];
291 // verify ini.get does not return nonsense
292 if (empty($dbport)) {
296 $this->mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname, $dbport, $dbsocket);
297 $dberr = ob_get_contents();
299 $errorno = @$this->mysqli->connect_errno;
301 if ($errorno !== 0) {
302 throw new dml_connection_exception($dberr);
305 $this->query_start("--set_charset()", null, SQL_QUERY_AUX);
306 $this->mysqli->set_charset('utf8');
307 $this->query_end(true);
309 // If available, enforce strict mode for the session. That guaranties
310 // standard behaviour under some situations, avoiding some MySQL nasty
311 // habits like truncating data or performing some transparent cast losses.
312 // With strict mode enforced, Moodle DB layer will be consistently throwing
313 // the corresponding exceptions as expected.
314 $si = $this->get_server_info();
315 if (version_compare($si['version'], '5.0.2', '>=')) {
316 $sql = "SET SESSION sql_mode = 'STRICT_ALL_TABLES'";
317 $this->query_start($sql, null, SQL_QUERY_AUX);
318 $result = $this->mysqli->query($sql);
319 $this->query_end($result);
322 // Connection stabilished and configured, going to instantiate the temptables controller
323 $this->temptables = new mysqli_native_moodle_temptables($this);
329 * Close database connection and release all resources
330 * and memory (especially circular memory references).
331 * Do NOT use connect() again, create a new instance if needed.
333 public function dispose() {
334 parent::dispose(); // Call parent dispose to write/close session and other common stuff before closing connection
336 $this->mysqli->close();
337 $this->mysqli = null;
342 * Returns database server info array
345 public function get_server_info() {
346 return array('description'=>$this->mysqli->server_info, 'version'=>$this->mysqli->server_info);
350 * Returns supported query parameter types
351 * @return int bitmask
353 protected function allowed_param_types() {
354 return SQL_PARAMS_QM;
358 * Returns last error reported by database engine.
359 * @return string error message
361 public function get_last_error() {
362 return $this->mysqli->error;
366 * Return tables in database WITHOUT current prefix
367 * @return array of table names in lowercase and without prefix
369 public function get_tables($usecache=true) {
370 if ($usecache and $this->tables !== null) {
371 return $this->tables;
373 $this->tables = array();
374 $sql = "SHOW TABLES";
375 $this->query_start($sql, null, SQL_QUERY_AUX);
376 $result = $this->mysqli->query($sql);
377 $this->query_end($result);
379 while ($arr = $result->fetch_assoc()) {
380 $tablename = reset($arr);
381 if ($this->prefix !== '') {
382 if (strpos($tablename, $this->prefix) !== 0) {
385 $tablename = substr($tablename, strlen($this->prefix));
387 $this->tables[$tablename] = $tablename;
392 // Add the currently available temptables
393 $this->tables = array_merge($this->tables, $this->temptables->get_temptables());
394 return $this->tables;
398 * Return table indexes - everything lowercased
399 * @return array of arrays
401 public function get_indexes($table) {
403 $sql = "SHOW INDEXES FROM {$this->prefix}$table";
404 $this->query_start($sql, null, SQL_QUERY_AUX);
405 $result = $this->mysqli->query($sql);
406 $this->query_end($result);
408 while ($res = $result->fetch_object()) {
409 if ($res->Key_name === 'PRIMARY') {
412 if (!isset($indexes[$res->Key_name])) {
413 $indexes[$res->Key_name] = array('unique'=>empty($res->Non_unique), 'columns'=>array());
415 $indexes[$res->Key_name]['columns'][$res->Seq_in_index-1] = $res->Column_name;
423 * Returns detailed information about columns in table. This information is cached internally.
424 * @param string $table name
425 * @param bool $usecache
426 * @return array array of database_column_info objects indexed with column names
428 public function get_columns($table, $usecache=true) {
429 if ($usecache and isset($this->columns[$table])) {
430 return $this->columns[$table];
433 $this->columns[$table] = array();
435 $sql = "SHOW COLUMNS FROM {$this->prefix}$table";
436 $this->query_start($sql, null, SQL_QUERY_AUX);
437 $result = $this->mysqli->query($sql);
438 $this->query_end($result);
440 if ($result === false) {
444 while ($rawcolumn = $result->fetch_assoc()) {
445 $rawcolumn = (object)array_change_key_case($rawcolumn, CASE_LOWER);
447 $info = new stdClass();
448 $info->name = $rawcolumn->field;
451 if (preg_match('/varchar\((\d+)\)/i', $rawcolumn->type, $matches)) {
452 $info->type = 'varchar';
453 $info->meta_type = 'C';
454 $info->max_length = $matches[1];
456 $info->not_null = ($rawcolumn->null === 'NO');
457 $info->default_value = $rawcolumn->default;
458 $info->has_default = is_null($info->default_value) ? false : true;
459 $info->primary_key = ($rawcolumn->key === 'PRI');
460 $info->binary = false;
461 $info->unsigned = null;
462 $info->auto_increment= false;
463 $info->unique = null;
465 } else if (preg_match('/([a-z]*int[a-z]*)\((\d+)\)/i', $rawcolumn->type, $matches)) {
466 $info->type = $matches[1];
467 $info->primary_key = ($rawcolumn->key === 'PRI');
468 if ($info->primary_key) {
469 $info->meta_type = 'R';
470 $info->max_length = $matches[2];
472 $info->not_null = ($rawcolumn->null === 'NO');
473 $info->default_value = $rawcolumn->default;
474 $info->has_default = is_null($info->default_value) ? false : true;
475 $info->binary = false;
476 $info->unsigned = (stripos($rawcolumn->type, 'unsigned') !== false);
477 $info->auto_increment= true;
478 $info->unique = true;
480 $info->meta_type = 'I';
481 $info->max_length = $matches[2];
483 $info->not_null = ($rawcolumn->null === 'NO');
484 $info->default_value = $rawcolumn->default;
485 $info->has_default = is_null($info->default_value) ? false : true;
486 $info->binary = false;
487 $info->unsigned = (stripos($rawcolumn->type, 'unsigned') !== false);
488 $info->auto_increment= false;
489 $info->unique = null;
492 } else if (preg_match('/(decimal|double|float)\((\d+),(\d+)\)/i', $rawcolumn->type, $matches)) {
493 $info->type = $matches[1];
494 $info->meta_type = 'N';
495 $info->max_length = $matches[2];
496 $info->scale = $matches[3];
497 $info->not_null = ($rawcolumn->null === 'NO');
498 $info->default_value = $rawcolumn->default;
499 $info->has_default = is_null($info->default_value) ? false : true;
500 $info->primary_key = ($rawcolumn->key === 'PRI');
501 $info->binary = false;
502 $info->unsigned = (stripos($rawcolumn->type, 'unsigned') !== false);
503 $info->auto_increment= false;
504 $info->unique = null;
506 } else if (preg_match('/([a-z]*text)/i', $rawcolumn->type, $matches)) {
507 $info->type = $matches[1];
508 $info->meta_type = 'X';
509 $info->max_length = -1;
511 $info->not_null = ($rawcolumn->null === 'NO');
512 $info->default_value = $rawcolumn->default;
513 $info->has_default = is_null($info->default_value) ? false : true;
514 $info->primary_key = ($rawcolumn->key === 'PRI');
515 $info->binary = false;
516 $info->unsigned = null;
517 $info->auto_increment= false;
518 $info->unique = null;
520 } else if (preg_match('/([a-z]*blob)/i', $rawcolumn->type, $matches)) {
521 $info->type = $matches[1];
522 $info->meta_type = 'B';
523 $info->max_length = -1;
525 $info->not_null = ($rawcolumn->null === 'NO');
526 $info->default_value = $rawcolumn->default;
527 $info->has_default = is_null($info->default_value) ? false : true;
528 $info->primary_key = false;
529 $info->binary = true;
530 $info->unsigned = null;
531 $info->auto_increment= false;
532 $info->unique = null;
534 } else if (preg_match('/enum\((.*)\)/i', $rawcolumn->type, $matches)) {
535 $info->type = 'enum';
536 $info->meta_type = 'C';
537 $info->enums = array();
538 $info->max_length = 0;
539 $values = $matches[1];
540 $values = explode(',', $values);
541 $textlib = textlib_get_instance();
542 foreach ($values as $val) {
543 $val = trim($val, "'");
544 $length = $textlib->strlen($val);
545 $info->enums[] = $val;
546 $info->max_length = ($info->max_length < $length) ? $length : $info->max_length;
549 $info->not_null = ($rawcolumn->null === 'NO');
550 $info->default_value = $rawcolumn->default;
551 $info->has_default = is_null($info->default_value) ? false : true;
552 $info->primary_key = ($rawcolumn->key === 'PRI');
553 $info->binary = false;
554 $info->unsigned = null;
555 $info->auto_increment= false;
556 $info->unique = null;
559 $this->columns[$table][$info->name] = new database_column_info($info);
564 return $this->columns[$table];
568 * Normalise values based in RDBMS dependencies (booleans, LOBs...)
570 * @param database_column_info $column column metadata corresponding with the value we are going to normalise
571 * @param mixed $value value we are going to normalise
572 * @return mixed the normalised value
574 protected function normalise_value($column, $value) {
575 if (is_bool($value)) { // Always, convert boolean to int
576 $value = (int)$value;
578 } else if ($value === '') {
579 if ($column->meta_type == 'I' or $column->meta_type == 'F' or $column->meta_type == 'N') {
580 $value = 0; // prevent '' problems in numeric fields
582 // Any float value being stored in varchar or text field is converted to string to avoid
583 // any implicit conversion by MySQL
584 } else if (is_float($value) and ($column->meta_type == 'C' or $column->meta_type == 'X')) {
587 // workaround for problem with wrong enums in mysql - TODO: Out in Moodle 2.1
588 if (!empty($column->enums)) {
589 if (is_null($value) and !$column->not_null) {
590 // ok - nulls allowed
592 if (!in_array((string)$value, $column->enums)) {
593 throw new dml_write_exception('Enum value '.s($value).' not allowed in field '.$field.' table '.$table.'.');
601 * Is db in unicode mode?
604 public function setup_is_unicodedb() {
605 $sql = "SHOW LOCAL VARIABLES LIKE 'character_set_database'";
606 $this->query_start($sql, null, SQL_QUERY_AUX);
607 $result = $this->mysqli->query($sql);
608 $this->query_end($result);
612 while($row = $result->fetch_assoc()) {
613 if (isset($row['Value'])) {
614 $return = (strtoupper($row['Value']) === 'UTF8' or strtoupper($row['Value']) === 'UTF-8');
625 $sql = "SHOW LOCAL VARIABLES LIKE 'collation_database'";
626 $this->query_start($sql, null, SQL_QUERY_AUX);
627 $result = $this->mysqli->query($sql);
628 $this->query_end($result);
632 while($row = $result->fetch_assoc()) {
633 if (isset($row['Value'])) {
634 $return = (strpos($row['Value'], 'latin1') !== 0);
645 * Do NOT use in code, to be used by database_manager only!
646 * @param string $sql query
648 * @throws dml_exception if error
650 public function change_database_structure($sql) {
651 $this->reset_caches();
653 $this->query_start($sql, null, SQL_QUERY_STRUCTURE);
654 $result = $this->mysqli->query($sql);
655 $this->query_end($result);
661 * Very ugly hack which emulates bound parameters in queries
662 * because prepared statements do not use query cache.
664 protected function emulate_bound_params($sql, array $params=null) {
665 if (empty($params)) {
668 /// ok, we have verified sql statement with ? and correct number of params
669 $return = strtok($sql, '?');
670 foreach ($params as $param) {
671 if (is_bool($param)) {
672 $return .= (int)$param;
673 } else if (is_null($param)) {
675 } else if (is_number($param)) {
676 $return .= "'".$param."'"; // we have to always use strings because mysql is using weird automatic int casting
677 } else if (is_float($param)) {
680 $param = $this->mysqli->real_escape_string($param);
681 $return .= "'$param'";
683 $return .= strtok('?');
689 * Execute general sql query. Should be used only when no other method suitable.
690 * Do NOT use this to make changes in db structure, use database_manager::execute_sql() instead!
691 * @param string $sql query
692 * @param array $params query parameters
694 * @throws dml_exception if error
696 public function execute($sql, array $params=null) {
697 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
699 if (strpos($sql, ';') !== false) {
700 throw new coding_exception('moodle_database::execute() Multiple sql statements found or bound parameters not used properly in query!');
703 $rawsql = $this->emulate_bound_params($sql, $params);
705 $this->query_start($sql, $params, SQL_QUERY_UPDATE);
706 $result = $this->mysqli->query($rawsql);
707 $this->query_end($result);
709 if ($result === true) {
719 * Get a number of records as a moodle_recordset using a SQL statement.
721 * Since this method is a little less readable, use of it should be restricted to
722 * code where it's possible there might be large datasets being returned. For known
723 * small datasets use get_records_sql - it leads to simpler code.
725 * The return type is as for @see function get_recordset.
727 * @param string $sql the SQL select query to execute.
728 * @param array $params array of sql parameters
729 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
730 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
731 * @return moodle_recordset instance
732 * @throws dml_exception if error
734 public function get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
735 $limitfrom = (int)$limitfrom;
736 $limitnum = (int)$limitnum;
737 $limitfrom = ($limitfrom < 0) ? 0 : $limitfrom;
738 $limitnum = ($limitnum < 0) ? 0 : $limitnum;
740 if ($limitfrom or $limitnum) {
742 $limitnum = "18446744073709551615";
744 $sql .= " LIMIT $limitfrom, $limitnum";
747 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
748 $rawsql = $this->emulate_bound_params($sql, $params);
750 $this->query_start($sql, $params, SQL_QUERY_SELECT);
751 // no MYSQLI_USE_RESULT here, it would block write ops on affected tables
752 $result = $this->mysqli->query($rawsql, MYSQLI_STORE_RESULT);
753 $this->query_end($result);
755 return $this->create_recordset($result);
758 protected function create_recordset($result) {
759 return new mysqli_native_moodle_recordset($result);
763 * Get a number of records as an array of objects using a SQL statement.
765 * Return value as for @see function get_records.
767 * @param string $sql the SQL select query to execute. The first column of this SELECT statement
768 * must be a unique value (usually the 'id' field), as it will be used as the key of the
770 * @param array $params array of sql parameters
771 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
772 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
773 * @return array of objects, or empty array if no records were found
774 * @throws dml_exception if error
776 public function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
777 $limitfrom = (int)$limitfrom;
778 $limitnum = (int)$limitnum;
779 $limitfrom = ($limitfrom < 0) ? 0 : $limitfrom;
780 $limitnum = ($limitnum < 0) ? 0 : $limitnum;
782 if ($limitfrom or $limitnum) {
784 $limitnum = "18446744073709551615";
786 $sql .= " LIMIT $limitfrom, $limitnum";
789 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
790 $rawsql = $this->emulate_bound_params($sql, $params);
792 $this->query_start($sql, $params, SQL_QUERY_SELECT);
793 $result = $this->mysqli->query($rawsql, MYSQLI_STORE_RESULT);
794 $this->query_end($result);
798 while($row = $result->fetch_assoc()) {
799 $row = array_change_key_case($row, CASE_LOWER);
801 if (isset($return[$id])) {
802 $colname = key($row);
803 debugging("Did you remember to make the first column something unique in your call to get_records? Duplicate value '$id' found in column '$colname'.", DEBUG_DEVELOPER);
805 $return[$id] = (object)$row;
813 * Selects records and return values (first field) as an array using a SQL statement.
815 * @param string $sql The SQL query
816 * @param array $params array of sql parameters
817 * @return array of values
818 * @throws dml_exception if error
820 public function get_fieldset_sql($sql, array $params=null) {
821 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
822 $rawsql = $this->emulate_bound_params($sql, $params);
824 $this->query_start($sql, $params, SQL_QUERY_SELECT);
825 $result = $this->mysqli->query($rawsql, MYSQLI_STORE_RESULT);
826 $this->query_end($result);
830 while($row = $result->fetch_assoc()) {
831 $return[] = reset($row);
839 * Insert new record into database, as fast as possible, no safety checks, lobs not supported.
840 * @param string $table name
841 * @param mixed $params data record as object or array
842 * @param bool $returnit return it of inserted record
843 * @param bool $bulk true means repeated inserts expected
844 * @param bool $customsequence true if 'id' included in $params, disables $returnid
845 * @return bool|int true or new id
846 * @throws dml_exception if error
848 public function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false) {
849 if (!is_array($params)) {
850 $params = (array)$params;
853 if ($customsequence) {
854 if (!isset($params['id'])) {
855 throw new coding_exception('moodle_database::insert_record_raw() id field must be specified if custom sequences used.');
859 unset($params['id']);
862 if (empty($params)) {
863 throw new coding_exception('moodle_database::insert_record_raw() no fields found.');
866 $fields = implode(',', array_keys($params));
867 $qms = array_fill(0, count($params), '?');
868 $qms = implode(',', $qms);
870 $sql = "INSERT INTO {$this->prefix}$table ($fields) VALUES($qms)";
872 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
873 $rawsql = $this->emulate_bound_params($sql, $params);
875 $this->query_start($sql, $params, SQL_QUERY_INSERT);
876 $result = $this->mysqli->query($rawsql);
877 $id = @$this->mysqli->insert_id; // must be called before query_end() which may insert log into db
878 $this->query_end($result);
881 throw new dml_write_exception('unknown error fetching inserted id');
892 * Insert a record into a table and return the "id" field if required.
894 * Some conversions and safety checks are carried out. Lobs are supported.
895 * If the return ID isn't required, then this just reports success as true/false.
896 * $data is an object containing needed data
897 * @param string $table The database table to be inserted into
898 * @param object $data A data object with values for one or more fields in the record
899 * @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.
900 * @return bool|int true or new id
901 * @throws dml_exception if error
903 public function insert_record($table, $dataobject, $returnid=true, $bulk=false) {
904 $dataobject = (array)$dataobject;
906 $columns = $this->get_columns($table);
909 foreach ($dataobject as $field=>$value) {
910 if ($field === 'id') {
913 if (!isset($columns[$field])) {
916 $column = $columns[$field];
917 $cleaned[$field] = $this->normalise_value($column, $value);
920 return $this->insert_record_raw($table, $cleaned, $returnid, $bulk);
924 * Import a record into a table, id field is required.
925 * Safety checks are NOT carried out. Lobs are supported.
927 * @param string $table name of database table to be inserted into
928 * @param object $dataobject A data object with values for one or more fields in the record
930 * @throws dml_exception if error
932 public function import_record($table, $dataobject) {
933 $dataobject = (array)$dataobject;
935 $columns = $this->get_columns($table);
938 foreach ($dataobject as $field=>$value) {
939 if (!isset($columns[$field])) {
942 $cleaned[$field] = $value;
945 return $this->insert_record_raw($table, $cleaned, false, true, true);
949 * Update record in database, as fast as possible, no safety checks, lobs not supported.
950 * @param string $table name
951 * @param mixed $params data record as object or array
952 * @param bool true means repeated updates expected
954 * @throws dml_exception if error
956 public function update_record_raw($table, $params, $bulk=false) {
957 $params = (array)$params;
959 if (!isset($params['id'])) {
960 throw new coding_exception('moodle_database::update_record_raw() id field must be specified.');
963 unset($params['id']);
965 if (empty($params)) {
966 throw new coding_exception('moodle_database::update_record_raw() no fields found.');
970 foreach ($params as $field=>$value) {
971 $sets[] = "$field = ?";
974 $params[] = $id; // last ? in WHERE condition
976 $sets = implode(',', $sets);
977 $sql = "UPDATE {$this->prefix}$table SET $sets WHERE id=?";
979 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
980 $rawsql = $this->emulate_bound_params($sql, $params);
982 $this->query_start($sql, $params, SQL_QUERY_UPDATE);
983 $result = $this->mysqli->query($rawsql);
984 $this->query_end($result);
990 * Update a record in a table
992 * $dataobject is an object containing needed data
993 * Relies on $dataobject having a variable "id" to
994 * specify the record to update
996 * @param string $table The database table to be checked against.
997 * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
998 * @param bool true means repeated updates expected
1000 * @throws dml_exception if error
1002 public function update_record($table, $dataobject, $bulk=false) {
1003 $dataobject = (array)$dataobject;
1005 $columns = $this->get_columns($table);
1008 foreach ($dataobject as $field=>$value) {
1009 if (!isset($columns[$field])) {
1012 $column = $columns[$field];
1013 $cleaned[$field] = $this->normalise_value($column, $value);
1016 return $this->update_record_raw($table, $cleaned, $bulk);
1020 * Set a single field in every table record which match a particular WHERE clause.
1022 * @param string $table The database table to be checked against.
1023 * @param string $newfield the field to set.
1024 * @param string $newvalue the value to set the field to.
1025 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1026 * @param array $params array of sql parameters
1028 * @throws dml_exception if error
1030 public function set_field_select($table, $newfield, $newvalue, $select, array $params=null) {
1032 $select = "WHERE $select";
1034 if (is_null($params)) {
1037 list($select, $params, $type) = $this->fix_sql_params($select, $params);
1039 // Get column metadata
1040 $columns = $this->get_columns($table);
1041 $column = $columns[$newfield];
1043 $normalised_value = $this->normalise_value($column, $newvalue);
1045 if (is_null($normalised_value)) {
1046 $newfield = "$newfield = NULL";
1048 $newfield = "$newfield = ?";
1049 array_unshift($params, $normalised_value);
1051 $sql = "UPDATE {$this->prefix}$table SET $newfield $select";
1052 $rawsql = $this->emulate_bound_params($sql, $params);
1054 $this->query_start($sql, $params, SQL_QUERY_UPDATE);
1055 $result = $this->mysqli->query($rawsql);
1056 $this->query_end($result);
1062 * Delete one or more records from a table which match a particular WHERE clause.
1064 * @param string $table The database table to be checked against.
1065 * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
1066 * @param array $params array of sql parameters
1068 * @throws dml_exception if error
1070 public function delete_records_select($table, $select, array $params=null) {
1072 $select = "WHERE $select";
1074 $sql = "DELETE FROM {$this->prefix}$table $select";
1076 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
1077 $rawsql = $this->emulate_bound_params($sql, $params);
1079 $this->query_start($sql, $params, SQL_QUERY_UPDATE);
1080 $result = $this->mysqli->query($rawsql);
1081 $this->query_end($result);
1086 public function sql_cast_char2int($fieldname, $text=false) {
1087 return ' CAST(' . $fieldname . ' AS SIGNED) ';
1090 public function sql_cast_char2real($fieldname, $text=false) {
1091 return ' CAST(' . $fieldname . ' AS DECIMAL) ';
1095 * Returns 'LIKE' part of a query.
1097 * @param string $fieldname usually name of the table column
1098 * @param string $param usually bound query parameter (?, :named)
1099 * @param bool $casesensitive use case sensitive search
1100 * @param bool $accensensitive use accent sensitive search (not all databases support accent insensitive)
1101 * @param bool $notlike true means "NOT LIKE"
1102 * @param string $escapechar escape char for '%' and '_'
1103 * @return string SQL code fragment
1105 public function sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = '\\') {
1106 if (strpos($param, '%') !== false) {
1107 debugging('Potential SQL injection detected, sql_ilike() expects bound parameters (? or :named)');
1109 $escapechar = $this->mysqli->real_escape_string($escapechar); // prevents problems with C-style escapes of enclosing '\'
1111 $LIKE = $notlike ? 'NOT LIKE' : 'LIKE';
1112 if ($casesensitive) {
1113 return "$fieldname $LIKE $param COLLATE utf8_bin ESCAPE '$escapechar'";
1115 if ($accentsensitive) {
1116 return "LOWER($fieldname) $LIKE LOWER($param) COLLATE utf8_bin ESCAPE '$escapechar'";
1118 return "$fieldname $LIKE $param ESCAPE '$escapechar'";
1124 * Returns the proper SQL to do CONCAT between the elements passed
1125 * Can take many parameters
1127 * @param string $str,... 1 or more fields/strings to concat
1129 * @return string The concat sql
1131 public function sql_concat() {
1132 $arr = func_get_args();
1133 $s = implode(', ', $arr);
1137 return "CONCAT($s)";
1141 * Returns the proper SQL to do CONCAT between the elements passed
1142 * with a given separator
1144 * @param string $separator The string to use as the separator
1145 * @param array $elements An array of items to concatenate
1146 * @return string The concat SQL
1148 public function sql_concat_join($separator="' '", $elements=array()) {
1149 $s = implode(', ', $elements);
1154 return "CONCAT_WS($separator, $s)";
1158 * Returns the SQL text to be used to calculate the length in characters of one expression.
1159 * @param string fieldname or expression to calculate its length in characters.
1160 * @return string the piece of SQL code to be used in the statement.
1162 public function sql_length($fieldname) {
1163 return ' CHAR_LENGTH(' . $fieldname . ')';
1167 * Does this driver support regex syntax when searching
1169 public function sql_regex_supported() {
1174 * Return regex positive or negative match sql
1175 * @param bool $positivematch
1176 * @return string or empty if not supported
1178 public function sql_regex($positivematch=true) {
1179 return $positivematch ? 'REGEXP' : 'NOT REGEXP';
1182 public function sql_cast_2signed($fieldname) {
1183 return ' CAST(' . $fieldname . ' AS SIGNED) ';
1187 public function session_lock_supported() {
1191 public function get_session_lock($rowid) {
1192 parent::get_session_lock($rowid);
1193 $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid;
1194 $sql = "SELECT GET_LOCK('$fullname',120)";
1195 $this->query_start($sql, null, SQL_QUERY_AUX);
1196 $result = $this->mysqli->query($sql);
1197 $this->query_end($result);
1200 $arr = $result->fetch_assoc();
1203 if (reset($arr) == 1) {
1207 $this->get_session_lock($rowid);
1212 public function release_session_lock($rowid) {
1213 parent::release_session_lock($rowid);
1214 $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid;
1215 $sql = "SELECT RELEASE_LOCK('$fullname')";
1216 $this->query_start($sql, null, SQL_QUERY_AUX);
1217 $result = $this->mysqli->query($sql);
1218 $this->query_end($result);
1227 * Are transactions supported?
1228 * It is not responsible to run productions servers
1229 * on databases without transaction support ;-)
1231 * MyISAM does not support support transactions.
1233 * You can override this via the dbtransactions option.
1237 protected function transactions_supported() {
1238 if (!is_null($this->transactions_supported)) {
1239 return $this->transactions_supported;
1242 // this is all just guessing, might be better to just specify it in config.php
1243 if (isset($this->dboptions['dbtransactions'])) {
1244 $this->transactions_supported = $this->dboptions['dbtransactions'];
1245 return $this->transactions_supported;
1248 $this->transactions_supported = false;
1250 $engine = $this->get_dbengine();
1252 // Only will accept transactions if using compatible storage engine (more engines can be added easily BDB, Falcon...)
1253 if (in_array($engine, array('InnoDB', 'INNOBASE', 'BDB', 'XtraDB', 'Aria', 'Falcon'))) {
1254 $this->transactions_supported = true;
1257 return $this->transactions_supported;
1261 * Driver specific start of real database transaction,
1262 * this can not be used directly in code.
1265 protected function begin_transaction() {
1266 if (!$this->transactions_supported()) {
1270 $sql = "SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED";
1271 $this->query_start($sql, NULL, SQL_QUERY_AUX);
1272 $result = $this->mysqli->query($sql);
1273 $this->query_end($result);
1275 $sql = "START TRANSACTION";
1276 $this->query_start($sql, NULL, SQL_QUERY_AUX);
1277 $result = $this->mysqli->query($sql);
1278 $this->query_end($result);
1282 * Driver specific commit of real database transaction,
1283 * this can not be used directly in code.
1286 protected function commit_transaction() {
1287 if (!$this->transactions_supported()) {
1292 $this->query_start($sql, NULL, SQL_QUERY_AUX);
1293 $result = $this->mysqli->query($sql);
1294 $this->query_end($result);
1298 * Driver specific abort of real database transaction,
1299 * this can not be used directly in code.
1302 protected function rollback_transaction() {
1303 if (!$this->transactions_supported()) {
1308 $this->query_start($sql, NULL, SQL_QUERY_AUX);
1309 $result = $this->mysqli->query($sql);
1310 $this->query_end($result);