PageRenderTime 52ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/dml/oci_native_moodle_database.php

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

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