PageRenderTime 48ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/moodle/lib/dml/oci_native_moodle_database.php

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

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