PageRenderTime 47ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/dml/oci_native_moodle_database.php

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