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