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