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

/lib/dml/oci_native_moodle_database.php

https://github.com/lsuits/moodle
PHP | 1811 lines | 1197 code | 169 blank | 445 comment | 161 complexity | 0ee0774761a30e7596b2284a89639e2d MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, BSD-3-Clause, Apache-2.0
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Native oci class representing moodle database interface.
  18. *
  19. * @package core_dml
  20. * @copyright 2008 Petr Skoda (http://skodak.org)
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. defined('MOODLE_INTERNAL') || die();
  24. require_once(__DIR__.'/moodle_database.php');
  25. require_once(__DIR__.'/oci_native_moodle_recordset.php');
  26. require_once(__DIR__.'/oci_native_moodle_temptables.php');
  27. /**
  28. * Native oci class representing moodle database interface.
  29. *
  30. * One complete reference for PHP + OCI:
  31. * http://www.oracle.com/technology/tech/php/underground-php-oracle-manual.html
  32. *
  33. * @package core_dml
  34. * @copyright 2008 Petr Skoda (http://skodak.org)
  35. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  36. */
  37. class oci_native_moodle_database extends moodle_database {
  38. protected $oci = null;
  39. /** @var To store stmt errors and enable get_last_error() to detect them.*/
  40. private $last_stmt_error = null;
  41. /** @var Default value initialised in connect method, we need the driver to be present.*/
  42. private $commit_status = null;
  43. /** @var To handle oci driver default verbosity.*/
  44. private $last_error_reporting;
  45. /** @var To store unique_session_id. Needed for temp tables unique naming.*/
  46. private $unique_session_id;
  47. /**
  48. * Detects if all needed PHP stuff installed.
  49. * Note: can be used before connect()
  50. * @return mixed true if ok, string if something
  51. */
  52. public function driver_installed() {
  53. if (!extension_loaded('oci8')) {
  54. return get_string('ociextensionisnotpresentinphp', 'install');
  55. }
  56. return true;
  57. }
  58. /**
  59. * Returns database family type - describes SQL dialect
  60. * Note: can be used before connect()
  61. * @return string db family name (mysql, postgres, mssql, oracle, etc.)
  62. */
  63. public function get_dbfamily() {
  64. return 'oracle';
  65. }
  66. /**
  67. * Returns more specific database driver type
  68. * Note: can be used before connect()
  69. * @return string db type mysqli, pgsql, oci, mssql, sqlsrv
  70. */
  71. protected function get_dbtype() {
  72. return 'oci';
  73. }
  74. /**
  75. * Returns general database library name
  76. * Note: can be used before connect()
  77. * @return string db type pdo, native
  78. */
  79. protected function get_dblibrary() {
  80. return 'native';
  81. }
  82. /**
  83. * Returns localised database type name
  84. * Note: can be used before connect()
  85. * @return string
  86. */
  87. public function get_name() {
  88. return get_string('nativeoci', 'install');
  89. }
  90. /**
  91. * Returns localised database configuration help.
  92. * Note: can be used before connect()
  93. * @return string
  94. */
  95. public function get_configuration_help() {
  96. return get_string('nativeocihelp', 'install');
  97. }
  98. /**
  99. * Diagnose database and tables, this function is used
  100. * to verify database and driver settings, db engine types, etc.
  101. *
  102. * @return string null means everything ok, string means problem found.
  103. */
  104. public function diagnose() {
  105. return null;
  106. }
  107. /**
  108. * Connect to db
  109. * Must be called before other methods.
  110. * @param string $dbhost The database host.
  111. * @param string $dbuser The database username.
  112. * @param string $dbpass The database username's password.
  113. * @param string $dbname The name of the database being connected to.
  114. * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
  115. * @param array $dboptions driver specific options
  116. * @return bool true
  117. * @throws dml_connection_exception if error
  118. */
  119. public function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null) {
  120. if ($prefix == '' and !$this->external) {
  121. //Enforce prefixes for everybody but mysql
  122. throw new dml_exception('prefixcannotbeempty', $this->get_dbfamily());
  123. }
  124. if (!$this->external and strlen($prefix) > 2) {
  125. //Max prefix length for Oracle is 2cc
  126. $a = (object)array('dbfamily'=>'oracle', 'maxlength'=>2);
  127. throw new dml_exception('prefixtoolong', $a);
  128. }
  129. $driverstatus = $this->driver_installed();
  130. if ($driverstatus !== true) {
  131. throw new dml_exception('dbdriverproblem', $driverstatus);
  132. }
  133. // Autocommit ON by default.
  134. // Switching to OFF (OCI_DEFAULT), when playing with transactions
  135. // please note this thing is not defined if oracle driver not present in PHP
  136. // which means it can not be used as default value of object property!
  137. $this->commit_status = OCI_COMMIT_ON_SUCCESS;
  138. $this->store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions);
  139. unset($this->dboptions['dbsocket']);
  140. // NOTE: use of ', ", / and \ is very problematic, even native oracle tools seem to have
  141. // problems with these, so just forget them and do not report problems into tracker...
  142. if (empty($this->dbhost)) {
  143. // old style full address (TNS)
  144. $dbstring = $this->dbname;
  145. } else {
  146. if (empty($this->dboptions['dbport'])) {
  147. $this->dboptions['dbport'] = 1521;
  148. }
  149. $dbstring = '//'.$this->dbhost.':'.$this->dboptions['dbport'].'/'.$this->dbname;
  150. }
  151. ob_start();
  152. if (empty($this->dboptions['dbpersist'])) {
  153. $this->oci = oci_new_connect($this->dbuser, $this->dbpass, $dbstring, 'AL32UTF8');
  154. } else {
  155. $this->oci = oci_pconnect($this->dbuser, $this->dbpass, $dbstring, 'AL32UTF8');
  156. }
  157. $dberr = ob_get_contents();
  158. ob_end_clean();
  159. if ($this->oci === false) {
  160. $this->oci = null;
  161. $e = oci_error();
  162. if (isset($e['message'])) {
  163. $dberr = $e['message'];
  164. }
  165. throw new dml_connection_exception($dberr);
  166. }
  167. // Make sure moodle package is installed - now required.
  168. if (!$this->oci_package_installed()) {
  169. try {
  170. $this->attempt_oci_package_install();
  171. } catch (Exception $e) {
  172. // Ignore problems, only the result counts,
  173. // admins have to fix it manually if necessary.
  174. }
  175. if (!$this->oci_package_installed()) {
  176. throw new dml_exception('dbdriverproblem', 'Oracle PL/SQL Moodle support package MOODLELIB is not installed! Database administrator has to execute /lib/dml/oci_native_moodle_package.sql script.');
  177. }
  178. }
  179. // get unique session id, to be used later for temp tables stuff
  180. $sql = 'SELECT DBMS_SESSION.UNIQUE_SESSION_ID() FROM DUAL';
  181. $this->query_start($sql, null, SQL_QUERY_AUX);
  182. $stmt = $this->parse_query($sql);
  183. $result = oci_execute($stmt, $this->commit_status);
  184. $this->query_end($result, $stmt);
  185. $records = null;
  186. oci_fetch_all($stmt, $records, 0, -1, OCI_FETCHSTATEMENT_BY_ROW);
  187. oci_free_statement($stmt);
  188. $this->unique_session_id = reset($records[0]);
  189. //note: do not send "ALTER SESSION SET NLS_NUMERIC_CHARACTERS='.,'" !
  190. // instead fix our PHP code to convert "," to "." properly!
  191. // Connection stabilised and configured, going to instantiate the temptables controller
  192. $this->temptables = new oci_native_moodle_temptables($this, $this->unique_session_id);
  193. return true;
  194. }
  195. /**
  196. * Close database connection and release all resources
  197. * and memory (especially circular memory references).
  198. * Do NOT use connect() again, create a new instance if needed.
  199. */
  200. public function dispose() {
  201. parent::dispose(); // Call parent dispose to write/close session and other common stuff before closing connection
  202. if ($this->oci) {
  203. oci_close($this->oci);
  204. $this->oci = null;
  205. }
  206. }
  207. /**
  208. * Called before each db query.
  209. * @param string $sql
  210. * @param array array of parameters
  211. * @param int $type type of query
  212. * @param mixed $extrainfo driver specific extra information
  213. * @return void
  214. */
  215. protected function query_start($sql, array $params=null, $type, $extrainfo=null) {
  216. parent::query_start($sql, $params, $type, $extrainfo);
  217. // oci driver tents to send debug to output, we do not need that ;-)
  218. $this->last_error_reporting = error_reporting(0);
  219. }
  220. /**
  221. * Called immediately after each db query.
  222. * @param mixed db specific result
  223. * @return void
  224. */
  225. protected function query_end($result, $stmt=null) {
  226. // reset original debug level
  227. error_reporting($this->last_error_reporting);
  228. if ($stmt and $result === false) {
  229. // Look for stmt error and store it
  230. if (is_resource($stmt)) {
  231. $e = oci_error($stmt);
  232. if ($e !== false) {
  233. $this->last_stmt_error = $e['message'];
  234. }
  235. }
  236. oci_free_statement($stmt);
  237. }
  238. parent::query_end($result);
  239. }
  240. /**
  241. * Returns database server info array
  242. * @return array Array containing 'description' and 'version' info
  243. */
  244. public function get_server_info() {
  245. static $info = null; // TODO: move to real object property
  246. if (is_null($info)) {
  247. $this->query_start("--oci_server_version()", null, SQL_QUERY_AUX);
  248. $description = oci_server_version($this->oci);
  249. $this->query_end(true);
  250. preg_match('/(\d+\.)+\d+/', $description, $matches);
  251. $info = array('description'=>$description, 'version'=>$matches[0]);
  252. }
  253. return $info;
  254. }
  255. /**
  256. * Converts short table name {tablename} to real table name
  257. * supporting temp tables ($this->unique_session_id based) if detected
  258. *
  259. * @param string sql
  260. * @return string sql
  261. */
  262. protected function fix_table_names($sql) {
  263. if (preg_match_all('/\{([a-z][a-z0-9_]*)\}/', $sql, $matches)) {
  264. foreach($matches[0] as $key=>$match) {
  265. $name = $matches[1][$key];
  266. if ($this->temptables && $this->temptables->is_temptable($name)) {
  267. $sql = str_replace($match, $this->temptables->get_correct_name($name), $sql);
  268. } else {
  269. $sql = str_replace($match, $this->prefix.$name, $sql);
  270. }
  271. }
  272. }
  273. return $sql;
  274. }
  275. /**
  276. * Returns supported query parameter types
  277. * @return int bitmask of accepted SQL_PARAMS_*
  278. */
  279. protected function allowed_param_types() {
  280. return SQL_PARAMS_NAMED;
  281. }
  282. /**
  283. * Returns last error reported by database engine.
  284. * @return string error message
  285. */
  286. public function get_last_error() {
  287. $error = false;
  288. // First look for any previously saved stmt error
  289. if (!empty($this->last_stmt_error)) {
  290. $error = $this->last_stmt_error;
  291. $this->last_stmt_error = null;
  292. } else { // Now try connection error
  293. $e = oci_error($this->oci);
  294. if ($e !== false) {
  295. $error = $e['message'];
  296. }
  297. }
  298. return $error;
  299. }
  300. /**
  301. * Prepare the statement for execution
  302. * @throws dml_connection_exception
  303. * @param string $sql
  304. * @return resource
  305. */
  306. protected function parse_query($sql) {
  307. $stmt = oci_parse($this->oci, $sql);
  308. if ($stmt == false) {
  309. throw new dml_connection_exception('Can not parse sql query'); //TODO: maybe add better info
  310. }
  311. return $stmt;
  312. }
  313. /**
  314. * Make sure there are no reserved words in param names...
  315. * @param string $sql
  316. * @param array $params
  317. * @return array ($sql, $params) updated query and parameters
  318. */
  319. protected function tweak_param_names($sql, array $params) {
  320. if (empty($params)) {
  321. return array($sql, $params);
  322. }
  323. $newparams = array();
  324. $searcharr = array(); // search => replace pairs
  325. foreach ($params as $name => $value) {
  326. // Keep the name within the 30 chars limit always (prefixing/replacing)
  327. if (strlen($name) <= 28) {
  328. $newname = 'o_' . $name;
  329. } else {
  330. $newname = 'o_' . substr($name, 2);
  331. }
  332. $newparams[$newname] = $value;
  333. $searcharr[':' . $name] = ':' . $newname;
  334. }
  335. // sort by length desc to avoid potential str_replace() overlap
  336. uksort($searcharr, array('oci_native_moodle_database', 'compare_by_length_desc'));
  337. $sql = str_replace(array_keys($searcharr), $searcharr, $sql);
  338. return array($sql, $newparams);
  339. }
  340. /**
  341. * Return tables in database WITHOUT current prefix
  342. * @param bool $usecache if true, returns list of cached tables.
  343. * @return array of table names in lowercase and without prefix
  344. */
  345. public function get_tables($usecache=true) {
  346. if ($usecache and $this->tables !== null) {
  347. return $this->tables;
  348. }
  349. $this->tables = array();
  350. $prefix = str_replace('_', "\\_", strtoupper($this->prefix));
  351. $sql = "SELECT TABLE_NAME
  352. FROM CAT
  353. WHERE TABLE_TYPE='TABLE'
  354. AND TABLE_NAME NOT LIKE 'BIN\$%'
  355. AND TABLE_NAME LIKE '$prefix%' ESCAPE '\\'";
  356. $this->query_start($sql, null, SQL_QUERY_AUX);
  357. $stmt = $this->parse_query($sql);
  358. $result = oci_execute($stmt, $this->commit_status);
  359. $this->query_end($result, $stmt);
  360. $records = null;
  361. oci_fetch_all($stmt, $records, 0, -1, OCI_ASSOC);
  362. oci_free_statement($stmt);
  363. $records = array_map('strtolower', $records['TABLE_NAME']);
  364. foreach ($records as $tablename) {
  365. if ($this->prefix !== false && $this->prefix !== '') {
  366. if (strpos($tablename, $this->prefix) !== 0) {
  367. continue;
  368. }
  369. $tablename = substr($tablename, strlen($this->prefix));
  370. }
  371. $this->tables[$tablename] = $tablename;
  372. }
  373. // Add the currently available temptables
  374. $this->tables = array_merge($this->tables, $this->temptables->get_temptables());
  375. return $this->tables;
  376. }
  377. /**
  378. * Return table indexes - everything lowercased.
  379. * @param string $table The table we want to get indexes from.
  380. * @return array An associative array of indexes containing 'unique' flag and 'columns' being indexed
  381. */
  382. public function get_indexes($table) {
  383. $indexes = array();
  384. $tablename = strtoupper($this->prefix.$table);
  385. $sql = "SELECT i.INDEX_NAME, i.UNIQUENESS, c.COLUMN_POSITION, c.COLUMN_NAME, ac.CONSTRAINT_TYPE
  386. FROM ALL_INDEXES i
  387. JOIN ALL_IND_COLUMNS c ON c.INDEX_NAME=i.INDEX_NAME
  388. LEFT JOIN ALL_CONSTRAINTS ac ON (ac.TABLE_NAME=i.TABLE_NAME AND ac.CONSTRAINT_NAME=i.INDEX_NAME AND ac.CONSTRAINT_TYPE='P')
  389. WHERE i.TABLE_NAME = '$tablename'
  390. ORDER BY i.INDEX_NAME, c.COLUMN_POSITION";
  391. $stmt = $this->parse_query($sql);
  392. $result = oci_execute($stmt, $this->commit_status);
  393. $this->query_end($result, $stmt);
  394. $records = null;
  395. oci_fetch_all($stmt, $records, 0, -1, OCI_FETCHSTATEMENT_BY_ROW);
  396. oci_free_statement($stmt);
  397. foreach ($records as $record) {
  398. if ($record['CONSTRAINT_TYPE'] === 'P') {
  399. //ignore for now;
  400. continue;
  401. }
  402. $indexname = strtolower($record['INDEX_NAME']);
  403. if (!isset($indexes[$indexname])) {
  404. $indexes[$indexname] = array('primary' => ($record['CONSTRAINT_TYPE'] === 'P'),
  405. 'unique' => ($record['UNIQUENESS'] === 'UNIQUE'),
  406. 'columns' => array());
  407. }
  408. $indexes[$indexname]['columns'][] = strtolower($record['COLUMN_NAME']);
  409. }
  410. return $indexes;
  411. }
  412. /**
  413. * Returns detailed information about columns in table. This information is cached internally.
  414. * @param string $table name
  415. * @param bool $usecache
  416. * @return array array of database_column_info objects indexed with column names
  417. */
  418. public function get_columns($table, $usecache=true) {
  419. if ($usecache) {
  420. $properties = array('dbfamily' => $this->get_dbfamily(), 'settings' => $this->get_settings_hash());
  421. $cache = cache::make('core', 'databasemeta', $properties);
  422. if ($data = $cache->get($table)) {
  423. return $data;
  424. }
  425. }
  426. if (!$table) { // table not specified, return empty array directly
  427. return array();
  428. }
  429. $structure = array();
  430. // We give precedence to CHAR_LENGTH for VARCHAR2 columns over WIDTH because the former is always
  431. // BYTE based and, for cross-db operations, we want CHAR based results. See MDL-29415
  432. // Instead of guessing sequence based exclusively on name, check tables against user_triggers to
  433. // ensure the table has a 'before each row' trigger to assume 'id' is auto_increment. MDL-32365
  434. $sql = "SELECT CNAME, COLTYPE, nvl(CHAR_LENGTH, WIDTH) AS WIDTH, SCALE, PRECISION, NULLS, DEFAULTVAL,
  435. DECODE(NVL(TRIGGER_NAME, '0'), '0', '0', '1') HASTRIGGER
  436. FROM COL c
  437. LEFT JOIN USER_TAB_COLUMNS u ON (u.TABLE_NAME = c.TNAME AND u.COLUMN_NAME = c.CNAME AND u.DATA_TYPE = 'VARCHAR2')
  438. LEFT JOIN USER_TRIGGERS t ON (t.TABLE_NAME = c.TNAME AND TRIGGER_TYPE = 'BEFORE EACH ROW' AND c.CNAME = 'ID')
  439. WHERE TNAME = UPPER('{" . $table . "}')
  440. ORDER BY COLNO";
  441. list($sql, $params, $type) = $this->fix_sql_params($sql, null);
  442. $this->query_start($sql, null, SQL_QUERY_AUX);
  443. $stmt = $this->parse_query($sql);
  444. $result = oci_execute($stmt, $this->commit_status);
  445. $this->query_end($result, $stmt);
  446. $records = null;
  447. oci_fetch_all($stmt, $records, 0, -1, OCI_FETCHSTATEMENT_BY_ROW);
  448. oci_free_statement($stmt);
  449. if (!$records) {
  450. return array();
  451. }
  452. foreach ($records as $rawcolumn) {
  453. $rawcolumn = (object)$rawcolumn;
  454. $info = new stdClass();
  455. $info->name = strtolower($rawcolumn->CNAME);
  456. $info->auto_increment = ((int)$rawcolumn->HASTRIGGER) ? true : false;
  457. $matches = null;
  458. if ($rawcolumn->COLTYPE === 'VARCHAR2'
  459. or $rawcolumn->COLTYPE === 'VARCHAR'
  460. or $rawcolumn->COLTYPE === 'NVARCHAR2'
  461. or $rawcolumn->COLTYPE === 'NVARCHAR'
  462. or $rawcolumn->COLTYPE === 'CHAR'
  463. or $rawcolumn->COLTYPE === 'NCHAR') {
  464. $info->type = $rawcolumn->COLTYPE;
  465. $info->meta_type = 'C';
  466. $info->max_length = $rawcolumn->WIDTH;
  467. $info->scale = null;
  468. $info->not_null = ($rawcolumn->NULLS === 'NOT NULL');
  469. $info->has_default = !is_null($rawcolumn->DEFAULTVAL);
  470. if ($info->has_default) {
  471. // this is hacky :-(
  472. if ($rawcolumn->DEFAULTVAL === 'NULL') {
  473. $info->default_value = null;
  474. } else if ($rawcolumn->DEFAULTVAL === "' ' ") { // Sometimes it's stored with trailing space
  475. $info->default_value = "";
  476. } else if ($rawcolumn->DEFAULTVAL === "' '") { // Sometimes it's stored without trailing space
  477. $info->default_value = "";
  478. } else {
  479. $info->default_value = trim($rawcolumn->DEFAULTVAL); // remove trailing space
  480. $info->default_value = substr($info->default_value, 1, strlen($info->default_value)-2); //trim ''
  481. }
  482. } else {
  483. $info->default_value = null;
  484. }
  485. $info->primary_key = false;
  486. $info->binary = false;
  487. $info->unsigned = null;
  488. $info->unique = null;
  489. } else if ($rawcolumn->COLTYPE === 'NUMBER') {
  490. $info->type = $rawcolumn->COLTYPE;
  491. $info->max_length = $rawcolumn->PRECISION;
  492. $info->binary = false;
  493. if (!is_null($rawcolumn->SCALE) && $rawcolumn->SCALE == 0) { // null in oracle scale allows decimals => not integer
  494. // integer
  495. if ($info->name === 'id') {
  496. $info->primary_key = true;
  497. $info->meta_type = 'R';
  498. $info->unique = true;
  499. $info->has_default = false;
  500. } else {
  501. $info->primary_key = false;
  502. $info->meta_type = 'I';
  503. $info->unique = null;
  504. }
  505. $info->scale = 0;
  506. } else {
  507. //float
  508. $info->meta_type = 'N';
  509. $info->primary_key = false;
  510. $info->unsigned = null;
  511. $info->unique = null;
  512. $info->scale = $rawcolumn->SCALE;
  513. }
  514. $info->not_null = ($rawcolumn->NULLS === 'NOT NULL');
  515. $info->has_default = !is_null($rawcolumn->DEFAULTVAL);
  516. if ($info->has_default) {
  517. $info->default_value = trim($rawcolumn->DEFAULTVAL); // remove trailing space
  518. } else {
  519. $info->default_value = null;
  520. }
  521. } else if ($rawcolumn->COLTYPE === 'FLOAT') {
  522. $info->type = $rawcolumn->COLTYPE;
  523. $info->max_length = (int)($rawcolumn->PRECISION * 3.32193);
  524. $info->primary_key = false;
  525. $info->meta_type = 'N';
  526. $info->unique = null;
  527. $info->not_null = ($rawcolumn->NULLS === 'NOT NULL');
  528. $info->has_default = !is_null($rawcolumn->DEFAULTVAL);
  529. if ($info->has_default) {
  530. $info->default_value = trim($rawcolumn->DEFAULTVAL); // remove trailing space
  531. } else {
  532. $info->default_value = null;
  533. }
  534. } else if ($rawcolumn->COLTYPE === 'CLOB'
  535. or $rawcolumn->COLTYPE === 'NCLOB') {
  536. $info->type = $rawcolumn->COLTYPE;
  537. $info->meta_type = 'X';
  538. $info->max_length = -1;
  539. $info->scale = null;
  540. $info->scale = null;
  541. $info->not_null = ($rawcolumn->NULLS === 'NOT NULL');
  542. $info->has_default = !is_null($rawcolumn->DEFAULTVAL);
  543. if ($info->has_default) {
  544. // this is hacky :-(
  545. if ($rawcolumn->DEFAULTVAL === 'NULL') {
  546. $info->default_value = null;
  547. } else if ($rawcolumn->DEFAULTVAL === "' ' ") { // Sometimes it's stored with trailing space
  548. $info->default_value = "";
  549. } else if ($rawcolumn->DEFAULTVAL === "' '") { // Other times it's stored without trailing space
  550. $info->default_value = "";
  551. } else {
  552. $info->default_value = trim($rawcolumn->DEFAULTVAL); // remove trailing space
  553. $info->default_value = substr($info->default_value, 1, strlen($info->default_value)-2); //trim ''
  554. }
  555. } else {
  556. $info->default_value = null;
  557. }
  558. $info->primary_key = false;
  559. $info->binary = false;
  560. $info->unsigned = null;
  561. $info->unique = null;
  562. } else if ($rawcolumn->COLTYPE === 'BLOB') {
  563. $info->type = $rawcolumn->COLTYPE;
  564. $info->meta_type = 'B';
  565. $info->max_length = -1;
  566. $info->scale = null;
  567. $info->scale = null;
  568. $info->not_null = ($rawcolumn->NULLS === 'NOT NULL');
  569. $info->has_default = !is_null($rawcolumn->DEFAULTVAL);
  570. if ($info->has_default) {
  571. // this is hacky :-(
  572. if ($rawcolumn->DEFAULTVAL === 'NULL') {
  573. $info->default_value = null;
  574. } else if ($rawcolumn->DEFAULTVAL === "' ' ") { // Sometimes it's stored with trailing space
  575. $info->default_value = "";
  576. } else if ($rawcolumn->DEFAULTVAL === "' '") { // Sometimes it's stored without trailing space
  577. $info->default_value = "";
  578. } else {
  579. $info->default_value = trim($rawcolumn->DEFAULTVAL); // remove trailing space
  580. $info->default_value = substr($info->default_value, 1, strlen($info->default_value)-2); //trim ''
  581. }
  582. } else {
  583. $info->default_value = null;
  584. }
  585. $info->primary_key = false;
  586. $info->binary = true;
  587. $info->unsigned = null;
  588. $info->unique = null;
  589. } else {
  590. // unknown type - sorry
  591. $info->type = $rawcolumn->COLTYPE;
  592. $info->meta_type = '?';
  593. }
  594. $structure[$info->name] = new database_column_info($info);
  595. }
  596. if ($usecache) {
  597. $cache->set($table, $structure);
  598. }
  599. return $structure;
  600. }
  601. /**
  602. * Normalise values based in RDBMS dependencies (booleans, LOBs...)
  603. *
  604. * @param database_column_info $column column metadata corresponding with the value we are going to normalise
  605. * @param mixed $value value we are going to normalise
  606. * @return mixed the normalised value
  607. */
  608. protected function normalise_value($column, $value) {
  609. $this->detect_objects($value);
  610. if (is_bool($value)) { // Always, convert boolean to int
  611. $value = (int)$value;
  612. } else if ($column->meta_type == 'B') { // CLOB detected, we return 'blob' array instead of raw value to allow
  613. if (!is_null($value)) { // binding/executing code later to know about its nature
  614. $value = array('blob' => $value);
  615. }
  616. } else if ($column->meta_type == 'X' && strlen($value) > 4000) { // CLOB detected (>4000 optimisation), we return 'clob'
  617. if (!is_null($value)) { // array instead of raw value to allow binding/
  618. $value = array('clob' => (string)$value); // executing code later to know about its nature
  619. }
  620. } else if ($value === '') {
  621. if ($column->meta_type == 'I' or $column->meta_type == 'F' or $column->meta_type == 'N') {
  622. $value = 0; // prevent '' problems in numeric fields
  623. }
  624. }
  625. return $value;
  626. }
  627. /**
  628. * Transforms the sql and params in order to emulate the LIMIT clause available in other DBs
  629. *
  630. * @param string $sql the SQL select query to execute.
  631. * @param array $params array of sql parameters
  632. * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
  633. * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
  634. * @return array with the transformed sql and params updated
  635. */
  636. private function get_limit_sql($sql, array $params = null, $limitfrom=0, $limitnum=0) {
  637. list($limitfrom, $limitnum) = $this->normalise_limit_from_num($limitfrom, $limitnum);
  638. // TODO: Add the /*+ FIRST_ROWS */ hint if there isn't another hint
  639. if ($limitfrom and $limitnum) {
  640. $sql = "SELECT oracle_o.*
  641. FROM (SELECT oracle_i.*, rownum AS oracle_rownum
  642. FROM ($sql) oracle_i
  643. WHERE rownum <= :oracle_num_rows
  644. ) oracle_o
  645. WHERE oracle_rownum > :oracle_skip_rows";
  646. $params['oracle_num_rows'] = $limitfrom + $limitnum;
  647. $params['oracle_skip_rows'] = $limitfrom;
  648. } else if ($limitfrom and !$limitnum) {
  649. $sql = "SELECT oracle_o.*
  650. FROM (SELECT oracle_i.*, rownum AS oracle_rownum
  651. FROM ($sql) oracle_i
  652. ) oracle_o
  653. WHERE oracle_rownum > :oracle_skip_rows";
  654. $params['oracle_skip_rows'] = $limitfrom;
  655. } else if (!$limitfrom and $limitnum) {
  656. $sql = "SELECT *
  657. FROM ($sql)
  658. WHERE rownum <= :oracle_num_rows";
  659. $params['oracle_num_rows'] = $limitnum;
  660. }
  661. return array($sql, $params);
  662. }
  663. /**
  664. * This function will handle all the column values before being inserted/updated to DB for Oracle
  665. * installations. This is because the "special feature" of Oracle where the empty string is
  666. * equal to NULL and this presents a problem with all our currently NOT NULL default '' fields.
  667. * (and with empties handling in general)
  668. *
  669. * Note that this function is 100% private and should be used, exclusively by DML functions
  670. * in this file. Also, this is considered a DIRTY HACK to be removed when possible.
  671. *
  672. * This function is private and must not be used outside this driver at all
  673. *
  674. * @param $table string the table where the record is going to be inserted/updated (without prefix)
  675. * @param $field string the field where the record is going to be inserted/updated
  676. * @param $value mixed the value to be inserted/updated
  677. */
  678. private function oracle_dirty_hack ($table, $field, $value) {
  679. // General bound parameter, just hack the spaces and pray it will work.
  680. if (!$table) {
  681. if ($value === '') {
  682. return ' ';
  683. } else if (is_bool($value)) {
  684. return (int)$value;
  685. } else {
  686. return $value;
  687. }
  688. }
  689. // Get metadata
  690. $columns = $this->get_columns($table);
  691. if (!isset($columns[$field])) {
  692. if ($value === '') {
  693. return ' ';
  694. } else if (is_bool($value)) {
  695. return (int)$value;
  696. } else {
  697. return $value;
  698. }
  699. }
  700. $column = $columns[$field];
  701. // !! This paragraph explains behaviour before Moodle 2.0:
  702. //
  703. // For Oracle DB, empty strings are converted to NULLs in DB
  704. // and this breaks a lot of NOT NULL columns currently Moodle. In the future it's
  705. // planned to move some of them to NULL, if they must accept empty values and this
  706. // piece of code will become less and less used. But, for now, we need it.
  707. // What we are going to do is to examine all the data being inserted and if it's
  708. // an empty string (NULL for Oracle) and the field is defined as NOT NULL, we'll modify
  709. // such data in the best form possible ("0" for booleans and numbers and " " for the
  710. // rest of strings. It isn't optimal, but the only way to do so.
  711. // In the opposite, when retrieving records from Oracle, we'll decode " " back to
  712. // empty strings to allow everything to work properly. DIRTY HACK.
  713. // !! These paragraphs explain the rationale about the change for Moodle 2.5:
  714. //
  715. // Before Moodle 2.0, we only used to apply this DIRTY HACK to NOT NULL columns, as
  716. // stated above, but it causes one problem in NULL columns where both empty strings
  717. // and real NULLs are stored as NULLs, being impossible to differentiate them when
  718. // being retrieved from DB.
  719. //
  720. // So, starting with Moodle 2.0, we are going to apply the DIRTY HACK to all the
  721. // CHAR/CLOB columns no matter of their nullability. That way, when retrieving
  722. // NULLABLE fields we'll get proper empties and NULLs differentiated, so we'll be able
  723. // to rely in NULL/empty/content contents without problems, until now that wasn't
  724. // possible at all.
  725. //
  726. // One space DIRTY HACK is now applied automatically for all query parameters
  727. // and results. The only problem is string concatenation where the glue must
  728. // be specified as "' '" sql fragment.
  729. //
  730. // !! Conclusions:
  731. //
  732. // From Moodle 2.5 onwards, ALL empty strings in Oracle DBs will be stored as
  733. // 1-whitespace char, ALL NULLs as NULLs and, obviously, content as content. And
  734. // those 1-whitespace chars will be converted back to empty strings by all the
  735. // get_field/record/set() functions transparently and any SQL needing direct handling
  736. // of empties will have to use placeholders or sql_isempty() helper function.
  737. // If the field isn't VARCHAR or CLOB, skip
  738. if ($column->meta_type != 'C' and $column->meta_type != 'X') {
  739. return $value;
  740. }
  741. // If the value isn't empty, skip
  742. if (!empty($value)) {
  743. return $value;
  744. }
  745. // Now, we have one empty value, going to be inserted to one VARCHAR2 or CLOB field
  746. // Try to get the best value to be inserted
  747. // The '0' string doesn't need any transformation, skip
  748. if ($value === '0') {
  749. return $value;
  750. }
  751. // Transformations start
  752. if (gettype($value) == 'boolean') {
  753. return '0'; // Transform false to '0' that evaluates the same for PHP
  754. } else if (gettype($value) == 'integer') {
  755. return '0'; // Transform 0 to '0' that evaluates the same for PHP
  756. } else if ($value === '') {
  757. return ' '; // Transform '' to ' ' that DON'T EVALUATE THE SAME
  758. // (we'll transform back again on get_records_XXX functions and others)!!
  759. }
  760. // Fail safe to original value
  761. return $value;
  762. }
  763. /**
  764. * Helper function to order by string length desc
  765. *
  766. * @param $a string first element to compare
  767. * @param $b string second element to compare
  768. * @return int < 0 $a goes first (is less), 0 $b goes first, 0 doesn't matter
  769. */
  770. private function compare_by_length_desc($a, $b) {
  771. return strlen($b) - strlen($a);
  772. }
  773. /**
  774. * Is db in unicode mode?
  775. * @return bool
  776. */
  777. public function setup_is_unicodedb() {
  778. $sql = "SELECT VALUE
  779. FROM NLS_DATABASE_PARAMETERS
  780. WHERE PARAMETER = 'NLS_CHARACTERSET'";
  781. $this->query_start($sql, null, SQL_QUERY_AUX);
  782. $stmt = $this->parse_query($sql);
  783. $result = oci_execute($stmt, $this->commit_status);
  784. $this->query_end($result, $stmt);
  785. $records = null;
  786. oci_fetch_all($stmt, $records, 0, -1, OCI_FETCHSTATEMENT_BY_COLUMN);
  787. oci_free_statement($stmt);
  788. return (isset($records['VALUE'][0]) and $records['VALUE'][0] === 'AL32UTF8');
  789. }
  790. /**
  791. * Do NOT use in code, to be used by database_manager only!
  792. * @param string|array $sql query
  793. * @return bool true
  794. * @throws ddl_change_structure_exception A DDL specific exception is thrown for any errors.
  795. */
  796. public function change_database_structure($sql) {
  797. $this->get_manager(); // Includes DDL exceptions classes ;-)
  798. $sqls = (array)$sql;
  799. try {
  800. foreach ($sqls as $sql) {
  801. $this->query_start($sql, null, SQL_QUERY_STRUCTURE);
  802. $stmt = $this->parse_query($sql);
  803. $result = oci_execute($stmt, $this->commit_status);
  804. $this->query_end($result, $stmt);
  805. oci_free_statement($stmt);
  806. }
  807. } catch (ddl_change_structure_exception $e) {
  808. $this->reset_caches();
  809. throw $e;
  810. }
  811. $this->reset_caches();
  812. return true;
  813. }
  814. protected function bind_params($stmt, array $params=null, $tablename=null) {
  815. $descriptors = array();
  816. if ($params) {
  817. $columns = array();
  818. if ($tablename) {
  819. $columns = $this->get_columns($tablename);
  820. }
  821. foreach($params as $key => $value) {
  822. // Decouple column name and param name as far as sometimes they aren't the same
  823. if ($key == 'o_newfieldtoset') { // found case where column and key diverge, handle that
  824. $columnname = key($value); // columnname is the key of the array
  825. $params[$key] = $value[$columnname]; // set the proper value in the $params array and
  826. $value = $value[$columnname]; // set the proper value in the $value variable
  827. } else {
  828. $columnname = preg_replace('/^o_/', '', $key); // Default columnname (for DB introspecting is key), but...
  829. }
  830. // Continue processing
  831. // Now, handle already detected LOBs
  832. if (is_array($value)) { // Let's go to bind special cases (lob descriptors)
  833. if (isset($value['clob'])) {
  834. $lob = oci_new_descriptor($this->oci, OCI_DTYPE_LOB);
  835. oci_bind_by_name($stmt, $key, $lob, -1, SQLT_CLOB);
  836. $lob->writeTemporary($this->oracle_dirty_hack($tablename, $columnname, $params[$key]['clob']), OCI_TEMP_CLOB);
  837. $descriptors[] = $lob;
  838. continue; // Column binding finished, go to next one
  839. } else if (isset($value['blob'])) {
  840. $lob = oci_new_descriptor($this->oci, OCI_DTYPE_LOB);
  841. oci_bind_by_name($stmt, $key, $lob, -1, SQLT_BLOB);
  842. $lob->writeTemporary($params[$key]['blob'], OCI_TEMP_BLOB);
  843. $descriptors[] = $lob;
  844. continue; // Column binding finished, go to next one
  845. }
  846. }
  847. // TODO: Put proper types and length is possible (enormous speedup)
  848. // Arrived here, continue with standard processing, using metadata if possible
  849. if (isset($columns[$columnname])) {
  850. $type = $columns[$columnname]->meta_type;
  851. $maxlength = $columns[$columnname]->max_length;
  852. } else {
  853. $type = '?';
  854. $maxlength = -1;
  855. }
  856. switch ($type) {
  857. case 'I':
  858. case 'R':
  859. // TODO: Optimise
  860. oci_bind_by_name($stmt, $key, $params[$key]);
  861. break;
  862. case 'N':
  863. case 'F':
  864. // TODO: Optimise
  865. oci_bind_by_name($stmt, $key, $params[$key]);
  866. break;
  867. case 'B':
  868. // TODO: Only arrive here if BLOB is null: Bind if so, else exception!
  869. // don't break here
  870. case 'X':
  871. // TODO: Only arrive here if CLOB is null or <= 4000 cc, else exception
  872. // don't break here
  873. default: // Bind as CHAR (applying dirty hack)
  874. // TODO: Optimise
  875. oci_bind_by_name($stmt, $key, $this->oracle_dirty_hack($tablename, $columnname, $params[$key]));
  876. }
  877. }
  878. }
  879. return $descriptors;
  880. }
  881. protected function free_descriptors($descriptors) {
  882. foreach ($descriptors as $descriptor) {
  883. oci_free_descriptor($descriptor);
  884. }
  885. }
  886. /**
  887. * This function is used to convert all the Oracle 1-space defaults to the empty string
  888. * like a really DIRTY HACK to allow it to work better until all those NOT NULL DEFAULT ''
  889. * fields will be out from Moodle.
  890. * @param string the string to be converted to '' (empty string) if it's ' ' (one space)
  891. * @param mixed the key of the array in case we are using this function from array_walk,
  892. * defaults to null for other (direct) uses
  893. * @return boolean always true (the converted variable is returned by reference)
  894. */
  895. public static function onespace2empty(&$item, $key=null) {
  896. $item = ($item === ' ') ? '' : $item;
  897. return true;
  898. }
  899. /**
  900. * Execute general sql query. Should be used only when no other method suitable.
  901. * Do NOT use this to make changes in db structure, use database_manager methods instead!
  902. * @param string $sql query
  903. * @param array $params query parameters
  904. * @return bool true
  905. * @throws dml_exception A DML specific exception is thrown for any errors.
  906. */
  907. public function execute($sql, array $params=null) {
  908. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  909. if (strpos($sql, ';') !== false) {
  910. throw new coding_exception('moodle_database::execute() Multiple sql statements found or bound parameters not used properly in query!');
  911. }
  912. list($sql, $params) = $this->tweak_param_names($sql, $params);
  913. $this->query_start($sql, $params, SQL_QUERY_UPDATE);
  914. $stmt = $this->parse_query($sql);
  915. $this->bind_params($stmt, $params);
  916. $result = oci_execute($stmt, $this->commit_status);
  917. $this->query_end($result, $stmt);
  918. oci_free_statement($stmt);
  919. return true;
  920. }
  921. /**
  922. * Get a single database record as an object using a SQL statement.
  923. *
  924. * The SQL statement should normally only return one record.
  925. * It is recommended to use get_records_sql() if more matches possible!
  926. *
  927. * @param string $sql The SQL string you wish to be executed, should normally only return one record.
  928. * @param array $params array of sql parameters
  929. * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
  930. * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
  931. * MUST_EXIST means throw exception if no record or multiple records found
  932. * @return mixed a fieldset object containing the first matching record, false or exception if error not found depending on mode
  933. * @throws dml_exception A DML specific exception is thrown for any errors.
  934. */
  935. public function get_record_sql($sql, array $params=null, $strictness=IGNORE_MISSING) {
  936. $strictness = (int)$strictness;
  937. if ($strictness == IGNORE_MULTIPLE) {
  938. // do not limit here - ORA does not like that
  939. $rs = $this->get_recordset_sql($sql, $params);
  940. $result = false;
  941. foreach ($rs as $rec) {
  942. $result = $rec;
  943. break;
  944. }
  945. $rs->close();
  946. return $result;
  947. }
  948. return parent::get_record_sql($sql, $params, $strictness);
  949. }
  950. /**
  951. * Get a number of records as a moodle_recordset using a SQL statement.
  952. *
  953. * Since this method is a little less readable, use of it should be restricted to
  954. * code where it's possible there might be large datasets being returned. For known
  955. * small datasets use get_records_sql - it leads to simpler code.
  956. *
  957. * The return type is like:
  958. * @see function get_recordset.
  959. *
  960. * @param string $sql the SQL select query to execute.
  961. * @param array $params array of sql parameters
  962. * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
  963. * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
  964. * @return moodle_recordset instance
  965. * @throws dml_exception A DML specific exception is thrown for any errors.
  966. */
  967. public function get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
  968. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  969. list($rawsql, $params) = $this->get_limit_sql($sql, $params, $limitfrom, $limitnum);
  970. list($rawsql, $params) = $this->tweak_param_names($rawsql, $params);
  971. $this->query_start($rawsql, $params, SQL_QUERY_SELECT);
  972. $stmt = $this->parse_query($rawsql);
  973. $this->bind_params($stmt, $params);
  974. $result = oci_execute($stmt, $this->commit_status);
  975. $this->query_end($result, $stmt);
  976. return $this->create_recordset($stmt);
  977. }
  978. protected function create_recordset($stmt) {
  979. return new oci_native_moodle_recordset($stmt);
  980. }
  981. /**
  982. * Get a number of records as an array of objects using a SQL statement.
  983. *
  984. * Return value is like:
  985. * @see function get_records.
  986. *
  987. * @param string $sql the SQL select query to execute. The first column of this SELECT statement
  988. * must be a unique value (usually the 'id' field), as it will be used as the key of the
  989. * returned array.
  990. * @param array $params array of sql parameters
  991. * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
  992. * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
  993. * @return array of objects, or empty array if no records were found
  994. * @throws dml_exception A DML specific exception is thrown for any errors.
  995. */
  996. public function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
  997. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  998. list($rawsql, $params) = $this->get_limit_sql($sql, $params, $limitfrom, $limitnum);
  999. list($rawsql, $params) = $this->tweak_param_names($rawsql, $params);
  1000. $this->query_start($rawsql, $params, SQL_QUERY_SELECT);
  1001. $stmt = $this->parse_query($rawsql);
  1002. $this->bind_params($stmt, $params);
  1003. $result = oci_execute($stmt, $this->commit_status);
  1004. $this->query_end($result, $stmt);
  1005. $records = null;
  1006. oci_fetch_all($stmt, $records, 0, -1, OCI_FETCHSTATEMENT_BY_ROW);
  1007. oci_free_statement($stmt);
  1008. $return = array();
  1009. foreach ($records as $row) {
  1010. $row = array_change_key_case($row, CASE_LOWER);
  1011. unset($row['oracle_rownum']);
  1012. array_walk($row, array('oci_native_moodle_database', 'onespace2empty'));
  1013. $id = reset($row);
  1014. if (isset($return[$id])) {
  1015. $colname = key($row);
  1016. debugging("Did you remember to make the first column something unique in your call to get_records? Duplicate value '$id' found in column '$colname'.", DEBUG_DEVELOPER);
  1017. }
  1018. $return[$id] = (object)$row;
  1019. }
  1020. return $return;
  1021. }
  1022. /**
  1023. * Selects records and return values (first field) as an array using a SQL statement.
  1024. *
  1025. * @param string $sql The SQL query
  1026. * @param array $params array of sql parameters
  1027. * @return array of values
  1028. * @throws dml_exception A DML specific exception is thrown for any errors.
  1029. */
  1030. public function get_fieldset_sql($sql, array $params=null) {
  1031. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  1032. list($sql, $params) = $this->tweak_param_names($sql, $params);
  1033. $this->query_start($sql, $params, SQL_QUERY_SELECT);
  1034. $stmt = $this->parse_query($sql);
  1035. $this->bind_params($stmt, $params);
  1036. $result = oci_execute($stmt, $this->commit_status);
  1037. $this->query_end($result, $stmt);
  1038. $records = null;
  1039. oci_fetch_all($stmt, $records, 0, -1, OCI_FETCHSTATEMENT_BY_COLUMN);
  1040. oci_free_statement($stmt);
  1041. $return = reset($records);
  1042. array_walk($return, array('oci_native_moodle_database', 'onespace2empty'));
  1043. return $return;
  1044. }
  1045. /**
  1046. * Insert new record into database, as fast as possible, no safety checks, lobs not supported.
  1047. * @param string $table name
  1048. * @param mixed $params data record as object or array
  1049. * @param bool $returnit return it of inserted record
  1050. * @param bool $bulk true means repeated inserts expected
  1051. * @param bool $customsequence true if 'id' included in $params, disables $returnid
  1052. * @return bool|int true or new id
  1053. * @throws dml_exception A DML specific exception is thrown for any errors.
  1054. */
  1055. public function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false) {
  1056. if (!is_array($params)) {
  1057. $params = (array)$params;
  1058. }
  1059. $returning = "";
  1060. if ($customsequence) {
  1061. if (!isset($params['id'])) {
  1062. throw new coding_exception('moodle_database::insert_record_raw() id field must be specified if custom sequences used.');
  1063. }
  1064. $returnid = false;
  1065. } else {
  1066. unset($params['id']);
  1067. if ($returnid) {
  1068. $returning = " RETURNING id INTO :oracle_id"; // crazy name nobody is ever going to use or parameter ;-)
  1069. }
  1070. }
  1071. if (empty($params)) {
  1072. throw new coding_exception('moodle_database::insert_record_raw() no fields found.');
  1073. }
  1074. $fields = implode(',', array_keys($params));
  1075. $values = array();
  1076. foreach ($params as $pname => $value) {
  1077. $values[] = ":$pname";
  1078. }
  1079. $values = implode(',', $values);
  1080. $sql = "INSERT INTO {" . $table . "} ($fields) VALUES ($values)";
  1081. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  1082. $sql .= $returning;
  1083. $id = null;
  1084. // note we don't need tweak_param_names() here. Placeholders are safe column names. MDL-28080
  1085. // list($sql, $params) = $this->tweak_param_names($sql, $params);
  1086. $this->query_start($sql, $params, SQL_QUERY_INSERT);
  1087. $stmt = $this->parse_query($sql);
  1088. $descriptors = $this->bind_params($stmt, $params, $table);
  1089. if ($returning) {
  1090. oci_bind_by_name($stmt, ":oracle_id", $id, 10, SQLT_INT);
  1091. }
  1092. $result = oci_execute($stmt, $this->commit_status);
  1093. $this->free_descriptors($descriptors);
  1094. $this->query_end($result, $stmt);
  1095. oci_free_statement($stmt);
  1096. if (!$returnid) {
  1097. return true;
  1098. }
  1099. if (!$returning) {
  1100. die('TODO - implement oracle 9.2 insert support'); //TODO
  1101. }
  1102. return (int)$id;
  1103. }
  1104. /**
  1105. * Insert a record into a table and return the "id" field if required.
  1106. *
  1107. * Some conversions and safety checks are carried out. Lobs are supported.
  1108. * If the return ID isn't required, then this just reports success as true/false.
  1109. * $data is an object containing needed data
  1110. * @param string $table The database table to be inserted into
  1111. * @param object $data A data object with values for one or more fields in the record
  1112. * @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.
  1113. * @return bool|int true or new id
  1114. * @throws dml_exception A DML specific exception is thrown for any errors.
  1115. */
  1116. public function insert_record($table, $dataobject, $returnid=true, $bulk=false) {
  1117. $dataobject = (array)$dataobject;
  1118. $columns = $this->get_columns($table);
  1119. if (empty($columns)) {
  1120. throw new dml_exception('ddltablenotexist', $table);
  1121. }
  1122. $cleaned = array();
  1123. foreach ($dataobject as $field=>$value) {
  1124. if ($field === 'id') {
  1125. continue;
  1126. }
  1127. if (!isset($columns[$field])) { // Non-existing table field, skip it
  1128. continue;
  1129. }
  1130. $column = $columns[$field];
  1131. $cleaned[$field] = $this->normalise_value($column, $value);
  1132. }
  1133. return $this->insert_record_raw($table, $cleaned, $returnid, $bulk);
  1134. }
  1135. /**
  1136. * Import a record into a table, id field is required.
  1137. * Safety checks are NOT carried out. Lobs are supported.
  1138. *
  1139. * @param string $table name of database table to be inserted into
  1140. * @param object $dataobject A data object with values for one or more fields in the record
  1141. * @return bool true
  1142. * @throws dml_exception A DML specific exception is thrown for any errors.
  1143. */
  1144. public function import_record($table, $dataobject) {
  1145. $dataobject = (array)$dataobject;
  1146. $columns = $this->get_columns($table);
  1147. $cleaned = array();
  1148. foreach ($dataobject as $field=>$value) {
  1149. if (!isset($columns[$field])) {
  1150. continue;
  1151. }
  1152. $column = $columns[$field];
  1153. $cleaned[$field] = $this->normalise_value($column, $value);
  1154. }
  1155. return $this->insert_record_raw($table, $cleaned, false, true, true);
  1156. }
  1157. /**
  1158. * Update record in database, as fast as possible, no safety checks, lobs not supported.
  1159. * @param string $table name
  1160. * @param mixed $params data record as object or array
  1161. * @param bool true means repeated updates expected
  1162. * @return bool true
  1163. * @throws dml_exception A DML specific exception is thrown for any errors.
  1164. */
  1165. public function update_record_raw($table, $params, $bulk=false) {
  1166. $params = (array)$params;
  1167. if (!isset($params['id'])) {
  1168. throw new coding_exception('moodle_database::update_record_raw() id field must be specified.');
  1169. }
  1170. if (empty($params)) {
  1171. throw new coding_exception('moodle_database::update_record_raw() no fields found.');
  1172. }
  1173. $sets = array();
  1174. foreach ($params as $field=>$value) {
  1175. if ($field == 'id') {
  1176. continue;
  1177. }
  1178. $sets[] = "$field = :$field";
  1179. }
  1180. $sets = implode(',', $sets);
  1181. $sql = "UPDATE {" . $table . "} SET $sets WHERE id=:id";
  1182. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  1183. // note we don't need tweak_param_names() here. Placeholders are safe column names. MDL-28080
  1184. // list($sql, $params) = $this->tweak_param_names($sql, $params);
  1185. $this->query_start($sql, $params, SQL_QUERY_UPDATE);
  1186. $stmt = $this->parse_query($sql);
  1187. $descriptors = $this->bind_params($stmt, $params, $table);
  1188. $result = oci_execute($stmt, $this->commit_status);
  1189. $this->free_descriptors($descriptors);
  1190. $this->query_end($result, $stmt);
  1191. oci_free_statement($stmt);
  1192. return true;
  1193. }
  1194. /**
  1195. * Update a record in a table
  1196. *
  1197. * $dataobject is an object containing needed data
  1198. * Relies on $dataobject having a variable "id" to
  1199. * specify the record to update
  1200. *
  1201. * @param string $table The database table to be checked against.
  1202. * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
  1203. * @param bool true means repeated updates expected
  1204. * @return bool true
  1205. * @throws dml_exception A DML specific exception is thrown for any errors.
  1206. */
  1207. public function update_record($table, $dataobject, $bulk=false) {
  1208. $dataobject = (array)$dataobject;
  1209. $columns = $this->get_columns($table);
  1210. $cleaned = array();
  1211. foreach ($dataobject as $field=>$value) {
  1212. if (!isset($columns[$field])) {
  1213. continue;
  1214. }
  1215. $column = $columns[$field];
  1216. $cleaned[$field] = $this->normalise_value($column, $value);
  1217. }
  1218. $this->update_record_raw($table, $cleaned, $bulk);
  1219. return true;
  1220. }
  1221. /**
  1222. * Set a single field in every table record which match a particular WHERE clause.
  1223. *
  1224. * @param string $table The database table to be checked against.
  1225. * @param string $newfield the field to set.
  1226. * @param string $newvalue the value to set the field to.
  1227. * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
  1228. * @param array $params array of sql parameters
  1229. * @return bool true
  1230. * @throws dml_exception A DML specific exception is thrown for any errors.
  1231. */
  1232. public function set_field_select($table, $newfield, $newvalue, $select, array $params=null) {
  1233. if ($select) {
  1234. $select = "WHERE $select";
  1235. }
  1236. if (is_null($params)) {
  1237. $params = array();
  1238. }
  1239. // Get column metadata
  1240. $columns = $this->get_columns($table);
  1241. $column = $columns[$newfield];
  1242. $newvalue = $this->normalise_value($column, $newvalue);
  1243. list($select, $params, $type) = $this->fix_sql_params($select, $params);
  1244. if (is_bool($newvalue)) {
  1245. $newvalue = (int)$newvalue; // prevent "false" problems
  1246. }
  1247. if (is_null($newvalue)) {
  1248. $newsql = "$newfield = NULL";
  1249. } else {
  1250. // Set the param to array ($newfield => $newvalue) and key to 'newfieldtoset'
  1251. // name in the build sql. Later, bind_params() will detect the value array and
  1252. // perform the needed modifications to allow the query to work. Note that
  1253. // 'newfieldtoset' is one arbitrary name that hopefully won't be used ever
  1254. // in order to avoid problems where the same field is used both in the set clause and in
  1255. // the conditions. This was breaking badly in drivers using NAMED params like oci.
  1256. $params['newfieldtoset'] = array($newfield => $newvalue);
  1257. $newsql = "$newfield = :newfieldtoset";
  1258. }
  1259. $sql = "UPDATE {" . $table . "} SET $newsql $select";
  1260. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  1261. list($sql, $params) = $this->tweak_param_names($sql, $params);
  1262. $this->query_start($sql, $params, SQL_QUERY_UPDATE);
  1263. $stmt = $this->parse_query($sql);
  1264. $descriptors = $this->bind_params($stmt, $params, $table);
  1265. $result = oci_execute($stmt, $this->commit_status);
  1266. $this->free_descriptors($descriptors);
  1267. $this->query_end($result, $stmt);
  1268. oci_free_statement($stmt);
  1269. return true;
  1270. }
  1271. /**
  1272. * Delete one or more records from a table which match a particular WHERE clause.
  1273. *
  1274. * @param string $table The database table to be checked against.
  1275. * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
  1276. * @param array $params array of sql parameters
  1277. * @return bool true
  1278. * @throws dml_exception A DML specific exception is thrown for any errors.
  1279. */
  1280. public function delete_records_select($table, $select, array $params=null) {
  1281. if ($select) {
  1282. $select = "WHERE $select";
  1283. }
  1284. $sql = "DELETE FROM {" . $table . "} $select";
  1285. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  1286. list($sql, $params) = $this->tweak_param_names($sql, $params);
  1287. $this->query_start($sql, $params, SQL_QUERY_UPDATE);
  1288. $stmt = $this->parse_query($sql);
  1289. $this->bind_params($stmt, $params);
  1290. $result = oci_execute($stmt, $this->commit_status);
  1291. $this->query_end($result, $stmt);
  1292. oci_free_statement($stmt);
  1293. return true;
  1294. }
  1295. function sql_null_from_clause() {
  1296. return ' FROM dual';
  1297. }
  1298. public function sql_bitand($int1, $int2) {
  1299. return 'bitand((' . $int1 . '), (' . $int2 . '))';
  1300. }
  1301. public function sql_bitnot($int1) {
  1302. return '((0 - (' . $int1 . ')) - 1)';
  1303. }
  1304. public function sql_bitor($int1, $int2) {
  1305. return 'MOODLELIB.BITOR(' . $int1 . ', ' . $int2 . ')';
  1306. }
  1307. public function sql_bitxor($int1, $int2) {
  1308. return 'MOODLELIB.BITXOR(' . $int1 . ', ' . $int2 . ')';
  1309. }
  1310. /**
  1311. * Returns the SQL text to be used in order to perform module '%'
  1312. * operation - remainder after division
  1313. *
  1314. * @param integer int1 first integer in the operation
  1315. * @param integer int2 second integer in the operation
  1316. * @return string the piece of SQL code to be used in your statement.
  1317. */
  1318. public function sql_modulo($int1, $int2) {
  1319. return 'MOD(' . $int1 . ', ' . $int2 . ')';
  1320. }
  1321. public function sql_cast_char2int($fieldname, $text=false) {
  1322. if (!$text) {
  1323. return ' CAST(' . $fieldname . ' AS INT) ';
  1324. } else {
  1325. return ' CAST(' . $this->sql_compare_text($fieldname) . ' AS INT) ';
  1326. }
  1327. }
  1328. public function sql_cast_char2real($fieldname, $text=false) {
  1329. if (!$text) {
  1330. return ' CAST(' . $fieldname . ' AS FLOAT) ';
  1331. } else {
  1332. return ' CAST(' . $this->sql_compare_text($fieldname) . ' AS FLOAT) ';
  1333. }
  1334. }
  1335. /**
  1336. * Returns 'LIKE' part of a query.
  1337. *
  1338. * @param string $fieldname usually name of the table column
  1339. * @param string $param usually bound query parameter (?, :named)
  1340. * @param bool $casesensitive use case sensitive search
  1341. * @param bool $accensensitive use accent sensitive search (not all databases support accent insensitive)
  1342. * @param bool $notlike true means "NOT LIKE"
  1343. * @param string $escapechar escape char for '%' and '_'
  1344. * @return string SQL code fragment
  1345. */
  1346. public function sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = '\\') {
  1347. if (strpos($param, '%') !== false) {
  1348. debugging('Potential SQL injection detected, sql_like() expects bound parameters (? or :named)');
  1349. }
  1350. $LIKE = $notlike ? 'NOT LIKE' : 'LIKE';
  1351. // no accent sensitiveness here for now, sorry
  1352. if ($casesensitive) {
  1353. return "$fieldname $LIKE $param ESCAPE '$escapechar'";
  1354. } else {
  1355. return "LOWER($fieldname) $LIKE LOWER($param) ESCAPE '$escapechar'";
  1356. }
  1357. }
  1358. public function sql_concat() {
  1359. $arr = func_get_args();
  1360. if (empty($arr)) {
  1361. return " ' ' ";
  1362. }
  1363. foreach ($arr as $k => $v) {
  1364. if ($v === "' '") {
  1365. $arr[$k] = "'*OCISP*'"; // New mega hack.
  1366. }
  1367. }
  1368. $s = $this->recursive_concat($arr);
  1369. return " MOODLELIB.UNDO_MEGA_HACK($s) ";
  1370. }
  1371. public function sql_concat_join($separator="' '", $elements = array()) {
  1372. if ($separator === "' '") {
  1373. $separator = "'*OCISP*'"; // New mega hack.
  1374. }
  1375. foreach ($elements as $k => $v) {
  1376. if ($v === "' '") {
  1377. $elements[$k] = "'*OCISP*'"; // New mega hack.
  1378. }
  1379. }
  1380. for ($n = count($elements)-1; $n > 0 ; $n--) {
  1381. array_splice($elements, $n, 0, $separator);
  1382. }
  1383. if (empty($elements)) {
  1384. return " ' ' ";
  1385. }
  1386. $s = $this->recursive_concat($elements);
  1387. return " MOODLELIB.UNDO_MEGA_HACK($s) ";
  1388. }
  1389. /**
  1390. * Constructs 'IN()' or '=' sql fragment
  1391. *
  1392. * Method overriding {@link moodle_database::get_in_or_equal} to be able to get
  1393. * more than 1000 elements working, to avoid ORA-01795. We use a pivoting technique
  1394. * to be able to transform the params into virtual rows, so the original IN()
  1395. * expression gets transformed into a subquery. Once more, be noted that we shouldn't
  1396. * be using ever get_in_or_equal() with such number of parameters (proper subquery and/or
  1397. * chunking should be used instead).
  1398. *
  1399. * @param mixed $items A single value or array of values for the expression.
  1400. * @param int $type Parameter bounding type : SQL_PARAMS_QM or SQL_PARAMS_NAMED.
  1401. * @param string $prefix Named parameter placeholder prefix (a unique counter value is appended to each parameter name).
  1402. * @param bool $equal True means we want to equate to the constructed expression, false means we don't want to equate to it.
  1403. * @param mixed $onemptyitems This defines the behavior when the array of items provided is empty. Defaults to false,
  1404. * meaning throw exceptions. Other values will become part of the returned SQL fragment.
  1405. * @throws coding_exception | dml_exception
  1406. * @return array A list containing the constructed sql fragment and an array of parameters.
  1407. */
  1408. public function get_in_or_equal($items, $type=SQL_PARAMS_QM, $prefix='param', $equal=true, $onemptyitems=false) {
  1409. list($sql, $params) = parent::get_in_or_equal($items, $type, $prefix, $equal, $onemptyitems);
  1410. // Less than 1000 elements, nothing to do.
  1411. if (count($params) < 1000) {
  1412. return array($sql, $params); // Return unmodified.
  1413. }
  1414. // Extract the interesting parts of the sql to rewrite.
  1415. if (preg_match('!(^.*IN \()([^\)]*)(.*)$!', $sql, $matches) === false) {
  1416. return array($sql, $params); // Return unmodified.
  1417. }
  1418. $instart = $matches[1];
  1419. $insql = $matches[2];
  1420. $inend = $matches[3];
  1421. $newsql = '';
  1422. // Some basic verification about the matching going ok.
  1423. $insqlarr = explode(',', $insql);
  1424. if (count($insqlarr) !== count($params)) {
  1425. return array($sql, $params); // Return unmodified.
  1426. }
  1427. // Arrived here, we need to chunk and pivot the params, building a new sql (params remain the same).
  1428. $addunionclause = false;
  1429. while ($chunk = array_splice($insqlarr, 0, 125)) { // Each chunk will handle up to 125 (+125 +1) elements (DECODE max is 255).
  1430. $chunksize = count($chunk);
  1431. if ($addunionclause) {
  1432. $newsql .= "\n UNION ALL";
  1433. }
  1434. $newsql .= "\n SELECT DECODE(pivot";
  1435. $counter = 1;
  1436. foreach ($chunk as $element) {
  1437. $newsql .= ",\n {$counter}, " . trim($element);
  1438. $counter++;
  1439. }
  1440. $newsql .= ")";
  1441. $newsql .= "\n FROM dual";
  1442. $newsql .= "\n CROSS JOIN (SELECT LEVEL AS pivot FROM dual CONNECT BY LEVEL <= {$chunksize})";
  1443. $addunionclause = true;
  1444. }
  1445. // Rebuild the complete IN() clause and return it.
  1446. return array($instart . $newsql . $inend, $params);
  1447. }
  1448. /**
  1449. * Mega hacky magic to work around crazy Oracle NULL concats.
  1450. * @param array $args
  1451. * @return string
  1452. */
  1453. protected function recursive_concat(array $args) {
  1454. $count = count($args);
  1455. if ($count == 1) {
  1456. $arg = reset($args);
  1457. return $arg;
  1458. }
  1459. if ($count == 2) {
  1460. $args[] = "' '";
  1461. // No return here intentionally.
  1462. }
  1463. $first = array_shift($args);
  1464. $second = array_shift($args);
  1465. $third = $this->recursive_concat($args);
  1466. return "MOODLELIB.TRICONCAT($first, $second, $third)";
  1467. }
  1468. /**
  1469. * Returns the SQL for returning searching one string for the location of another.
  1470. */
  1471. public function sql_position($needle, $haystack) {
  1472. return "INSTR(($haystack), ($needle))";
  1473. }
  1474. /**
  1475. * Returns the SQL to know if one field is empty.
  1476. *
  1477. * @param string $tablename Name of the table (without prefix). Not used for now but can be
  1478. * necessary in the future if we want to use some introspection using
  1479. * meta information against the DB.
  1480. * @param string $fieldname Name of the field we are going to check
  1481. * @param bool $nullablefield For specifying if the field is nullable (true) or no (false) in the DB.
  1482. * @param bool $textfield For specifying if it is a text (also called clob) field (true) or a varchar one (false)
  1483. * @return string the sql code to be added to check for empty values
  1484. */
  1485. public function sql_isempty($tablename, $fieldname, $nullablefield, $textfield) {
  1486. if ($textfield) {
  1487. return " (".$this->sql_compare_text($fieldname)." = ' ') ";
  1488. } else {
  1489. return " ($fieldname = ' ') ";
  1490. }
  1491. }
  1492. public function sql_order_by_text($fieldname, $numchars=32) {
  1493. return 'dbms_lob.substr(' . $fieldname . ', ' . $numchars . ',1)';
  1494. }
  1495. /**
  1496. * Is the required OCI server package installed?
  1497. * @return bool
  1498. */
  1499. protected function oci_package_installed() {
  1500. $sql = "SELECT 1
  1501. FROM user_objects
  1502. WHERE object_type = 'PACKAGE BODY'
  1503. AND object_name = 'MOODLELIB'
  1504. AND status = 'VALID'";
  1505. $this->query_start($sql, null, SQL_QUERY_AUX);
  1506. $stmt = $this->parse_query($sql);
  1507. $result = oci_execute($stmt, $this->commit_status);
  1508. $this->query_end($result, $stmt);
  1509. $records = null;
  1510. oci_fetch_all($stmt, $records, 0, -1, OCI_FETCHSTATEMENT_BY_ROW);
  1511. oci_free_statement($stmt);
  1512. return isset($records[0]) && reset($records[0]) ? true : false;
  1513. }
  1514. /**
  1515. * Try to add required moodle package into oracle server.
  1516. */
  1517. protected function attempt_oci_package_install() {
  1518. $sqls = file_get_contents(__DIR__.'/oci_native_moodle_package.sql');
  1519. $sqls = preg_split('/^\/$/sm', $sqls);
  1520. foreach ($sqls as $sql) {
  1521. $sql = trim($sql);
  1522. if ($sql === '' or $sql === 'SHOW ERRORS') {
  1523. continue;
  1524. }
  1525. $this->change_database_structure($sql);
  1526. }
  1527. }
  1528. public function session_lock_supported() {
  1529. return true;
  1530. }
  1531. /**
  1532. * Obtain session lock
  1533. * @param int $rowid id of the row with session record
  1534. * @param int $timeout max allowed time to wait for the lock in seconds
  1535. * @return void
  1536. */
  1537. public function get_session_lock($rowid, $timeout) {
  1538. parent::get_session_lock($rowid, $timeout);
  1539. $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid;
  1540. $sql = 'SELECT MOODLELIB.GET_LOCK(:lockname, :locktimeout) FROM DUAL';
  1541. $params = array('lockname' => $fullname , 'locktimeout' => $timeout);
  1542. $this->query_start($sql, $params, SQL_QUERY_AUX);
  1543. $stmt = $this->parse_query($sql);
  1544. $this->bind_params($stmt, $params);
  1545. $result = oci_execute($stmt, $this->commit_status);
  1546. if ($result === false) { // Any failure in get_lock() raises error, causing return of bool false
  1547. throw new dml_sessionwait_exception();
  1548. }
  1549. $this->query_end($result, $stmt);
  1550. oci_free_statement($stmt);
  1551. }
  1552. public function release_session_lock($rowid) {
  1553. if (!$this->used_for_db_sessions) {
  1554. return;
  1555. }
  1556. parent::release_session_lock($rowid);
  1557. $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid;
  1558. $params = array('lockname' => $fullname);
  1559. $sql = 'SELECT MOODLELIB.RELEASE_LOCK(:lockname) FROM DUAL';
  1560. $this->query_start($sql, $params, SQL_QUERY_AUX);
  1561. $stmt = $this->parse_query($sql);
  1562. $this->bind_params($stmt, $params);
  1563. $result = oci_execute($stmt, $this->commit_status);
  1564. $this->query_end($result, $stmt);
  1565. oci_free_statement($stmt);
  1566. }
  1567. /**
  1568. * Driver specific start of real database transaction,
  1569. * this can not be used directly in code.
  1570. * @return void
  1571. */
  1572. protected function begin_transaction() {
  1573. $this->commit_status = OCI_DEFAULT; //Done! ;-)
  1574. }
  1575. /**
  1576. * Driver specific commit of real database transaction,
  1577. * this can not be used directly in code.
  1578. * @return void
  1579. */
  1580. protected function commit_transaction() {
  1581. $this->query_start('--oracle_commit', NULL, SQL_QUERY_AUX);
  1582. $result = oci_commit($this->oci);
  1583. $this->commit_status = OCI_COMMIT_ON_SUCCESS;
  1584. $this->query_end($result);
  1585. }
  1586. /**
  1587. * Driver specific abort of real database transaction,
  1588. * this can not be used directly in code.
  1589. * @return void
  1590. */
  1591. protected function rollback_transaction() {
  1592. $this->query_start('--oracle_rollback', NULL, SQL_QUERY_AUX);
  1593. $result = oci_rollback($this->oci);
  1594. $this->commit_status = OCI_COMMIT_ON_SUCCESS;
  1595. $this->query_end($result);
  1596. }
  1597. }