PageRenderTime 70ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/dml/oci_native_moodle_database.php

http://github.com/moodle/moodle
PHP | 1855 lines | 1227 code | 170 blank | 458 comment | 167 complexity | f6025ae2175e303ef60506d04a754d62 MD5 | raw file
Possible License(s): MIT, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, Apache-2.0, LGPL-2.1, BSD-3-Clause

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 oci 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__.'/oci_native_moodle_recordset.php');
  26. require_once(__DIR__.'/oci_native_moodle_temptables.php');
  27. /**
  28. * Native oci class representing moodle database interface.
  29. *
  30. * One complete reference for PHP + OCI:
  31. * http://www.oracle.com/technology/tech/php/underground-php-oracle-manual.html
  32. *
  33. * @package core_dml
  34. * @copyright 2008 Petr Skoda (http://skodak.org)
  35. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  36. */
  37. class oci_native_moodle_database extends moodle_database {
  38. protected $oci = null;
  39. /** @var To store stmt errors and enable get_last_error() to detect them.*/
  40. private $last_stmt_error = null;
  41. /** @var Default value initialised in connect method, we need the driver to be present.*/
  42. private $commit_status = null;
  43. /** @var To handle oci driver default verbosity.*/
  44. private $last_error_reporting;
  45. /** @var To store unique_session_id. Needed for temp tables unique naming.*/
  46. private $unique_session_id;
  47. /**
  48. * Detects if all needed PHP stuff installed.
  49. * Note: can be used before connect()
  50. * @return mixed true if ok, string if something
  51. */
  52. public function driver_installed() {
  53. if (!extension_loaded('oci8')) {
  54. return get_string('ociextensionisnotpresentinphp', 'install');
  55. }
  56. return true;
  57. }
  58. /**
  59. * Returns database family type - describes SQL dialect
  60. * Note: can be used before connect()
  61. * @return string db family name (mysql, postgres, mssql, oracle, etc.)
  62. */
  63. public function get_dbfamily() {
  64. return 'oracle';
  65. }
  66. /**
  67. * Returns more specific database driver type
  68. * Note: can be used before connect()
  69. * @return string db type mysqli, pgsql, oci, mssql, sqlsrv
  70. */
  71. protected function get_dbtype() {
  72. return 'oci';
  73. }
  74. /**
  75. * Returns general database library name
  76. * Note: can be used before connect()
  77. * @return string db type pdo, native
  78. */
  79. protected function get_dblibrary() {
  80. return 'native';
  81. }
  82. /**
  83. * Returns localised database type name
  84. * Note: can be used before connect()
  85. * @return string
  86. */
  87. public function get_name() {
  88. return get_string('nativeoci', 'install');
  89. }
  90. /**
  91. * Returns localised database configuration help.
  92. * Note: can be used before connect()
  93. * @return string
  94. */
  95. public function get_configuration_help() {
  96. return get_string('nativeocihelp', 'install');
  97. }
  98. /**
  99. * Diagnose database and tables, this function is used
  100. * to verify database and driver settings, db engine types, etc.
  101. *
  102. * @return string null means everything ok, string means problem found.
  103. */
  104. public function diagnose() {
  105. return null;
  106. }
  107. /**
  108. * Connect to db
  109. * Must be called before other methods.
  110. * @param string $dbhost The database host.
  111. * @param string $dbuser The database username.
  112. * @param string $dbpass The database username's password.
  113. * @param string $dbname The name of the database being connected to.
  114. * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
  115. * @param array $dboptions driver specific options
  116. * @return bool true
  117. * @throws dml_connection_exception if error
  118. */
  119. public function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null) {
  120. if ($prefix == '' and !$this->external) {
  121. //Enforce prefixes for everybody but mysql
  122. throw new dml_exception('prefixcannotbeempty', $this->get_dbfamily());
  123. }
  124. if (!$this->external and strlen($prefix) > 2) {
  125. //Max prefix length for Oracle is 2cc
  126. $a = (object)array('dbfamily'=>'oracle', 'maxlength'=>2);
  127. throw new dml_exception('prefixtoolong', $a);
  128. }
  129. $driverstatus = $this->driver_installed();
  130. if ($driverstatus !== true) {
  131. throw new dml_exception('dbdriverproblem', $driverstatus);
  132. }
  133. // Autocommit ON by default.
  134. // Switching to OFF (OCI_DEFAULT), when playing with transactions
  135. // please note this thing is not defined if oracle driver not present in PHP
  136. // which means it can not be used as default value of object property!
  137. $this->commit_status = OCI_COMMIT_ON_SUCCESS;
  138. $this->store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions);
  139. unset($this->dboptions['dbsocket']);
  140. // NOTE: use of ', ", / and \ is very problematic, even native oracle tools seem to have
  141. // problems with these, so just forget them and do not report problems into tracker...
  142. if (empty($this->dbhost)) {
  143. // old style full address (TNS)
  144. $dbstring = $this->dbname;
  145. } else {
  146. if (empty($this->dboptions['dbport'])) {
  147. $this->dboptions['dbport'] = 1521;
  148. }
  149. $dbstring = '//'.$this->dbhost.':'.$this->dboptions['dbport'].'/'.$this->dbname;
  150. }
  151. ob_start();
  152. if (empty($this->dboptions['dbpersist'])) {
  153. $this->oci = oci_new_connect($this->dbuser, $this->dbpass, $dbstring, 'AL32UTF8');
  154. } else {
  155. $this->oci = oci_pconnect($this->dbuser, $this->dbpass, $dbstring, 'AL32UTF8');
  156. }
  157. $dberr = ob_get_contents();
  158. ob_end_clean();
  159. if ($this->oci === false) {
  160. $this->oci = null;
  161. $e = oci_error();
  162. if (isset($e['message'])) {
  163. $dberr = $e['message'];
  164. }
  165. throw new dml_connection_exception($dberr);
  166. }
  167. // Disable logging until we are fully setup.
  168. $this->query_log_prevent();
  169. // Make sure moodle package is installed - now required.
  170. if (!$this->oci_package_installed()) {
  171. try {
  172. $this->attempt_oci_package_install();
  173. } catch (Exception $e) {
  174. // Ignore problems, only the result counts,
  175. // admins have to fix it manually if necessary.
  176. }
  177. if (!$this->oci_package_installed()) {
  178. throw new dml_exception('dbdriverproblem', 'Oracle PL/SQL Moodle support package MOODLELIB is not installed! Database administrator has to execute /lib/dml/oci_native_moodle_package.sql script.');
  179. }
  180. }
  181. // get unique session id, to be used later for temp tables stuff
  182. $sql = 'SELECT DBMS_SESSION.UNIQUE_SESSION_ID() FROM DUAL';
  183. $this->query_start($sql, null, SQL_QUERY_AUX);
  184. $stmt = $this->parse_query($sql);
  185. $result = oci_execute($stmt, $this->commit_status);
  186. $this->query_end($result, $stmt);
  187. $records = null;
  188. oci_fetch_all($stmt, $records, 0, -1, OCI_FETCHSTATEMENT_BY_ROW);
  189. oci_free_statement($stmt);
  190. $this->unique_session_id = reset($records[0]);
  191. //note: do not send "ALTER SESSION SET NLS_NUMERIC_CHARACTERS='.,'" !
  192. // instead fix our PHP code to convert "," to "." properly!
  193. // We can enable logging now.
  194. $this->query_log_allow();
  195. // Connection stabilised and configured, going to instantiate the temptables controller
  196. $this->temptables = new oci_native_moodle_temptables($this, $this->unique_session_id);
  197. return true;
  198. }
  199. /**
  200. * Close database connection and release all resources
  201. * and memory (especially circular memory references).
  202. * Do NOT use connect() again, create a new instance if needed.
  203. */
  204. public function dispose() {
  205. parent::dispose(); // Call parent dispose to write/close session and other common stuff before closing connection
  206. if ($this->oci) {
  207. oci_close($this->oci);
  208. $this->oci = null;
  209. }
  210. }
  211. /**
  212. * Called before each db query.
  213. * @param string $sql
  214. * @param array array of parameters
  215. * @param int $type type of query
  216. * @param mixed $extrainfo driver specific extra information
  217. * @return void
  218. */
  219. protected function query_start($sql, array $params=null, $type, $extrainfo=null) {
  220. parent::query_start($sql, $params, $type, $extrainfo);
  221. // oci driver tents to send debug to output, we do not need that ;-)
  222. $this->last_error_reporting = error_reporting(0);
  223. }
  224. /**
  225. * Called immediately after each db query.
  226. * @param mixed db specific result
  227. * @return void
  228. */
  229. protected function query_end($result, $stmt=null) {
  230. // reset original debug level
  231. error_reporting($this->last_error_reporting);
  232. if ($stmt and $result === false) {
  233. // Look for stmt error and store it
  234. if (is_resource($stmt)) {
  235. $e = oci_error($stmt);
  236. if ($e !== false) {
  237. $this->last_stmt_error = $e['message'];
  238. }
  239. }
  240. oci_free_statement($stmt);
  241. }
  242. parent::query_end($result);
  243. }
  244. /**
  245. * Returns database server info array
  246. * @return array Array containing 'description' and 'version' info
  247. */
  248. public function get_server_info() {
  249. static $info = null; // TODO: move to real object property
  250. if (is_null($info)) {
  251. $this->query_start("--oci_server_version()", null, SQL_QUERY_AUX);
  252. $description = oci_server_version($this->oci);
  253. $this->query_end(true);
  254. preg_match('/(\d+\.)+\d+/', $description, $matches);
  255. $info = array('description'=>$description, 'version'=>$matches[0]);
  256. }
  257. return $info;
  258. }
  259. /**
  260. * Converts short table name {tablename} to real table name
  261. * supporting temp tables ($this->unique_session_id based) if detected
  262. *
  263. * @param string sql
  264. * @return string sql
  265. */
  266. protected function fix_table_names($sql) {
  267. if (preg_match_all('/\{([a-z][a-z0-9_]*)\}/', $sql, $matches)) {
  268. foreach($matches[0] as $key=>$match) {
  269. $name = $matches[1][$key];
  270. if ($this->temptables && $this->temptables->is_temptable($name)) {
  271. $sql = str_replace($match, $this->temptables->get_correct_name($name), $sql);
  272. } else {
  273. $sql = str_replace($match, $this->prefix.$name, $sql);
  274. }
  275. }
  276. }
  277. return $sql;
  278. }
  279. /**
  280. * Returns supported query parameter types
  281. * @return int bitmask of accepted SQL_PARAMS_*
  282. */
  283. protected function allowed_param_types() {
  284. return SQL_PARAMS_NAMED;
  285. }
  286. /**
  287. * Returns last error reported by database engine.
  288. * @return string error message
  289. */
  290. public function get_last_error() {
  291. $error = false;
  292. // First look for any previously saved stmt error
  293. if (!empty($this->last_stmt_error)) {
  294. $error = $this->last_stmt_error;
  295. $this->last_stmt_error = null;
  296. } else { // Now try connection error
  297. $e = oci_error($this->oci);
  298. if ($e !== false) {
  299. $error = $e['message'];
  300. }
  301. }
  302. return $error;
  303. }
  304. /**
  305. * Prepare the statement for execution
  306. * @throws dml_connection_exception
  307. * @param string $sql
  308. * @return resource
  309. */
  310. protected function parse_query($sql) {
  311. $stmt = oci_parse($this->oci, $sql);
  312. if ($stmt == false) {
  313. throw new dml_connection_exception('Can not parse sql query'); //TODO: maybe add better info
  314. }
  315. return $stmt;
  316. }
  317. /**
  318. * Make sure there are no reserved words in param names...
  319. * @param string $sql
  320. * @param array $params
  321. * @return array ($sql, $params) updated query and parameters
  322. */
  323. protected function tweak_param_names($sql, array $params) {
  324. if (empty($params)) {
  325. return array($sql, $params);
  326. }
  327. $newparams = array();
  328. $searcharr = array(); // search => replace pairs
  329. foreach ($params as $name => $value) {
  330. // Keep the name within the 30 chars limit always (prefixing/replacing)
  331. if (strlen($name) <= 28) {
  332. $newname = 'o_' . $name;
  333. } else {
  334. $newname = 'o_' . substr($name, 2);
  335. }
  336. $newparams[$newname] = $value;
  337. $searcharr[':' . $name] = ':' . $newname;
  338. }
  339. // sort by length desc to avoid potential str_replace() overlap
  340. uksort($searcharr, array('oci_native_moodle_database', 'compare_by_length_desc'));
  341. $sql = str_replace(array_keys($searcharr), $searcharr, $sql);
  342. return array($sql, $newparams);
  343. }
  344. /**
  345. * Return tables in database WITHOUT current prefix
  346. * @param bool $usecache if true, returns list of cached tables.
  347. * @return array of table names in lowercase and without prefix
  348. */
  349. public function get_tables($usecache=true) {
  350. if ($usecache and $this->tables !== null) {
  351. return $this->tables;
  352. }
  353. $this->tables = array();
  354. $prefix = str_replace('_', "\\_", strtoupper($this->prefix));
  355. $sql = "SELECT TABLE_NAME
  356. FROM CAT
  357. WHERE TABLE_TYPE='TABLE'
  358. AND TABLE_NAME NOT LIKE 'BIN\$%'
  359. AND TABLE_NAME LIKE '$prefix%' ESCAPE '\\'";
  360. $this->query_start($sql, null, SQL_QUERY_AUX);
  361. $stmt = $this->parse_query($sql);
  362. $result = oci_execute($stmt, $this->commit_status);
  363. $this->query_end($result, $stmt);
  364. $records = null;
  365. oci_fetch_all($stmt, $records, 0, -1, OCI_ASSOC);
  366. oci_free_statement($stmt);
  367. $records = array_map('strtolower', $records['TABLE_NAME']);
  368. foreach ($records as $tablename) {
  369. if ($this->prefix !== false && $this->prefix !== '') {
  370. if (strpos($tablename, $this->prefix) !== 0) {
  371. continue;
  372. }
  373. $tablename = substr($tablename, strlen($this->prefix));
  374. }
  375. $this->tables[$tablename] = $tablename;
  376. }
  377. // Add the currently available temptables
  378. $this->tables = array_merge($this->tables, $this->temptables->get_temptables());
  379. return $this->tables;
  380. }
  381. /**
  382. * Return table indexes - everything lowercased.
  383. * @param string $table The table we want to get indexes from.
  384. * @return array An associative array of indexes containing 'unique' flag and 'columns' being indexed
  385. */
  386. public function get_indexes($table) {
  387. $indexes = array();
  388. $tablename = strtoupper($this->prefix.$table);
  389. $sql = "SELECT i.INDEX_NAME, i.UNIQUENESS, c.COLUMN_POSITION, c.COLUMN_NAME, ac.CONSTRAINT_TYPE
  390. FROM ALL_INDEXES i
  391. JOIN ALL_IND_COLUMNS c ON c.INDEX_NAME=i.INDEX_NAME
  392. LEFT JOIN ALL_CONSTRAINTS ac ON (ac.TABLE_NAME=i.TABLE_NAME AND ac.CONSTRAINT_NAME=i.INDEX_NAME AND ac.CONSTRAINT_TYPE='P')
  393. WHERE i.TABLE_NAME = '$tablename'
  394. ORDER BY i.INDEX_NAME, c.COLUMN_POSITION";
  395. $stmt = $this->parse_query($sql);
  396. $result = oci_execute($stmt, $this->commit_status);
  397. $this->query_end($result, $stmt);
  398. $records = null;
  399. oci_fetch_all($stmt, $records, 0, -1, OCI_FETCHSTATEMENT_BY_ROW);
  400. oci_free_statement($stmt);
  401. foreach ($records as $record) {
  402. if ($record['CONSTRAINT_TYPE'] === 'P') {
  403. //ignore for now;
  404. continue;
  405. }
  406. $indexname = strtolower($record['INDEX_NAME']);
  407. if (!isset($indexes[$indexname])) {
  408. $indexes[$indexname] = array('primary' => ($record['CONSTRAINT_TYPE'] === 'P'),
  409. 'unique' => ($record['UNIQUENESS'] === 'UNIQUE'),
  410. 'columns' => array());
  411. }
  412. $indexes[$indexname]['columns'][] = strtolower($record['COLUMN_NAME']);
  413. }
  414. return $indexes;
  415. }
  416. /**
  417. * Fetches detailed information about columns in table.
  418. *
  419. * @param string $table name
  420. * @return array array of database_column_info objects indexed with column names
  421. */
  422. protected function fetch_columns(string $table): array {
  423. $structure = array();
  424. // We give precedence to CHAR_LENGTH for VARCHAR2 columns over WIDTH because the former is always
  425. // BYTE based and, for cross-db operations, we want CHAR based results. See MDL-29415
  426. // Instead of guessing sequence based exclusively on name, check tables against user_triggers to
  427. // ensure the table has a 'before each row' trigger to assume 'id' is auto_increment. MDL-32365
  428. $sql = "SELECT CNAME, COLTYPE, nvl(CHAR_LENGTH, WIDTH) AS WIDTH, SCALE, PRECISION, NULLS, DEFAULTVAL,
  429. DECODE(NVL(TRIGGER_NAME, '0'), '0', '0', '1') HASTRIGGER
  430. FROM COL c
  431. LEFT JOIN USER_TAB_COLUMNS u ON (u.TABLE_NAME = c.TNAME AND u.COLUMN_NAME = c.CNAME AND u.DATA_TYPE = 'VARCHAR2')
  432. LEFT JOIN USER_TRIGGERS t ON (t.TABLE_NAME = c.TNAME AND TRIGGER_TYPE = 'BEFORE EACH ROW' AND c.CNAME = 'ID')
  433. WHERE TNAME = UPPER('{" . $table . "}')
  434. ORDER BY COLNO";
  435. list($sql, $params, $type) = $this->fix_sql_params($sql, null);
  436. $this->query_start($sql, null, SQL_QUERY_AUX);
  437. $stmt = $this->parse_query($sql);
  438. $result = oci_execute($stmt, $this->commit_status);
  439. $this->query_end($result, $stmt);
  440. $records = null;
  441. oci_fetch_all($stmt, $records, 0, -1, OCI_FETCHSTATEMENT_BY_ROW);
  442. oci_free_statement($stmt);
  443. if (!$records) {
  444. return array();
  445. }
  446. foreach ($records as $rawcolumn) {
  447. $rawcolumn = (object)$rawcolumn;
  448. $info = new stdClass();
  449. $info->name = strtolower($rawcolumn->CNAME);
  450. $info->auto_increment = ((int)$rawcolumn->HASTRIGGER) ? true : false;
  451. $matches = null;
  452. if ($rawcolumn->COLTYPE === 'VARCHAR2'
  453. or $rawcolumn->COLTYPE === 'VARCHAR'
  454. or $rawcolumn->COLTYPE === 'NVARCHAR2'
  455. or $rawcolumn->COLTYPE === 'NVARCHAR'
  456. or $rawcolumn->COLTYPE === 'CHAR'
  457. or $rawcolumn->COLTYPE === 'NCHAR') {
  458. $info->type = $rawcolumn->COLTYPE;
  459. $info->meta_type = 'C';
  460. $info->max_length = $rawcolumn->WIDTH;
  461. $info->scale = null;
  462. $info->not_null = ($rawcolumn->NULLS === 'NOT NULL');
  463. $info->has_default = !is_null($rawcolumn->DEFAULTVAL);
  464. if ($info->has_default) {
  465. // this is hacky :-(
  466. if ($rawcolumn->DEFAULTVAL === 'NULL') {
  467. $info->default_value = null;
  468. } else if ($rawcolumn->DEFAULTVAL === "' ' ") { // Sometimes it's stored with trailing space
  469. $info->default_value = "";
  470. } else if ($rawcolumn->DEFAULTVAL === "' '") { // Sometimes it's stored without trailing space
  471. $info->default_value = "";
  472. } else {
  473. $info->default_value = trim($rawcolumn->DEFAULTVAL); // remove trailing space
  474. $info->default_value = substr($info->default_value, 1, strlen($info->default_value)-2); //trim ''
  475. }
  476. } else {
  477. $info->default_value = null;
  478. }
  479. $info->primary_key = false;
  480. $info->binary = false;
  481. $info->unsigned = null;
  482. $info->unique = null;
  483. } else if ($rawcolumn->COLTYPE === 'NUMBER') {
  484. $info->type = $rawcolumn->COLTYPE;
  485. $info->max_length = $rawcolumn->PRECISION;
  486. $info->binary = false;
  487. if (!is_null($rawcolumn->SCALE) && $rawcolumn->SCALE == 0) { // null in oracle scale allows decimals => not integer
  488. // integer
  489. if ($info->name === 'id') {
  490. $info->primary_key = true;
  491. $info->meta_type = 'R';
  492. $info->unique = true;
  493. $info->has_default = false;
  494. } else {
  495. $info->primary_key = false;
  496. $info->meta_type = 'I';
  497. $info->unique = null;
  498. }
  499. $info->scale = 0;
  500. } else {
  501. //float
  502. $info->meta_type = 'N';
  503. $info->primary_key = false;
  504. $info->unsigned = null;
  505. $info->unique = null;
  506. $info->scale = $rawcolumn->SCALE;
  507. }
  508. $info->not_null = ($rawcolumn->NULLS === 'NOT NULL');
  509. $info->has_default = !is_null($rawcolumn->DEFAULTVAL);
  510. if ($info->has_default) {
  511. $info->default_value = trim($rawcolumn->DEFAULTVAL); // remove trailing space
  512. } else {
  513. $info->default_value = null;
  514. }
  515. } else if ($rawcolumn->COLTYPE === 'FLOAT') {
  516. $info->type = $rawcolumn->COLTYPE;
  517. $info->max_length = (int)($rawcolumn->PRECISION * 3.32193);
  518. $info->primary_key = false;
  519. $info->meta_type = 'N';
  520. $info->unique = null;
  521. $info->not_null = ($rawcolumn->NULLS === 'NOT NULL');
  522. $info->has_default = !is_null($rawcolumn->DEFAULTVAL);
  523. if ($info->has_default) {
  524. $info->default_value = trim($rawcolumn->DEFAULTVAL); // remove trailing space
  525. } else {
  526. $info->default_value = null;
  527. }
  528. } else if ($rawcolumn->COLTYPE === 'CLOB'
  529. or $rawcolumn->COLTYPE === 'NCLOB') {
  530. $info->type = $rawcolumn->COLTYPE;
  531. $info->meta_type = 'X';
  532. $info->max_length = -1;
  533. $info->scale = null;
  534. $info->scale = null;
  535. $info->not_null = ($rawcolumn->NULLS === 'NOT NULL');
  536. $info->has_default = !is_null($rawcolumn->DEFAULTVAL);
  537. if ($info->has_default) {
  538. // this is hacky :-(
  539. if ($rawcolumn->DEFAULTVAL === 'NULL') {
  540. $info->default_value = null;
  541. } else if ($rawcolumn->DEFAULTVAL === "' ' ") { // Sometimes it's stored with trailing space
  542. $info->default_value = "";
  543. } else if ($rawcolumn->DEFAULTVAL === "' '") { // Other times it's stored without trailing space
  544. $info->default_value = "";
  545. } else {
  546. $info->default_value = trim($rawcolumn->DEFAULTVAL); // remove trailing space
  547. $info->default_value = substr($info->default_value, 1, strlen($info->default_value)-2); //trim ''
  548. }
  549. } else {
  550. $info->default_value = null;
  551. }
  552. $info->primary_key = false;
  553. $info->binary = false;
  554. $info->unsigned = null;
  555. $info->unique = null;
  556. } else if ($rawcolumn->COLTYPE === 'BLOB') {
  557. $info->type = $rawcolumn->COLTYPE;
  558. $info->meta_type = 'B';
  559. $info->max_length = -1;
  560. $info->scale = null;
  561. $info->scale = null;
  562. $info->not_null = ($rawcolumn->NULLS === 'NOT NULL');
  563. $info->has_default = !is_null($rawcolumn->DEFAULTVAL);
  564. if ($info->has_default) {
  565. // this is hacky :-(
  566. if ($rawcolumn->DEFAULTVAL === 'NULL') {
  567. $info->default_value = null;
  568. } else if ($rawcolumn->DEFAULTVAL === "' ' ") { // Sometimes it's stored with trailing space
  569. $info->default_value = "";
  570. } else if ($rawcolumn->DEFAULTVAL === "' '") { // Sometimes it's stored without trailing space
  571. $info->default_value = "";
  572. } else {
  573. $info->default_value = trim($rawcolumn->DEFAULTVAL); // remove trailing space
  574. $info->default_value = substr($info->default_value, 1, strlen($info->default_value)-2); //trim ''
  575. }
  576. } else {
  577. $info->default_value = null;
  578. }
  579. $info->primary_key = false;
  580. $info->binary = true;
  581. $info->unsigned = null;
  582. $info->unique = null;
  583. } else {
  584. // unknown type - sorry
  585. $info->type = $rawcolumn->COLTYPE;
  586. $info->meta_type = '?';
  587. }
  588. $structure[$info->name] = new database_column_info($info);
  589. }
  590. return $structure;
  591. }
  592. /**
  593. * Normalise values based in RDBMS dependencies (booleans, LOBs...)
  594. *
  595. * @param database_column_info $column column metadata corresponding with the value we are going to normalise
  596. * @param mixed $value value we are going to normalise
  597. * @return mixed the normalised value
  598. */
  599. protected function normalise_value($column, $value) {
  600. $this->detect_objects($value);
  601. if (is_bool($value)) { // Always, convert boolean to int
  602. $value = (int)$value;
  603. } else if ($column->meta_type == 'B') { // BLOB detected, we return 'blob' array instead of raw value to allow
  604. if (!is_null($value)) { // binding/executing code later to know about its nature
  605. $value = array('blob' => $value);
  606. }
  607. } else if ($column->meta_type == 'X' && strlen($value) > 4000) { // CLOB detected (>4000 optimisation), we return 'clob'
  608. if (!is_null($value)) { // array instead of raw value to allow binding/
  609. $value = array('clob' => (string)$value); // executing code later to know about its nature
  610. }
  611. } else if ($value === '') {
  612. if ($column->meta_type == 'I' or $column->meta_type == 'F' or $column->meta_type == 'N') {
  613. $value = 0; // prevent '' problems in numeric fields
  614. }
  615. }
  616. return $value;
  617. }
  618. /**
  619. * Transforms the sql and params in order to emulate the LIMIT clause available in other DBs
  620. *
  621. * @param string $sql the SQL select query to execute.
  622. * @param array $params array of sql parameters
  623. * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
  624. * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
  625. * @return array with the transformed sql and params updated
  626. */
  627. private function get_limit_sql($sql, array $params = null, $limitfrom=0, $limitnum=0) {
  628. list($limitfrom, $limitnum) = $this->normalise_limit_from_num($limitfrom, $limitnum);
  629. // TODO: Add the /*+ FIRST_ROWS */ hint if there isn't another hint
  630. if ($limitfrom and $limitnum) {
  631. $sql = "SELECT oracle_o.*
  632. FROM (SELECT oracle_i.*, rownum AS oracle_rownum
  633. FROM ($sql) oracle_i
  634. WHERE rownum <= :oracle_num_rows
  635. ) oracle_o
  636. WHERE oracle_rownum > :oracle_skip_rows";
  637. $params['oracle_num_rows'] = $limitfrom + $limitnum;
  638. $params['oracle_skip_rows'] = $limitfrom;
  639. } else if ($limitfrom and !$limitnum) {
  640. $sql = "SELECT oracle_o.*
  641. FROM (SELECT oracle_i.*, rownum AS oracle_rownum
  642. FROM ($sql) oracle_i
  643. ) oracle_o
  644. WHERE oracle_rownum > :oracle_skip_rows";
  645. $params['oracle_skip_rows'] = $limitfrom;
  646. } else if (!$limitfrom and $limitnum) {
  647. $sql = "SELECT *
  648. FROM ($sql)
  649. WHERE rownum <= :oracle_num_rows";
  650. $params['oracle_num_rows'] = $limitnum;
  651. }
  652. return array($sql, $params);
  653. }
  654. /**
  655. * This function will handle all the column values before being inserted/updated to DB for Oracle
  656. * installations. This is because the "special feature" of Oracle where the empty string is
  657. * equal to NULL and this presents a problem with all our currently NOT NULL default '' fields.
  658. * (and with empties handling in general)
  659. *
  660. * Note that this function is 100% private and should be used, exclusively by DML functions
  661. * in this file. Also, this is considered a DIRTY HACK to be removed when possible.
  662. *
  663. * This function is private and must not be used outside this driver at all
  664. *
  665. * @param $table string the table where the record is going to be inserted/updated (without prefix)
  666. * @param $field string the field where the record is going to be inserted/updated
  667. * @param $value mixed the value to be inserted/updated
  668. */
  669. private function oracle_dirty_hack ($table, $field, $value) {
  670. // General bound parameter, just hack the spaces and pray it will work.
  671. if (!$table) {
  672. if ($value === '') {
  673. return ' ';
  674. } else if (is_bool($value)) {
  675. return (int)$value;
  676. } else {
  677. return $value;
  678. }
  679. }
  680. // Get metadata
  681. $columns = $this->get_columns($table);
  682. if (!isset($columns[$field])) {
  683. if ($value === '') {
  684. return ' ';
  685. } else if (is_bool($value)) {
  686. return (int)$value;
  687. } else {
  688. return $value;
  689. }
  690. }
  691. $column = $columns[$field];
  692. // !! This paragraph explains behaviour before Moodle 2.0:
  693. //
  694. // For Oracle DB, empty strings are converted to NULLs in DB
  695. // and this breaks a lot of NOT NULL columns currently Moodle. In the future it's
  696. // planned to move some of them to NULL, if they must accept empty values and this
  697. // piece of code will become less and less used. But, for now, we need it.
  698. // What we are going to do is to examine all the data being inserted and if it's
  699. // an empty string (NULL for Oracle) and the field is defined as NOT NULL, we'll modify
  700. // such data in the best form possible ("0" for booleans and numbers and " " for the
  701. // rest of strings. It isn't optimal, but the only way to do so.
  702. // In the opposite, when retrieving records from Oracle, we'll decode " " back to
  703. // empty strings to allow everything to work properly. DIRTY HACK.
  704. // !! These paragraphs explain the rationale about the change for Moodle 2.5:
  705. //
  706. // Before Moodle 2.0, we only used to apply this DIRTY HACK to NOT NULL columns, as
  707. // stated above, but it causes one problem in NULL columns where both empty strings
  708. // and real NULLs are stored as NULLs, being impossible to differentiate them when
  709. // being retrieved from DB.
  710. //
  711. // So, starting with Moodle 2.0, we are going to apply the DIRTY HACK to all the
  712. // CHAR/CLOB columns no matter of their nullability. That way, when retrieving
  713. // NULLABLE fields we'll get proper empties and NULLs differentiated, so we'll be able
  714. // to rely in NULL/empty/content contents without problems, until now that wasn't
  715. // possible at all.
  716. //
  717. // One space DIRTY HACK is now applied automatically for all query parameters
  718. // and results. The only problem is string concatenation where the glue must
  719. // be specified as "' '" sql fragment.
  720. //
  721. // !! Conclusions:
  722. //
  723. // From Moodle 2.5 onwards, ALL empty strings in Oracle DBs will be stored as
  724. // 1-whitespace char, ALL NULLs as NULLs and, obviously, content as content. And
  725. // those 1-whitespace chars will be converted back to empty strings by all the
  726. // get_field/record/set() functions transparently and any SQL needing direct handling
  727. // of empties will have to use placeholders or sql_isempty() helper function.
  728. // If the field isn't VARCHAR or CLOB, skip
  729. if ($column->meta_type != 'C' and $column->meta_type != 'X') {
  730. return $value;
  731. }
  732. // If the value isn't empty, skip
  733. if (!empty($value)) {
  734. return $value;
  735. }
  736. // Now, we have one empty value, going to be inserted to one VARCHAR2 or CLOB field
  737. // Try to get the best value to be inserted
  738. // The '0' string doesn't need any transformation, skip
  739. if ($value === '0') {
  740. return $value;
  741. }
  742. // Transformations start
  743. if (gettype($value) == 'boolean') {
  744. return '0'; // Transform false to '0' that evaluates the same for PHP
  745. } else if (gettype($value) == 'integer') {
  746. return '0'; // Transform 0 to '0' that evaluates the same for PHP
  747. } else if ($value === '') {
  748. return ' '; // Transform '' to ' ' that DON'T EVALUATE THE SAME
  749. // (we'll transform back again on get_records_XXX functions and others)!!
  750. }
  751. // Fail safe to original value
  752. return $value;
  753. }
  754. /**
  755. * Helper function to order by string length desc
  756. *
  757. * @param $a string first element to compare
  758. * @param $b string second element to compare
  759. * @return int < 0 $a goes first (is less), 0 $b goes first, 0 doesn't matter
  760. */
  761. private function compare_by_length_desc($a, $b) {
  762. return strlen($b) - strlen($a);
  763. }
  764. /**
  765. * Is db in unicode mode?
  766. * @return bool
  767. */
  768. public function setup_is_unicodedb() {
  769. $sql = "SELECT VALUE
  770. FROM NLS_DATABASE_PARAMETERS
  771. WHERE PARAMETER = 'NLS_CHARACTERSET'";
  772. $this->query_start($sql, null, SQL_QUERY_AUX);
  773. $stmt = $this->parse_query($sql);
  774. $result = oci_execute($stmt, $this->commit_status);
  775. $this->query_end($result, $stmt);
  776. $records = null;
  777. oci_fetch_all($stmt, $records, 0, -1, OCI_FETCHSTATEMENT_BY_COLUMN);
  778. oci_free_statement($stmt);
  779. return (isset($records['VALUE'][0]) and $records['VALUE'][0] === 'AL32UTF8');
  780. }
  781. /**
  782. * Do NOT use in code, to be used by database_manager only!
  783. * @param string|array $sql query
  784. * @param array|null $tablenames an array of xmldb table names affected by this request.
  785. * @return bool true
  786. * @throws ddl_change_structure_exception A DDL specific exception is thrown for any errors.
  787. */
  788. public function change_database_structure($sql, $tablenames = null) {
  789. $this->get_manager(); // Includes DDL exceptions classes ;-)
  790. $sqls = (array)$sql;
  791. try {
  792. foreach ($sqls as $sql) {
  793. $this->query_start($sql, null, SQL_QUERY_STRUCTURE);
  794. $stmt = $this->parse_query($sql);
  795. $result = oci_execute($stmt, $this->commit_status);
  796. $this->query_end($result, $stmt);
  797. oci_free_statement($stmt);
  798. }
  799. } catch (ddl_change_structure_exception $e) {
  800. $this->reset_caches($tablenames);
  801. throw $e;
  802. }
  803. $this->reset_caches($tablenames);
  804. return true;
  805. }
  806. protected function bind_params($stmt, array &$params=null, $tablename=null, array &$descriptors = null) {
  807. if ($params) {
  808. $columns = array();
  809. if ($tablename) {
  810. $columns = $this->get_columns($tablename);
  811. }
  812. foreach($params as $key => $value) {
  813. // Decouple column name and param name as far as sometimes they aren't the same
  814. if ($key == 'o_newfieldtoset') { // found case where column and key diverge, handle that
  815. $columnname = key($value); // columnname is the key of the array
  816. $params[$key] = $value[$columnname]; // set the proper value in the $params array and
  817. $value = $value[$columnname]; // set the proper value in the $value variable
  818. } else {
  819. $columnname = preg_replace('/^o_/', '', $key); // Default columnname (for DB introspecting is key), but...
  820. }
  821. // Continue processing
  822. // Now, handle already detected LOBs
  823. if (is_array($value)) { // Let's go to bind special cases (lob descriptors)
  824. if (isset($value['clob'])) {
  825. $lob = oci_new_descriptor($this->oci, OCI_DTYPE_LOB);
  826. if ($descriptors === null) {
  827. throw new coding_exception('moodle_database::bind_params() $descriptors not specified for clob');
  828. }
  829. $descriptors[] = $lob;
  830. oci_bind_by_name($stmt, $key, $lob, -1, SQLT_CLOB);
  831. $lob->writeTemporary($this->oracle_dirty_hack($tablename, $columnname, $params[$key]['clob']), OCI_TEMP_CLOB);
  832. continue; // Column binding finished, go to next one
  833. } else if (isset($value['blob'])) {
  834. $lob = oci_new_descriptor($this->oci, OCI_DTYPE_LOB);
  835. if ($descriptors === null) {
  836. throw new coding_exception('moodle_database::bind_params() $descriptors not specified for clob');
  837. }
  838. $descriptors[] = $lob;
  839. oci_bind_by_name($stmt, $key, $lob, -1, SQLT_BLOB);
  840. $lob->writeTemporary($params[$key]['blob'], OCI_TEMP_BLOB);
  841. continue; // Column binding finished, go to next one
  842. }
  843. } else {
  844. // If, at this point, the param value > 4000 (bytes), let's assume it's a clob
  845. // passed in an arbitrary sql (not processed by normalise_value() ever,
  846. // and let's handle it as such. This will provide proper binding of CLOBs in
  847. // conditions and other raw SQLs not covered by the above function.
  848. if (strlen($value) > 4000) {
  849. $lob = oci_new_descriptor($this->oci, OCI_DTYPE_LOB);
  850. if ($descriptors === null) {
  851. throw new coding_exception('moodle_database::bind_params() $descriptors not specified for clob');
  852. }
  853. $descriptors[] = $lob;
  854. oci_bind_by_name($stmt, $key, $lob, -1, SQLT_CLOB);
  855. $lob->writeTemporary($this->oracle_dirty_hack($tablename, $columnname, $params[$key]), OCI_TEMP_CLOB);
  856. continue; // Param binding finished, go to next one.
  857. }
  858. }
  859. // TODO: Put proper types and length is possible (enormous speedup)
  860. // Arrived here, continue with standard processing, using metadata if possible
  861. if (isset($columns[$columnname])) {
  862. $type = $columns[$columnname]->meta_type;
  863. $maxlength = $columns[$columnname]->max_length;
  864. } else {
  865. $type = '?';
  866. $maxlength = -1;
  867. }
  868. switch ($type) {
  869. case 'I':
  870. case 'R':
  871. // TODO: Optimise
  872. oci_bind_by_name($stmt, $key, $params[$key]);
  873. break;
  874. case 'N':
  875. case 'F':
  876. // TODO: Optimise
  877. oci_bind_by_name($stmt, $key, $params[$key]);
  878. break;
  879. case 'B':
  880. // TODO: Only arrive here if BLOB is null: Bind if so, else exception!
  881. // don't break here
  882. case 'X':
  883. // TODO: Only arrive here if CLOB is null or <= 4000 cc, else exception
  884. // don't break here
  885. default: // Bind as CHAR (applying dirty hack)
  886. // TODO: Optimise
  887. $params[$key] = $this->oracle_dirty_hack($tablename, $columnname, $params[$key]);
  888. // Because of PHP7 bug (https://bugs.php.net/bug.php?id=72524) it seems that it's
  889. // impossible to bind NULL values in a reliable way, let's use empty string
  890. // instead in the mean time.
  891. if ($params[$key] === null && version_compare(PHP_VERSION, '7.0.0', '>=')) {
  892. $params[$key] = '';
  893. }
  894. oci_bind_by_name($stmt, $key, $params[$key]);
  895. }
  896. }
  897. }
  898. return $descriptors;
  899. }
  900. protected function free_descriptors($descriptors) {
  901. foreach ($descriptors as $descriptor) {
  902. // Because all descriptors used in the driver come from LOB::writeTemporary() calls
  903. // we can safely close them here unconditionally.
  904. $descriptor->close();
  905. // Free resources.
  906. oci_free_descriptor($descriptor);
  907. }
  908. }
  909. /**
  910. * This function is used to convert all the Oracle 1-space defaults to the empty string
  911. * like a really DIRTY HACK to allow it to work better until all those NOT NULL DEFAULT ''
  912. * fields will be out from Moodle.
  913. * @param string the string to be converted to '' (empty string) if it's ' ' (one space)
  914. * @param mixed the key of the array in case we are using this function from array_walk,
  915. * defaults to null for other (direct) uses
  916. * @return boolean always true (the converted variable is returned by reference)
  917. */
  918. public static function onespace2empty(&$item, $key=null) {
  919. $item = ($item === ' ') ? '' : $item;
  920. return true;
  921. }
  922. /**
  923. * Execute general sql query. Should be used only when no other method suitable.
  924. * Do NOT use this to make changes in db structure, use database_manager methods instead!
  925. * @param string $sql query
  926. * @param array $params query parameters
  927. * @return bool true
  928. * @throws dml_exception A DML specific exception is thrown for any errors.
  929. */
  930. public function execute($sql, array $params=null) {
  931. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  932. if (strpos($sql, ';') !== false) {
  933. throw new coding_exception('moodle_database::execute() Multiple sql statements found or bound parameters not used properly in query!');
  934. }
  935. list($sql, $params) = $this->tweak_param_names($sql, $params);
  936. $this->query_start($sql, $params, SQL_QUERY_UPDATE);
  937. $stmt = $this->parse_query($sql);
  938. $descriptors = array();
  939. $this->bind_params($stmt, $params, null, $descriptors);
  940. $result = oci_execute($stmt, $this->commit_status);
  941. $this->free_descriptors($descriptors);
  942. $this->query_end($result, $stmt);
  943. oci_free_statement($stmt);
  944. return true;
  945. }
  946. /**
  947. * Get a single database record as an object using a SQL statement.
  948. *
  949. * The SQL statement should normally only return one record.
  950. * It is recommended to use get_records_sql() if more matches possible!
  951. *
  952. * @param string $sql The SQL string you wish to be executed, should normally only return one record.
  953. * @param array $params array of sql parameters
  954. * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
  955. * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
  956. * MUST_EXIST means throw exception if no record or multiple records found
  957. * @return mixed a fieldset object containing the first matching record, false or exception if error not found depending on mode
  958. * @throws dml_exception A DML specific exception is thrown for any errors.
  959. */
  960. public function get_record_sql($sql, array $params=null, $strictness=IGNORE_MISSING) {
  961. $strictness = (int)$strictness;
  962. if ($strictness == IGNORE_MULTIPLE) {
  963. // do not limit here - ORA does not like that
  964. $rs = $this->get_recordset_sql($sql, $params);
  965. $result = false;
  966. foreach ($rs as $rec) {
  967. $result = $rec;
  968. break;
  969. }
  970. $rs->close();
  971. return $result;
  972. }
  973. return parent::get_record_sql($sql, $params, $strictness);
  974. }
  975. /**
  976. * Get a number of records as a moodle_recordset using a SQL statement.
  977. *
  978. * Since this method is a little less readable, use of it should be restricted to
  979. * code where it's possible there might be large datasets being returned. For known
  980. * small datasets use get_records_sql - it leads to simpler code.
  981. *
  982. * The return type is like:
  983. * @see function get_recordset.
  984. *
  985. * @param string $sql the SQL select query to execute.
  986. * @param array $params array of sql parameters
  987. * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
  988. * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
  989. * @return moodle_recordset instance
  990. * @throws dml_exception A DML specific exception is thrown for any errors.
  991. */
  992. public function get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
  993. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  994. list($rawsql, $params) = $this->get_limit_sql($sql, $params, $limitfrom, $limitnum);
  995. list($rawsql, $params) = $this->tweak_param_names($rawsql, $params);
  996. $this->query_start($rawsql, $params, SQL_QUERY_SELECT);
  997. $stmt = $this->parse_query($rawsql);
  998. $descriptors = array();
  999. $this->bind_params($stmt, $params, null, $descriptors);
  1000. $result = oci_execute($stmt, $this->commit_status);
  1001. $this->free_descriptors($descriptors);
  1002. $this->query_end($result, $stmt);
  1003. return $this->create_recordset($stmt);
  1004. }
  1005. protected function create_recordset($stmt) {
  1006. return new oci_native_moodle_recordset($stmt);
  1007. }
  1008. /**
  1009. * Get a number of records as an array of objects using a SQL statement.
  1010. *
  1011. * Return value is like:
  1012. * @see function get_records.
  1013. *
  1014. * @param string $sql the SQL select query to execute. The first column of this SELECT statement
  1015. * must be a unique value (usually the 'id' field), as it will be used as the key of the
  1016. * returned array.
  1017. * @param array $params array of sql parameters
  1018. * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
  1019. * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
  1020. * @return array of objects, or empty array if no records were found
  1021. * @throws dml_exception A DML specific exception is thrown for any errors.
  1022. */
  1023. public function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
  1024. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  1025. list($rawsql, $params) = $this->get_limit_sql($sql, $params, $limitfrom, $limitnum);
  1026. list($rawsql, $params) = $this->tweak_param_names($rawsql, $params);
  1027. $this->query_start($rawsql, $params, SQL_QUERY_SELECT);
  1028. $stmt = $this->parse_query($rawsql);
  1029. $descriptors = array();
  1030. $this->bind_params($stmt, $params, null, $descriptors);
  1031. $result = oci_execute($stmt, $this->commit_status);
  1032. $this->

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