MDL-23925, MDL-23888 new sql_ilike() and sql_binary_equal() - this should finally...
[moodle.git] / lib / dml / mysqli_native_moodle_database.php
CommitLineData
49926145 1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
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.
9//
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.
14//
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/>.
17
18
19/**
20 * Native mysqli class representing moodle database interface.
21 *
66c0ee78 22 * @package core
f2ed3f05 23 * @subpackage dml
49926145 24 * @copyright 2008 Petr Skoda (http://skodak.org)
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 */
7466a42f 27
f2ed3f05
PS
28defined('MOODLE_INTERNAL') || die();
29
7466a42f 30require_once($CFG->libdir.'/dml/moodle_database.php');
31require_once($CFG->libdir.'/dml/mysqli_native_moodle_recordset.php');
3f33c9e2 32require_once($CFG->libdir.'/dml/mysqli_native_moodle_temptables.php');
7466a42f 33
34/**
35 * Native mysqli class representing moodle database interface.
7466a42f 36 */
37class mysqli_native_moodle_database extends moodle_database {
38
0487f9e2 39 protected $mysqli = null;
7466a42f 40
d5a8d9aa
PS
41 private $transactions_supported = null;
42
30d2832d 43 /**
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
51 */
3b093310 52 public function create_database($dbhost, $dbuser, $dbpass, $dbname, array $dboptions=null) {
797ffad0 53 $driverstatus = $this->driver_installed();
54
55 if ($driverstatus !== true) {
56 throw new dml_exception('dbdriverproblem', $driverstatus);
57 }
58
30d2832d 59 ob_start();
7f79aaea 60 $conn = new mysqli($dbhost, $dbuser, $dbpass); /// Connect without db
30d2832d 61 $dberr = ob_get_contents();
62 ob_end_clean();
63 $errorno = @$conn->connect_errno;
64
65 if ($errorno !== 0) {
66 throw new dml_connection_exception($dberr);
67 }
68
69 $result = $conn->query("CREATE DATABASE $dbname DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci");
70
71 $conn->close();
72
73 if (!$result) {
74 throw new dml_exception('cannotcreatedb');
75 }
76
77 return true;
78 }
79
7466a42f 80 /**
81 * Detects if all needed PHP stuff installed.
82 * Note: can be used before connect()
83 * @return mixed true if ok, string if something
84 */
85 public function driver_installed() {
86 if (!extension_loaded('mysqli')) {
87 return get_string('mysqliextensionisnotpresentinphp', 'install');
88 }
89 return true;
90 }
91
92 /**
93 * Returns database family type - describes SQL dialect
94 * Note: can be used before connect()
95 * @return string db family name (mysql, postgres, mssql, oracle, etc.)
96 */
97 public function get_dbfamily() {
98 return 'mysql';
99 }
100
101 /**
102 * Returns more specific database driver type
103 * Note: can be used before connect()
4a6c2ab8 104 * @return string db type mysqli, pgsql, oci, mssql, sqlsrv
7466a42f 105 */
106 protected function get_dbtype() {
107 return 'mysqli';
108 }
109
110 /**
111 * Returns general database library name
112 * Note: can be used before connect()
eb123deb 113 * @return string db type pdo, native
7466a42f 114 */
115 protected function get_dblibrary() {
116 return 'native';
117 }
118
d35ece6c
PS
119 /**
120 * Returns the current MySQL db engine.
121 *
122 * This is an ugly workaround for MySQL default engine problems,
123 * Moodle is designed to work best on ACID compliant databases
124 * with full transaction support. Do not use MyISAM.
125 *
126 * @return string or null MySQL engine name
127 */
128 public function get_dbengine() {
129 if (isset($this->dboptions['dbengine'])) {
130 return $this->dboptions['dbengine'];
131 }
132
133 $engine = null;
134
135 if (!$this->external) {
136 // look for current engine of our config table (the first table that gets created),
137 // so that we create all tables with the same engine
138 $sql = "SELECT engine FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = DATABASE() AND table_name = '{$this->prefix}config'";
139 $this->query_start($sql, NULL, SQL_QUERY_AUX);
140 $result = $this->mysqli->query($sql);
141 $this->query_end($result);
142 if ($rec = $result->fetch_assoc()) {
143 $engine = $rec['engine'];
144 }
145 $result->close();
146 }
147
148 if ($engine) {
149 return $engine;
150 }
151
152 // get the default database engine
153 $sql = "SELECT @@storage_engine";
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['@@storage_engine'];
159 }
160 $result->close();
161
162 if (!$this->external and $engine === 'MyISAM') {
163 // we really do not want MyISAM for Moodle, InnoDB or XtraDB is a reasonable defaults if supported
164 $sql = "SHOW STORAGE ENGINES";
165 $this->query_start($sql, NULL, SQL_QUERY_AUX);
166 $result = $this->mysqli->query($sql);
167 $this->query_end($result);
ed22700d 168 $engines = array();
d35ece6c 169 while ($res = $result->fetch_assoc()) {
ed22700d
PS
170 if ($res['Support'] === 'YES' or $res['Support'] === 'DEFAULT') {
171 $engines[$res['Engine']] = true;
d35ece6c
PS
172 }
173 }
174 $result->close();
ed22700d
PS
175 if (isset($engines['InnoDB'])) {
176 $engine = 'InnoDB';
177 }
178 if (isset($engines['XtraDB'])) {
179 $engine = 'XtraDB';
180 }
d35ece6c
PS
181 }
182
183 return $engine;
184 }
185
7466a42f 186 /**
187 * Returns localised database type name
188 * Note: can be used before connect()
189 * @return string
190 */
191 public function get_name() {
2aeb3bcb 192 return get_string('nativemysqli', 'install');
7466a42f 193 }
194
3b093310 195 /**
196 * Returns localised database configuration help.
197 * Note: can be used before connect()
198 * @return string
199 */
200 public function get_configuration_help() {
201 return get_string('nativemysqlihelp', 'install');
202 }
203
7466a42f 204 /**
205 * Returns localised database description
206 * Note: can be used before connect()
207 * @return string
208 */
209 public function get_configuration_hints() {
2aeb3bcb 210 return get_string('databasesettingssub_mysqli', 'install');
7466a42f 211 }
212
d35ece6c
PS
213 /**
214 * Diagnose database and tables, this function is used
215 * to verify database and driver settings, db engine types, etc.
216 *
217 * @return string null means everything ok, string means problem found.
218 */
219 public function diagnose() {
220 $sloppymyisamfound = false;
221 $prefix = str_replace('_', '\\_', $this->prefix);
222 $sql = "SHOW TABLE STATUS WHERE Name LIKE BINARY '$prefix%'";
223 $this->query_start($sql, null, SQL_QUERY_AUX);
224 $result = $this->mysqli->query($sql);
225 $this->query_end($result);
226 if ($result) {
227 while ($arr = $result->fetch_assoc()) {
228 if ($arr['Engine'] === 'MyISAM') {
229 $sloppymyisamfound = true;
230 break;
231 }
232 }
233 $result->close();
234 }
235
236 if ($sloppymyisamfound) {
237 return get_string('myisamproblem', 'error');
238 } else {
239 return null;
240 }
241 }
242
7466a42f 243 /**
244 * Connect to db
245 * Must be called before other methods.
246 * @param string $dbhost
247 * @param string $dbuser
248 * @param string $dbpass
249 * @param string $dbname
7466a42f 250 * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
251 * @param array $dboptions driver specific options
252 * @return bool success
253 */
beaa43db 254 public function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null) {
ce152606 255 $driverstatus = $this->driver_installed();
256
257 if ($driverstatus !== true) {
258 throw new dml_exception('dbdriverproblem', $driverstatus);
259 }
260
beaa43db 261 $this->store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions);
3b093310 262 unset($this->dboptions['dbsocket']);
7466a42f 263
ce152606 264 ob_start();
7466a42f 265 $this->mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
ce152606 266 $dberr = ob_get_contents();
267 ob_end_clean();
268 $errorno = @$this->mysqli->connect_errno;
269
270 if ($errorno !== 0) {
271 throw new dml_connection_exception($dberr);
7466a42f 272 }
ce152606 273
a6283e91 274 $this->query_start("--set_charset()", null, SQL_QUERY_AUX);
7466a42f 275 $this->mysqli->set_charset('utf8');
a6283e91 276 $this->query_end(true);
277
77abbc47 278 // If available, enforce strict mode for the session. That guaranties
279 // standard behaviour under some situations, avoiding some MySQL nasty
280 // habits like truncating data or performing some transparent cast losses.
02df9cfd 281 // With strict mode enforced, Moodle DB layer will be consistently throwing
77abbc47 282 // the corresponding exceptions as expected.
283 $si = $this->get_server_info();
284 if (version_compare($si['version'], '5.0.2', '>=')) {
285 $sql = "SET SESSION sql_mode = 'STRICT_ALL_TABLES'";
286 $this->query_start($sql, null, SQL_QUERY_AUX);
287 $result = $this->mysqli->query($sql);
288 $this->query_end($result);
289 }
290
3f33c9e2 291 // Connection stabilished and configured, going to instantiate the temptables controller
292 $this->temptables = new mysqli_native_moodle_temptables($this);
293
7466a42f 294 return true;
295 }
296
297 /**
298 * Close database connection and release all resources
299 * and memory (especially circular memory references).
300 * Do NOT use connect() again, create a new instance if needed.
301 */
302 public function dispose() {
02df9cfd 303 parent::dispose(); // Call parent dispose to write/close session and other common stuff before closing connection
7466a42f 304 if ($this->mysqli) {
305 $this->mysqli->close();
306 $this->mysqli = null;
307 }
7466a42f 308 }
309
310 /**
311 * Returns database server info array
312 * @return array
313 */
314 public function get_server_info() {
315 return array('description'=>$this->mysqli->server_info, 'version'=>$this->mysqli->server_info);
316 }
317
318 /**
319 * Returns supported query parameter types
9331d879 320 * @return int bitmask
7466a42f 321 */
322 protected function allowed_param_types() {
323 return SQL_PARAMS_QM;
324 }
325
326 /**
327 * Returns last error reported by database engine.
9331d879 328 * @return string error message
7466a42f 329 */
330 public function get_last_error() {
331 return $this->mysqli->error;
332 }
333
334 /**
335 * Return tables in database WITHOUT current prefix
336 * @return array of table names in lowercase and without prefix
337 */
117679db 338 public function get_tables($usecache=true) {
339 if ($usecache and $this->tables !== null) {
340 return $this->tables;
341 }
342 $this->tables = array();
a6283e91 343 $sql = "SHOW TABLES";
344 $this->query_start($sql, null, SQL_QUERY_AUX);
345 $result = $this->mysqli->query($sql);
346 $this->query_end($result);
347 if ($result) {
7466a42f 348 while ($arr = $result->fetch_assoc()) {
349 $tablename = reset($arr);
7fdcb779 350 if ($this->prefix !== '') {
351 if (strpos($tablename, $this->prefix) !== 0) {
352 continue;
353 }
354 $tablename = substr($tablename, strlen($this->prefix));
7466a42f 355 }
117679db 356 $this->tables[$tablename] = $tablename;
7466a42f 357 }
358 $result->close();
359 }
3f33c9e2 360
361 // Add the currently available temptables
362 $this->tables = array_merge($this->tables, $this->temptables->get_temptables());
117679db 363 return $this->tables;
7466a42f 364 }
365
366 /**
367 * Return table indexes - everything lowercased
368 * @return array of arrays
369 */
370 public function get_indexes($table) {
7466a42f 371 $indexes = array();
a6283e91 372 $sql = "SHOW INDEXES FROM {$this->prefix}$table";
373 $this->query_start($sql, null, SQL_QUERY_AUX);
374 $result = $this->mysqli->query($sql);
375 $this->query_end($result);
376 if ($result) {
7466a42f 377 while ($res = $result->fetch_object()) {
378 if ($res->Key_name === 'PRIMARY') {
379 continue;
380 }
381 if (!isset($indexes[$res->Key_name])) {
382 $indexes[$res->Key_name] = array('unique'=>empty($res->Non_unique), 'columns'=>array());
383 }
384 $indexes[$res->Key_name]['columns'][$res->Seq_in_index-1] = $res->Column_name;
385 }
386 $result->close();
387 }
388 return $indexes;
389 }
390
391 /**
02df9cfd 392 * Returns detailed information about columns in table. This information is cached internally.
7466a42f 393 * @param string $table name
394 * @param bool $usecache
395 * @return array array of database_column_info objects indexed with column names
396 */
397 public function get_columns($table, $usecache=true) {
398 if ($usecache and isset($this->columns[$table])) {
399 return $this->columns[$table];
400 }
401
402 $this->columns[$table] = array();
403
a6283e91 404 $sql = "SHOW COLUMNS FROM {$this->prefix}$table";
405 $this->query_start($sql, null, SQL_QUERY_AUX);
406 $result = $this->mysqli->query($sql);
407 $this->query_end($result);
408
409 if ($result === false) {
7466a42f 410 return array();
411 }
412
a6283e91 413 while ($rawcolumn = $result->fetch_assoc()) {
414 $rawcolumn = (object)array_change_key_case($rawcolumn, CASE_LOWER);
415
7466a42f 416 $info = new object();
417 $info->name = $rawcolumn->field;
418 $matches = null;
419
420 if (preg_match('/varchar\((\d+)\)/i', $rawcolumn->type, $matches)) {
421 $info->type = 'varchar';
422 $info->meta_type = 'C';
423 $info->max_length = $matches[1];
424 $info->scale = null;
425 $info->not_null = ($rawcolumn->null === 'NO');
426 $info->default_value = $rawcolumn->default;
427 $info->has_default = is_null($info->default_value) ? false : true;
428 $info->primary_key = ($rawcolumn->key === 'PRI');
429 $info->binary = false;
430 $info->unsigned = null;
431 $info->auto_increment= false;
432 $info->unique = null;
433
434 } else if (preg_match('/([a-z]*int[a-z]*)\((\d+)\)/i', $rawcolumn->type, $matches)) {
435 $info->type = $matches[1];
436 $info->primary_key = ($rawcolumn->key === 'PRI');
437 if ($info->primary_key) {
438 $info->meta_type = 'R';
439 $info->max_length = $matches[2];
440 $info->scale = null;
441 $info->not_null = ($rawcolumn->null === 'NO');
442 $info->default_value = $rawcolumn->default;
443 $info->has_default = is_null($info->default_value) ? false : true;
444 $info->binary = false;
445 $info->unsigned = (stripos($rawcolumn->type, 'unsigned') !== false);
446 $info->auto_increment= true;
447 $info->unique = true;
448 } else {
449 $info->meta_type = 'I';
450 $info->max_length = $matches[2];
451 $info->scale = null;
452 $info->not_null = ($rawcolumn->null === 'NO');
453 $info->default_value = $rawcolumn->default;
454 $info->has_default = is_null($info->default_value) ? false : true;
455 $info->binary = false;
456 $info->unsigned = (stripos($rawcolumn->type, 'unsigned') !== false);
457 $info->auto_increment= false;
458 $info->unique = null;
459 }
460
c65845cc 461 } else if (preg_match('/(decimal|double|float)\((\d+),(\d+)\)/i', $rawcolumn->type, $matches)) {
462 $info->type = $matches[1];
7466a42f 463 $info->meta_type = 'N';
c65845cc 464 $info->max_length = $matches[2];
465 $info->scale = $matches[3];
7466a42f 466 $info->not_null = ($rawcolumn->null === 'NO');
467 $info->default_value = $rawcolumn->default;
468 $info->has_default = is_null($info->default_value) ? false : true;
469 $info->primary_key = ($rawcolumn->key === 'PRI');
470 $info->binary = false;
471 $info->unsigned = null;
472 $info->auto_increment= false;
473 $info->unique = null;
474
475 } else if (preg_match('/([a-z]*text)/i', $rawcolumn->type, $matches)) {
476 $info->type = $matches[1];
477 $info->meta_type = 'X';
478 $info->max_length = -1;
479 $info->scale = null;
480 $info->not_null = ($rawcolumn->null === 'NO');
481 $info->default_value = $rawcolumn->default;
482 $info->has_default = is_null($info->default_value) ? false : true;
483 $info->primary_key = ($rawcolumn->key === 'PRI');
484 $info->binary = false;
485 $info->unsigned = null;
486 $info->auto_increment= false;
487 $info->unique = null;
488
75dfa4a3 489 } else if (preg_match('/([a-z]*blob)/i', $rawcolumn->type, $matches)) {
490 $info->type = $matches[1];
491 $info->meta_type = 'B';
492 $info->max_length = -1;
493 $info->scale = null;
494 $info->not_null = ($rawcolumn->null === 'NO');
495 $info->default_value = $rawcolumn->default;
496 $info->has_default = is_null($info->default_value) ? false : true;
497 $info->primary_key = false;
498 $info->binary = true;
499 $info->unsigned = null;
500 $info->auto_increment= false;
501 $info->unique = null;
502
7466a42f 503 } else if (preg_match('/enum\((.*)\)/i', $rawcolumn->type, $matches)) {
504 $info->type = 'enum';
505 $info->meta_type = 'C';
506 $info->enums = array();
507 $info->max_length = 0;
508 $values = $matches[1];
509 $values = explode(',', $values);
510 $textlib = textlib_get_instance();
511 foreach ($values as $val) {
512 $val = trim($val, "'");
513 $length = $textlib->strlen($val);
514 $info->enums[] = $val;
515 $info->max_length = ($info->max_length < $length) ? $length : $info->max_length;
516 }
517 $info->scale = null;
518 $info->not_null = ($rawcolumn->null === 'NO');
519 $info->default_value = $rawcolumn->default;
520 $info->has_default = is_null($info->default_value) ? false : true;
521 $info->primary_key = ($rawcolumn->key === 'PRI');
522 $info->binary = false;
523 $info->unsigned = null;
524 $info->auto_increment= false;
525 $info->unique = null;
526 }
527
528 $this->columns[$table][$info->name] = new database_column_info($info);
529 }
530
a6283e91 531 $result->close();
532
7466a42f 533 return $this->columns[$table];
534 }
535
8fb501e9
EL
536 /**
537 * Normalise values based in RDBMS dependencies (booleans, LOBs...)
538 *
539 * @param database_column_info $column column metadata corresponding with the value we are going to normalise
540 * @param mixed $value value we are going to normalise
541 * @return mixed the normalised value
542 */
e3acc8af 543 protected function normalise_value($column, $value) {
8fb501e9
EL
544 if (is_bool($value)) { // Always, convert boolean to int
545 $value = (int)$value;
546
547 } else if ($value === '') {
548 if ($column->meta_type == 'I' or $column->meta_type == 'F' or $column->meta_type == 'N') {
549 $value = 0; // prevent '' problems in numeric fields
550 }
551 }
552 // workaround for problem with wrong enums in mysql - TODO: Out in Moodle 2.1
553 if (!empty($column->enums)) {
554 if (is_null($value) and !$column->not_null) {
555 // ok - nulls allowed
556 } else {
557 if (!in_array((string)$value, $column->enums)) {
558 throw new dml_write_exception('Enum value '.s($value).' not allowed in field '.$field.' table '.$table.'.');
559 }
560 }
561 }
562 return $value;
563 }
564
7466a42f 565 /**
566 * Is db in unicode mode?
567 * @return bool
568 */
569 public function setup_is_unicodedb() {
a6283e91 570 $sql = "SHOW LOCAL VARIABLES LIKE 'character_set_database'";
571 $this->query_start($sql, null, SQL_QUERY_AUX);
572 $result = $this->mysqli->query($sql);
573 $this->query_end($result);
574
575 if ($result) {
7466a42f 576 $result->close();
577 return true;
578 }
579 return false;
580 }
581
7466a42f 582 /**
583 * Do NOT use in code, to be used by database_manager only!
584 * @param string $sql query
22d77567 585 * @return bool true
586 * @throws dml_exception if error
7466a42f 587 */
588 public function change_database_structure($sql) {
117679db 589 $this->reset_caches();
a6283e91 590
591 $this->query_start($sql, null, SQL_QUERY_STRUCTURE);
592 $result = $this->mysqli->query($sql);
593 $this->query_end($result);
594
12e09c6b 595 return true;
7466a42f 596 }
597
598 /**
599 * Very ugly hack which emulates bound parameters in queries
600 * because prepared statements do not use query cache.
601 */
602 protected function emulate_bound_params($sql, array $params=null) {
603 if (empty($params)) {
604 return $sql;
605 }
606 /// ok, we have verified sql statement with ? and correct number of params
607 $return = strtok($sql, '?');
608 foreach ($params as $param) {
609 if (is_bool($param)) {
610 $return .= (int)$param;
611 } else if (is_null($param)) {
612 $return .= 'NULL';
c1a6529b 613 } else if (is_number($param)) { // we can not use is_numeric() because it eats leading zeros from strings like 0045646
614 $return .= $param;
615 } else if (is_float($param)) {
7466a42f 616 $return .= $param;
617 } else {
618 $param = $this->mysqli->real_escape_string($param);
619 $return .= "'$param'";
620 }
621 $return .= strtok('?');
622 }
623 return $return;
624 }
625
626 /**
627 * Execute general sql query. Should be used only when no other method suitable.
628 * Do NOT use this to make changes in db structure, use database_manager::execute_sql() instead!
629 * @param string $sql query
630 * @param array $params query parameters
22d77567 631 * @return bool true
632 * @throws dml_exception if error
7466a42f 633 */
634 public function execute($sql, array $params=null) {
635 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
636
637 if (strpos($sql, ';') !== false) {
22d77567 638 throw new coding_exception('moodle_database::execute() Multiple sql statements found or bound parameters not used properly in query!');
7466a42f 639 }
640
641 $rawsql = $this->emulate_bound_params($sql, $params);
642
a6283e91 643 $this->query_start($sql, $params, SQL_QUERY_UPDATE);
7466a42f 644 $result = $this->mysqli->query($rawsql);
a6283e91 645 $this->query_end($result);
7466a42f 646
22d77567 647 if ($result === true) {
7466a42f 648 return true;
649
650 } else {
651 $result->close();
652 return true;
653 }
654 }
655
656 /**
657 * Get a number of records as a moodle_recordset using a SQL statement.
658 *
659 * Since this method is a little less readable, use of it should be restricted to
660 * code where it's possible there might be large datasets being returned. For known
661 * small datasets use get_records_sql - it leads to simpler code.
662 *
663 * The return type is as for @see function get_recordset.
664 *
665 * @param string $sql the SQL select query to execute.
666 * @param array $params array of sql parameters
667 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
668 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
5212b07f 669 * @return moodle_recordset instance
22d77567 670 * @throws dml_exception if error
7466a42f 671 */
672 public function get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
088a4df8 673 $limitfrom = (int)$limitfrom;
674 $limitnum = (int)$limitnum;
3ff8bf26 675 $limitfrom = ($limitfrom < 0) ? 0 : $limitfrom;
676 $limitnum = ($limitnum < 0) ? 0 : $limitnum;
677
7466a42f 678 if ($limitfrom or $limitnum) {
7466a42f 679 if ($limitnum < 1) {
680 $limitnum = "18446744073709551615";
681 }
0487f9e2 682 $sql .= " LIMIT $limitfrom, $limitnum";
7466a42f 683 }
684
0487f9e2 685 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
686 $rawsql = $this->emulate_bound_params($sql, $params);
687
a6283e91 688 $this->query_start($sql, $params, SQL_QUERY_SELECT);
7466a42f 689 // no MYSQLI_USE_RESULT here, it would block write ops on affected tables
e0eda209 690 $result = $this->mysqli->query($rawsql, MYSQLI_STORE_RESULT);
691 $this->query_end($result);
7466a42f 692
e0eda209 693 return $this->create_recordset($result);
7466a42f 694 }
695
696 protected function create_recordset($result) {
697 return new mysqli_native_moodle_recordset($result);
698 }
699
700 /**
701 * Get a number of records as an array of objects using a SQL statement.
702 *
703 * Return value as for @see function get_records.
704 *
705 * @param string $sql the SQL select query to execute. The first column of this SELECT statement
706 * must be a unique value (usually the 'id' field), as it will be used as the key of the
707 * returned array.
708 * @param array $params array of sql parameters
709 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
710 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
3503dcad 711 * @return array of objects, or empty array if no records were found
22d77567 712 * @throws dml_exception if error
7466a42f 713 */
714 public function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
088a4df8 715 $limitfrom = (int)$limitfrom;
716 $limitnum = (int)$limitnum;
3ff8bf26 717 $limitfrom = ($limitfrom < 0) ? 0 : $limitfrom;
718 $limitnum = ($limitnum < 0) ? 0 : $limitnum;
719
7466a42f 720 if ($limitfrom or $limitnum) {
7466a42f 721 if ($limitnum < 1) {
722 $limitnum = "18446744073709551615";
723 }
0487f9e2 724 $sql .= " LIMIT $limitfrom, $limitnum";
7466a42f 725 }
726
0487f9e2 727 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
728 $rawsql = $this->emulate_bound_params($sql, $params);
729
a6283e91 730 $this->query_start($sql, $params, SQL_QUERY_SELECT);
7466a42f 731 $result = $this->mysqli->query($rawsql, MYSQLI_STORE_RESULT);
a6283e91 732 $this->query_end($result);
7466a42f 733
7466a42f 734 $return = array();
a6283e91 735
7466a42f 736 while($row = $result->fetch_assoc()) {
737 $row = array_change_key_case($row, CASE_LOWER);
738 $id = reset($row);
758ba89a 739 if (isset($return[$id])) {
740 $colname = key($row);
741 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);
742 }
7466a42f 743 $return[$id] = (object)$row;
744 }
745 $result->close();
a6283e91 746
7466a42f 747 return $return;
748 }
749
750 /**
751 * Selects records and return values (first field) as an array using a SQL statement.
752 *
753 * @param string $sql The SQL query
754 * @param array $params array of sql parameters
3503dcad 755 * @return array of values
22d77567 756 * @throws dml_exception if error
7466a42f 757 */
758 public function get_fieldset_sql($sql, array $params=null) {
759 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
760 $rawsql = $this->emulate_bound_params($sql, $params);
761
a6283e91 762 $this->query_start($sql, $params, SQL_QUERY_SELECT);
7466a42f 763 $result = $this->mysqli->query($rawsql, MYSQLI_STORE_RESULT);
a6283e91 764 $this->query_end($result);
7466a42f 765
7466a42f 766 $return = array();
a6283e91 767
7466a42f 768 while($row = $result->fetch_assoc()) {
769 $return[] = reset($row);
770 }
771 $result->close();
a6283e91 772
7466a42f 773 return $return;
774 }
775
776 /**
777 * Insert new record into database, as fast as possible, no safety checks, lobs not supported.
778 * @param string $table name
779 * @param mixed $params data record as object or array
780 * @param bool $returnit return it of inserted record
781 * @param bool $bulk true means repeated inserts expected
782 * @param bool $customsequence true if 'id' included in $params, disables $returnid
3503dcad 783 * @return bool|int true or new id
22d77567 784 * @throws dml_exception if error
7466a42f 785 */
786 public function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false) {
787 if (!is_array($params)) {
788 $params = (array)$params;
789 }
790
791 if ($customsequence) {
792 if (!isset($params['id'])) {
22d77567 793 throw new coding_exception('moodle_database::insert_record_raw() id field must be specified if custom sequences used.');
7466a42f 794 }
795 $returnid = false;
796 } else {
797 unset($params['id']);
798 }
799
800 if (empty($params)) {
22d77567 801 throw new coding_exception('moodle_database::insert_record_raw() no fields found.');
7466a42f 802 }
803
7466a42f 804 $fields = implode(',', array_keys($params));
805 $qms = array_fill(0, count($params), '?');
806 $qms = implode(',', $qms);
807
808 $sql = "INSERT INTO {$this->prefix}$table ($fields) VALUES($qms)";
76b6daf2 809
810 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
7466a42f 811 $rawsql = $this->emulate_bound_params($sql, $params);
812
a6283e91 813 $this->query_start($sql, $params, SQL_QUERY_INSERT);
7466a42f 814 $result = $this->mysqli->query($rawsql);
b4154c2d 815 $id = @$this->mysqli->insert_id; // must be called before query_end() which may insert log into db
a6283e91 816 $this->query_end($result);
7466a42f 817
b4154c2d 818 if (!$id) {
22d77567 819 throw new dml_write_exception('unknown error fetching inserted id');
7466a42f 820 }
821
822 if (!$returnid) {
823 return true;
824 } else {
825 return (int)$id;
826 }
827 }
828
829 /**
830 * Insert a record into a table and return the "id" field if required.
831 *
832 * Some conversions and safety checks are carried out. Lobs are supported.
833 * If the return ID isn't required, then this just reports success as true/false.
834 * $data is an object containing needed data
835 * @param string $table The database table to be inserted into
836 * @param object $data A data object with values for one or more fields in the record
837 * @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.
3503dcad 838 * @return bool|int true or new id
22d77567 839 * @throws dml_exception if error
7466a42f 840 */
841 public function insert_record($table, $dataobject, $returnid=true, $bulk=false) {
d8fa8e40 842 $dataobject = (array)$dataobject;
7466a42f 843
844 $columns = $this->get_columns($table);
7466a42f 845 $cleaned = array();
846
847 foreach ($dataobject as $field=>$value) {
d8fa8e40
PS
848 if ($field === 'id') {
849 continue;
850 }
7466a42f 851 if (!isset($columns[$field])) {
852 continue;
853 }
854 $column = $columns[$field];
8fb501e9 855 $cleaned[$field] = $this->normalise_value($column, $value);
7466a42f 856 }
857
7466a42f 858 return $this->insert_record_raw($table, $cleaned, $returnid, $bulk);
859 }
860
861 /**
862 * Import a record into a table, id field is required.
863 * Safety checks are NOT carried out. Lobs are supported.
864 *
865 * @param string $table name of database table to be inserted into
866 * @param object $dataobject A data object with values for one or more fields in the record
22d77567 867 * @return bool true
868 * @throws dml_exception if error
7466a42f 869 */
870 public function import_record($table, $dataobject) {
d8fa8e40 871 $dataobject = (array)$dataobject;
7466a42f 872
7466a42f 873 $columns = $this->get_columns($table);
874 $cleaned = array();
875
876 foreach ($dataobject as $field=>$value) {
877 if (!isset($columns[$field])) {
878 continue;
879 }
880 $cleaned[$field] = $value;
881 }
882
883 return $this->insert_record_raw($table, $cleaned, false, true, true);
884 }
885
886 /**
887 * Update record in database, as fast as possible, no safety checks, lobs not supported.
888 * @param string $table name
889 * @param mixed $params data record as object or array
890 * @param bool true means repeated updates expected
22d77567 891 * @return bool true
892 * @throws dml_exception if error
7466a42f 893 */
894 public function update_record_raw($table, $params, $bulk=false) {
d8fa8e40
PS
895 $params = (array)$params;
896
7466a42f 897 if (!isset($params['id'])) {
22d77567 898 throw new coding_exception('moodle_database::update_record_raw() id field must be specified.');
7466a42f 899 }
900 $id = $params['id'];
901 unset($params['id']);
902
903 if (empty($params)) {
22d77567 904 throw new coding_exception('moodle_database::update_record_raw() no fields found.');
7466a42f 905 }
906
7466a42f 907 $sets = array();
908 foreach ($params as $field=>$value) {
909 $sets[] = "$field = ?";
910 }
911
912 $params[] = $id; // last ? in WHERE condition
913
914 $sets = implode(',', $sets);
915 $sql = "UPDATE {$this->prefix}$table SET $sets WHERE id=?";
76b6daf2 916
917 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
7466a42f 918 $rawsql = $this->emulate_bound_params($sql, $params);
919
a6283e91 920 $this->query_start($sql, $params, SQL_QUERY_UPDATE);
7466a42f 921 $result = $this->mysqli->query($rawsql);
a6283e91 922 $this->query_end($result);
7466a42f 923
7466a42f 924 return true;
925 }
926
927 /**
928 * Update a record in a table
929 *
930 * $dataobject is an object containing needed data
931 * Relies on $dataobject having a variable "id" to
932 * specify the record to update
933 *
934 * @param string $table The database table to be checked against.
935 * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
936 * @param bool true means repeated updates expected
22d77567 937 * @return bool true
938 * @throws dml_exception if error
7466a42f 939 */
940 public function update_record($table, $dataobject, $bulk=false) {
d8fa8e40 941 $dataobject = (array)$dataobject;
7466a42f 942
7466a42f 943 $columns = $this->get_columns($table);
944 $cleaned = array();
945
946 foreach ($dataobject as $field=>$value) {
947 if (!isset($columns[$field])) {
948 continue;
949 }
8fb501e9
EL
950 $column = $columns[$field];
951 $cleaned[$field] = $this->normalise_value($column, $value);
7466a42f 952 }
953
954 return $this->update_record_raw($table, $cleaned, $bulk);
955 }
956
957 /**
958 * Set a single field in every table record which match a particular WHERE clause.
959 *
960 * @param string $table The database table to be checked against.
961 * @param string $newfield the field to set.
962 * @param string $newvalue the value to set the field to.
963 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
964 * @param array $params array of sql parameters
22d77567 965 * @return bool true
966 * @throws dml_exception if error
7466a42f 967 */
968 public function set_field_select($table, $newfield, $newvalue, $select, array $params=null) {
969 if ($select) {
970 $select = "WHERE $select";
971 }
972 if (is_null($params)) {
973 $params = array();
974 }
975 list($select, $params, $type) = $this->fix_sql_params($select, $params);
976
8fb501e9
EL
977 // Get column metadata
978 $columns = $this->get_columns($table);
979 $column = $columns[$newfield];
980
981 $normalised_value = $this->normalise_value($column, $newvalue);
982
983 if (is_null($normalised_value)) {
7466a42f 984 $newfield = "$newfield = NULL";
985 } else {
986 $newfield = "$newfield = ?";
8fb501e9 987 array_unshift($params, $normalised_value);
7466a42f 988 }
989 $sql = "UPDATE {$this->prefix}$table SET $newfield $select";
990 $rawsql = $this->emulate_bound_params($sql, $params);
991
a6283e91 992 $this->query_start($sql, $params, SQL_QUERY_UPDATE);
7466a42f 993 $result = $this->mysqli->query($rawsql);
a6283e91 994 $this->query_end($result);
7466a42f 995
7466a42f 996 return true;
997 }
998
999 /**
1000 * Delete one or more records from a table which match a particular WHERE clause.
1001 *
1002 * @param string $table The database table to be checked against.
1003 * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
1004 * @param array $params array of sql parameters
22d77567 1005 * @return bool true
1006 * @throws dml_exception if error
7466a42f 1007 */
1008 public function delete_records_select($table, $select, array $params=null) {
1009 if ($select) {
1010 $select = "WHERE $select";
1011 }
1012 $sql = "DELETE FROM {$this->prefix}$table $select";
1013
1014 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
1015 $rawsql = $this->emulate_bound_params($sql, $params);
1016
a6283e91 1017 $this->query_start($sql, $params, SQL_QUERY_UPDATE);
7466a42f 1018 $result = $this->mysqli->query($rawsql);
a6283e91 1019 $this->query_end($result);
7466a42f 1020
7466a42f 1021 return true;
1022 }
1023
1024 public function sql_cast_char2int($fieldname, $text=false) {
1025 return ' CAST(' . $fieldname . ' AS SIGNED) ';
1026 }
1027
6055f89d
PS
1028
1029 /**
1030 * Case and collation sensitive string 'string = string'
1031 * @param string $string1
1032 * @param string $string2
1033 * @return string SQL fragment
1034 */
1035 public function sql_binary_equal($string1, $string2) {
1036 return "BINARY $string1 = $string2";
1037 }
1038
1039 /**
1040 * Returns 'LIKE' part of a query.
1041 *
1042 * @param string $fieldname usually name of the table column
1043 * @param string $param usually bound query parameter (?, :named)
1044 * @param bool $casesensitive use case sensitive search
1045 * @param bool $accensensitive use accent sensitive search (not all databases support accent insensitive)
1046 * @param string $escapechar escape char for '%' and '_'
1047 * @return string SQL code fragment
1048 */
1049 public function sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $escapechar = '\\') {
1050 if (strpos($param, '%') !== false) {
1051 debugging('Potential SQL injection detected, sql_ilike() expects bound parameters (? or :named)');
1052 }
1053 $escapechar = $this->mysqli->real_escape_string($escapechar); // prevents problems with C-style escapes of enclosing '\'
1054
1055 if ($casesensitive) {
1056 return "$fieldname LIKE $param COLLATE utf8_bin ESCAPE '$escapechar'";
1057 } else {
1058 if ($accentsensitive) {
1059 return "LOWER($fieldname) LIKE LOWER($param) COLLATE utf8_bin ESCAPE '$escapechar'";
1060 } else {
1061 return "$fieldname LIKE $param ESCAPE '$escapechar'";
1062 }
1063 }
1064 }
1065
7466a42f 1066 public function sql_concat() {
1067 $arr = func_get_args();
082ae821 1068 $s = implode(', ', $arr);
7466a42f 1069 if ($s === '') {
d5d0890c 1070 return "''";
7466a42f 1071 }
1072 return "CONCAT($s)";
1073 }
1074
1075 public function sql_concat_join($separator="' '", $elements=array()) {
082ae821 1076 $s = implode(', ', $elements);
1077
7466a42f 1078 if ($s === '') {
d5d0890c 1079 return "''";
7466a42f 1080 }
082ae821 1081 return "CONCAT_WS($separator, $s)";
7466a42f 1082 }
1083
7e0db2e2 1084 /**
1085 * Returns the SQL text to be used to calculate the length in characters of one expression.
1086 * @param string fieldname or expression to calculate its length in characters.
1087 * @return string the piece of SQL code to be used in the statement.
1088 */
1089 public function sql_length($fieldname) {
1090 return ' CHAR_LENGTH(' . $fieldname . ')';
1091 }
1092
7466a42f 1093 /**
02df9cfd 1094 * Does this driver support regex syntax when searching
7466a42f 1095 */
1096 public function sql_regex_supported() {
1097 return true;
1098 }
1099
1100 /**
1101 * Return regex positive or negative match sql
1102 * @param bool $positivematch
1103 * @return string or empty if not supported
1104 */
1105 public function sql_regex($positivematch=true) {
1106 return $positivematch ? 'REGEXP' : 'NOT REGEXP';
1107 }
fa76662b 1108
adff97c5 1109 public function sql_cast_2signed($fieldname) {
1110 return ' CAST(' . $fieldname . ' AS SIGNED) ';
1111 }
1112
7f79aaea 1113/// session locking
5e9dd017 1114 public function session_lock_supported() {
1115 return true;
1116 }
1117
3b1a9849 1118 public function get_session_lock($rowid) {
5e9dd017 1119 parent::get_session_lock($rowid);
3b1a9849 1120 $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid;
1121 $sql = "SELECT GET_LOCK('$fullname',120)";
1122 $this->query_start($sql, null, SQL_QUERY_AUX);
1123 $result = $this->mysqli->query($sql);
7f79aaea 1124 $this->query_end($result);
1125
1126 if ($result) {
1127 $arr = $result->fetch_assoc();
1128 $result->close();
1129
1130 if (reset($arr) == 1) {
5e9dd017 1131 return;
3b1a9849 1132 } else {
1133 // try again!
5e9dd017 1134 $this->get_session_lock($rowid);
7f79aaea 1135 }
1136 }
7f79aaea 1137 }
1138
3b1a9849 1139 public function release_session_lock($rowid) {
5e9dd017 1140 parent::release_session_lock($rowid);
3b1a9849 1141 $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid;
1142 $sql = "SELECT RELEASE_LOCK('$fullname')";
1143 $this->query_start($sql, null, SQL_QUERY_AUX);
1144 $result = $this->mysqli->query($sql);
7f79aaea 1145 $this->query_end($result);
1146
1147 if ($result) {
7f79aaea 1148 $result->close();
7f79aaea 1149 }
7f79aaea 1150 }
1151
fa76662b 1152/// transactions
1153 /**
d5a8d9aa
PS
1154 * Are transactions supported?
1155 * It is not responsible to run productions servers
1156 * on databases without transaction support ;-)
1157 *
1158 * MyISAM does not support support transactions.
fa76662b 1159 *
d35ece6c
PS
1160 * You can override this via the dbtransactions option.
1161 *
d5a8d9aa 1162 * @return bool
fa76662b 1163 */
d5a8d9aa
PS
1164 protected function transactions_supported() {
1165 if (!is_null($this->transactions_supported)) {
1166 return $this->transactions_supported;
1167 }
1168
d35ece6c
PS
1169 // this is all just guessing, might be better to just specify it in config.php
1170 if (isset($this->dboptions['dbtransactions'])) {
1171 $this->transactions_supported = $this->dboptions['dbtransactions'];
1172 return $this->transactions_supported;
1173 }
1174
d5a8d9aa
PS
1175 $this->transactions_supported = false;
1176
d35ece6c 1177 $engine = $this->get_dbengine();
d5a8d9aa 1178
d35ece6c
PS
1179 // Only will accept transactions if using compatible storage engine (more engines can be added easily BDB, Falcon...)
1180 if (in_array($engine, array('InnoDB', 'INNOBASE', 'BDB', 'XtraDB', 'Aria', 'Falcon'))) {
1181 $this->transactions_supported = true;
dd67e10c 1182 }
dd67e10c 1183
d5a8d9aa
PS
1184 return $this->transactions_supported;
1185 }
1186
1187 /**
1188 * Driver specific start of real database transaction,
1189 * this can not be used directly in code.
1190 * @return void
1191 */
1192 protected function begin_transaction() {
1193 if (!$this->transactions_supported()) {
1194 return;
a1dda107 1195 }
dd67e10c 1196
a6283e91 1197 $sql = "SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED";
1198 $this->query_start($sql, NULL, SQL_QUERY_AUX);
1199 $result = $this->mysqli->query($sql);
1200 $this->query_end($result);
1201
dd67e10c 1202 $sql = "START TRANSACTION";
a6283e91 1203 $this->query_start($sql, NULL, SQL_QUERY_AUX);
1204 $result = $this->mysqli->query($sql);
1205 $this->query_end($result);
fa76662b 1206 }
1207
1208 /**
d5a8d9aa
PS
1209 * Driver specific commit of real database transaction,
1210 * this can not be used directly in code.
1211 * @return void
fa76662b 1212 */
d5a8d9aa
PS
1213 protected function commit_transaction() {
1214 if (!$this->transactions_supported()) {
1215 return;
a1dda107 1216 }
d5a8d9aa 1217
a6283e91 1218 $sql = "COMMIT";
1219 $this->query_start($sql, NULL, SQL_QUERY_AUX);
1220 $result = $this->mysqli->query($sql);
1221 $this->query_end($result);
fa76662b 1222 }
1223
1224 /**
d5a8d9aa
PS
1225 * Driver specific abort of real database transaction,
1226 * this can not be used directly in code.
1227 * @return void
fa76662b 1228 */
d5a8d9aa
PS
1229 protected function rollback_transaction() {
1230 if (!$this->transactions_supported()) {
1231 return;
a1dda107 1232 }
d5a8d9aa 1233
a6283e91 1234 $sql = "ROLLBACK";
1235 $this->query_start($sql, NULL, SQL_QUERY_AUX);
1236 $result = $this->mysqli->query($sql);
1237 $this->query_end($result);
1238
fa76662b 1239 return true;
1240 }
7466a42f 1241}