PageRenderTime 56ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/dml/mysqli_native_moodle_database.php

https://bitbucket.org/moodle/moodle
PHP | 2110 lines | 1344 code | 223 blank | 543 comment | 200 complexity | a40477db8f33a318f56d2d22fef39638 MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1, BSD-3-Clause, MIT, GPL-3.0
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Native mysqli class representing moodle database interface.
  18. *
  19. * @package core_dml
  20. * @copyright 2008 Petr Skoda (http://skodak.org)
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. defined('MOODLE_INTERNAL') || die();
  24. require_once(__DIR__.'/moodle_database.php');
  25. require_once(__DIR__.'/moodle_read_slave_trait.php');
  26. require_once(__DIR__.'/mysqli_native_moodle_recordset.php');
  27. require_once(__DIR__.'/mysqli_native_moodle_temptables.php');
  28. /**
  29. * Native mysqli class representing moodle database interface.
  30. *
  31. * @package core_dml
  32. * @copyright 2008 Petr Skoda (http://skodak.org)
  33. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  34. */
  35. class mysqli_native_moodle_database extends moodle_database {
  36. use moodle_read_slave_trait {
  37. can_use_readonly as read_slave_can_use_readonly;
  38. }
  39. /** @var mysqli $mysqli */
  40. protected $mysqli = null;
  41. /** @var bool is compressed row format supported cache */
  42. protected $compressedrowformatsupported = null;
  43. private $transactions_supported = null;
  44. /**
  45. * Attempt to create the database
  46. * @param string $dbhost
  47. * @param string $dbuser
  48. * @param string $dbpass
  49. * @param string $dbname
  50. * @return bool success
  51. * @throws dml_exception A DML specific exception is thrown for any errors.
  52. */
  53. public function create_database($dbhost, $dbuser, $dbpass, $dbname, array $dboptions=null) {
  54. $driverstatus = $this->driver_installed();
  55. if ($driverstatus !== true) {
  56. throw new dml_exception('dbdriverproblem', $driverstatus);
  57. }
  58. if (!empty($dboptions['dbsocket'])
  59. and (strpos($dboptions['dbsocket'], '/') !== false or strpos($dboptions['dbsocket'], '\\') !== false)) {
  60. $dbsocket = $dboptions['dbsocket'];
  61. } else {
  62. $dbsocket = ini_get('mysqli.default_socket');
  63. }
  64. if (empty($dboptions['dbport'])) {
  65. $dbport = (int)ini_get('mysqli.default_port');
  66. } else {
  67. $dbport = (int)$dboptions['dbport'];
  68. }
  69. // verify ini.get does not return nonsense
  70. if (empty($dbport)) {
  71. $dbport = 3306;
  72. }
  73. ob_start();
  74. $conn = new mysqli($dbhost, $dbuser, $dbpass, '', $dbport, $dbsocket); // Connect without db
  75. $dberr = ob_get_contents();
  76. ob_end_clean();
  77. $errorno = @$conn->connect_errno;
  78. if ($errorno !== 0) {
  79. throw new dml_connection_exception($dberr);
  80. }
  81. // Normally a check would be done before setting utf8mb4, but the database can be created
  82. // before the enviroment checks are done. We'll proceed with creating the database and then do checks next.
  83. $charset = 'utf8mb4';
  84. if (isset($dboptions['dbcollation']) and (strpos($dboptions['dbcollation'], 'utf8_') === 0
  85. || strpos($dboptions['dbcollation'], 'utf8mb4_') === 0)) {
  86. $collation = $dboptions['dbcollation'];
  87. $collationinfo = explode('_', $dboptions['dbcollation']);
  88. $charset = reset($collationinfo);
  89. } else {
  90. $collation = 'utf8mb4_unicode_ci';
  91. }
  92. $result = $conn->query("CREATE DATABASE $dbname DEFAULT CHARACTER SET $charset DEFAULT COLLATE ".$collation);
  93. $conn->close();
  94. if (!$result) {
  95. throw new dml_exception('cannotcreatedb');
  96. }
  97. return true;
  98. }
  99. /**
  100. * Detects if all needed PHP stuff installed.
  101. * Note: can be used before connect()
  102. * @return mixed true if ok, string if something
  103. */
  104. public function driver_installed() {
  105. if (!extension_loaded('mysqli')) {
  106. return get_string('mysqliextensionisnotpresentinphp', 'install');
  107. }
  108. return true;
  109. }
  110. /**
  111. * Returns database family type - describes SQL dialect
  112. * Note: can be used before connect()
  113. * @return string db family name (mysql, postgres, mssql, oracle, etc.)
  114. */
  115. public function get_dbfamily() {
  116. return 'mysql';
  117. }
  118. /**
  119. * Returns more specific database driver type
  120. * Note: can be used before connect()
  121. * @return string db type mysqli, pgsql, oci, mssql, sqlsrv
  122. */
  123. protected function get_dbtype() {
  124. return 'mysqli';
  125. }
  126. /**
  127. * Returns general database library name
  128. * Note: can be used before connect()
  129. * @return string db type pdo, native
  130. */
  131. protected function get_dblibrary() {
  132. return 'native';
  133. }
  134. /**
  135. * Returns the current MySQL db engine.
  136. *
  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.
  140. *
  141. * @return string or null MySQL engine name
  142. */
  143. public function get_dbengine() {
  144. if (isset($this->dboptions['dbengine'])) {
  145. return $this->dboptions['dbengine'];
  146. }
  147. if ($this->external) {
  148. return null;
  149. }
  150. $engine = null;
  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
  154. FROM INFORMATION_SCHEMA.TABLES
  155. WHERE table_schema = DATABASE() AND table_name = '{$this->prefix}config'";
  156. $this->query_start($sql, NULL, SQL_QUERY_AUX);
  157. $result = $this->mysqli->query($sql);
  158. $this->query_end($result);
  159. if ($rec = $result->fetch_assoc()) {
  160. // MySQL 8 BC: information_schema.* returns the fields in upper case.
  161. $rec = array_change_key_case($rec, CASE_LOWER);
  162. $engine = $rec['engine'];
  163. }
  164. $result->close();
  165. if ($engine) {
  166. // Cache the result to improve performance.
  167. $this->dboptions['dbengine'] = $engine;
  168. return $engine;
  169. }
  170. // Get the default database engine.
  171. $sql = "SELECT @@default_storage_engine engine";
  172. $this->query_start($sql, NULL, SQL_QUERY_AUX);
  173. $result = $this->mysqli->query($sql);
  174. $this->query_end($result);
  175. if ($rec = $result->fetch_assoc()) {
  176. $engine = $rec['engine'];
  177. }
  178. $result->close();
  179. if ($engine === 'MyISAM') {
  180. // we really do not want MyISAM for Moodle, InnoDB or XtraDB is a reasonable defaults if supported
  181. $sql = "SHOW STORAGE ENGINES";
  182. $this->query_start($sql, NULL, SQL_QUERY_AUX);
  183. $result = $this->mysqli->query($sql);
  184. $this->query_end($result);
  185. $engines = array();
  186. while ($res = $result->fetch_assoc()) {
  187. if ($res['Support'] === 'YES' or $res['Support'] === 'DEFAULT') {
  188. $engines[$res['Engine']] = true;
  189. }
  190. }
  191. $result->close();
  192. if (isset($engines['InnoDB'])) {
  193. $engine = 'InnoDB';
  194. }
  195. if (isset($engines['XtraDB'])) {
  196. $engine = 'XtraDB';
  197. }
  198. }
  199. // Cache the result to improve performance.
  200. $this->dboptions['dbengine'] = $engine;
  201. return $engine;
  202. }
  203. /**
  204. * Returns the current MySQL db collation.
  205. *
  206. * This is an ugly workaround for MySQL default collation problems.
  207. *
  208. * @return string or null MySQL collation name
  209. */
  210. public function get_dbcollation() {
  211. if (isset($this->dboptions['dbcollation'])) {
  212. return $this->dboptions['dbcollation'];
  213. }
  214. }
  215. /**
  216. * Set 'dbcollation' option
  217. *
  218. * @return string $dbcollation
  219. */
  220. private function detect_collation(): string {
  221. if ($this->external) {
  222. return null;
  223. }
  224. $collation = null;
  225. // Look for current collation of our config table (the first table that gets created),
  226. // so that we create all tables with the same collation.
  227. $sql = "SELECT collation_name
  228. FROM INFORMATION_SCHEMA.COLUMNS
  229. WHERE table_schema = DATABASE() AND table_name = '{$this->prefix}config' AND column_name = 'value'";
  230. $result = $this->mysqli->query($sql);
  231. if ($rec = $result->fetch_assoc()) {
  232. // MySQL 8 BC: information_schema.* returns the fields in upper case.
  233. $rec = array_change_key_case($rec, CASE_LOWER);
  234. $collation = $rec['collation_name'];
  235. }
  236. $result->close();
  237. if (!$collation) {
  238. // Get the default database collation, but only if using UTF-8.
  239. $sql = "SELECT @@collation_database";
  240. $result = $this->mysqli->query($sql);
  241. if ($rec = $result->fetch_assoc()) {
  242. if (strpos($rec['@@collation_database'], 'utf8_') === 0 || strpos($rec['@@collation_database'], 'utf8mb4_') === 0) {
  243. $collation = $rec['@@collation_database'];
  244. }
  245. }
  246. $result->close();
  247. }
  248. if (!$collation) {
  249. // We want only utf8 compatible collations.
  250. $collation = null;
  251. $sql = "SHOW COLLATION WHERE Collation LIKE 'utf8mb4\_%' AND Charset = 'utf8mb4'";
  252. $result = $this->mysqli->query($sql);
  253. while ($res = $result->fetch_assoc()) {
  254. $collation = $res['Collation'];
  255. if (strtoupper($res['Default']) === 'YES') {
  256. $collation = $res['Collation'];
  257. break;
  258. }
  259. }
  260. $result->close();
  261. }
  262. // Cache the result to improve performance.
  263. $this->dboptions['dbcollation'] = $collation;
  264. return $collation;
  265. }
  266. /**
  267. * Tests if the Antelope file format is still supported or it has been removed.
  268. * When removed, only Barracuda file format is supported, given the XtraDB/InnoDB engine.
  269. *
  270. * @return bool True if the Antelope file format has been removed; otherwise, false.
  271. */
  272. protected function is_antelope_file_format_no_more_supported() {
  273. // Breaking change: Antelope file format support has been removed from both MySQL and MariaDB.
  274. // The following InnoDB file format configuration parameters were deprecated and then removed:
  275. // - innodb_file_format
  276. // - innodb_file_format_check
  277. // - innodb_file_format_max
  278. // - innodb_large_prefix
  279. // 1. MySQL: deprecated in 5.7.7 and removed 8.0.0+.
  280. $ismysqlge8d0d0 = ($this->get_dbtype() == 'mysqli') &&
  281. version_compare($this->get_server_info()['version'], '8.0.0', '>=');
  282. // 2. MariaDB: deprecated in 10.2.0 and removed 10.3.1+.
  283. $ismariadbge10d3d1 = ($this->get_dbtype() == 'mariadb') &&
  284. version_compare($this->get_server_info()['version'], '10.3.1', '>=');
  285. return $ismysqlge8d0d0 || $ismariadbge10d3d1;
  286. }
  287. /**
  288. * Get the row format from the database schema.
  289. *
  290. * @param string $table
  291. * @return string row_format name or null if not known or table does not exist.
  292. */
  293. public function get_row_format($table = null) {
  294. $rowformat = null;
  295. if (isset($table)) {
  296. $table = $this->mysqli->real_escape_string($table);
  297. $sql = "SELECT row_format
  298. FROM INFORMATION_SCHEMA.TABLES
  299. WHERE table_schema = DATABASE() AND table_name = '{$this->prefix}$table'";
  300. } else {
  301. if ($this->is_antelope_file_format_no_more_supported()) {
  302. // Breaking change: Antelope file format support has been removed, only Barracuda.
  303. $dbengine = $this->get_dbengine();
  304. $supporteddbengines = array('InnoDB', 'XtraDB');
  305. if (in_array($dbengine, $supporteddbengines)) {
  306. $rowformat = 'Barracuda';
  307. }
  308. return $rowformat;
  309. }
  310. $sql = "SHOW VARIABLES LIKE 'innodb_file_format'";
  311. }
  312. $this->query_start($sql, NULL, SQL_QUERY_AUX);
  313. $result = $this->mysqli->query($sql);
  314. $this->query_end($result);
  315. if ($rec = $result->fetch_assoc()) {
  316. // MySQL 8 BC: information_schema.* returns the fields in upper case.
  317. $rec = array_change_key_case($rec, CASE_LOWER);
  318. if (isset($table)) {
  319. $rowformat = $rec['row_format'];
  320. } else {
  321. $rowformat = $rec['value'];
  322. }
  323. }
  324. $result->close();
  325. return $rowformat;
  326. }
  327. /**
  328. * Is this database compatible with compressed row format?
  329. * This feature is necessary for support of large number of text
  330. * columns in InnoDB/XtraDB database.
  331. *
  332. * @param bool $cached use cached result
  333. * @return bool true if table can be created or changed to compressed row format.
  334. */
  335. public function is_compressed_row_format_supported($cached = true) {
  336. if ($cached and isset($this->compressedrowformatsupported)) {
  337. return($this->compressedrowformatsupported);
  338. }
  339. $engine = strtolower($this->get_dbengine());
  340. $info = $this->get_server_info();
  341. if (version_compare($info['version'], '5.5.0') < 0) {
  342. // MySQL 5.1 is not supported here because we cannot read the file format.
  343. $this->compressedrowformatsupported = false;
  344. } else if ($engine !== 'innodb' and $engine !== 'xtradb') {
  345. // Other engines are not supported, most probably not compatible.
  346. $this->compressedrowformatsupported = false;
  347. } else if (!$this->is_file_per_table_enabled()) {
  348. $this->compressedrowformatsupported = false;
  349. } else if ($this->get_row_format() !== 'Barracuda') {
  350. $this->compressedrowformatsupported = false;
  351. } else {
  352. // All the tests passed, we can safely use ROW_FORMAT=Compressed in sql statements.
  353. $this->compressedrowformatsupported = true;
  354. }
  355. return $this->compressedrowformatsupported;
  356. }
  357. /**
  358. * Check the database to see if innodb_file_per_table is on.
  359. *
  360. * @return bool True if on otherwise false.
  361. */
  362. public function is_file_per_table_enabled() {
  363. if ($filepertable = $this->get_record_sql("SHOW VARIABLES LIKE 'innodb_file_per_table'")) {
  364. if ($filepertable->value == 'ON') {
  365. return true;
  366. }
  367. }
  368. return false;
  369. }
  370. /**
  371. * Check the database to see if innodb_large_prefix is on.
  372. *
  373. * @return bool True if on otherwise false.
  374. */
  375. public function is_large_prefix_enabled() {
  376. if ($this->is_antelope_file_format_no_more_supported()) {
  377. // Breaking change: Antelope file format support has been removed, only Barracuda.
  378. return true;
  379. }
  380. if ($largeprefix = $this->get_record_sql("SHOW VARIABLES LIKE 'innodb_large_prefix'")) {
  381. if ($largeprefix->value == 'ON') {
  382. return true;
  383. }
  384. }
  385. return false;
  386. }
  387. /**
  388. * Determine if the row format should be set to compressed, dynamic, or default.
  389. *
  390. * Terrible kludge. If we're using utf8mb4 AND we're using InnoDB, we need to specify row format to
  391. * be either dynamic or compressed (default is compact) in order to allow for bigger indexes (MySQL
  392. * errors #1709 and #1071).
  393. *
  394. * @param string $engine The database engine being used. Will be looked up if not supplied.
  395. * @param string $collation The database collation to use. Will look up the current collation if not supplied.
  396. * @return string An sql fragment to add to sql statements.
  397. */
  398. public function get_row_format_sql($engine = null, $collation = null) {
  399. if (!isset($engine)) {
  400. $engine = $this->get_dbengine();
  401. }
  402. $engine = strtolower($engine);
  403. if (!isset($collation)) {
  404. $collation = $this->get_dbcollation();
  405. }
  406. $rowformat = '';
  407. if (($engine === 'innodb' || $engine === 'xtradb') && strpos($collation, 'utf8mb4_') === 0) {
  408. if ($this->is_compressed_row_format_supported()) {
  409. $rowformat = "ROW_FORMAT=Compressed";
  410. } else {
  411. $rowformat = "ROW_FORMAT=Dynamic";
  412. }
  413. }
  414. return $rowformat;
  415. }
  416. /**
  417. * Returns localised database type name
  418. * Note: can be used before connect()
  419. * @return string
  420. */
  421. public function get_name() {
  422. return get_string('nativemysqli', 'install');
  423. }
  424. /**
  425. * Returns localised database configuration help.
  426. * Note: can be used before connect()
  427. * @return string
  428. */
  429. public function get_configuration_help() {
  430. return get_string('nativemysqlihelp', 'install');
  431. }
  432. /**
  433. * Diagnose database and tables, this function is used
  434. * to verify database and driver settings, db engine types, etc.
  435. *
  436. * @return string null means everything ok, string means problem found.
  437. */
  438. public function diagnose() {
  439. $sloppymyisamfound = false;
  440. $prefix = str_replace('_', '\\_', $this->prefix);
  441. $sql = "SELECT COUNT('x')
  442. FROM INFORMATION_SCHEMA.TABLES
  443. WHERE table_schema = DATABASE()
  444. AND table_name LIKE BINARY '$prefix%'
  445. AND Engine = 'MyISAM'";
  446. $this->query_start($sql, null, SQL_QUERY_AUX);
  447. $result = $this->mysqli->query($sql);
  448. $this->query_end($result);
  449. if ($result) {
  450. if ($arr = $result->fetch_assoc()) {
  451. $count = reset($arr);
  452. if ($count) {
  453. $sloppymyisamfound = true;
  454. }
  455. }
  456. $result->close();
  457. }
  458. if ($sloppymyisamfound) {
  459. return get_string('myisamproblem', 'error');
  460. } else {
  461. return null;
  462. }
  463. }
  464. /**
  465. * Connect to db
  466. * @param string $dbhost The database host.
  467. * @param string $dbuser The database username.
  468. * @param string $dbpass The database username's password.
  469. * @param string $dbname The name of the database being connected to.e
  470. * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
  471. * @param array $dboptions driver specific options
  472. * @return bool success
  473. */
  474. public function raw_connect(string $dbhost, string $dbuser, string $dbpass, string $dbname, $prefix, array $dboptions=null): bool {
  475. $driverstatus = $this->driver_installed();
  476. if ($driverstatus !== true) {
  477. throw new dml_exception('dbdriverproblem', $driverstatus);
  478. }
  479. $this->store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions);
  480. // dbsocket is used ONLY if host is NULL or 'localhost',
  481. // you can not disable it because it is always tried if dbhost is 'localhost'
  482. if (!empty($this->dboptions['dbsocket'])
  483. and (strpos($this->dboptions['dbsocket'], '/') !== false or strpos($this->dboptions['dbsocket'], '\\') !== false)) {
  484. $dbsocket = $this->dboptions['dbsocket'];
  485. } else {
  486. $dbsocket = ini_get('mysqli.default_socket');
  487. }
  488. if (empty($this->dboptions['dbport'])) {
  489. $dbport = (int)ini_get('mysqli.default_port');
  490. } else {
  491. $dbport = (int)$this->dboptions['dbport'];
  492. }
  493. // verify ini.get does not return nonsense
  494. if (empty($dbport)) {
  495. $dbport = 3306;
  496. }
  497. if ($dbhost and !empty($this->dboptions['dbpersist'])) {
  498. $dbhost = "p:$dbhost";
  499. }
  500. $this->mysqli = mysqli_init();
  501. if (!empty($this->dboptions['connecttimeout'])) {
  502. $this->mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, $this->dboptions['connecttimeout']);
  503. }
  504. $conn = null;
  505. $dberr = null;
  506. try {
  507. // real_connect() is doing things we don't expext.
  508. $conn = @$this->mysqli->real_connect($dbhost, $dbuser, $dbpass, $dbname, $dbport, $dbsocket);
  509. } catch (\Exception $e) {
  510. $dberr = "$e";
  511. }
  512. if (!$conn) {
  513. $dberr = $dberr ?: $this->mysqli->connect_error;
  514. $this->mysqli = null;
  515. throw new dml_connection_exception($dberr);
  516. }
  517. // Disable logging until we are fully setup.
  518. $this->query_log_prevent();
  519. if (isset($dboptions['dbcollation'])) {
  520. $collation = $this->dboptions['dbcollation'] = $dboptions['dbcollation'];
  521. } else {
  522. $collation = $this->detect_collation();
  523. }
  524. $collationinfo = explode('_', $collation);
  525. $charset = reset($collationinfo);
  526. $this->mysqli->set_charset($charset);
  527. // If available, enforce strict mode for the session. That guaranties
  528. // standard behaviour under some situations, avoiding some MySQL nasty
  529. // habits like truncating data or performing some transparent cast losses.
  530. // With strict mode enforced, Moodle DB layer will be consistently throwing
  531. // the corresponding exceptions as expected.
  532. $si = $this->get_server_info();
  533. if (version_compare($si['version'], '5.0.2', '>=')) {
  534. $sql = "SET SESSION sql_mode = 'STRICT_ALL_TABLES'";
  535. $result = $this->mysqli->query($sql);
  536. }
  537. // We can enable logging now.
  538. $this->query_log_allow();
  539. // Connection stabilised and configured, going to instantiate the temptables controller
  540. $this->temptables = new mysqli_native_moodle_temptables($this);
  541. return true;
  542. }
  543. /**
  544. * Close database connection and release all resources
  545. * and memory (especially circular memory references).
  546. * Do NOT use connect() again, create a new instance if needed.
  547. */
  548. public function dispose() {
  549. parent::dispose(); // Call parent dispose to write/close session and other common stuff before closing connection
  550. if ($this->mysqli) {
  551. $this->mysqli->close();
  552. $this->mysqli = null;
  553. }
  554. }
  555. /**
  556. * Gets db handle currently used with queries
  557. * @return resource
  558. */
  559. protected function get_db_handle() {
  560. return $this->mysqli;
  561. }
  562. /**
  563. * Sets db handle to be used with subsequent queries
  564. * @param resource $dbh
  565. * @return void
  566. */
  567. protected function set_db_handle($dbh): void {
  568. $this->mysqli = $dbh;
  569. }
  570. /**
  571. * Check if The query qualifies for readonly connection execution
  572. * Logging queries are exempt, those are write operations that circumvent
  573. * standard query_start/query_end paths.
  574. * @param int $type type of query
  575. * @param string $sql
  576. * @return bool
  577. */
  578. protected function can_use_readonly(int $type, string $sql): bool {
  579. // ... *_LOCK queries always go to master.
  580. if (preg_match('/\b(GET|RELEASE)_LOCK/i', $sql)) {
  581. return false;
  582. }
  583. return $this->read_slave_can_use_readonly($type, $sql);
  584. }
  585. /**
  586. * Returns database server info array
  587. * @return array Array containing 'description' and 'version' info
  588. */
  589. public function get_server_info() {
  590. return array('description'=>$this->mysqli->server_info, 'version'=>$this->mysqli->server_info);
  591. }
  592. /**
  593. * Returns supported query parameter types
  594. * @return int bitmask of accepted SQL_PARAMS_*
  595. */
  596. protected function allowed_param_types() {
  597. return SQL_PARAMS_QM;
  598. }
  599. /**
  600. * Returns last error reported by database engine.
  601. * @return string error message
  602. */
  603. public function get_last_error() {
  604. return $this->mysqli->error;
  605. }
  606. /**
  607. * Return tables in database WITHOUT current prefix
  608. * @param bool $usecache if true, returns list of cached tables.
  609. * @return array of table names in lowercase and without prefix
  610. */
  611. public function get_tables($usecache=true) {
  612. if ($usecache and $this->tables !== null) {
  613. return $this->tables;
  614. }
  615. $this->tables = array();
  616. $prefix = str_replace('_', '\\_', $this->prefix);
  617. $sql = "SHOW TABLES LIKE '$prefix%'";
  618. $this->query_start($sql, null, SQL_QUERY_AUX);
  619. $result = $this->mysqli->query($sql);
  620. $this->query_end($result);
  621. $len = strlen($this->prefix);
  622. if ($result) {
  623. while ($arr = $result->fetch_assoc()) {
  624. $tablename = reset($arr);
  625. $tablename = substr($tablename, $len);
  626. $this->tables[$tablename] = $tablename;
  627. }
  628. $result->close();
  629. }
  630. // Add the currently available temptables
  631. $this->tables = array_merge($this->tables, $this->temptables->get_temptables());
  632. return $this->tables;
  633. }
  634. /**
  635. * Return table indexes - everything lowercased.
  636. * @param string $table The table we want to get indexes from.
  637. * @return array An associative array of indexes containing 'unique' flag and 'columns' being indexed
  638. */
  639. public function get_indexes($table) {
  640. $indexes = array();
  641. $fixedtable = $this->fix_table_name($table);
  642. $sql = "SHOW INDEXES FROM $fixedtable";
  643. $this->query_start($sql, null, SQL_QUERY_AUX);
  644. $result = $this->mysqli->query($sql);
  645. try {
  646. $this->query_end($result);
  647. } catch (dml_read_exception $e) {
  648. return $indexes; // table does not exist - no indexes...
  649. }
  650. if ($result) {
  651. while ($res = $result->fetch_object()) {
  652. if ($res->Key_name === 'PRIMARY') {
  653. continue;
  654. }
  655. if (!isset($indexes[$res->Key_name])) {
  656. $indexes[$res->Key_name] = array('unique'=>empty($res->Non_unique), 'columns'=>array());
  657. }
  658. $indexes[$res->Key_name]['columns'][$res->Seq_in_index-1] = $res->Column_name;
  659. }
  660. $result->close();
  661. }
  662. return $indexes;
  663. }
  664. /**
  665. * Fetches detailed information about columns in table.
  666. *
  667. * @param string $table name
  668. * @return database_column_info[] array of database_column_info objects indexed with column names
  669. */
  670. protected function fetch_columns(string $table): array {
  671. $structure = array();
  672. $sql = "SELECT column_name, data_type, character_maximum_length, numeric_precision,
  673. numeric_scale, is_nullable, column_type, column_default, column_key, extra
  674. FROM information_schema.columns
  675. WHERE table_name = '" . $this->prefix.$table . "'
  676. AND table_schema = '" . $this->dbname . "'
  677. ORDER BY ordinal_position";
  678. $this->query_start($sql, null, SQL_QUERY_AUX);
  679. $result = $this->mysqli->query($sql);
  680. $this->query_end(true); // Don't want to throw anything here ever. MDL-30147
  681. if ($result === false) {
  682. return array();
  683. }
  684. if ($result->num_rows > 0) {
  685. // standard table exists
  686. while ($rawcolumn = $result->fetch_assoc()) {
  687. // MySQL 8 BC: information_schema.* returns the fields in upper case.
  688. $rawcolumn = array_change_key_case($rawcolumn, CASE_LOWER);
  689. $info = (object)$this->get_column_info((object)$rawcolumn);
  690. $structure[$info->name] = new database_column_info($info);
  691. }
  692. $result->close();
  693. } else {
  694. // temporary tables are not in information schema, let's try it the old way
  695. $result->close();
  696. $fixedtable = $this->fix_table_name($table);
  697. $sql = "SHOW COLUMNS FROM $fixedtable";
  698. $this->query_start($sql, null, SQL_QUERY_AUX);
  699. $result = $this->mysqli->query($sql);
  700. $this->query_end(true);
  701. if ($result === false) {
  702. return array();
  703. }
  704. while ($rawcolumn = $result->fetch_assoc()) {
  705. $rawcolumn = (object)array_change_key_case($rawcolumn, CASE_LOWER);
  706. $rawcolumn->column_name = $rawcolumn->field; unset($rawcolumn->field);
  707. $rawcolumn->column_type = $rawcolumn->type; unset($rawcolumn->type);
  708. $rawcolumn->character_maximum_length = null;
  709. $rawcolumn->numeric_precision = null;
  710. $rawcolumn->numeric_scale = null;
  711. $rawcolumn->is_nullable = $rawcolumn->null; unset($rawcolumn->null);
  712. $rawcolumn->column_default = $rawcolumn->default; unset($rawcolumn->default);
  713. $rawcolumn->column_key = $rawcolumn->key; unset($rawcolumn->key);
  714. if (preg_match('/(enum|varchar)\((\d+)\)/i', $rawcolumn->column_type, $matches)) {
  715. $rawcolumn->data_type = $matches[1];
  716. $rawcolumn->character_maximum_length = $matches[2];
  717. } else if (preg_match('/([a-z]*int[a-z]*)\((\d+)\)/i', $rawcolumn->column_type, $matches)) {
  718. $rawcolumn->data_type = $matches[1];
  719. $rawcolumn->numeric_precision = $matches[2];
  720. $rawcolumn->max_length = $rawcolumn->numeric_precision;
  721. $type = strtoupper($matches[1]);
  722. if ($type === 'BIGINT') {
  723. $maxlength = 18;
  724. } else if ($type === 'INT' or $type === 'INTEGER') {
  725. $maxlength = 9;
  726. } else if ($type === 'MEDIUMINT') {
  727. $maxlength = 6;
  728. } else if ($type === 'SMALLINT') {
  729. $maxlength = 4;
  730. } else if ($type === 'TINYINT') {
  731. $maxlength = 2;
  732. } else {
  733. // This should not happen.
  734. $maxlength = 0;
  735. }
  736. if ($maxlength < $rawcolumn->max_length) {
  737. $rawcolumn->max_length = $maxlength;
  738. }
  739. } else if (preg_match('/(decimal)\((\d+),(\d+)\)/i', $rawcolumn->column_type, $matches)) {
  740. $rawcolumn->data_type = $matches[1];
  741. $rawcolumn->numeric_precision = $matches[2];
  742. $rawcolumn->numeric_scale = $matches[3];
  743. } else if (preg_match('/(double|float)(\((\d+),(\d+)\))?/i', $rawcolumn->column_type, $matches)) {
  744. $rawcolumn->data_type = $matches[1];
  745. $rawcolumn->numeric_precision = isset($matches[3]) ? $matches[3] : null;
  746. $rawcolumn->numeric_scale = isset($matches[4]) ? $matches[4] : null;
  747. } else if (preg_match('/([a-z]*text)/i', $rawcolumn->column_type, $matches)) {
  748. $rawcolumn->data_type = $matches[1];
  749. $rawcolumn->character_maximum_length = -1; // unknown
  750. } else if (preg_match('/([a-z]*blob)/i', $rawcolumn->column_type, $matches)) {
  751. $rawcolumn->data_type = $matches[1];
  752. } else {
  753. $rawcolumn->data_type = $rawcolumn->column_type;
  754. }
  755. $info = $this->get_column_info($rawcolumn);
  756. $structure[$info->name] = new database_column_info($info);
  757. }
  758. $result->close();
  759. }
  760. return $structure;
  761. }
  762. /**
  763. * Indicates whether column information retrieved from `information_schema.columns` has default values quoted or not.
  764. * @return boolean True when default values are quoted (breaking change); otherwise, false.
  765. */
  766. protected function has_breaking_change_quoted_defaults() {
  767. return false;
  768. }
  769. /**
  770. * Indicates whether SQL_MODE default value has changed in a not backward compatible way.
  771. * @return boolean True when SQL_MODE breaks BC; otherwise, false.
  772. */
  773. public function has_breaking_change_sqlmode() {
  774. return false;
  775. }
  776. /**
  777. * Returns moodle column info for raw column from information schema.
  778. * @param stdClass $rawcolumn
  779. * @return stdClass standardised colum info
  780. */
  781. private function get_column_info(stdClass $rawcolumn) {
  782. $rawcolumn = (object)$rawcolumn;
  783. $info = new stdClass();
  784. $info->name = $rawcolumn->column_name;
  785. $info->type = $rawcolumn->data_type;
  786. $info->meta_type = $this->mysqltype2moodletype($rawcolumn->data_type);
  787. if ($this->has_breaking_change_quoted_defaults()) {
  788. $info->default_value = is_null($rawcolumn->column_default) ? null : trim($rawcolumn->column_default, "'");
  789. if ($info->default_value === 'NULL') {
  790. $info->default_value = null;
  791. }
  792. } else {
  793. $info->default_value = $rawcolumn->column_default;
  794. }
  795. $info->has_default = !is_null($info->default_value);
  796. $info->not_null = ($rawcolumn->is_nullable === 'NO');
  797. $info->primary_key = ($rawcolumn->column_key === 'PRI');
  798. $info->binary = false;
  799. $info->unsigned = null;
  800. $info->auto_increment = false;
  801. $info->unique = null;
  802. $info->scale = null;
  803. if ($info->meta_type === 'C') {
  804. $info->max_length = $rawcolumn->character_maximum_length;
  805. } else if ($info->meta_type === 'I') {
  806. if ($info->primary_key) {
  807. $info->meta_type = 'R';
  808. $info->unique = true;
  809. }
  810. // Return number of decimals, not bytes here.
  811. $info->max_length = $rawcolumn->numeric_precision;
  812. if (preg_match('/([a-z]*int[a-z]*)\((\d+)\)/i', $rawcolumn->column_type, $matches)) {
  813. $type = strtoupper($matches[1]);
  814. if ($type === 'BIGINT') {
  815. $maxlength = 18;
  816. } else if ($type === 'INT' or $type === 'INTEGER') {
  817. $maxlength = 9;
  818. } else if ($type === 'MEDIUMINT') {
  819. $maxlength = 6;
  820. } else if ($type === 'SMALLINT') {
  821. $maxlength = 4;
  822. } else if ($type === 'TINYINT') {
  823. $maxlength = 2;
  824. } else {
  825. // This should not happen.
  826. $maxlength = 0;
  827. }
  828. // It is possible that display precision is different from storage type length,
  829. // always use the smaller value to make sure our data fits.
  830. if ($maxlength < $info->max_length) {
  831. $info->max_length = $maxlength;
  832. }
  833. }
  834. $info->unsigned = (stripos($rawcolumn->column_type, 'unsigned') !== false);
  835. $info->auto_increment= (strpos($rawcolumn->extra, 'auto_increment') !== false);
  836. } else if ($info->meta_type === 'N') {
  837. $info->max_length = $rawcolumn->numeric_precision;
  838. $info->scale = $rawcolumn->numeric_scale;
  839. $info->unsigned = (stripos($rawcolumn->column_type, 'unsigned') !== false);
  840. } else if ($info->meta_type === 'X') {
  841. if ("$rawcolumn->character_maximum_length" === '4294967295') { // watch out for PHP max int limits!
  842. // means maximum moodle size for text column, in other drivers it may also mean unknown size
  843. $info->max_length = -1;
  844. } else {
  845. $info->max_length = $rawcolumn->character_maximum_length;
  846. }
  847. $info->primary_key = false;
  848. } else if ($info->meta_type === 'B') {
  849. $info->max_length = -1;
  850. $info->primary_key = false;
  851. $info->binary = true;
  852. }
  853. return $info;
  854. }
  855. /**
  856. * Normalise column type.
  857. * @param string $mysql_type
  858. * @return string one character
  859. * @throws dml_exception
  860. */
  861. private function mysqltype2moodletype($mysql_type) {
  862. $type = null;
  863. switch(strtoupper($mysql_type)) {
  864. case 'BIT':
  865. $type = 'L';
  866. break;
  867. case 'TINYINT':
  868. case 'SMALLINT':
  869. case 'MEDIUMINT':
  870. case 'INT':
  871. case 'INTEGER':
  872. case 'BIGINT':
  873. $type = 'I';
  874. break;
  875. case 'FLOAT':
  876. case 'DOUBLE':
  877. case 'DECIMAL':
  878. $type = 'N';
  879. break;
  880. case 'CHAR':
  881. case 'ENUM':
  882. case 'SET':
  883. case 'VARCHAR':
  884. $type = 'C';
  885. break;
  886. case 'TINYTEXT':
  887. case 'TEXT':
  888. case 'MEDIUMTEXT':
  889. case 'LONGTEXT':
  890. $type = 'X';
  891. break;
  892. case 'BINARY':
  893. case 'VARBINARY':
  894. case 'BLOB':
  895. case 'TINYBLOB':
  896. case 'MEDIUMBLOB':
  897. case 'LONGBLOB':
  898. $type = 'B';
  899. break;
  900. case 'DATE':
  901. case 'TIME':
  902. case 'DATETIME':
  903. case 'TIMESTAMP':
  904. case 'YEAR':
  905. $type = 'D';
  906. break;
  907. }
  908. if (!$type) {
  909. throw new dml_exception('invalidmysqlnativetype', $mysql_type);
  910. }
  911. return $type;
  912. }
  913. /**
  914. * Normalise values based in RDBMS dependencies (booleans, LOBs...)
  915. *
  916. * @param database_column_info $column column metadata corresponding with the value we are going to normalise
  917. * @param mixed $value value we are going to normalise
  918. * @return mixed the normalised value
  919. */
  920. protected function normalise_value($column, $value) {
  921. $this->detect_objects($value);
  922. if (is_bool($value)) { // Always, convert boolean to int
  923. $value = (int)$value;
  924. } else if ($value === '') {
  925. if ($column->meta_type == 'I' or $column->meta_type == 'F' or $column->meta_type == 'N') {
  926. $value = 0; // prevent '' problems in numeric fields
  927. }
  928. // Any float value being stored in varchar or text field is converted to string to avoid
  929. // any implicit conversion by MySQL
  930. } else if (is_float($value) and ($column->meta_type == 'C' or $column->meta_type == 'X')) {
  931. $value = "$value";
  932. }
  933. return $value;
  934. }
  935. /**
  936. * Is this database compatible with utf8?
  937. * @return bool
  938. */
  939. public function setup_is_unicodedb() {
  940. // All new tables are created with this collation, we just have to make sure it is utf8 compatible,
  941. // if config table already exists it has this collation too.
  942. $collation = $this->get_dbcollation();
  943. $collationinfo = explode('_', $collation);
  944. $charset = reset($collationinfo);
  945. $sql = "SHOW COLLATION WHERE Collation ='$collation' AND Charset = '$charset'";
  946. $this->query_start($sql, NULL, SQL_QUERY_AUX);
  947. $result = $this->mysqli->query($sql);
  948. $this->query_end($result);
  949. if ($result->fetch_assoc()) {
  950. $return = true;
  951. } else {
  952. $return = false;
  953. }
  954. $result->close();
  955. return $return;
  956. }
  957. /**
  958. * Do NOT use in code, to be used by database_manager only!
  959. * @param string|array $sql query
  960. * @param array|null $tablenames an array of xmldb table names affected by this request.
  961. * @return bool true
  962. * @throws ddl_change_structure_exception A DDL specific exception is thrown for any errors.
  963. */
  964. public function change_database_structure($sql, $tablenames = null) {
  965. $this->get_manager(); // Includes DDL exceptions classes ;-)
  966. if (is_array($sql)) {
  967. $sql = implode("\n;\n", $sql);
  968. }
  969. try {
  970. $this->query_start($sql, null, SQL_QUERY_STRUCTURE);
  971. $result = $this->mysqli->multi_query($sql);
  972. if ($result === false) {
  973. $this->query_end(false);
  974. }
  975. while ($this->mysqli->more_results()) {
  976. $result = $this->mysqli->next_result();
  977. if ($result === false) {
  978. $this->query_end(false);
  979. }
  980. }
  981. $this->query_end(true);
  982. } catch (ddl_change_structure_exception $e) {
  983. while (@$this->mysqli->more_results()) {
  984. @$this->mysqli->next_result();
  985. }
  986. $this->reset_caches($tablenames);
  987. throw $e;
  988. }
  989. $this->reset_caches($tablenames);
  990. return true;
  991. }
  992. /**
  993. * Very ugly hack which emulates bound parameters in queries
  994. * because prepared statements do not use query cache.
  995. */
  996. protected function emulate_bound_params($sql, array $params=null) {
  997. if (empty($params)) {
  998. return $sql;
  999. }
  1000. // ok, we have verified sql statement with ? and correct number of params
  1001. $parts = array_reverse(explode('?', $sql));
  1002. $return = array_pop($parts);
  1003. foreach ($params as $param) {
  1004. if (is_bool($param)) {
  1005. $return .= (int)$param;
  1006. } else if (is_null($param)) {
  1007. $return .= 'NULL';
  1008. } else if (is_number($param)) {
  1009. $return .= "'".$param."'"; // we have to always use strings because mysql is using weird automatic int casting
  1010. } else if (is_float($param)) {
  1011. $return .= $param;
  1012. } else {
  1013. $param = $this->mysqli->real_escape_string($param);
  1014. $return .= "'$param'";
  1015. }
  1016. $return .= array_pop($parts);
  1017. }
  1018. return $return;
  1019. }
  1020. /**
  1021. * Execute general sql query. Should be used only when no other method suitable.
  1022. * Do NOT use this to make changes in db structure, use database_manager methods instead!
  1023. * @param string $sql query
  1024. * @param array $params query parameters
  1025. * @return bool true
  1026. * @throws dml_exception A DML specific exception is thrown for any errors.
  1027. */
  1028. public function execute($sql, array $params=null) {
  1029. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  1030. if (strpos($sql, ';') !== false) {
  1031. throw new coding_exception('moodle_database::execute() Multiple sql statements found or bound parameters not used properly in query!');
  1032. }
  1033. $rawsql = $this->emulate_bound_params($sql, $params);
  1034. $this->query_start($sql, $params, SQL_QUERY_UPDATE);
  1035. $result = $this->mysqli->query($rawsql);
  1036. $this->query_end($result);
  1037. if ($result === true) {
  1038. return true;
  1039. } else {
  1040. $result->close();
  1041. return true;
  1042. }
  1043. }
  1044. /**
  1045. * Get a number of records as a moodle_recordset using a SQL statement.
  1046. *
  1047. * Since this method is a little less readable, use of it should be restricted to
  1048. * code where it's possible there might be large datasets being returned. For known
  1049. * small datasets use get_records_sql - it leads to simpler code.
  1050. *
  1051. * The return type is like:
  1052. * @see function get_recordset.
  1053. *
  1054. * @param string $sql the SQL select query to execute.
  1055. * @param array $params array of sql parameters
  1056. * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
  1057. * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
  1058. * @return moodle_recordset instance
  1059. * @throws dml_exception A DML specific exception is thrown for any errors.
  1060. */
  1061. public function get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
  1062. list($limitfrom, $limitnum) = $this->normalise_limit_from_num($limitfrom, $limitnum);
  1063. if ($limitfrom or $limitnum) {
  1064. if ($limitnum < 1) {
  1065. $limitnum = "18446744073709551615";
  1066. }
  1067. $sql .= " LIMIT $limitfrom, $limitnum";
  1068. }
  1069. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  1070. $rawsql = $this->emulate_bound_params($sql, $params);
  1071. $this->query_start($sql, $params, SQL_QUERY_SELECT);
  1072. // no MYSQLI_USE_RESULT here, it would block write ops on affected tables
  1073. $result = $this->mysqli->query($rawsql, MYSQLI_STORE_RESULT);
  1074. $this->query_end($result);
  1075. return $this->create_recordset($result);
  1076. }
  1077. /**
  1078. * Get all records from a table.
  1079. *
  1080. * This method works around potential memory problems and may improve performance,
  1081. * this method may block access to table until the recordset is closed.
  1082. *
  1083. * @param string $table Name of database table.
  1084. * @return moodle_recordset A moodle_recordset instance {@link function get_recordset}.
  1085. * @throws dml_exception A DML specific exception is thrown for any errors.
  1086. */
  1087. public function export_table_recordset($table) {
  1088. $sql = $this->fix_table_names("SELECT * FROM {{$table}}");
  1089. $this->query_start($sql, array(), SQL_QUERY_SELECT);
  1090. // MYSQLI_STORE_RESULT may eat all memory for large tables, unfortunately MYSQLI_USE_RESULT blocks other queries.
  1091. $result = $this->mysqli->query($sql, MYSQLI_USE_RESULT);
  1092. $this->query_end($result);
  1093. return $this->create_recordset($result);
  1094. }
  1095. protected function create_recordset($result) {
  1096. return new mysqli_native_moodle_recordset($result);
  1097. }
  1098. /**
  1099. * Get a number of records as an array of objects using a SQL statement.
  1100. *
  1101. * Return value is like:
  1102. * @see function get_records.
  1103. *
  1104. * @param string $sql the SQL select query to execute. The first column of this SELECT statement
  1105. * must be a unique value (usually the 'id' field), as it will be used as the key of the
  1106. * returned array.
  1107. * @param array $params array of sql parameters
  1108. * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
  1109. * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
  1110. * @return array of objects, or empty array if no records were found
  1111. * @throws dml_exception A DML specific exception is thrown for any errors.
  1112. */
  1113. public function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
  1114. list($limitfrom, $limitnum) = $this->normalise_limit_from_num($limitfrom, $limitnum);
  1115. if ($limitfrom or $limitnum) {
  1116. if ($limitnum < 1) {
  1117. $limitnum = "18446744073709551615";
  1118. }
  1119. $sql .= " LIMIT $limitfrom, $limitnum";
  1120. }
  1121. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  1122. $rawsql = $this->emulate_bound_params($sql, $params);
  1123. $this->query_start($sql, $params, SQL_QUERY_SELECT);
  1124. $result = $this->mysqli->query($rawsql, MYSQLI_STORE_RESULT);
  1125. $this->query_end($result);
  1126. $return = array();
  1127. while($row = $result->fetch_assoc()) {
  1128. $row = array_change_key_case($row, CASE_LOWER);
  1129. $id = reset($row);
  1130. if (isset($return[$id])) {
  1131. $colname = key($row);
  1132. 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);
  1133. }
  1134. $return[$id] = (object)$row;
  1135. }
  1136. $result->close();
  1137. return $return;
  1138. }
  1139. /**
  1140. * Selects records and return values (first field) as an array using a SQL statement.
  1141. *
  1142. * @param string $sql The SQL query
  1143. * @param array $params array of sql parameters
  1144. * @return array of values
  1145. * @throws dml_exception A DML specific exception is thrown for any errors.
  1146. */
  1147. public function get_fieldset_sql($sql, array $params=null) {
  1148. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  1149. $rawsql = $this->emulate_bound_params($sql, $params);
  1150. $this->query_start($sql, $params, SQL_QUERY_SELECT);
  1151. $result = $this->mysqli->query($rawsql, MYSQLI_STORE_RESULT);
  1152. $this->query_end($result);
  1153. $return = array();
  1154. while($row = $result->fetch_assoc()) {
  1155. $return[] = reset($row);
  1156. }
  1157. $result->close();
  1158. return $return;
  1159. }
  1160. /**
  1161. * Insert new record into database, as fast as possible, no safety checks, lobs not supported.
  1162. * @param string $table name
  1163. * @param mixed $params data record as object or array
  1164. * @param bool $returnit return it of inserted record
  1165. * @param bool $bulk true means repeated inserts expected
  1166. * @param bool $customsequence true if 'id' included in $params, disables $returnid
  1167. * @return bool|int true or new id
  1168. * @throws dml_exception A DML specific exception is thrown for any errors.
  1169. */
  1170. public function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false) {
  1171. if (!is_array($params)) {
  1172. $params = (array)$params;
  1173. }
  1174. if ($customsequence) {
  1175. if (!isset($params['id'])) {
  1176. throw new coding_exception('moodle_database::insert_record_raw() id field must be specified if custom sequences used.');
  1177. }
  1178. $returnid = false;
  1179. } else {
  1180. unset($params['id']);
  1181. }
  1182. if (empty($params)) {
  1183. throw new coding_exception('moodle_database::insert_record_raw() no fields found.');
  1184. }
  1185. $fields = implode(',', array_keys($params));
  1186. $qms = array_fill(0, count($params), '?');
  1187. $qms = implode(',', $qms);
  1188. $fixedtable = $this->fix_table_name($table);
  1189. $sql = "INSERT INTO $fixedtable ($fields) VALUES($qms)";
  1190. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  1191. $rawsql = $this->emulate_bound_params($sql, $params);
  1192. $this->query_start($sql, $params, SQL_QUERY_INSERT);
  1193. $result = $this->mysqli->query($rawsql);
  1194. $id = @$this->mysqli->insert_id; // must be called before query_end() which may insert log into db
  1195. $this->query_end($result);
  1196. if (!$customsequence and !$id) {
  1197. throw new dml_write_exception('unknown error fetching inserted id');
  1198. }
  1199. if (!$returnid) {
  1200. return true;
  1201. } else {
  1202. return (int)$id;
  1203. }
  1204. }
  1205. /**
  1206. * Insert a record into a table and return the "id" field if required.
  1207. *
  1208. * Some conversions and safety checks are carried out. Lobs are supported.
  1209. * If the return ID isn't required, then this just reports success as true/false.
  1210. * $data is an object containing needed data
  1211. * @param string $table The database table to be inserted into
  1212. * @param object|array $dataobject A data object with values for one or more fields in the record
  1213. * @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.
  1214. * @return bool|int true or new id
  1215. * @throws dml_exception A DML specific exception is thrown for any errors.
  1216. */
  1217. public function insert_record($table, $dataobject, $returnid=true, $bulk=false) {
  1218. $dataobject = (array)$dataobject;
  1219. $columns = $this->get_columns($table);
  1220. if (empty($columns)) {
  1221. throw new dml_exception('ddltablenotexist', $table);
  1222. }
  1223. $cleaned = array();
  1224. foreach ($dataobject as $field=>$value) {
  1225. if ($field === 'id') {
  1226. continue;
  1227. }
  1228. if (!isset($columns[$field])) {
  1229. continue;
  1230. }
  1231. $column = $columns[$field];
  1232. $cleaned[$field] = $this->normalise_value($column, $value);
  1233. }
  1234. return $this->insert_record_raw($table, $cleaned, $returnid, $bulk);
  1235. }
  1236. /**
  1237. * Insert multiple records into database as fast as possible.
  1238. *
  1239. * Order of inserts is maintained, but the operation is not atomic,
  1240. * use transactions if necessary.
  1241. *
  1242. * This method is intended for inserting of large number of small objects,
  1243. * do not use for huge objects with text or binary fields.
  1244. *
  1245. * @since Moodle 2.7
  1246. *
  1247. * @param string $table The database table to be inserted into
  1248. * @param array|Traversable $dataobjects list of objects to be inserted, must be compatible with foreach
  1249. * @return void does not return new record ids
  1250. *
  1251. * @throws coding_exception if data objects have different structure
  1252. * @throws dml_exception A DML specific exception is thrown for any errors.
  1253. */
  1254. public function insert_records($table, $dataobjects) {
  1255. if (!is_array($dataobjects) and !$dataobjects instanceof Traversable) {
  1256. throw new coding_exception('insert_records() passed non-traversable object');
  1257. }
  1258. // MySQL has a relatively small query length limit by default,
  1259. // make sure 'max_allowed_packet' in my.cnf is high enough
  1260. // if you change the following default...
  1261. static $chunksize = null;
  1262. if ($chunksize === null) {
  1263. if (!empty($this->dboptions['bulkinsertsize'])) {
  1264. $chunksize = (int)$this->dboptions['bulkinsertsize'];
  1265. } else {
  1266. if (PHP_INT_SIZE === 4) {
  1267. // Bad luck for Windows, we cannot do any maths with large numbers.
  1268. $chunksize = 5;
  1269. } else {
  1270. $sql = "SHOW VARIABLES LIKE 'max_allowed_packet'";
  1271. $this->query_start($sql, null, SQL_QUERY_AUX);
  1272. $result = $this->mysqli->query($sql);
  1273. $this->query_end($result);
  1274. $size = 0;
  1275. if ($rec = $result->fetch_assoc()) {
  1276. $size = $rec['Value'];
  1277. }
  1278. $result->close();
  1279. // Hopefully 200kb per object are enough.
  1280. $chunksize = (int)($size / 200000);
  1281. if ($chunksize > 50) {
  1282. $chunksize = 50;
  1283. }
  1284. }
  1285. }
  1286. }
  1287. $columns = $this->get_columns($table, true);
  1288. $fields = null;
  1289. $count = 0;
  1290. $chunk = array();
  1291. foreach ($dataobjects as $dataobject) {
  1292. if (!is_array($dataobject) and !is_object($dataobject)) {
  1293. throw new coding_exception('insert_records() passed invalid record object');
  1294. }
  1295. $dataobject = (array)$dataobject;
  1296. if ($fields === null) {
  1297. $fields = array_keys($dataobject);
  1298. $columns = array_intersect_key($columns, $dataobject);
  1299. unset($columns['id']);
  1300. } else if ($fields !== array_keys($dataobject)) {
  1301. throw new coding_exception('All dataobjects in insert_records() must have the same structure!');
  1302. }
  1303. $count++;
  1304. $chunk[] = $dataobject;
  1305. if ($count === $chunksize) {
  1306. $this->insert_chunk($table, $chunk, $columns);
  1307. $chunk = array();
  1308. $count = 0;
  1309. }
  1310. }
  1311. if ($count) {
  1312. $this->insert_chunk($table, $chunk, $columns);
  1313. }
  1314. }
  1315. /**
  1316. * Insert records in chunks.
  1317. *
  1318. * Note: can be used only from insert_records().
  1319. *
  1320. * @param string $table
  1321. * @param array $chunk
  1322. * @param database_column_info[] $columns
  1323. */
  1324. protected function insert_chunk($table, array $chunk, array $columns) {
  1325. $fieldssql = '('.implode(',', array_keys($columns)).')';
  1326. $valuessql = '('.implode(',', array_fill(0, count($columns), '?')).')';
  1327. $valuessql = implode(',', array_fill(0, count($chunk), $valuessql));
  1328. $params = array();
  1329. foreach ($chunk as $dataobject) {
  1330. foreach ($columns as $field => $column) {
  1331. $params[] = $this->normalise_value($column, $dataobject[$field]);
  1332. }
  1333. }
  1334. $fixedtable = $this->fix_table_name($table);
  1335. $sql = "INSERT INTO $fixedtable $fieldssql VALUES $valuessql";
  1336. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  1337. $rawsql = $this->emulate_bound_params($sql, $params);
  1338. $this->query_start($sql, $params, SQL_QUERY_INSERT);
  1339. $result = $this->mysqli->query($rawsql);
  1340. $this->query_end($result);
  1341. }
  1342. /**
  1343. * Import a record into a table, id field is required.
  1344. * Safety checks are NOT carried out. Lobs are supported.
  1345. *
  1346. * @param string $table name of database table to be inserted into
  1347. * @param object $dataobject A data object with values for one or more fields in the record
  1348. * @return bool true
  1349. * @throws dml_exception A DML specific exception is thrown for any errors.
  1350. */
  1351. public function import_record($table, $dataobject) {
  1352. $dataobject = (array)$dataobject;
  1353. $columns = $this->get_columns($table);
  1354. $cleaned = array();
  1355. foreach ($dataobject as $field=>$value) {
  1356. if (!isset($columns[$field])) {
  1357. continue;
  1358. }
  1359. $cleaned[$field] = $value;
  1360. }
  1361. return $this->insert_record_raw($table, $cleaned, false, true, true);
  1362. }
  1363. /**
  1364. * Update record in database, as fast as possible, no safety checks, lobs not supported.
  1365. * @param string $table name
  1366. * @param mixed $params data record as object or array
  1367. * @param bool true means repeated updates expected
  1368. * @return bool true
  1369. * @throws dml_exception A DML specific exception is thrown for any errors.
  1370. */
  1371. public function update_record_raw($table, $params, $bulk=false) {
  1372. $params = (array)$params;
  1373. if (!isset($params['id'])) {
  1374. throw new coding_exception('moodle_database::update_record_raw() id field must be specified.');
  1375. }
  1376. $id = $params['id'];
  1377. unset($params['id']);
  1378. if (empty($params)) {
  1379. throw new coding_exception('moodle_database::update_record_raw() no fields found.');
  1380. }
  1381. $sets = array();
  1382. foreach ($params as $field=>$value) {
  1383. $sets[] = "$field = ?";
  1384. }
  1385. $params[] = $id; // last ? in WHERE condition
  1386. $sets = implode(',', $sets);
  1387. $fixedtable = $this->fix_table_name($table);
  1388. $sql = "UPDATE $fixedtable SET $sets WHERE id=?";
  1389. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  1390. $rawsql = $this->emulate_bound_params($sql, $params);
  1391. $this->query_start($sql, $params, SQL_QUERY_UPDATE);
  1392. $result = $this->mysqli->query($rawsql);
  1393. $this->query_end($result);
  1394. return true;
  1395. }
  1396. /**
  1397. * Update a record in a table
  1398. *
  1399. * $dataobject is an object containing needed data
  1400. * Relies on $dataobject having a variable "id" to
  1401. * specify the record to update
  1402. *
  1403. * @param string $table The database table to be checked against.
  1404. * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
  1405. * @param bool true means repeated updates expected
  1406. * @return bool true
  1407. * @throws dml_exception A DML specific exception is thrown for any errors.
  1408. */
  1409. public function update_record($table, $dataobject, $bulk=false) {
  1410. $dataobject = (array)$dataobject;
  1411. $columns = $this->get_columns($table);
  1412. $cleaned = array();
  1413. foreach ($dataobject as $field=>$value) {
  1414. if (!isset($columns[$field])) {
  1415. continue;
  1416. }
  1417. $column = $columns[$field];
  1418. $cleaned[$field] = $this->normalise_value($column, $value);
  1419. }
  1420. return $this->update_record_raw($table, $cleaned, $bulk);
  1421. }
  1422. /**
  1423. * Set a single field in every table record which match a particular WHERE clause.
  1424. *
  1425. * @param string $table The database table to be checked against.
  1426. * @param string $newfield the field to set.
  1427. * @param string $newvalue the value to set the field to.
  1428. * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
  1429. * @param array $params array of sql parameters
  1430. * @return bool true
  1431. * @throws dml_exception A DML specific exception is thrown for any errors.
  1432. */
  1433. public function set_field_select($table, $newfield, $newvalue, $select, array $params=null) {
  1434. if ($select) {
  1435. $select = "WHERE $select";
  1436. }
  1437. if (is_null($params)) {
  1438. $params = array();
  1439. }
  1440. list($select, $params, $type) = $this->fix_sql_params($select, $params);
  1441. // Get column metadata
  1442. $columns = $this->get_columns($table);
  1443. $column = $columns[$newfield];
  1444. $normalised_value = $this->normalise_value($column, $newvalue);
  1445. if (is_null($normalised_value)) {
  1446. $newfield = "$newfield = NULL";
  1447. } else {
  1448. $newfield = "$newfield = ?";
  1449. array_unshift($params, $normalised_value);
  1450. }
  1451. $fixedtable = $this->fix_table_name($table);
  1452. $sql = "UPDATE $fixedtable SET $newfield $select";
  1453. $rawsql = $this->emulate_bound_params($sql, $params);
  1454. $this->query_start($sql, $params, SQL_QUERY_UPDATE);
  1455. $result = $this->mysqli->query($rawsql);
  1456. $this->query_end($result);
  1457. return true;
  1458. }
  1459. /**
  1460. * Delete one or more records from a table which match a particular WHERE clause.
  1461. *
  1462. * @param string $table The database table to be checked against.
  1463. * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
  1464. * @param array $params array of sql parameters
  1465. * @return bool true
  1466. * @throws dml_exception A DML specific exception is thrown for any errors.
  1467. */
  1468. public function delete_records_select($table, $select, array $params=null) {
  1469. if ($select) {
  1470. $select = "WHERE $select";
  1471. }
  1472. $fixedtable = $this->fix_table_name($table);
  1473. $sql = "DELETE FROM $fixedtable $select";
  1474. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  1475. $rawsql = $this->emulate_bound_params($sql, $params);
  1476. $this->query_start($sql, $params, SQL_QUERY_UPDATE);
  1477. $result = $this->mysqli->query($rawsql);
  1478. $this->query_end($result);
  1479. return true;
  1480. }
  1481. /**
  1482. * Deletes records using a subquery, which is done with a strange DELETE...JOIN syntax in MySQL
  1483. * because it performs very badly with normal subqueries.
  1484. *
  1485. * @param string $table Table to delete from
  1486. * @param string $field Field in table to match
  1487. * @param string $alias Name of single column in subquery e.g. 'id'
  1488. * @param string $subquery Query that will return values of the field to delete
  1489. * @param array $params Parameters for query
  1490. * @throws dml_exception If there is any error
  1491. */
  1492. public function delete_records_subquery(string $table, string $field, string $alias, string $subquery, array $params = []): void {
  1493. // Aliases mysql_deltable and mysql_subquery are chosen to be unlikely to conflict.
  1494. $this->execute("DELETE mysql_deltable FROM {" . $table . "} mysql_deltable JOIN " .
  1495. "($subquery) mysql_subquery ON mysql_subquery.$alias = mysql_deltable.$field", $params);
  1496. }
  1497. public function sql_cast_char2int($fieldname, $text=false) {
  1498. return ' CAST(' . $fieldname . ' AS SIGNED) ';
  1499. }
  1500. public function sql_cast_char2real($fieldname, $text=false) {
  1501. // Set to 65 (max mysql 5.5 precision) with 7 as scale
  1502. // because we must ensure at least 6 decimal positions
  1503. // per casting given that postgres is casting to that scale (::real::).
  1504. // Can be raised easily but that must be done in all DBs and tests.
  1505. return ' CAST(' . $fieldname . ' AS DECIMAL(65,7)) ';
  1506. }
  1507. public function sql_equal($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notequal = false) {
  1508. $equalop = $notequal ? '<>' : '=';
  1509. $collationinfo = explode('_', $this->get_dbcollation());
  1510. $bincollate = reset($collationinfo) . '_bin';
  1511. if ($casesensitive) {
  1512. // Current MySQL versions do not support case sensitive and accent insensitive.
  1513. return "$fieldname COLLATE $bincollate $equalop $param";
  1514. } else if ($accentsensitive) {
  1515. // Case insensitive and accent sensitive, we can force a binary comparison once all texts are using the same case.
  1516. return "LOWER($fieldname) COLLATE $bincollate $equalop LOWER($param)";
  1517. } else {
  1518. // Case insensitive and accent insensitive. All collations are that way, but utf8_bin.
  1519. $collation = '';
  1520. if ($this->get_dbcollation() == 'utf8_bin') {
  1521. $collation = 'COLLATE utf8_unicode_ci';
  1522. } else if ($this->get_dbcollation() == 'utf8mb4_bin') {
  1523. $collation = 'COLLATE utf8mb4_unicode_ci';
  1524. }
  1525. return "$fieldname $collation $equalop $param";
  1526. }
  1527. }
  1528. /**
  1529. * Returns 'LIKE' part of a query.
  1530. *
  1531. * Note that mysql does not support $casesensitive = true and $accentsensitive = false.
  1532. * More information in http://bugs.mysql.com/bug.php?id=19567.
  1533. *
  1534. * @param string $fieldname usually name of the table column
  1535. * @param string $param usually bound query parameter (?, :named)
  1536. * @param bool $casesensitive use case sensitive search
  1537. * @param bool $accensensitive use accent sensitive search (ignored if $casesensitive is true)
  1538. * @param bool $notlike true means "NOT LIKE"
  1539. * @param string $escapechar escape char for '%' and '_'
  1540. * @return string SQL code fragment
  1541. */
  1542. public function sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = '\\') {
  1543. if (strpos($param, '%') !== false) {
  1544. debugging('Potential SQL injection detected, sql_like() expects bound parameters (? or :named)');
  1545. }
  1546. $escapechar = $this->mysqli->real_escape_string($escapechar); // prevents problems with C-style escapes of enclosing '\'
  1547. $collationinfo = explode('_', $this->get_dbcollation());
  1548. $bincollate = reset($collationinfo) . '_bin';
  1549. $LIKE = $notlike ? 'NOT LIKE' : 'LIKE';
  1550. if ($casesensitive) {
  1551. // Current MySQL versions do not support case sensitive and accent insensitive.
  1552. return "$fieldname $LIKE $param COLLATE $bincollate ESCAPE '$escapechar'";
  1553. } else if ($accentsensitive) {
  1554. // Case insensitive and accent sensitive, we can force a binary comparison once all texts are using the same case.
  1555. return "LOWER($fieldname) $LIKE LOWER($param) COLLATE $bincollate ESCAPE '$escapechar'";
  1556. } else {
  1557. // Case insensitive and accent insensitive.
  1558. $collation = '';
  1559. if ($this->get_dbcollation() == 'utf8_bin') {
  1560. // Force a case insensitive comparison if using utf8_bin.
  1561. $collation = 'COLLATE utf8_unicode_ci';
  1562. } else if ($this->get_dbcollation() == 'utf8mb4_bin') {
  1563. // Force a case insensitive comparison if using utf8mb4_bin.
  1564. $collation = 'COLLATE utf8mb4_unicode_ci';
  1565. }
  1566. return "$fieldname $LIKE $param $collation ESCAPE '$escapechar'";
  1567. }
  1568. }
  1569. /**
  1570. * Returns the proper SQL to do CONCAT between the elements passed
  1571. * Can take many parameters
  1572. *
  1573. * @param string $str,... 1 or more fields/strings to concat
  1574. *
  1575. * @return string The concat sql
  1576. */
  1577. public function sql_concat() {
  1578. $arr = func_get_args();
  1579. $s = implode(', ', $arr);
  1580. if ($s === '') {
  1581. return "''";
  1582. }
  1583. return "CONCAT($s)";
  1584. }
  1585. /**
  1586. * Returns the proper SQL to do CONCAT between the elements passed
  1587. * with a given separator
  1588. *
  1589. * @param string $separator The string to use as the separator
  1590. * @param array $elements An array of items to concatenate
  1591. * @return string The concat SQL
  1592. */
  1593. public function sql_concat_join($separator="' '", $elements=array()) {
  1594. $s = implode(', ', $elements);
  1595. if ($s === '') {
  1596. return "''";
  1597. }
  1598. return "CONCAT_WS($separator, $s)";
  1599. }
  1600. /**
  1601. * Return SQL for performing group concatenation on given field/expression
  1602. *
  1603. * @param string $field
  1604. * @param string $separator
  1605. * @param string $sort
  1606. * @return string
  1607. */
  1608. public function sql_group_concat(string $field, string $separator = ', ', string $sort = ''): string {
  1609. $fieldsort = $sort ? "ORDER BY {$sort}" : '';
  1610. return "GROUP_CONCAT({$field} {$fieldsort} SEPARATOR '{$separator}')";
  1611. }
  1612. /**
  1613. * Returns the SQL text to be used to calculate the length in characters of one expression.
  1614. * @param string fieldname or expression to calculate its length in characters.
  1615. * @return string the piece of SQL code to be used in the statement.
  1616. */
  1617. public function sql_length($fieldname) {
  1618. return ' CHAR_LENGTH(' . $fieldname . ')';
  1619. }
  1620. /**
  1621. * Does this driver support regex syntax when searching
  1622. */
  1623. public function sql_regex_supported() {
  1624. return true;
  1625. }
  1626. /**
  1627. * Return regex positive or negative match sql
  1628. * @param bool $positivematch
  1629. * @param bool $casesensitive
  1630. * @return string or empty if not supported
  1631. */
  1632. public function sql_regex($positivematch = true, $casesensitive = false) {
  1633. $collation = '';
  1634. if ($casesensitive) {
  1635. if (substr($this->get_dbcollation(), -4) !== '_bin') {
  1636. $collationinfo = explode('_', $this->get_dbcollation());
  1637. $collation = 'COLLATE ' . $collationinfo[0] . '_bin ';
  1638. }
  1639. } else {
  1640. if ($this->get_dbcollation() == 'utf8_bin') {
  1641. $collation = 'COLLATE utf8_unicode_ci ';
  1642. } else if ($this->get_dbcollation() == 'utf8mb4_bin') {
  1643. $collation = 'COLLATE utf8mb4_unicode_ci ';
  1644. }
  1645. }
  1646. return $collation . ($positivematch ? 'REGEXP' : 'NOT REGEXP');
  1647. }
  1648. /**
  1649. * Returns the SQL to be used in order to an UNSIGNED INTEGER column to SIGNED.
  1650. *
  1651. * @deprecated since 2.3
  1652. * @param string $fieldname The name of the field to be cast
  1653. * @return string The piece of SQL code to be used in your statement.
  1654. */
  1655. public function sql_cast_2signed($fieldname) {
  1656. return ' CAST(' . $fieldname . ' AS SIGNED) ';
  1657. }
  1658. /**
  1659. * Returns the SQL that allows to find intersection of two or more queries
  1660. *
  1661. * @since Moodle 2.8
  1662. *
  1663. * @param array $selects array of SQL select queries, each of them only returns fields with the names from $fields
  1664. * @param string $fields comma-separated list of fields
  1665. * @return string SQL query that will return only values that are present in each of selects
  1666. */
  1667. public function sql_intersect($selects, $fields) {
  1668. if (count($selects) <= 1) {
  1669. return parent::sql_intersect($selects, $fields);
  1670. }
  1671. $fields = preg_replace('/\s/', '', $fields);
  1672. static $aliascnt = 0;
  1673. $falias = 'intsctal'.($aliascnt++);
  1674. $rv = "SELECT $falias.".
  1675. preg_replace('/,/', ','.$falias.'.', $fields).
  1676. " FROM ($selects[0]) $falias";
  1677. for ($i = 1; $i < count($selects); $i++) {
  1678. $alias = 'intsctal'.($aliascnt++);
  1679. $rv .= " JOIN (".$selects[$i].") $alias ON ".
  1680. join(' AND ',
  1681. array_map(
  1682. function($a) use ($alias, $falias) {
  1683. return $falias . '.' . $a .' = ' . $alias . '.' . $a;
  1684. },
  1685. preg_split('/,/', $fields))
  1686. );
  1687. }
  1688. return $rv;
  1689. }
  1690. /**
  1691. * Does this driver support tool_replace?
  1692. *
  1693. * @since Moodle 2.6.1
  1694. * @return bool
  1695. */
  1696. public function replace_all_text_supported() {
  1697. return true;
  1698. }
  1699. public function session_lock_supported() {
  1700. return true;
  1701. }
  1702. /**
  1703. * Obtain session lock
  1704. * @param int $rowid id of the row with session record
  1705. * @param int $timeout max allowed time to wait for the lock in seconds
  1706. * @return void
  1707. */
  1708. public function get_session_lock($rowid, $timeout) {
  1709. parent::get_session_lock($rowid, $timeout);
  1710. $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid;
  1711. $sql = "SELECT GET_LOCK('$fullname', $timeout)";
  1712. $this->query_start($sql, null, SQL_QUERY_AUX);
  1713. $result = $this->mysqli->query($sql);
  1714. $this->query_end($result);
  1715. if ($result) {
  1716. $arr = $result->fetch_assoc();
  1717. $result->close();
  1718. if (reset($arr) == 1) {
  1719. return;
  1720. } else {
  1721. throw new dml_sessionwait_exception();
  1722. }
  1723. }
  1724. }
  1725. public function release_session_lock($rowid) {
  1726. if (!$this->used_for_db_sessions) {
  1727. return;
  1728. }
  1729. parent::release_session_lock($rowid);
  1730. $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid;
  1731. $sql = "SELECT RELEASE_LOCK('$fullname')";
  1732. $this->query_start($sql, null, SQL_QUERY_AUX);
  1733. $result = $this->mysqli->query($sql);
  1734. $this->query_end($result);
  1735. if ($result) {
  1736. $result->close();
  1737. }
  1738. }
  1739. /**
  1740. * Are transactions supported?
  1741. * It is not responsible to run productions servers
  1742. * on databases without transaction support ;-)
  1743. *
  1744. * MyISAM does not support support transactions.
  1745. *
  1746. * You can override this via the dbtransactions option.
  1747. *
  1748. * @return bool
  1749. */
  1750. protected function transactions_supported() {
  1751. if (!is_null($this->transactions_supported)) {
  1752. return $this->transactions_supported;
  1753. }
  1754. // this is all just guessing, might be better to just specify it in config.php
  1755. if (isset($this->dboptions['dbtransactions'])) {
  1756. $this->transactions_supported = $this->dboptions['dbtransactions'];
  1757. return $this->transactions_supported;
  1758. }
  1759. $this->transactions_supported = false;
  1760. $engine = $this->get_dbengine();
  1761. // Only will accept transactions if using compatible storage engine (more engines can be added easily BDB, Falcon...)
  1762. if (in_array($engine, array('InnoDB', 'INNOBASE', 'BDB', 'XtraDB', 'Aria', 'Falcon'))) {
  1763. $this->transactions_supported = true;
  1764. }
  1765. return $this->transactions_supported;
  1766. }
  1767. /**
  1768. * Driver specific start of real database transaction,
  1769. * this can not be used directly in code.
  1770. * @return void
  1771. */
  1772. protected function begin_transaction() {
  1773. if (!$this->transactions_supported()) {
  1774. return;
  1775. }
  1776. $sql = "SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED";
  1777. $this->query_start($sql, NULL, SQL_QUERY_AUX);
  1778. $result = $this->mysqli->query($sql);
  1779. $this->query_end($result);
  1780. $sql = "START TRANSACTION";
  1781. $this->query_start($sql, NULL, SQL_QUERY_AUX);
  1782. $result = $this->mysqli->query($sql);
  1783. $this->query_end($result);
  1784. }
  1785. /**
  1786. * Driver specific commit of real database transaction,
  1787. * this can not be used directly in code.
  1788. * @return void
  1789. */
  1790. protected function commit_transaction() {
  1791. if (!$this->transactions_supported()) {
  1792. return;
  1793. }
  1794. $sql = "COMMIT";
  1795. $this->query_start($sql, NULL, SQL_QUERY_AUX);
  1796. $result = $this->mysqli->query($sql);
  1797. $this->query_end($result);
  1798. }
  1799. /**
  1800. * Driver specific abort of real database transaction,
  1801. * this can not be used directly in code.
  1802. * @return void
  1803. */
  1804. protected function rollback_transaction() {
  1805. if (!$this->transactions_supported()) {
  1806. return;
  1807. }
  1808. $sql = "ROLLBACK";
  1809. $this->query_start($sql, NULL, SQL_QUERY_AUX);
  1810. $result = $this->mysqli->query($sql);
  1811. $this->query_end($result);
  1812. return true;
  1813. }
  1814. /**
  1815. * Converts a table to either 'Compressed' or 'Dynamic' row format.
  1816. *
  1817. * @param string $tablename Name of the table to convert to the new row format.
  1818. */
  1819. public function convert_table_row_format($tablename) {
  1820. $currentrowformat = $this->get_row_format($tablename);
  1821. if ($currentrowformat == 'Compact' || $currentrowformat == 'Redundant') {
  1822. $rowformat = ($this->is_compressed_row_format_supported(false)) ? "ROW_FORMAT=Compressed" : "ROW_FORMAT=Dynamic";
  1823. $prefix = $this->get_prefix();
  1824. $this->change_database_structure("ALTER TABLE {$prefix}$tablename $rowformat");
  1825. }
  1826. }
  1827. /**
  1828. * Does this mysql instance support fulltext indexes?
  1829. *
  1830. * @return bool
  1831. */
  1832. public function is_fulltext_search_supported() {
  1833. $info = $this->get_server_info();
  1834. if (version_compare($info['version'], '5.6.4', '>=')) {
  1835. return true;
  1836. }
  1837. return false;
  1838. }
  1839. /**
  1840. * Fixes any table names that clash with reserved words.
  1841. *
  1842. * @param string $tablename The table name
  1843. * @return string The fixed table name
  1844. */
  1845. protected function fix_table_name($tablename) {
  1846. $prefixedtablename = parent::fix_table_name($tablename);
  1847. // This function quotes the table name if it matches one of the MySQL reserved
  1848. // words, e.g. groups.
  1849. return $this->get_manager()->generator->getEncQuoted($prefixedtablename);
  1850. }
  1851. }