PageRenderTime 29ms CodeModel.GetById 27ms RepoModel.GetById 1ms 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

Large files files are truncated, but you can click here to view the full file

  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

Large files files are truncated, but you can click here to view the full file