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