PageRenderTime 37ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/dml/oci_native_moodle_database.php

https://github.com/glovenone/moodle
PHP | 1652 lines | 1018 code | 181 blank | 453 comment | 158 complexity | 4290e4f14b7600fe5bf0fbde66c8fff3 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, BSD-3-Clause, AGPL-3.0, MPL-2.0-no-copyleft-exception, 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->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. foreach ($params as $name=>$value) {
  324. $newparams['o_'.$name] = $value;
  325. }
  326. $sql = preg_replace('/:([a-z0-9_-]+[$a-z0-9_-])/', ':o_$1', $sql);
  327. return array($sql, $newparams);
  328. }
  329. /**
  330. * Return tables in database WITHOUT current prefix
  331. * @return array of table names in lowercase and without prefix
  332. */
  333. public function get_tables($usecache=true) {
  334. if ($usecache and $this->tables !== null) {
  335. return $this->tables;
  336. }
  337. $this->tables = array();
  338. $prefix = str_replace('_', "\\_", strtoupper($this->prefix));
  339. $sql = "SELECT TABLE_NAME
  340. FROM CAT
  341. WHERE TABLE_TYPE='TABLE'
  342. AND TABLE_NAME NOT LIKE 'BIN\$%'
  343. AND TABLE_NAME LIKE '$prefix%' ESCAPE '\\'";
  344. $this->query_start($sql, null, SQL_QUERY_AUX);
  345. $stmt = $this->parse_query($sql);
  346. $result = oci_execute($stmt, $this->commit_status);
  347. $this->query_end($result, $stmt);
  348. $records = null;
  349. oci_fetch_all($stmt, $records, 0, -1, OCI_ASSOC);
  350. oci_free_statement($stmt);
  351. $records = array_map('strtolower', $records['TABLE_NAME']);
  352. foreach ($records as $tablename) {
  353. if (strpos($tablename, $this->prefix) !== 0) {
  354. continue;
  355. }
  356. $tablename = substr($tablename, strlen($this->prefix));
  357. $this->tables[$tablename] = $tablename;
  358. }
  359. // Add the currently available temptables
  360. $this->tables = array_merge($this->tables, $this->temptables->get_temptables());
  361. return $this->tables;
  362. }
  363. /**
  364. * Return table indexes - everything lowercased
  365. * @return array of arrays
  366. */
  367. public function get_indexes($table) {
  368. $indexes = array();
  369. $tablename = strtoupper($this->prefix.$table);
  370. $sql = "SELECT i.INDEX_NAME, i.UNIQUENESS, c.COLUMN_POSITION, c.COLUMN_NAME, ac.CONSTRAINT_TYPE
  371. FROM ALL_INDEXES i
  372. JOIN ALL_IND_COLUMNS c ON c.INDEX_NAME=i.INDEX_NAME
  373. LEFT JOIN ALL_CONSTRAINTS ac ON (ac.TABLE_NAME=i.TABLE_NAME AND ac.CONSTRAINT_NAME=i.INDEX_NAME AND ac.CONSTRAINT_TYPE='P')
  374. WHERE i.TABLE_NAME = '$tablename'
  375. ORDER BY i.INDEX_NAME, c.COLUMN_POSITION";
  376. $stmt = $this->parse_query($sql);
  377. $result = oci_execute($stmt, $this->commit_status);
  378. $this->query_end($result, $stmt);
  379. $records = null;
  380. oci_fetch_all($stmt, $records, 0, -1, OCI_FETCHSTATEMENT_BY_ROW);
  381. oci_free_statement($stmt);
  382. foreach ($records as $record) {
  383. if ($record['CONSTRAINT_TYPE'] === 'P') {
  384. //ignore for now;
  385. continue;
  386. }
  387. $indexname = strtolower($record['INDEX_NAME']);
  388. if (!isset($indexes[$indexname])) {
  389. $indexes[$indexname] = array('primary' => ($record['CONSTRAINT_TYPE'] === 'P'),
  390. 'unique' => ($record['UNIQUENESS'] === 'UNIQUE'),
  391. 'columns' => array());
  392. }
  393. $indexes[$indexname]['columns'][] = strtolower($record['COLUMN_NAME']);
  394. }
  395. return $indexes;
  396. }
  397. /**
  398. * Returns detailed information about columns in table. This information is cached internally.
  399. * @param string $table name
  400. * @param bool $usecache
  401. * @return array array of database_column_info objects indexed with column names
  402. */
  403. public function get_columns($table, $usecache=true) {
  404. if ($usecache and isset($this->columns[$table])) {
  405. return $this->columns[$table];
  406. }
  407. if (!$table) { // table not specified, return empty array directly
  408. return array();
  409. }
  410. $this->columns[$table] = array();
  411. $sql = "SELECT CNAME, COLTYPE, WIDTH, SCALE, PRECISION, NULLS, DEFAULTVAL
  412. FROM COL
  413. WHERE TNAME = UPPER('{" . $table . "}')
  414. ORDER BY COLNO";
  415. list($sql, $params, $type) = $this->fix_sql_params($sql, null);
  416. $this->query_start($sql, null, SQL_QUERY_AUX);
  417. $stmt = $this->parse_query($sql);
  418. $result = oci_execute($stmt, $this->commit_status);
  419. $this->query_end($result, $stmt);
  420. $records = null;
  421. oci_fetch_all($stmt, $records, 0, -1, OCI_FETCHSTATEMENT_BY_ROW);
  422. oci_free_statement($stmt);
  423. if (!$records) {
  424. return array();
  425. }
  426. foreach ($records as $rawcolumn) {
  427. $rawcolumn = (object)$rawcolumn;
  428. $info = new stdClass();
  429. $info->name = strtolower($rawcolumn->CNAME);
  430. $matches = null;
  431. if ($rawcolumn->COLTYPE === 'VARCHAR2'
  432. or $rawcolumn->COLTYPE === 'VARCHAR'
  433. or $rawcolumn->COLTYPE === 'NVARCHAR2'
  434. or $rawcolumn->COLTYPE === 'NVARCHAR'
  435. or $rawcolumn->COLTYPE === 'CHAR'
  436. or $rawcolumn->COLTYPE === 'NCHAR') {
  437. //TODO add some basic enum support here
  438. $info->type = $rawcolumn->COLTYPE;
  439. $info->meta_type = 'C';
  440. $info->max_length = $rawcolumn->WIDTH;
  441. $info->scale = null;
  442. $info->not_null = ($rawcolumn->NULLS === 'NOT NULL');
  443. $info->has_default = !is_null($rawcolumn->DEFAULTVAL);
  444. if ($info->has_default) {
  445. // this is hacky :-(
  446. if ($rawcolumn->DEFAULTVAL === 'NULL') {
  447. $info->default_value = null;
  448. } else if ($rawcolumn->DEFAULTVAL === "' ' ") { // Sometimes it's stored with trailing space
  449. $info->default_value = "";
  450. } else if ($rawcolumn->DEFAULTVAL === "' '") { // Sometimes it's stored without trailing space
  451. $info->default_value = "";
  452. } else {
  453. $info->default_value = trim($rawcolumn->DEFAULTVAL); // remove trailing space
  454. $info->default_value = substr($info->default_value, 1, strlen($info->default_value)-2); //trim ''
  455. }
  456. } else {
  457. $info->default_value = null;
  458. }
  459. $info->primary_key = false;
  460. $info->binary = false;
  461. $info->unsigned = null;
  462. $info->auto_increment= false;
  463. $info->unique = null;
  464. } else if ($rawcolumn->COLTYPE === 'NUMBER') {
  465. $info->type = $rawcolumn->COLTYPE;
  466. $info->max_length = $rawcolumn->PRECISION;
  467. $info->binary = false;
  468. if (!is_null($rawcolumn->SCALE) && $rawcolumn->SCALE == 0) { // null in oracle scale allows decimals => not integer
  469. // integer
  470. if ($info->name === 'id') {
  471. $info->primary_key = true;
  472. $info->meta_type = 'R';
  473. $info->unique = true;
  474. $info->auto_increment= true;
  475. $info->has_default = false;
  476. } else {
  477. $info->primary_key = false;
  478. $info->meta_type = 'I';
  479. $info->unique = null;
  480. $info->auto_increment= false;
  481. }
  482. $info->scale = null;
  483. } else {
  484. //float
  485. $info->meta_type = 'N';
  486. $info->primary_key = false;
  487. $info->unsigned = null;
  488. $info->auto_increment= false;
  489. $info->unique = null;
  490. $info->scale = $rawcolumn->SCALE;
  491. }
  492. $info->not_null = ($rawcolumn->NULLS === 'NOT NULL');
  493. $info->has_default = !is_null($rawcolumn->DEFAULTVAL);
  494. if ($info->has_default) {
  495. $info->default_value = trim($rawcolumn->DEFAULTVAL); // remove trailing space
  496. } else {
  497. $info->default_value = null;
  498. }
  499. } else if ($rawcolumn->COLTYPE === 'FLOAT') {
  500. $info->type = $rawcolumn->COLTYPE;
  501. $info->max_length = (int)($rawcolumn->PRECISION * 3.32193);
  502. $info->primary_key = false;
  503. $info->meta_type = 'N';
  504. $info->unique = null;
  505. $info->auto_increment= false;
  506. $info->not_null = ($rawcolumn->NULLS === 'NOT NULL');
  507. $info->has_default = !is_null($rawcolumn->DEFAULTVAL);
  508. if ($info->has_default) {
  509. $info->default_value = trim($rawcolumn->DEFAULTVAL); // remove trailing space
  510. } else {
  511. $info->default_value = null;
  512. }
  513. } else if ($rawcolumn->COLTYPE === 'CLOB'
  514. or $rawcolumn->COLTYPE === 'NCLOB') {
  515. $info->type = $rawcolumn->COLTYPE;
  516. $info->meta_type = 'X';
  517. $info->max_length = -1;
  518. $info->scale = null;
  519. $info->scale = null;
  520. $info->not_null = ($rawcolumn->NULLS === 'NOT NULL');
  521. $info->has_default = !is_null($rawcolumn->DEFAULTVAL);
  522. if ($info->has_default) {
  523. // this is hacky :-(
  524. if ($rawcolumn->DEFAULTVAL === 'NULL') {
  525. $info->default_value = null;
  526. } else if ($rawcolumn->DEFAULTVAL === "' ' ") { // Sometimes it's stored with trailing space
  527. $info->default_value = "";
  528. } else if ($rawcolumn->DEFAULTVAL === "' '") { // Other times it's stored without trailing space
  529. $info->default_value = "";
  530. } else {
  531. $info->default_value = trim($rawcolumn->DEFAULTVAL); // remove trailing space
  532. $info->default_value = substr($info->default_value, 1, strlen($info->default_value)-2); //trim ''
  533. }
  534. } else {
  535. $info->default_value = null;
  536. }
  537. $info->primary_key = false;
  538. $info->binary = false;
  539. $info->unsigned = null;
  540. $info->auto_increment= false;
  541. $info->unique = null;
  542. } else if ($rawcolumn->COLTYPE === 'BLOB') {
  543. $info->type = $rawcolumn->COLTYPE;
  544. $info->meta_type = 'B';
  545. $info->max_length = -1;
  546. $info->scale = null;
  547. $info->scale = null;
  548. $info->not_null = ($rawcolumn->NULLS === 'NOT NULL');
  549. $info->has_default = !is_null($rawcolumn->DEFAULTVAL);
  550. if ($info->has_default) {
  551. // this is hacky :-(
  552. if ($rawcolumn->DEFAULTVAL === 'NULL') {
  553. $info->default_value = null;
  554. } else if ($rawcolumn->DEFAULTVAL === "' ' ") { // Sometimes it's stored with trailing space
  555. $info->default_value = "";
  556. } else if ($rawcolumn->DEFAULTVAL === "' '") { // Sometimes it's stored without trailing space
  557. $info->default_value = "";
  558. } else {
  559. $info->default_value = trim($rawcolumn->DEFAULTVAL); // remove trailing space
  560. $info->default_value = substr($info->default_value, 1, strlen($info->default_value)-2); //trim ''
  561. }
  562. } else {
  563. $info->default_value = null;
  564. }
  565. $info->primary_key = false;
  566. $info->binary = true;
  567. $info->unsigned = null;
  568. $info->auto_increment= false;
  569. $info->unique = null;
  570. } else {
  571. // unknown type - sorry
  572. $info->type = $rawcolumn->COLTYPE;
  573. $info->meta_type = '?';
  574. }
  575. $this->columns[$table][$info->name] = new database_column_info($info);
  576. }
  577. return $this->columns[$table];
  578. }
  579. /**
  580. * Normalise values based in RDBMS dependencies (booleans, LOBs...)
  581. *
  582. * @param database_column_info $column column metadata corresponding with the value we are going to normalise
  583. * @param mixed $value value we are going to normalise
  584. * @return mixed the normalised value
  585. */
  586. protected function normalise_value($column, $value) {
  587. if (is_bool($value)) { // Always, convert boolean to int
  588. $value = (int)$value;
  589. } else if ($column->meta_type == 'B') { // CLOB detected, we return 'blob' array instead of raw value to allow
  590. if (!is_null($value)) { // binding/executing code later to know about its nature
  591. $value = array('blob' => $value);
  592. }
  593. } else if ($column->meta_type == 'X' && strlen($value) > 4000) { // CLOB detected (>4000 optimisation), we return 'clob'
  594. if (!is_null($value)) { // array instead of raw value to allow binding/
  595. $value = array('clob' => (string)$value); // executing code later to know about its nature
  596. }
  597. } else if ($value === '') {
  598. if ($column->meta_type == 'I' or $column->meta_type == 'F' or $column->meta_type == 'N') {
  599. $value = 0; // prevent '' problems in numeric fields
  600. }
  601. }
  602. return $value;
  603. }
  604. /**
  605. * Transforms the sql and params in order to emulate the LIMIT clause available in other DBs
  606. *
  607. * @param string $sql the SQL select query to execute.
  608. * @param array $params array of sql parameters
  609. * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
  610. * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
  611. * @return array with the transformed sql and params updated
  612. */
  613. private function get_limit_sql($sql, array $params = null, $limitfrom=0, $limitnum=0) {
  614. $limitfrom = (int)$limitfrom;
  615. $limitnum = (int)$limitnum;
  616. $limitfrom = ($limitfrom < 0) ? 0 : $limitfrom;
  617. $limitnum = ($limitnum < 0) ? 0 : $limitnum;
  618. // TODO: Add the /*+ FIRST_ROWS */ hint if there isn't another hint
  619. if ($limitfrom and $limitnum) {
  620. $sql = "SELECT oracle_o.*
  621. FROM (SELECT oracle_i.*, rownum AS oracle_rownum
  622. FROM ($sql) oracle_i
  623. WHERE rownum <= :oracle_num_rows
  624. ) oracle_o
  625. WHERE oracle_rownum > :oracle_skip_rows";
  626. $params['oracle_num_rows'] = $limitfrom + $limitnum;
  627. $params['oracle_skip_rows'] = $limitfrom;
  628. } else if ($limitfrom and !$limitnum) {
  629. $sql = "SELECT oracle_o.*
  630. FROM (SELECT oracle_i.*, rownum AS oracle_rownum
  631. FROM ($sql) oracle_i
  632. ) oracle_o
  633. WHERE oracle_rownum > :oracle_skip_rows";
  634. $params['oracle_skip_rows'] = $limitfrom;
  635. } else if (!$limitfrom and $limitnum) {
  636. $sql = "SELECT *
  637. FROM ($sql)
  638. WHERE rownum <= :oracle_num_rows";
  639. $params['oracle_num_rows'] = $limitnum;
  640. }
  641. return array($sql, $params);
  642. }
  643. /**
  644. * This function will handle all the column values before being inserted/updated to DB for Oracle
  645. * installations. This is because the "special feature" of Oracle where the empty string is
  646. * equal to NULL and this presents a problem with all our currently NOT NULL default '' fields.
  647. * (and with empties handling in general)
  648. *
  649. * Note that this function is 100% private and should be used, exclusively by DML functions
  650. * in this file. Also, this is considered a DIRTY HACK to be removed when possible.
  651. *
  652. * This function is private and must not be used outside this driver at all
  653. *
  654. * @param $table string the table where the record is going to be inserted/updated (without prefix)
  655. * @param $field string the field where the record is going to be inserted/updated
  656. * @param $value mixed the value to be inserted/updated
  657. */
  658. private function oracle_dirty_hack ($table, $field, $value) {
  659. // Get metadata
  660. $columns = $this->get_columns($table);
  661. if (!isset($columns[$field])) {
  662. return $value;
  663. }
  664. $column = $columns[$field];
  665. // !! This paragraph explains behaviour before Moodle 2.0:
  666. //
  667. // For Oracle DB, empty strings are converted to NULLs in DB
  668. // and this breaks a lot of NOT NULL columns currently Moodle. In the future it's
  669. // planned to move some of them to NULL, if they must accept empty values and this
  670. // piece of code will become less and less used. But, for now, we need it.
  671. // What we are going to do is to examine all the data being inserted and if it's
  672. // an empty string (NULL for Oracle) and the field is defined as NOT NULL, we'll modify
  673. // such data in the best form possible ("0" for booleans and numbers and " " for the
  674. // rest of strings. It isn't optimal, but the only way to do so.
  675. // In the opposite, when retrieving records from Oracle, we'll decode " " back to
  676. // empty strings to allow everything to work properly. DIRTY HACK.
  677. // !! These paragraphs explain the rationale about the change for Moodle 2.0:
  678. //
  679. // Before Moodle 2.0, we only used to apply this DIRTY HACK to NOT NULL columns, as
  680. // stated above, but it causes one problem in NULL columns where both empty strings
  681. // and real NULLs are stored as NULLs, being impossible to differentiate them when
  682. // being retrieved from DB.
  683. //
  684. // So, starting with Moodle 2.0, we are going to apply the DIRTY HACK to all the
  685. // CHAR/CLOB columns no matter of their nullability. That way, when retrieving
  686. // NULLABLE fields we'll get proper empties and NULLs differentiated, so we'll be able
  687. // to rely in NULL/empty/content contents without problems, until now that wasn't
  688. // possible at all.
  689. //
  690. // No breakage with old data is expected as long as at the time of writing this
  691. // (20090922) all the current uses of both sql_empty() and sql_isempty() has been
  692. // revised in 2.0 and all them were being performed against NOT NULL columns,
  693. // where nothing has changed (the DIRTY HACK was already being applied).
  694. //
  695. // !! Conclusions:
  696. //
  697. // From Moodle 2.0 onwards, ALL empty strings in Oracle DBs will be stored as
  698. // 1-whitespace char, ALL NULLs as NULLs and, obviously, content as content. And
  699. // those 1-whitespace chars will be converted back to empty strings by all the
  700. // get_field/record/set() functions transparently and any SQL needing direct handling
  701. // of empties will need to use the sql_empty() and sql_isempty() helper functions.
  702. // MDL-17491.
  703. // If the field ins't VARCHAR or CLOB, skip
  704. if ($column->meta_type != 'C' and $column->meta_type != 'X') {
  705. return $value;
  706. }
  707. // If the value isn't empty, skip
  708. if (!empty($value)) {
  709. return $value;
  710. }
  711. // Now, we have one empty value, going to be inserted to one VARCHAR2 or CLOB field
  712. // Try to get the best value to be inserted
  713. // The '0' string doesn't need any transformation, skip
  714. if ($value === '0') {
  715. return $value;
  716. }
  717. // Transformations start
  718. if (gettype($value) == 'boolean') {
  719. return '0'; // Transform false to '0' that evaluates the same for PHP
  720. } else if (gettype($value) == 'integer') {
  721. return '0'; // Transform 0 to '0' that evaluates the same for PHP
  722. } else if ($value === '') {
  723. return ' '; // Transform '' to ' ' that DONT'T EVALUATE THE SAME
  724. // (we'll transform back again on get_records_XXX functions and others)!!
  725. }
  726. // Fail safe to original value
  727. return $value;
  728. }
  729. /**
  730. * Is db in unicode mode?
  731. * @return bool
  732. */
  733. public function setup_is_unicodedb() {
  734. $sql = "SELECT VALUE
  735. FROM NLS_DATABASE_PARAMETERS
  736. WHERE PARAMETER = 'NLS_CHARACTERSET'";
  737. $this->query_start($sql, null, SQL_QUERY_AUX);
  738. $stmt = $this->parse_query($sql);
  739. $result = oci_execute($stmt, $this->commit_status);
  740. $this->query_end($result, $stmt);
  741. $records = null;
  742. oci_fetch_all($stmt, $records, 0, -1, OCI_FETCHSTATEMENT_BY_COLUMN);
  743. oci_free_statement($stmt);
  744. return (isset($records['VALUE'][0]) and $records['VALUE'][0] === 'AL32UTF8');
  745. }
  746. /**
  747. * Do NOT use in code, to be used by database_manager only!
  748. * @param string $sql query
  749. * @return bool true
  750. * @throws dml_exception if error
  751. */
  752. public function change_database_structure($sql) {
  753. $this->reset_caches();
  754. $this->query_start($sql, null, SQL_QUERY_STRUCTURE);
  755. $stmt = $this->parse_query($sql);
  756. $result = oci_execute($stmt, $this->commit_status);
  757. $this->query_end($result, $stmt);
  758. oci_free_statement($stmt);
  759. return true;
  760. }
  761. protected function bind_params($stmt, array $params=null, $tablename=null) {
  762. $descriptors = array();
  763. if ($params) {
  764. $columns = array();
  765. if ($tablename) {
  766. $columns = $this->get_columns($tablename);
  767. }
  768. foreach($params as $key => $value) {
  769. // Decouple column name and param name as far as sometimes they aren't the same
  770. if ($key == 'o_newfieldtoset') { // found case where column and key diverge, handle that
  771. $columnname = key($value); // columnname is the key of the array
  772. $params[$key] = $value[$columnname]; // set the proper value in the $params array and
  773. $value = $value[$columnname]; // set the proper value in the $value variable
  774. } else {
  775. $columnname = preg_replace('/^o_/', '', $key); // Default columnname (for DB introspecting is key), but...
  776. }
  777. // Continue processing
  778. // Now, handle already detected LOBs
  779. if (is_array($value)) { // Let's go to bind special cases (lob descriptors)
  780. if (isset($value['clob'])) {
  781. $lob = oci_new_descriptor($this->oci, OCI_DTYPE_LOB);
  782. oci_bind_by_name($stmt, $key, $lob, -1, SQLT_CLOB);
  783. $lob->writeTemporary($this->oracle_dirty_hack($tablename, $columnname, $params[$key]['clob']), OCI_TEMP_CLOB);
  784. $descriptors[] = $lob;
  785. continue; // Column binding finished, go to next one
  786. } else if (isset($value['blob'])) {
  787. $lob = oci_new_descriptor($this->oci, OCI_DTYPE_LOB);
  788. oci_bind_by_name($stmt, $key, $lob, -1, SQLT_BLOB);
  789. $lob->writeTemporary($params[$key]['blob'], OCI_TEMP_BLOB);
  790. $descriptors[] = $lob;
  791. continue; // Column binding finished, go to next one
  792. }
  793. }
  794. // TODO: Put proper types and length is possible (enormous speedup)
  795. // Arrived here, continue with standard processing, using metadata if possible
  796. if (isset($columns[$columnname])) {
  797. $type = $columns[$columnname]->meta_type;
  798. $maxlength = $columns[$columnname]->max_length;
  799. } else {
  800. $type = '?';
  801. $maxlength = -1;
  802. }
  803. switch ($type) {
  804. case 'I':
  805. case 'R':
  806. // TODO: Optimise
  807. oci_bind_by_name($stmt, $key, $params[$key]);
  808. break;
  809. case 'N':
  810. case 'F':
  811. // TODO: Optimise
  812. oci_bind_by_name($stmt, $key, $params[$key]);
  813. break;
  814. case 'B':
  815. // TODO: Only arrive here if BLOB is null: Bind if so, else exception!
  816. // don't break here
  817. case 'X':
  818. // TODO: Only arrive here if CLOB is null or <= 4000 cc, else exception
  819. // don't break here
  820. default: // Bind as CHAR (applying dirty hack)
  821. // TODO: Optimise
  822. oci_bind_by_name($stmt, $key, $this->oracle_dirty_hack($tablename, $columnname, $params[$key]));
  823. }
  824. }
  825. }
  826. return $descriptors;
  827. }
  828. protected function free_descriptors($descriptors) {
  829. foreach ($descriptors as $descriptor) {
  830. oci_free_descriptor($descriptor);
  831. }
  832. }
  833. /**
  834. * This function is used to convert all the Oracle 1-space defaults to the empty string
  835. * like a really DIRTY HACK to allow it to work better until all those NOT NULL DEFAULT ''
  836. * fields will be out from Moodle.
  837. * @param string the string to be converted to '' (empty string) if it's ' ' (one space)
  838. * @param mixed the key of the array in case we are using this function from array_walk,
  839. * defaults to null for other (direct) uses
  840. * @return boolean always true (the converted variable is returned by reference)
  841. */
  842. public static function onespace2empty(&$item, $key=null) {
  843. $item = ($item === ' ') ? '' : $item;
  844. return true;
  845. }
  846. /**
  847. * Execute general sql query. Should be used only when no other method suitable.
  848. * Do NOT use this to make changes in db structure, use database_manager::execute_sql() instead!
  849. * @param string $sql query
  850. * @param array $params query parameters
  851. * @return bool true
  852. * @throws dml_exception if error
  853. */
  854. public function execute($sql, array $params=null) {
  855. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  856. if (strpos($sql, ';') !== false) {
  857. throw new coding_exception('moodle_database::execute() Multiple sql statements found or bound parameters not used properly in query!');
  858. }
  859. list($sql, $params) = $this->tweak_param_names($sql, $params);
  860. $this->query_start($sql, $params, SQL_QUERY_UPDATE);
  861. $stmt = $this->parse_query($sql);
  862. $this->bind_params($stmt, $params);
  863. $result = oci_execute($stmt, $this->commit_status);
  864. $this->query_end($result, $stmt);
  865. oci_free_statement($stmt);
  866. return true;
  867. }
  868. /**
  869. * Get a single database record as an object using a SQL statement.
  870. *
  871. * The SQL statement should normally only return one record.
  872. * It is recommended to use get_records_sql() if more matches possible!
  873. *
  874. * @param string $sql The SQL string you wish to be executed, should normally only return one record.
  875. * @param array $params array of sql parameters
  876. * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
  877. * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
  878. * MUST_EXIST means throw exception if no record or multiple records found
  879. * @return mixed a fieldset object containing the first matching record, false or exception if error not found depending on mode
  880. * @throws dml_exception if error
  881. */
  882. public function get_record_sql($sql, array $params=null, $strictness=IGNORE_MISSING) {
  883. $strictness = (int)$strictness;
  884. if ($strictness == IGNORE_MULTIPLE) {
  885. // do not limit here - ORA does not like that
  886. $rs = $this->get_recordset_sql($sql, $params);
  887. $result = false;
  888. foreach ($rs as $rec) {
  889. $result = $rec;
  890. break;
  891. }
  892. $rs->close();
  893. return $result;
  894. }
  895. return parent::get_record_sql($sql, $params, $strictness);
  896. }
  897. /**
  898. * Get a number of records as a moodle_recordset using a SQL statement.
  899. *
  900. * Since this method is a little less readable, use of it should be restricted to
  901. * code where it's possible there might be large datasets being returned. For known
  902. * small datasets use get_records_sql - it leads to simpler code.
  903. *
  904. * The return type is as for @see function get_recordset.
  905. *
  906. * @param string $sql the SQL select query to execute.
  907. * @param array $params array of sql parameters
  908. * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
  909. * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
  910. * @return moodle_recordset instance
  911. * @throws dml_exception if error
  912. */
  913. public function get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
  914. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  915. list($rawsql, $params) = $this->get_limit_sql($sql, $params, $limitfrom, $limitnum);
  916. list($rawsql, $params) = $this->tweak_param_names($rawsql, $params);
  917. $this->query_start($rawsql, $params, SQL_QUERY_SELECT);
  918. $stmt = $this->parse_query($rawsql);
  919. $this->bind_params($stmt, $params);
  920. $result = oci_execute($stmt, $this->commit_status);
  921. $this->query_end($result, $stmt);
  922. return $this->create_recordset($stmt);
  923. }
  924. protected function create_recordset($stmt) {
  925. return new oci_native_moodle_recordset($stmt);
  926. }
  927. /**
  928. * Get a number of records as an array of objects using a SQL statement.
  929. *
  930. * Return value as for @see function get_records.
  931. *
  932. * @param string $sql the SQL select query to execute. The first column of this SELECT statement
  933. * must be a unique value (usually the 'id' field), as it will be used as the key of the
  934. * returned array.
  935. * @param array $params array of sql parameters
  936. * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
  937. * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
  938. * @return array of objects, or empty array if no records were found
  939. * @throws dml_exception if error
  940. */
  941. public function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
  942. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  943. list($rawsql, $params) = $this->get_limit_sql($sql, $params, $limitfrom, $limitnum);
  944. list($rawsql, $params) = $this->tweak_param_names($rawsql, $params);
  945. $this->query_start($rawsql, $params, SQL_QUERY_SELECT);
  946. $stmt = $this->parse_query($rawsql);
  947. $this->bind_params($stmt, $params);
  948. $result = oci_execute($stmt, $this->commit_status);
  949. $this->query_end($result, $stmt);
  950. $records = null;
  951. oci_fetch_all($stmt, $records, 0, -1, OCI_FETCHSTATEMENT_BY_ROW);
  952. oci_free_statement($stmt);
  953. $return = array();
  954. foreach ($records as $row) {
  955. $row = array_change_key_case($row, CASE_LOWER);
  956. unset($row['oracle_rownum']);
  957. array_walk($row, array('oci_native_moodle_database', 'onespace2empty'));
  958. $id = reset($row);
  959. if (isset($return[$id])) {
  960. $colname = key($row);
  961. 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);
  962. }
  963. $return[$id] = (object)$row;
  964. }
  965. return $return;
  966. }
  967. /**
  968. * Selects records and return values (first field) as an array using a SQL statement.
  969. *
  970. * @param string $sql The SQL query
  971. * @param array $params array of sql parameters
  972. * @return array of values
  973. * @throws dml_exception if error
  974. */
  975. public function get_fieldset_sql($sql, array $params=null) {
  976. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  977. list($sql, $params) = $this->tweak_param_names($sql, $params);
  978. $this->query_start($sql, $params, SQL_QUERY_SELECT);
  979. $stmt = $this->parse_query($sql);
  980. $this->bind_params($stmt, $params);
  981. $result = oci_execute($stmt, $this->commit_status);
  982. $this->query_end($result, $stmt);
  983. $records = null;
  984. oci_fetch_all($stmt, $records, 0, -1, OCI_FETCHSTATEMENT_BY_COLUMN);
  985. oci_free_statement($stmt);
  986. $return = reset($records);
  987. array_walk($return, array('oci_native_moodle_database', 'onespace2empty'));
  988. return $return;
  989. }
  990. /**
  991. * Insert new record into database, as fast as possible, no safety checks, lobs not supported.
  992. * @param string $table name
  993. * @param mixed $params data record as object or array
  994. * @param bool $returnit return it of inserted record
  995. * @param bool $bulk true means repeated inserts expected
  996. * @param bool $customsequence true if 'id' included in $params, disables $returnid
  997. * @return bool|int true or new id
  998. * @throws dml_exception if error
  999. */
  1000. public function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false) {
  1001. if (!is_array($params)) {
  1002. $params = (array)$params;
  1003. }
  1004. $returning = "";
  1005. if ($customsequence) {
  1006. if (!isset($params['id'])) {
  1007. throw new coding_exception('moodle_database::insert_record_raw() id field must be specified if custom sequences used.');
  1008. }
  1009. $returnid = false;
  1010. } else {
  1011. unset($params['id']);
  1012. if ($returnid) {
  1013. $returning = " RETURNING id INTO :oracle_id"; // crazy name nobody is ever going to use or parameter ;-)
  1014. }
  1015. }
  1016. if (empty($params)) {
  1017. throw new coding_exception('moodle_database::insert_record_raw() no fields found.');
  1018. }
  1019. $fields = implode(',', array_keys($params));
  1020. $values = array();
  1021. foreach ($params as $pname => $value) {
  1022. $values[] = ":$pname";
  1023. }
  1024. $values = implode(',', $values);
  1025. $sql = "INSERT INTO {" . $table . "} ($fields) VALUES ($values)";
  1026. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  1027. $sql .= $returning;
  1028. $id = null;
  1029. list($sql, $params) = $this->tweak_param_names($sql, $params);
  1030. $this->query_start($sql, $params, SQL_QUERY_INSERT);
  1031. $stmt = $this->parse_query($sql);
  1032. $descriptors = $this->bind_params($stmt, $params, $table);
  1033. if ($returning) {
  1034. oci_bind_by_name($stmt, ":o_oracle_id", $id, 10, SQLT_INT); // :o_ prefix added in tweak_param_names()
  1035. }
  1036. $result = oci_execute($stmt, $this->commit_status);
  1037. $this->free_descriptors($descriptors);
  1038. $this->query_end($result, $stmt);
  1039. oci_free_statement($stmt);
  1040. if (!$returnid) {
  1041. return true;
  1042. }
  1043. if (!$returning) {
  1044. die('TODO - implement oracle 9.2 insert support'); //TODO
  1045. }
  1046. return (int)$id;
  1047. }
  1048. /**
  1049. * Insert a record into a table and return the "id" field if required.
  1050. *
  1051. * Some conversions and safety checks are carried out. Lobs are supported.
  1052. * If the return ID isn't required, then this just reports success as true/false.
  1053. * $data is an object containing needed data
  1054. * @param string $table The database table to be inserted into
  1055. * @param object $data A data object with values for one or more fields in the record
  1056. * @param bool $returnid Should the id of the newly created record entry be returned? If this option is not requested then true/false is returned.
  1057. * @return bool|int true or new id
  1058. * @throws dml_exception if error
  1059. */

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