PageRenderTime 29ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/dml/oci_native_moodle_database.php

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