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