Merge branch 'MDL-64012' of https://github.com/timhunt/moodle
[moodle.git] / lib / dml / oci_native_moodle_database.php
blob6f9161087f383787fb3c5c1ffdd93c5b752f3d32
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.
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/>.
17 /**
18 * Native oci class representing moodle database interface.
20 * @package core_dml
21 * @copyright 2008 Petr Skoda (http://skodak.org)
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') || die();
27 require_once(__DIR__.'/moodle_database.php');
28 require_once(__DIR__.'/oci_native_moodle_recordset.php');
29 require_once(__DIR__.'/oci_native_moodle_temptables.php');
31 /**
32 * Native oci class representing moodle database interface.
34 * One complete reference for PHP + OCI:
35 * http://www.oracle.com/technology/tech/php/underground-php-oracle-manual.html
37 * @package core_dml
38 * @copyright 2008 Petr Skoda (http://skodak.org)
39 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41 class oci_native_moodle_database extends moodle_database {
43 protected $oci = null;
45 /** @var To store stmt errors and enable get_last_error() to detect them.*/
46 private $last_stmt_error = null;
47 /** @var Default value initialised in connect method, we need the driver to be present.*/
48 private $commit_status = null;
50 /** @var To handle oci driver default verbosity.*/
51 private $last_error_reporting;
52 /** @var To store unique_session_id. Needed for temp tables unique naming.*/
53 private $unique_session_id;
55 /**
56 * Detects if all needed PHP stuff installed.
57 * Note: can be used before connect()
58 * @return mixed true if ok, string if something
60 public function driver_installed() {
61 if (!extension_loaded('oci8')) {
62 return get_string('ociextensionisnotpresentinphp', 'install');
64 return true;
67 /**
68 * Returns database family type - describes SQL dialect
69 * Note: can be used before connect()
70 * @return string db family name (mysql, postgres, mssql, oracle, etc.)
72 public function get_dbfamily() {
73 return 'oracle';
76 /**
77 * Returns more specific database driver type
78 * Note: can be used before connect()
79 * @return string db type mysqli, pgsql, oci, mssql, sqlsrv
81 protected function get_dbtype() {
82 return 'oci';
85 /**
86 * Returns general database library name
87 * Note: can be used before connect()
88 * @return string db type pdo, native
90 protected function get_dblibrary() {
91 return 'native';
94 /**
95 * Returns localised database type name
96 * Note: can be used before connect()
97 * @return string
99 public function get_name() {
100 return get_string('nativeoci', 'install');
104 * Returns localised database configuration help.
105 * Note: can be used before connect()
106 * @return string
108 public function get_configuration_help() {
109 return get_string('nativeocihelp', 'install');
113 * Diagnose database and tables, this function is used
114 * to verify database and driver settings, db engine types, etc.
116 * @return string null means everything ok, string means problem found.
118 public function diagnose() {
119 return null;
123 * Connect to db
124 * Must be called before other methods.
125 * @param string $dbhost The database host.
126 * @param string $dbuser The database username.
127 * @param string $dbpass The database username's password.
128 * @param string $dbname The name of the database being connected to.
129 * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
130 * @param array $dboptions driver specific options
131 * @return bool true
132 * @throws dml_connection_exception if error
134 public function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null) {
135 if ($prefix == '' and !$this->external) {
136 //Enforce prefixes for everybody but mysql
137 throw new dml_exception('prefixcannotbeempty', $this->get_dbfamily());
139 if (!$this->external and strlen($prefix) > 2) {
140 //Max prefix length for Oracle is 2cc
141 $a = (object)array('dbfamily'=>'oracle', 'maxlength'=>2);
142 throw new dml_exception('prefixtoolong', $a);
145 $driverstatus = $this->driver_installed();
147 if ($driverstatus !== true) {
148 throw new dml_exception('dbdriverproblem', $driverstatus);
151 // Autocommit ON by default.
152 // Switching to OFF (OCI_DEFAULT), when playing with transactions
153 // please note this thing is not defined if oracle driver not present in PHP
154 // which means it can not be used as default value of object property!
155 $this->commit_status = OCI_COMMIT_ON_SUCCESS;
157 $this->store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions);
158 unset($this->dboptions['dbsocket']);
160 // NOTE: use of ', ", / and \ is very problematic, even native oracle tools seem to have
161 // problems with these, so just forget them and do not report problems into tracker...
163 if (empty($this->dbhost)) {
164 // old style full address (TNS)
165 $dbstring = $this->dbname;
166 } else {
167 if (empty($this->dboptions['dbport'])) {
168 $this->dboptions['dbport'] = 1521;
170 $dbstring = '//'.$this->dbhost.':'.$this->dboptions['dbport'].'/'.$this->dbname;
173 ob_start();
174 if (empty($this->dboptions['dbpersist'])) {
175 $this->oci = oci_new_connect($this->dbuser, $this->dbpass, $dbstring, 'AL32UTF8');
176 } else {
177 $this->oci = oci_pconnect($this->dbuser, $this->dbpass, $dbstring, 'AL32UTF8');
179 $dberr = ob_get_contents();
180 ob_end_clean();
183 if ($this->oci === false) {
184 $this->oci = null;
185 $e = oci_error();
186 if (isset($e['message'])) {
187 $dberr = $e['message'];
189 throw new dml_connection_exception($dberr);
192 // Disable logging until we are fully setup.
193 $this->query_log_prevent();
195 // Make sure moodle package is installed - now required.
196 if (!$this->oci_package_installed()) {
197 try {
198 $this->attempt_oci_package_install();
199 } catch (Exception $e) {
200 // Ignore problems, only the result counts,
201 // admins have to fix it manually if necessary.
203 if (!$this->oci_package_installed()) {
204 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.');
208 // get unique session id, to be used later for temp tables stuff
209 $sql = 'SELECT DBMS_SESSION.UNIQUE_SESSION_ID() FROM DUAL';
210 $this->query_start($sql, null, SQL_QUERY_AUX);
211 $stmt = $this->parse_query($sql);
212 $result = oci_execute($stmt, $this->commit_status);
213 $this->query_end($result, $stmt);
214 $records = null;
215 oci_fetch_all($stmt, $records, 0, -1, OCI_FETCHSTATEMENT_BY_ROW);
216 oci_free_statement($stmt);
217 $this->unique_session_id = reset($records[0]);
219 //note: do not send "ALTER SESSION SET NLS_NUMERIC_CHARACTERS='.,'" !
220 // instead fix our PHP code to convert "," to "." properly!
222 // We can enable logging now.
223 $this->query_log_allow();
225 // Connection stabilised and configured, going to instantiate the temptables controller
226 $this->temptables = new oci_native_moodle_temptables($this, $this->unique_session_id);
228 return true;
232 * Close database connection and release all resources
233 * and memory (especially circular memory references).
234 * Do NOT use connect() again, create a new instance if needed.
236 public function dispose() {
237 parent::dispose(); // Call parent dispose to write/close session and other common stuff before closing connection
238 if ($this->oci) {
239 oci_close($this->oci);
240 $this->oci = null;
246 * Called before each db query.
247 * @param string $sql
248 * @param array array of parameters
249 * @param int $type type of query
250 * @param mixed $extrainfo driver specific extra information
251 * @return void
253 protected function query_start($sql, array $params=null, $type, $extrainfo=null) {
254 parent::query_start($sql, $params, $type, $extrainfo);
255 // oci driver tents to send debug to output, we do not need that ;-)
256 $this->last_error_reporting = error_reporting(0);
260 * Called immediately after each db query.
261 * @param mixed db specific result
262 * @return void
264 protected function query_end($result, $stmt=null) {
265 // reset original debug level
266 error_reporting($this->last_error_reporting);
267 if ($stmt and $result === false) {
268 // Look for stmt error and store it
269 if (is_resource($stmt)) {
270 $e = oci_error($stmt);
271 if ($e !== false) {
272 $this->last_stmt_error = $e['message'];
275 oci_free_statement($stmt);
277 parent::query_end($result);
281 * Returns database server info array
282 * @return array Array containing 'description' and 'version' info
284 public function get_server_info() {
285 static $info = null; // TODO: move to real object property
287 if (is_null($info)) {
288 $this->query_start("--oci_server_version()", null, SQL_QUERY_AUX);
289 $description = oci_server_version($this->oci);
290 $this->query_end(true);
291 preg_match('/(\d+\.)+\d+/', $description, $matches);
292 $info = array('description'=>$description, 'version'=>$matches[0]);
295 return $info;
299 * Converts short table name {tablename} to real table name
300 * supporting temp tables ($this->unique_session_id based) if detected
302 * @param string sql
303 * @return string sql
305 protected function fix_table_names($sql) {
306 if (preg_match_all('/\{([a-z][a-z0-9_]*)\}/', $sql, $matches)) {
307 foreach($matches[0] as $key=>$match) {
308 $name = $matches[1][$key];
309 if ($this->temptables && $this->temptables->is_temptable($name)) {
310 $sql = str_replace($match, $this->temptables->get_correct_name($name), $sql);
311 } else {
312 $sql = str_replace($match, $this->prefix.$name, $sql);
316 return $sql;
320 * Returns supported query parameter types
321 * @return int bitmask of accepted SQL_PARAMS_*
323 protected function allowed_param_types() {
324 return SQL_PARAMS_NAMED;
328 * Returns last error reported by database engine.
329 * @return string error message
331 public function get_last_error() {
332 $error = false;
333 // First look for any previously saved stmt error
334 if (!empty($this->last_stmt_error)) {
335 $error = $this->last_stmt_error;
336 $this->last_stmt_error = null;
337 } else { // Now try connection error
338 $e = oci_error($this->oci);
339 if ($e !== false) {
340 $error = $e['message'];
343 return $error;
347 * Prepare the statement for execution
348 * @throws dml_connection_exception
349 * @param string $sql
350 * @return resource
352 protected function parse_query($sql) {
353 $stmt = oci_parse($this->oci, $sql);
354 if ($stmt == false) {
355 throw new dml_connection_exception('Can not parse sql query'); //TODO: maybe add better info
357 return $stmt;
361 * Make sure there are no reserved words in param names...
362 * @param string $sql
363 * @param array $params
364 * @return array ($sql, $params) updated query and parameters
366 protected function tweak_param_names($sql, array $params) {
367 if (empty($params)) {
368 return array($sql, $params);
371 $newparams = array();
372 $searcharr = array(); // search => replace pairs
373 foreach ($params as $name => $value) {
374 // Keep the name within the 30 chars limit always (prefixing/replacing)
375 if (strlen($name) <= 28) {
376 $newname = 'o_' . $name;
377 } else {
378 $newname = 'o_' . substr($name, 2);
380 $newparams[$newname] = $value;
381 $searcharr[':' . $name] = ':' . $newname;
383 // sort by length desc to avoid potential str_replace() overlap
384 uksort($searcharr, array('oci_native_moodle_database', 'compare_by_length_desc'));
386 $sql = str_replace(array_keys($searcharr), $searcharr, $sql);
387 return array($sql, $newparams);
391 * Return tables in database WITHOUT current prefix
392 * @param bool $usecache if true, returns list of cached tables.
393 * @return array of table names in lowercase and without prefix
395 public function get_tables($usecache=true) {
396 if ($usecache and $this->tables !== null) {
397 return $this->tables;
399 $this->tables = array();
400 $prefix = str_replace('_', "\\_", strtoupper($this->prefix));
401 $sql = "SELECT TABLE_NAME
402 FROM CAT
403 WHERE TABLE_TYPE='TABLE'
404 AND TABLE_NAME NOT LIKE 'BIN\$%'
405 AND TABLE_NAME LIKE '$prefix%' ESCAPE '\\'";
406 $this->query_start($sql, null, SQL_QUERY_AUX);
407 $stmt = $this->parse_query($sql);
408 $result = oci_execute($stmt, $this->commit_status);
409 $this->query_end($result, $stmt);
410 $records = null;
411 oci_fetch_all($stmt, $records, 0, -1, OCI_ASSOC);
412 oci_free_statement($stmt);
413 $records = array_map('strtolower', $records['TABLE_NAME']);
414 foreach ($records as $tablename) {
415 if ($this->prefix !== false && $this->prefix !== '') {
416 if (strpos($tablename, $this->prefix) !== 0) {
417 continue;
419 $tablename = substr($tablename, strlen($this->prefix));
421 $this->tables[$tablename] = $tablename;
424 // Add the currently available temptables
425 $this->tables = array_merge($this->tables, $this->temptables->get_temptables());
427 return $this->tables;
431 * Return table indexes - everything lowercased.
432 * @param string $table The table we want to get indexes from.
433 * @return array An associative array of indexes containing 'unique' flag and 'columns' being indexed
435 public function get_indexes($table) {
436 $indexes = array();
437 $tablename = strtoupper($this->prefix.$table);
439 $sql = "SELECT i.INDEX_NAME, i.UNIQUENESS, c.COLUMN_POSITION, c.COLUMN_NAME, ac.CONSTRAINT_TYPE
440 FROM ALL_INDEXES i
441 JOIN ALL_IND_COLUMNS c ON c.INDEX_NAME=i.INDEX_NAME
442 LEFT JOIN ALL_CONSTRAINTS ac ON (ac.TABLE_NAME=i.TABLE_NAME AND ac.CONSTRAINT_NAME=i.INDEX_NAME AND ac.CONSTRAINT_TYPE='P')
443 WHERE i.TABLE_NAME = '$tablename'
444 ORDER BY i.INDEX_NAME, c.COLUMN_POSITION";
446 $stmt = $this->parse_query($sql);
447 $result = oci_execute($stmt, $this->commit_status);
448 $this->query_end($result, $stmt);
449 $records = null;
450 oci_fetch_all($stmt, $records, 0, -1, OCI_FETCHSTATEMENT_BY_ROW);
451 oci_free_statement($stmt);
453 foreach ($records as $record) {
454 if ($record['CONSTRAINT_TYPE'] === 'P') {
455 //ignore for now;
456 continue;
458 $indexname = strtolower($record['INDEX_NAME']);
459 if (!isset($indexes[$indexname])) {
460 $indexes[$indexname] = array('primary' => ($record['CONSTRAINT_TYPE'] === 'P'),
461 'unique' => ($record['UNIQUENESS'] === 'UNIQUE'),
462 'columns' => array());
464 $indexes[$indexname]['columns'][] = strtolower($record['COLUMN_NAME']);
467 return $indexes;
471 * Returns detailed information about columns in table. This information is cached internally.
472 * @param string $table name
473 * @param bool $usecache
474 * @return array array of database_column_info objects indexed with column names
476 public function get_columns($table, $usecache=true) {
478 if ($usecache) {
479 if ($this->temptables->is_temptable($table)) {
480 if ($data = $this->get_temp_tables_cache()->get($table)) {
481 return $data;
483 } else {
484 if ($data = $this->get_metacache()->get($table)) {
485 return $data;
490 if (!$table) { // table not specified, return empty array directly
491 return array();
494 $structure = array();
496 // We give precedence to CHAR_LENGTH for VARCHAR2 columns over WIDTH because the former is always
497 // BYTE based and, for cross-db operations, we want CHAR based results. See MDL-29415
498 // Instead of guessing sequence based exclusively on name, check tables against user_triggers to
499 // ensure the table has a 'before each row' trigger to assume 'id' is auto_increment. MDL-32365
500 $sql = "SELECT CNAME, COLTYPE, nvl(CHAR_LENGTH, WIDTH) AS WIDTH, SCALE, PRECISION, NULLS, DEFAULTVAL,
501 DECODE(NVL(TRIGGER_NAME, '0'), '0', '0', '1') HASTRIGGER
502 FROM COL c
503 LEFT JOIN USER_TAB_COLUMNS u ON (u.TABLE_NAME = c.TNAME AND u.COLUMN_NAME = c.CNAME AND u.DATA_TYPE = 'VARCHAR2')
504 LEFT JOIN USER_TRIGGERS t ON (t.TABLE_NAME = c.TNAME AND TRIGGER_TYPE = 'BEFORE EACH ROW' AND c.CNAME = 'ID')
505 WHERE TNAME = UPPER('{" . $table . "}')
506 ORDER BY COLNO";
508 list($sql, $params, $type) = $this->fix_sql_params($sql, null);
510 $this->query_start($sql, null, SQL_QUERY_AUX);
511 $stmt = $this->parse_query($sql);
512 $result = oci_execute($stmt, $this->commit_status);
513 $this->query_end($result, $stmt);
514 $records = null;
515 oci_fetch_all($stmt, $records, 0, -1, OCI_FETCHSTATEMENT_BY_ROW);
516 oci_free_statement($stmt);
518 if (!$records) {
519 return array();
521 foreach ($records as $rawcolumn) {
522 $rawcolumn = (object)$rawcolumn;
524 $info = new stdClass();
525 $info->name = strtolower($rawcolumn->CNAME);
526 $info->auto_increment = ((int)$rawcolumn->HASTRIGGER) ? true : false;
527 $matches = null;
529 if ($rawcolumn->COLTYPE === 'VARCHAR2'
530 or $rawcolumn->COLTYPE === 'VARCHAR'
531 or $rawcolumn->COLTYPE === 'NVARCHAR2'
532 or $rawcolumn->COLTYPE === 'NVARCHAR'
533 or $rawcolumn->COLTYPE === 'CHAR'
534 or $rawcolumn->COLTYPE === 'NCHAR') {
535 $info->type = $rawcolumn->COLTYPE;
536 $info->meta_type = 'C';
537 $info->max_length = $rawcolumn->WIDTH;
538 $info->scale = null;
539 $info->not_null = ($rawcolumn->NULLS === 'NOT NULL');
540 $info->has_default = !is_null($rawcolumn->DEFAULTVAL);
541 if ($info->has_default) {
543 // this is hacky :-(
544 if ($rawcolumn->DEFAULTVAL === 'NULL') {
545 $info->default_value = null;
546 } else if ($rawcolumn->DEFAULTVAL === "' ' ") { // Sometimes it's stored with trailing space
547 $info->default_value = "";
548 } else if ($rawcolumn->DEFAULTVAL === "' '") { // Sometimes it's stored without trailing space
549 $info->default_value = "";
550 } else {
551 $info->default_value = trim($rawcolumn->DEFAULTVAL); // remove trailing space
552 $info->default_value = substr($info->default_value, 1, strlen($info->default_value)-2); //trim ''
554 } else {
555 $info->default_value = null;
557 $info->primary_key = false;
558 $info->binary = false;
559 $info->unsigned = null;
560 $info->unique = null;
562 } else if ($rawcolumn->COLTYPE === 'NUMBER') {
563 $info->type = $rawcolumn->COLTYPE;
564 $info->max_length = $rawcolumn->PRECISION;
565 $info->binary = false;
566 if (!is_null($rawcolumn->SCALE) && $rawcolumn->SCALE == 0) { // null in oracle scale allows decimals => not integer
567 // integer
568 if ($info->name === 'id') {
569 $info->primary_key = true;
570 $info->meta_type = 'R';
571 $info->unique = true;
572 $info->has_default = false;
573 } else {
574 $info->primary_key = false;
575 $info->meta_type = 'I';
576 $info->unique = null;
578 $info->scale = 0;
580 } else {
581 //float
582 $info->meta_type = 'N';
583 $info->primary_key = false;
584 $info->unsigned = null;
585 $info->unique = null;
586 $info->scale = $rawcolumn->SCALE;
588 $info->not_null = ($rawcolumn->NULLS === 'NOT NULL');
589 $info->has_default = !is_null($rawcolumn->DEFAULTVAL);
590 if ($info->has_default) {
591 $info->default_value = trim($rawcolumn->DEFAULTVAL); // remove trailing space
592 } else {
593 $info->default_value = null;
596 } else if ($rawcolumn->COLTYPE === 'FLOAT') {
597 $info->type = $rawcolumn->COLTYPE;
598 $info->max_length = (int)($rawcolumn->PRECISION * 3.32193);
599 $info->primary_key = false;
600 $info->meta_type = 'N';
601 $info->unique = null;
602 $info->not_null = ($rawcolumn->NULLS === 'NOT NULL');
603 $info->has_default = !is_null($rawcolumn->DEFAULTVAL);
604 if ($info->has_default) {
605 $info->default_value = trim($rawcolumn->DEFAULTVAL); // remove trailing space
606 } else {
607 $info->default_value = null;
610 } else if ($rawcolumn->COLTYPE === 'CLOB'
611 or $rawcolumn->COLTYPE === 'NCLOB') {
612 $info->type = $rawcolumn->COLTYPE;
613 $info->meta_type = 'X';
614 $info->max_length = -1;
615 $info->scale = null;
616 $info->scale = null;
617 $info->not_null = ($rawcolumn->NULLS === 'NOT NULL');
618 $info->has_default = !is_null($rawcolumn->DEFAULTVAL);
619 if ($info->has_default) {
620 // this is hacky :-(
621 if ($rawcolumn->DEFAULTVAL === 'NULL') {
622 $info->default_value = null;
623 } else if ($rawcolumn->DEFAULTVAL === "' ' ") { // Sometimes it's stored with trailing space
624 $info->default_value = "";
625 } else if ($rawcolumn->DEFAULTVAL === "' '") { // Other times it's stored without trailing space
626 $info->default_value = "";
627 } else {
628 $info->default_value = trim($rawcolumn->DEFAULTVAL); // remove trailing space
629 $info->default_value = substr($info->default_value, 1, strlen($info->default_value)-2); //trim ''
631 } else {
632 $info->default_value = null;
634 $info->primary_key = false;
635 $info->binary = false;
636 $info->unsigned = null;
637 $info->unique = null;
639 } else if ($rawcolumn->COLTYPE === 'BLOB') {
640 $info->type = $rawcolumn->COLTYPE;
641 $info->meta_type = 'B';
642 $info->max_length = -1;
643 $info->scale = null;
644 $info->scale = null;
645 $info->not_null = ($rawcolumn->NULLS === 'NOT NULL');
646 $info->has_default = !is_null($rawcolumn->DEFAULTVAL);
647 if ($info->has_default) {
648 // this is hacky :-(
649 if ($rawcolumn->DEFAULTVAL === 'NULL') {
650 $info->default_value = null;
651 } else if ($rawcolumn->DEFAULTVAL === "' ' ") { // Sometimes it's stored with trailing space
652 $info->default_value = "";
653 } else if ($rawcolumn->DEFAULTVAL === "' '") { // Sometimes it's stored without trailing space
654 $info->default_value = "";
655 } else {
656 $info->default_value = trim($rawcolumn->DEFAULTVAL); // remove trailing space
657 $info->default_value = substr($info->default_value, 1, strlen($info->default_value)-2); //trim ''
659 } else {
660 $info->default_value = null;
662 $info->primary_key = false;
663 $info->binary = true;
664 $info->unsigned = null;
665 $info->unique = null;
667 } else {
668 // unknown type - sorry
669 $info->type = $rawcolumn->COLTYPE;
670 $info->meta_type = '?';
673 $structure[$info->name] = new database_column_info($info);
676 if ($usecache) {
677 if ($this->temptables->is_temptable($table)) {
678 $this->get_temp_tables_cache()->set($table, $structure);
679 } else {
680 $this->get_metacache()->set($table, $structure);
684 return $structure;
688 * Normalise values based in RDBMS dependencies (booleans, LOBs...)
690 * @param database_column_info $column column metadata corresponding with the value we are going to normalise
691 * @param mixed $value value we are going to normalise
692 * @return mixed the normalised value
694 protected function normalise_value($column, $value) {
695 $this->detect_objects($value);
697 if (is_bool($value)) { // Always, convert boolean to int
698 $value = (int)$value;
700 } else if ($column->meta_type == 'B') { // BLOB detected, we return 'blob' array instead of raw value to allow
701 if (!is_null($value)) { // binding/executing code later to know about its nature
702 $value = array('blob' => $value);
705 } else if ($column->meta_type == 'X' && strlen($value) > 4000) { // CLOB detected (>4000 optimisation), we return 'clob'
706 if (!is_null($value)) { // array instead of raw value to allow binding/
707 $value = array('clob' => (string)$value); // executing code later to know about its nature
710 } else if ($value === '') {
711 if ($column->meta_type == 'I' or $column->meta_type == 'F' or $column->meta_type == 'N') {
712 $value = 0; // prevent '' problems in numeric fields
715 return $value;
719 * Transforms the sql and params in order to emulate the LIMIT clause available in other DBs
721 * @param string $sql the SQL select query to execute.
722 * @param array $params array of sql parameters
723 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
724 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
725 * @return array with the transformed sql and params updated
727 private function get_limit_sql($sql, array $params = null, $limitfrom=0, $limitnum=0) {
729 list($limitfrom, $limitnum) = $this->normalise_limit_from_num($limitfrom, $limitnum);
730 // TODO: Add the /*+ FIRST_ROWS */ hint if there isn't another hint
732 if ($limitfrom and $limitnum) {
733 $sql = "SELECT oracle_o.*
734 FROM (SELECT oracle_i.*, rownum AS oracle_rownum
735 FROM ($sql) oracle_i
736 WHERE rownum <= :oracle_num_rows
737 ) oracle_o
738 WHERE oracle_rownum > :oracle_skip_rows";
739 $params['oracle_num_rows'] = $limitfrom + $limitnum;
740 $params['oracle_skip_rows'] = $limitfrom;
742 } else if ($limitfrom and !$limitnum) {
743 $sql = "SELECT oracle_o.*
744 FROM (SELECT oracle_i.*, rownum AS oracle_rownum
745 FROM ($sql) oracle_i
746 ) oracle_o
747 WHERE oracle_rownum > :oracle_skip_rows";
748 $params['oracle_skip_rows'] = $limitfrom;
750 } else if (!$limitfrom and $limitnum) {
751 $sql = "SELECT *
752 FROM ($sql)
753 WHERE rownum <= :oracle_num_rows";
754 $params['oracle_num_rows'] = $limitnum;
757 return array($sql, $params);
761 * This function will handle all the column values before being inserted/updated to DB for Oracle
762 * installations. This is because the "special feature" of Oracle where the empty string is
763 * equal to NULL and this presents a problem with all our currently NOT NULL default '' fields.
764 * (and with empties handling in general)
766 * Note that this function is 100% private and should be used, exclusively by DML functions
767 * in this file. Also, this is considered a DIRTY HACK to be removed when possible.
769 * This function is private and must not be used outside this driver at all
771 * @param $table string the table where the record is going to be inserted/updated (without prefix)
772 * @param $field string the field where the record is going to be inserted/updated
773 * @param $value mixed the value to be inserted/updated
775 private function oracle_dirty_hack ($table, $field, $value) {
777 // General bound parameter, just hack the spaces and pray it will work.
778 if (!$table) {
779 if ($value === '') {
780 return ' ';
781 } else if (is_bool($value)) {
782 return (int)$value;
783 } else {
784 return $value;
788 // Get metadata
789 $columns = $this->get_columns($table);
790 if (!isset($columns[$field])) {
791 if ($value === '') {
792 return ' ';
793 } else if (is_bool($value)) {
794 return (int)$value;
795 } else {
796 return $value;
799 $column = $columns[$field];
801 // !! This paragraph explains behaviour before Moodle 2.0:
803 // For Oracle DB, empty strings are converted to NULLs in DB
804 // and this breaks a lot of NOT NULL columns currently Moodle. In the future it's
805 // planned to move some of them to NULL, if they must accept empty values and this
806 // piece of code will become less and less used. But, for now, we need it.
807 // What we are going to do is to examine all the data being inserted and if it's
808 // an empty string (NULL for Oracle) and the field is defined as NOT NULL, we'll modify
809 // such data in the best form possible ("0" for booleans and numbers and " " for the
810 // rest of strings. It isn't optimal, but the only way to do so.
811 // In the opposite, when retrieving records from Oracle, we'll decode " " back to
812 // empty strings to allow everything to work properly. DIRTY HACK.
814 // !! These paragraphs explain the rationale about the change for Moodle 2.5:
816 // Before Moodle 2.0, we only used to apply this DIRTY HACK to NOT NULL columns, as
817 // stated above, but it causes one problem in NULL columns where both empty strings
818 // and real NULLs are stored as NULLs, being impossible to differentiate them when
819 // being retrieved from DB.
821 // So, starting with Moodle 2.0, we are going to apply the DIRTY HACK to all the
822 // CHAR/CLOB columns no matter of their nullability. That way, when retrieving
823 // NULLABLE fields we'll get proper empties and NULLs differentiated, so we'll be able
824 // to rely in NULL/empty/content contents without problems, until now that wasn't
825 // possible at all.
827 // One space DIRTY HACK is now applied automatically for all query parameters
828 // and results. The only problem is string concatenation where the glue must
829 // be specified as "' '" sql fragment.
831 // !! Conclusions:
833 // From Moodle 2.5 onwards, ALL empty strings in Oracle DBs will be stored as
834 // 1-whitespace char, ALL NULLs as NULLs and, obviously, content as content. And
835 // those 1-whitespace chars will be converted back to empty strings by all the
836 // get_field/record/set() functions transparently and any SQL needing direct handling
837 // of empties will have to use placeholders or sql_isempty() helper function.
839 // If the field isn't VARCHAR or CLOB, skip
840 if ($column->meta_type != 'C' and $column->meta_type != 'X') {
841 return $value;
844 // If the value isn't empty, skip
845 if (!empty($value)) {
846 return $value;
849 // Now, we have one empty value, going to be inserted to one VARCHAR2 or CLOB field
850 // Try to get the best value to be inserted
852 // The '0' string doesn't need any transformation, skip
853 if ($value === '0') {
854 return $value;
857 // Transformations start
858 if (gettype($value) == 'boolean') {
859 return '0'; // Transform false to '0' that evaluates the same for PHP
861 } else if (gettype($value) == 'integer') {
862 return '0'; // Transform 0 to '0' that evaluates the same for PHP
864 } else if ($value === '') {
865 return ' '; // Transform '' to ' ' that DON'T EVALUATE THE SAME
866 // (we'll transform back again on get_records_XXX functions and others)!!
869 // Fail safe to original value
870 return $value;
874 * Helper function to order by string length desc
876 * @param $a string first element to compare
877 * @param $b string second element to compare
878 * @return int < 0 $a goes first (is less), 0 $b goes first, 0 doesn't matter
880 private function compare_by_length_desc($a, $b) {
881 return strlen($b) - strlen($a);
885 * Is db in unicode mode?
886 * @return bool
888 public function setup_is_unicodedb() {
889 $sql = "SELECT VALUE
890 FROM NLS_DATABASE_PARAMETERS
891 WHERE PARAMETER = 'NLS_CHARACTERSET'";
892 $this->query_start($sql, null, SQL_QUERY_AUX);
893 $stmt = $this->parse_query($sql);
894 $result = oci_execute($stmt, $this->commit_status);
895 $this->query_end($result, $stmt);
896 $records = null;
897 oci_fetch_all($stmt, $records, 0, -1, OCI_FETCHSTATEMENT_BY_COLUMN);
898 oci_free_statement($stmt);
900 return (isset($records['VALUE'][0]) and $records['VALUE'][0] === 'AL32UTF8');
904 * Do NOT use in code, to be used by database_manager only!
905 * @param string|array $sql query
906 * @param array|null $tablenames an array of xmldb table names affected by this request.
907 * @return bool true
908 * @throws ddl_change_structure_exception A DDL specific exception is thrown for any errors.
910 public function change_database_structure($sql, $tablenames = null) {
911 $this->get_manager(); // Includes DDL exceptions classes ;-)
912 $sqls = (array)$sql;
914 try {
915 foreach ($sqls as $sql) {
916 $this->query_start($sql, null, SQL_QUERY_STRUCTURE);
917 $stmt = $this->parse_query($sql);
918 $result = oci_execute($stmt, $this->commit_status);
919 $this->query_end($result, $stmt);
920 oci_free_statement($stmt);
922 } catch (ddl_change_structure_exception $e) {
923 $this->reset_caches($tablenames);
924 throw $e;
927 $this->reset_caches($tablenames);
928 return true;
931 protected function bind_params($stmt, array &$params=null, $tablename=null, array &$descriptors = null) {
932 if ($params) {
933 $columns = array();
934 if ($tablename) {
935 $columns = $this->get_columns($tablename);
937 foreach($params as $key => $value) {
938 // Decouple column name and param name as far as sometimes they aren't the same
939 if ($key == 'o_newfieldtoset') { // found case where column and key diverge, handle that
940 $columnname = key($value); // columnname is the key of the array
941 $params[$key] = $value[$columnname]; // set the proper value in the $params array and
942 $value = $value[$columnname]; // set the proper value in the $value variable
943 } else {
944 $columnname = preg_replace('/^o_/', '', $key); // Default columnname (for DB introspecting is key), but...
946 // Continue processing
947 // Now, handle already detected LOBs
948 if (is_array($value)) { // Let's go to bind special cases (lob descriptors)
949 if (isset($value['clob'])) {
950 $lob = oci_new_descriptor($this->oci, OCI_DTYPE_LOB);
951 if ($descriptors === null) {
952 throw new coding_exception('moodle_database::bind_params() $descriptors not specified for clob');
954 $descriptors[] = $lob;
955 oci_bind_by_name($stmt, $key, $lob, -1, SQLT_CLOB);
956 $lob->writeTemporary($this->oracle_dirty_hack($tablename, $columnname, $params[$key]['clob']), OCI_TEMP_CLOB);
957 continue; // Column binding finished, go to next one
958 } else if (isset($value['blob'])) {
959 $lob = oci_new_descriptor($this->oci, OCI_DTYPE_LOB);
960 if ($descriptors === null) {
961 throw new coding_exception('moodle_database::bind_params() $descriptors not specified for clob');
963 $descriptors[] = $lob;
964 oci_bind_by_name($stmt, $key, $lob, -1, SQLT_BLOB);
965 $lob->writeTemporary($params[$key]['blob'], OCI_TEMP_BLOB);
966 continue; // Column binding finished, go to next one
968 } else {
969 // If, at this point, the param value > 4000 (bytes), let's assume it's a clob
970 // passed in an arbitrary sql (not processed by normalise_value() ever,
971 // and let's handle it as such. This will provide proper binding of CLOBs in
972 // conditions and other raw SQLs not covered by the above function.
973 if (strlen($value) > 4000) {
974 $lob = oci_new_descriptor($this->oci, OCI_DTYPE_LOB);
975 if ($descriptors === null) {
976 throw new coding_exception('moodle_database::bind_params() $descriptors not specified for clob');
978 $descriptors[] = $lob;
979 oci_bind_by_name($stmt, $key, $lob, -1, SQLT_CLOB);
980 $lob->writeTemporary($this->oracle_dirty_hack($tablename, $columnname, $params[$key]), OCI_TEMP_CLOB);
981 continue; // Param binding finished, go to next one.
984 // TODO: Put proper types and length is possible (enormous speedup)
985 // Arrived here, continue with standard processing, using metadata if possible
986 if (isset($columns[$columnname])) {
987 $type = $columns[$columnname]->meta_type;
988 $maxlength = $columns[$columnname]->max_length;
989 } else {
990 $type = '?';
991 $maxlength = -1;
993 switch ($type) {
994 case 'I':
995 case 'R':
996 // TODO: Optimise
997 oci_bind_by_name($stmt, $key, $params[$key]);
998 break;
1000 case 'N':
1001 case 'F':
1002 // TODO: Optimise
1003 oci_bind_by_name($stmt, $key, $params[$key]);
1004 break;
1006 case 'B':
1007 // TODO: Only arrive here if BLOB is null: Bind if so, else exception!
1008 // don't break here
1010 case 'X':
1011 // TODO: Only arrive here if CLOB is null or <= 4000 cc, else exception
1012 // don't break here
1014 default: // Bind as CHAR (applying dirty hack)
1015 // TODO: Optimise
1016 $params[$key] = $this->oracle_dirty_hack($tablename, $columnname, $params[$key]);
1017 // Because of PHP7 bug (https://bugs.php.net/bug.php?id=72524) it seems that it's
1018 // impossible to bind NULL values in a reliable way, let's use empty string
1019 // instead in the mean time.
1020 if ($params[$key] === null && version_compare(PHP_VERSION, '7.0.0', '>=')) {
1021 $params[$key] = '';
1023 oci_bind_by_name($stmt, $key, $params[$key]);
1027 return $descriptors;
1030 protected function free_descriptors($descriptors) {
1031 foreach ($descriptors as $descriptor) {
1032 // Because all descriptors used in the driver come from LOB::writeTemporary() calls
1033 // we can safely close them here unconditionally.
1034 $descriptor->close();
1035 // Free resources.
1036 oci_free_descriptor($descriptor);
1041 * This function is used to convert all the Oracle 1-space defaults to the empty string
1042 * like a really DIRTY HACK to allow it to work better until all those NOT NULL DEFAULT ''
1043 * fields will be out from Moodle.
1044 * @param string the string to be converted to '' (empty string) if it's ' ' (one space)
1045 * @param mixed the key of the array in case we are using this function from array_walk,
1046 * defaults to null for other (direct) uses
1047 * @return boolean always true (the converted variable is returned by reference)
1049 public static function onespace2empty(&$item, $key=null) {
1050 $item = ($item === ' ') ? '' : $item;
1051 return true;
1055 * Execute general sql query. Should be used only when no other method suitable.
1056 * Do NOT use this to make changes in db structure, use database_manager methods instead!
1057 * @param string $sql query
1058 * @param array $params query parameters
1059 * @return bool true
1060 * @throws dml_exception A DML specific exception is thrown for any errors.
1062 public function execute($sql, array $params=null) {
1063 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
1065 if (strpos($sql, ';') !== false) {
1066 throw new coding_exception('moodle_database::execute() Multiple sql statements found or bound parameters not used properly in query!');
1069 list($sql, $params) = $this->tweak_param_names($sql, $params);
1070 $this->query_start($sql, $params, SQL_QUERY_UPDATE);
1071 $stmt = $this->parse_query($sql);
1072 $descriptors = array();
1073 $this->bind_params($stmt, $params, null, $descriptors);
1074 $result = oci_execute($stmt, $this->commit_status);
1075 $this->free_descriptors($descriptors);
1076 $this->query_end($result, $stmt);
1077 oci_free_statement($stmt);
1079 return true;
1083 * Get a single database record as an object using a SQL statement.
1085 * The SQL statement should normally only return one record.
1086 * It is recommended to use get_records_sql() if more matches possible!
1088 * @param string $sql The SQL string you wish to be executed, should normally only return one record.
1089 * @param array $params array of sql parameters
1090 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1091 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1092 * MUST_EXIST means throw exception if no record or multiple records found
1093 * @return mixed a fieldset object containing the first matching record, false or exception if error not found depending on mode
1094 * @throws dml_exception A DML specific exception is thrown for any errors.
1096 public function get_record_sql($sql, array $params=null, $strictness=IGNORE_MISSING) {
1097 $strictness = (int)$strictness;
1098 if ($strictness == IGNORE_MULTIPLE) {
1099 // do not limit here - ORA does not like that
1100 $rs = $this->get_recordset_sql($sql, $params);
1101 $result = false;
1102 foreach ($rs as $rec) {
1103 $result = $rec;
1104 break;
1106 $rs->close();
1107 return $result;
1109 return parent::get_record_sql($sql, $params, $strictness);
1113 * Get a number of records as a moodle_recordset using a SQL statement.
1115 * Since this method is a little less readable, use of it should be restricted to
1116 * code where it's possible there might be large datasets being returned. For known
1117 * small datasets use get_records_sql - it leads to simpler code.
1119 * The return type is like:
1120 * @see function get_recordset.
1122 * @param string $sql the SQL select query to execute.
1123 * @param array $params array of sql parameters
1124 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
1125 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1126 * @return moodle_recordset instance
1127 * @throws dml_exception A DML specific exception is thrown for any errors.
1129 public function get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
1131 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
1133 list($rawsql, $params) = $this->get_limit_sql($sql, $params, $limitfrom, $limitnum);
1135 list($rawsql, $params) = $this->tweak_param_names($rawsql, $params);
1136 $this->query_start($rawsql, $params, SQL_QUERY_SELECT);
1137 $stmt = $this->parse_query($rawsql);
1138 $descriptors = array();
1139 $this->bind_params($stmt, $params, null, $descriptors);
1140 $result = oci_execute($stmt, $this->commit_status);
1141 $this->free_descriptors($descriptors);
1142 $this->query_end($result, $stmt);
1144 return $this->create_recordset($stmt);
1147 protected function create_recordset($stmt) {
1148 return new oci_native_moodle_recordset($stmt);
1152 * Get a number of records as an array of objects using a SQL statement.
1154 * Return value is like:
1155 * @see function get_records.
1157 * @param string $sql the SQL select query to execute. The first column of this SELECT statement
1158 * must be a unique value (usually the 'id' field), as it will be used as the key of the
1159 * returned array.
1160 * @param array $params array of sql parameters
1161 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
1162 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1163 * @return array of objects, or empty array if no records were found
1164 * @throws dml_exception A DML specific exception is thrown for any errors.
1166 public function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
1168 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
1170 list($rawsql, $params) = $this->get_limit_sql($sql, $params, $limitfrom, $limitnum);
1172 list($rawsql, $params) = $this->tweak_param_names($rawsql, $params);
1173 $this->query_start($rawsql, $params, SQL_QUERY_SELECT);
1174 $stmt = $this->parse_query($rawsql);
1175 $descriptors = array();
1176 $this->bind_params($stmt, $params, null, $descriptors);
1177 $result = oci_execute($stmt, $this->commit_status);
1178 $this->free_descriptors($descriptors);
1179 $this->query_end($result, $stmt);
1181 $records = null;
1182 oci_fetch_all($stmt, $records, 0, -1, OCI_FETCHSTATEMENT_BY_ROW);
1183 oci_free_statement($stmt);
1185 $return = array();
1187 foreach ($records as $row) {
1188 $row = array_change_key_case($row, CASE_LOWER);
1189 unset($row['oracle_rownum']);
1190 array_walk($row, array('oci_native_moodle_database', 'onespace2empty'));
1191 $id = reset($row);
1192 if (isset($return[$id])) {
1193 $colname = key($row);
1194 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);
1196 $return[$id] = (object)$row;
1199 return $return;
1203 * Selects records and return values (first field) as an array using a SQL statement.
1205 * @param string $sql The SQL query
1206 * @param array $params array of sql parameters
1207 * @return array of values
1208 * @throws dml_exception A DML specific exception is thrown for any errors.
1210 public function get_fieldset_sql($sql, array $params=null) {
1211 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
1213 list($sql, $params) = $this->tweak_param_names($sql, $params);
1214 $this->query_start($sql, $params, SQL_QUERY_SELECT);
1215 $stmt = $this->parse_query($sql);
1216 $descriptors = array();
1217 $this->bind_params($stmt, $params, null, $descriptors);
1218 $result = oci_execute($stmt, $this->commit_status);
1219 $this->free_descriptors($descriptors);
1220 $this->query_end($result, $stmt);
1222 $records = null;
1223 oci_fetch_all($stmt, $records, 0, -1, OCI_FETCHSTATEMENT_BY_COLUMN);
1224 oci_free_statement($stmt);
1226 $return = reset($records);
1227 array_walk($return, array('oci_native_moodle_database', 'onespace2empty'));
1229 return $return;
1233 * Insert new record into database, as fast as possible, no safety checks, lobs not supported.
1234 * @param string $table name
1235 * @param mixed $params data record as object or array
1236 * @param bool $returnit return it of inserted record
1237 * @param bool $bulk true means repeated inserts expected
1238 * @param bool $customsequence true if 'id' included in $params, disables $returnid
1239 * @return bool|int true or new id
1240 * @throws dml_exception A DML specific exception is thrown for any errors.
1242 public function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false) {
1243 if (!is_array($params)) {
1244 $params = (array)$params;
1247 $returning = "";
1249 if ($customsequence) {
1250 if (!isset($params['id'])) {
1251 throw new coding_exception('moodle_database::insert_record_raw() id field must be specified if custom sequences used.');
1253 $returnid = false;
1254 } else {
1255 unset($params['id']);
1256 if ($returnid) {
1257 $returning = " RETURNING id INTO :oracle_id"; // crazy name nobody is ever going to use or parameter ;-)
1261 if (empty($params)) {
1262 throw new coding_exception('moodle_database::insert_record_raw() no fields found.');
1265 $fields = implode(',', array_keys($params));
1266 $values = array();
1267 foreach ($params as $pname => $value) {
1268 $values[] = ":$pname";
1270 $values = implode(',', $values);
1272 $sql = "INSERT INTO {" . $table . "} ($fields) VALUES ($values)";
1273 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
1274 $sql .= $returning;
1276 $id = 0;
1278 // note we don't need tweak_param_names() here. Placeholders are safe column names. MDL-28080
1279 // list($sql, $params) = $this->tweak_param_names($sql, $params);
1280 $this->query_start($sql, $params, SQL_QUERY_INSERT);
1281 $stmt = $this->parse_query($sql);
1282 if ($returning) {
1283 oci_bind_by_name($stmt, ":oracle_id", $id, 10, SQLT_INT);
1285 $descriptors = array();
1286 $this->bind_params($stmt, $params, $table, $descriptors);
1287 $result = oci_execute($stmt, $this->commit_status);
1288 $this->free_descriptors($descriptors);
1289 $this->query_end($result, $stmt);
1290 oci_free_statement($stmt);
1292 if (!$returnid) {
1293 return true;
1296 if (!$returning) {
1297 die('TODO - implement oracle 9.2 insert support'); //TODO
1300 return (int)$id;
1304 * Insert a record into a table and return the "id" field if required.
1306 * Some conversions and safety checks are carried out. Lobs are supported.
1307 * If the return ID isn't required, then this just reports success as true/false.
1308 * $data is an object containing needed data
1309 * @param string $table The database table to be inserted into
1310 * @param object $data A data object with values for one or more fields in the record
1311 * @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.
1312 * @return bool|int true or new id
1313 * @throws dml_exception A DML specific exception is thrown for any errors.
1315 public function insert_record($table, $dataobject, $returnid=true, $bulk=false) {
1316 $dataobject = (array)$dataobject;
1318 $columns = $this->get_columns($table);
1319 if (empty($columns)) {
1320 throw new dml_exception('ddltablenotexist', $table);
1323 $cleaned = array();
1325 foreach ($dataobject as $field=>$value) {
1326 if ($field === 'id') {
1327 continue;
1329 if (!isset($columns[$field])) { // Non-existing table field, skip it
1330 continue;
1332 $column = $columns[$field];
1333 $cleaned[$field] = $this->normalise_value($column, $value);
1336 return $this->insert_record_raw($table, $cleaned, $returnid, $bulk);
1340 * Import a record into a table, id field is required.
1341 * Safety checks are NOT carried out. Lobs are supported.
1343 * @param string $table name of database table to be inserted into
1344 * @param object $dataobject A data object with values for one or more fields in the record
1345 * @return bool true
1346 * @throws dml_exception A DML specific exception is thrown for any errors.
1348 public function import_record($table, $dataobject) {
1349 $dataobject = (array)$dataobject;
1351 $columns = $this->get_columns($table);
1352 $cleaned = array();
1354 foreach ($dataobject as $field=>$value) {
1355 if (!isset($columns[$field])) {
1356 continue;
1358 $column = $columns[$field];
1359 $cleaned[$field] = $this->normalise_value($column, $value);
1362 return $this->insert_record_raw($table, $cleaned, false, true, true);
1366 * Update record in database, as fast as possible, no safety checks, lobs not supported.
1367 * @param string $table name
1368 * @param mixed $params data record as object or array
1369 * @param bool true means repeated updates expected
1370 * @return bool true
1371 * @throws dml_exception A DML specific exception is thrown for any errors.
1373 public function update_record_raw($table, $params, $bulk=false) {
1374 $params = (array)$params;
1376 if (!isset($params['id'])) {
1377 throw new coding_exception('moodle_database::update_record_raw() id field must be specified.');
1380 if (empty($params)) {
1381 throw new coding_exception('moodle_database::update_record_raw() no fields found.');
1384 $sets = array();
1385 foreach ($params as $field=>$value) {
1386 if ($field == 'id') {
1387 continue;
1389 $sets[] = "$field = :$field";
1392 $sets = implode(',', $sets);
1393 $sql = "UPDATE {" . $table . "} SET $sets WHERE id=:id";
1394 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
1396 // note we don't need tweak_param_names() here. Placeholders are safe column names. MDL-28080
1397 // list($sql, $params) = $this->tweak_param_names($sql, $params);
1398 $this->query_start($sql, $params, SQL_QUERY_UPDATE);
1399 $stmt = $this->parse_query($sql);
1400 $descriptors = array();
1401 $this->bind_params($stmt, $params, $table, $descriptors);
1402 $result = oci_execute($stmt, $this->commit_status);
1403 $this->free_descriptors($descriptors);
1404 $this->query_end($result, $stmt);
1405 oci_free_statement($stmt);
1407 return true;
1411 * Update a record in a table
1413 * $dataobject is an object containing needed data
1414 * Relies on $dataobject having a variable "id" to
1415 * specify the record to update
1417 * @param string $table The database table to be checked against.
1418 * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
1419 * @param bool true means repeated updates expected
1420 * @return bool true
1421 * @throws dml_exception A DML specific exception is thrown for any errors.
1423 public function update_record($table, $dataobject, $bulk=false) {
1424 $dataobject = (array)$dataobject;
1426 $columns = $this->get_columns($table);
1427 $cleaned = array();
1429 foreach ($dataobject as $field=>$value) {
1430 if (!isset($columns[$field])) {
1431 continue;
1433 $column = $columns[$field];
1434 $cleaned[$field] = $this->normalise_value($column, $value);
1437 $this->update_record_raw($table, $cleaned, $bulk);
1439 return true;
1443 * Set a single field in every table record which match a particular WHERE clause.
1445 * @param string $table The database table to be checked against.
1446 * @param string $newfield the field to set.
1447 * @param string $newvalue the value to set the field to.
1448 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1449 * @param array $params array of sql parameters
1450 * @return bool true
1451 * @throws dml_exception A DML specific exception is thrown for any errors.
1453 public function set_field_select($table, $newfield, $newvalue, $select, array $params=null) {
1455 if ($select) {
1456 $select = "WHERE $select";
1458 if (is_null($params)) {
1459 $params = array();
1462 // Get column metadata
1463 $columns = $this->get_columns($table);
1464 $column = $columns[$newfield];
1466 $newvalue = $this->normalise_value($column, $newvalue);
1468 list($select, $params, $type) = $this->fix_sql_params($select, $params);
1470 if (is_bool($newvalue)) {
1471 $newvalue = (int)$newvalue; // prevent "false" problems
1473 if (is_null($newvalue)) {
1474 $newsql = "$newfield = NULL";
1475 } else {
1476 // Set the param to array ($newfield => $newvalue) and key to 'newfieldtoset'
1477 // name in the build sql. Later, bind_params() will detect the value array and
1478 // perform the needed modifications to allow the query to work. Note that
1479 // 'newfieldtoset' is one arbitrary name that hopefully won't be used ever
1480 // in order to avoid problems where the same field is used both in the set clause and in
1481 // the conditions. This was breaking badly in drivers using NAMED params like oci.
1482 $params['newfieldtoset'] = array($newfield => $newvalue);
1483 $newsql = "$newfield = :newfieldtoset";
1485 $sql = "UPDATE {" . $table . "} SET $newsql $select";
1486 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
1488 list($sql, $params) = $this->tweak_param_names($sql, $params);
1489 $this->query_start($sql, $params, SQL_QUERY_UPDATE);
1490 $stmt = $this->parse_query($sql);
1491 $descriptors = array();
1492 $this->bind_params($stmt, $params, $table, $descriptors);
1493 $result = oci_execute($stmt, $this->commit_status);
1494 $this->free_descriptors($descriptors);
1495 $this->query_end($result, $stmt);
1496 oci_free_statement($stmt);
1498 return true;
1502 * Delete one or more records from a table which match a particular WHERE clause.
1504 * @param string $table The database table to be checked against.
1505 * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
1506 * @param array $params array of sql parameters
1507 * @return bool true
1508 * @throws dml_exception A DML specific exception is thrown for any errors.
1510 public function delete_records_select($table, $select, array $params=null) {
1512 if ($select) {
1513 $select = "WHERE $select";
1516 $sql = "DELETE FROM {" . $table . "} $select";
1518 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
1520 list($sql, $params) = $this->tweak_param_names($sql, $params);
1521 $this->query_start($sql, $params, SQL_QUERY_UPDATE);
1522 $stmt = $this->parse_query($sql);
1523 $descriptors = array();
1524 $this->bind_params($stmt, $params, null, $descriptors);
1525 $result = oci_execute($stmt, $this->commit_status);
1526 $this->free_descriptors($descriptors);
1527 $this->query_end($result, $stmt);
1528 oci_free_statement($stmt);
1530 return true;
1533 function sql_null_from_clause() {
1534 return ' FROM dual';
1537 public function sql_bitand($int1, $int2) {
1538 return 'bitand((' . $int1 . '), (' . $int2 . '))';
1541 public function sql_bitnot($int1) {
1542 return '((0 - (' . $int1 . ')) - 1)';
1545 public function sql_bitor($int1, $int2) {
1546 return 'MOODLELIB.BITOR(' . $int1 . ', ' . $int2 . ')';
1549 public function sql_bitxor($int1, $int2) {
1550 return 'MOODLELIB.BITXOR(' . $int1 . ', ' . $int2 . ')';
1554 * Returns the SQL text to be used in order to perform module '%'
1555 * operation - remainder after division
1557 * @param integer int1 first integer in the operation
1558 * @param integer int2 second integer in the operation
1559 * @return string the piece of SQL code to be used in your statement.
1561 public function sql_modulo($int1, $int2) {
1562 return 'MOD(' . $int1 . ', ' . $int2 . ')';
1565 public function sql_cast_char2int($fieldname, $text=false) {
1566 if (!$text) {
1567 return ' CAST(' . $fieldname . ' AS INT) ';
1568 } else {
1569 return ' CAST(' . $this->sql_compare_text($fieldname) . ' AS INT) ';
1573 public function sql_cast_char2real($fieldname, $text=false) {
1574 if (!$text) {
1575 return ' CAST(' . $fieldname . ' AS FLOAT) ';
1576 } else {
1577 return ' CAST(' . $this->sql_compare_text($fieldname) . ' AS FLOAT) ';
1582 * Returns 'LIKE' part of a query.
1584 * @param string $fieldname usually name of the table column
1585 * @param string $param usually bound query parameter (?, :named)
1586 * @param bool $casesensitive use case sensitive search
1587 * @param bool $accensensitive use accent sensitive search (not all databases support accent insensitive)
1588 * @param bool $notlike true means "NOT LIKE"
1589 * @param string $escapechar escape char for '%' and '_'
1590 * @return string SQL code fragment
1592 public function sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = '\\') {
1593 if (strpos($param, '%') !== false) {
1594 debugging('Potential SQL injection detected, sql_like() expects bound parameters (? or :named)');
1597 $LIKE = $notlike ? 'NOT LIKE' : 'LIKE';
1599 // no accent sensitiveness here for now, sorry
1601 if ($casesensitive) {
1602 return "$fieldname $LIKE $param ESCAPE '$escapechar'";
1603 } else {
1604 return "LOWER($fieldname) $LIKE LOWER($param) ESCAPE '$escapechar'";
1608 public function sql_concat() {
1609 $arr = func_get_args();
1610 if (empty($arr)) {
1611 return " ' ' ";
1613 foreach ($arr as $k => $v) {
1614 if ($v === "' '") {
1615 $arr[$k] = "'*OCISP*'"; // New mega hack.
1618 $s = $this->recursive_concat($arr);
1619 return " MOODLELIB.UNDO_MEGA_HACK($s) ";
1622 public function sql_concat_join($separator="' '", $elements = array()) {
1623 if ($separator === "' '") {
1624 $separator = "'*OCISP*'"; // New mega hack.
1626 foreach ($elements as $k => $v) {
1627 if ($v === "' '") {
1628 $elements[$k] = "'*OCISP*'"; // New mega hack.
1631 for ($n = count($elements)-1; $n > 0 ; $n--) {
1632 array_splice($elements, $n, 0, $separator);
1634 if (empty($elements)) {
1635 return " ' ' ";
1637 $s = $this->recursive_concat($elements);
1638 return " MOODLELIB.UNDO_MEGA_HACK($s) ";
1642 * Constructs 'IN()' or '=' sql fragment
1644 * Method overriding {@link moodle_database::get_in_or_equal} to be able to get
1645 * more than 1000 elements working, to avoid ORA-01795. We use a pivoting technique
1646 * to be able to transform the params into virtual rows, so the original IN()
1647 * expression gets transformed into a subquery. Once more, be noted that we shouldn't
1648 * be using ever get_in_or_equal() with such number of parameters (proper subquery and/or
1649 * chunking should be used instead).
1651 * @param mixed $items A single value or array of values for the expression.
1652 * @param int $type Parameter bounding type : SQL_PARAMS_QM or SQL_PARAMS_NAMED.
1653 * @param string $prefix Named parameter placeholder prefix (a unique counter value is appended to each parameter name).
1654 * @param bool $equal True means we want to equate to the constructed expression, false means we don't want to equate to it.
1655 * @param mixed $onemptyitems This defines the behavior when the array of items provided is empty. Defaults to false,
1656 * meaning throw exceptions. Other values will become part of the returned SQL fragment.
1657 * @throws coding_exception | dml_exception
1658 * @return array A list containing the constructed sql fragment and an array of parameters.
1660 public function get_in_or_equal($items, $type=SQL_PARAMS_QM, $prefix='param', $equal=true, $onemptyitems=false) {
1661 list($sql, $params) = parent::get_in_or_equal($items, $type, $prefix, $equal, $onemptyitems);
1663 // Less than 1000 elements, nothing to do.
1664 if (count($params) < 1000) {
1665 return array($sql, $params); // Return unmodified.
1668 // Extract the interesting parts of the sql to rewrite.
1669 if (preg_match('!(^.*IN \()([^\)]*)(.*)$!', $sql, $matches) === false) {
1670 return array($sql, $params); // Return unmodified.
1673 $instart = $matches[1];
1674 $insql = $matches[2];
1675 $inend = $matches[3];
1676 $newsql = '';
1678 // Some basic verification about the matching going ok.
1679 $insqlarr = explode(',', $insql);
1680 if (count($insqlarr) !== count($params)) {
1681 return array($sql, $params); // Return unmodified.
1684 // Arrived here, we need to chunk and pivot the params, building a new sql (params remain the same).
1685 $addunionclause = false;
1686 while ($chunk = array_splice($insqlarr, 0, 125)) { // Each chunk will handle up to 125 (+125 +1) elements (DECODE max is 255).
1687 $chunksize = count($chunk);
1688 if ($addunionclause) {
1689 $newsql .= "\n UNION ALL";
1691 $newsql .= "\n SELECT DECODE(pivot";
1692 $counter = 1;
1693 foreach ($chunk as $element) {
1694 $newsql .= ",\n {$counter}, " . trim($element);
1695 $counter++;
1697 $newsql .= ")";
1698 $newsql .= "\n FROM dual";
1699 $newsql .= "\n CROSS JOIN (SELECT LEVEL AS pivot FROM dual CONNECT BY LEVEL <= {$chunksize})";
1700 $addunionclause = true;
1703 // Rebuild the complete IN() clause and return it.
1704 return array($instart . $newsql . $inend, $params);
1708 * Mega hacky magic to work around crazy Oracle NULL concats.
1709 * @param array $args
1710 * @return string
1712 protected function recursive_concat(array $args) {
1713 $count = count($args);
1714 if ($count == 1) {
1715 $arg = reset($args);
1716 return $arg;
1718 if ($count == 2) {
1719 $args[] = "' '";
1720 // No return here intentionally.
1722 $first = array_shift($args);
1723 $second = array_shift($args);
1724 $third = $this->recursive_concat($args);
1725 return "MOODLELIB.TRICONCAT($first, $second, $third)";
1729 * Returns the SQL for returning searching one string for the location of another.
1731 public function sql_position($needle, $haystack) {
1732 return "INSTR(($haystack), ($needle))";
1736 * Returns the SQL to know if one field is empty.
1738 * @param string $tablename Name of the table (without prefix). Not used for now but can be
1739 * necessary in the future if we want to use some introspection using
1740 * meta information against the DB.
1741 * @param string $fieldname Name of the field we are going to check
1742 * @param bool $nullablefield For specifying if the field is nullable (true) or no (false) in the DB.
1743 * @param bool $textfield For specifying if it is a text (also called clob) field (true) or a varchar one (false)
1744 * @return string the sql code to be added to check for empty values
1746 public function sql_isempty($tablename, $fieldname, $nullablefield, $textfield) {
1747 if ($textfield) {
1748 return " (".$this->sql_compare_text($fieldname)." = ' ') ";
1749 } else {
1750 return " ($fieldname = ' ') ";
1754 public function sql_order_by_text($fieldname, $numchars=32) {
1755 return 'dbms_lob.substr(' . $fieldname . ', ' . $numchars . ',1)';
1759 * Is the required OCI server package installed?
1760 * @return bool
1762 protected function oci_package_installed() {
1763 $sql = "SELECT 1
1764 FROM user_objects
1765 WHERE object_type = 'PACKAGE BODY'
1766 AND object_name = 'MOODLELIB'
1767 AND status = 'VALID'";
1768 $this->query_start($sql, null, SQL_QUERY_AUX);
1769 $stmt = $this->parse_query($sql);
1770 $result = oci_execute($stmt, $this->commit_status);
1771 $this->query_end($result, $stmt);
1772 $records = null;
1773 oci_fetch_all($stmt, $records, 0, -1, OCI_FETCHSTATEMENT_BY_ROW);
1774 oci_free_statement($stmt);
1775 return isset($records[0]) && reset($records[0]) ? true : false;
1779 * Try to add required moodle package into oracle server.
1781 protected function attempt_oci_package_install() {
1782 $sqls = file_get_contents(__DIR__.'/oci_native_moodle_package.sql');
1783 $sqls = preg_split('/^\/$/sm', $sqls);
1784 foreach ($sqls as $sql) {
1785 $sql = trim($sql);
1786 if ($sql === '' or $sql === 'SHOW ERRORS') {
1787 continue;
1789 $this->change_database_structure($sql);
1794 * Does this driver support tool_replace?
1796 * @since Moodle 2.8
1797 * @return bool
1799 public function replace_all_text_supported() {
1800 return true;
1803 public function session_lock_supported() {
1804 return true;
1808 * Obtain session lock
1809 * @param int $rowid id of the row with session record
1810 * @param int $timeout max allowed time to wait for the lock in seconds
1811 * @return void
1813 public function get_session_lock($rowid, $timeout) {
1814 parent::get_session_lock($rowid, $timeout);
1816 $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid;
1817 $sql = 'SELECT MOODLELIB.GET_LOCK(:lockname, :locktimeout) FROM DUAL';
1818 $params = array('lockname' => $fullname , 'locktimeout' => $timeout);
1819 $this->query_start($sql, $params, SQL_QUERY_AUX);
1820 $stmt = $this->parse_query($sql);
1821 $this->bind_params($stmt, $params);
1822 $result = oci_execute($stmt, $this->commit_status);
1823 if ($result === false) { // Any failure in get_lock() raises error, causing return of bool false
1824 throw new dml_sessionwait_exception();
1826 $this->query_end($result, $stmt);
1827 oci_free_statement($stmt);
1830 public function release_session_lock($rowid) {
1831 if (!$this->used_for_db_sessions) {
1832 return;
1835 parent::release_session_lock($rowid);
1837 $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid;
1838 $params = array('lockname' => $fullname);
1839 $sql = 'SELECT MOODLELIB.RELEASE_LOCK(:lockname) FROM DUAL';
1840 $this->query_start($sql, $params, SQL_QUERY_AUX);
1841 $stmt = $this->parse_query($sql);
1842 $this->bind_params($stmt, $params);
1843 $result = oci_execute($stmt, $this->commit_status);
1844 $this->query_end($result, $stmt);
1845 oci_free_statement($stmt);
1849 * Driver specific start of real database transaction,
1850 * this can not be used directly in code.
1851 * @return void
1853 protected function begin_transaction() {
1854 $this->commit_status = OCI_DEFAULT; //Done! ;-)
1858 * Driver specific commit of real database transaction,
1859 * this can not be used directly in code.
1860 * @return void
1862 protected function commit_transaction() {
1863 $this->query_start('--oracle_commit', NULL, SQL_QUERY_AUX);
1864 $result = oci_commit($this->oci);
1865 $this->commit_status = OCI_COMMIT_ON_SUCCESS;
1866 $this->query_end($result);
1870 * Driver specific abort of real database transaction,
1871 * this can not be used directly in code.
1872 * @return void
1874 protected function rollback_transaction() {
1875 $this->query_start('--oracle_rollback', NULL, SQL_QUERY_AUX);
1876 $result = oci_rollback($this->oci);
1877 $this->commit_status = OCI_COMMIT_ON_SUCCESS;
1878 $this->query_end($result);