3 ///////////////////////////////////////////////////////////////////////////
5 // NOTICE OF COPYRIGHT //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.com //
10 // Copyright (C) 2001-3001 Martin Dougiamas http://dougiamas.com //
12 // This program is free software; you can redistribute it and/or modify //
13 // it under the terms of the GNU General Public License as published by //
14 // the Free Software Foundation; either version 2 of the License, or //
15 // (at your option) any later version. //
17 // This program is distributed in the hope that it will be useful, //
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20 // GNU General Public License for more details: //
22 // http://www.gnu.org/copyleft/gpl.html //
24 ///////////////////////////////////////////////////////////////////////////
26 /// This library contains all the Data Manipulation Language (DML) functions
27 /// used to interact with the DB. All the dunctions in this library must be
28 /// generic and work against the major number of RDBMS possible. This is the
29 /// list of currently supported and tested DBs: mysql, postresql, mssql, oracle
31 /// This library is automatically included by Moodle core so you never need to
32 /// include it yourself.
34 /// For more info about the functions available in this library, please visit:
35 /// http://docs.moodle.org/en/DML_functions
36 /// (feel free to modify, improve and document such page, thanks!)
38 /// GLOBAL CONSTANTS /////////////////////////////////////////////////////////
40 $empty_rs_cache = array(); // Keeps copies of the recordsets used in one invocation
41 $metadata_cache = array(); // Keeps copies of the MetaColumns() for each table used in one invocations
43 $rcache = new StdClass
; // Cache simple get_record results
44 $rcache->data
= array();
48 /// FUNCTIONS FOR DATABASE HANDLING ////////////////////////////////
51 * Execute a given sql command string
53 * Completely general function - it just runs some SQL and reports success.
56 * @param string $command The sql string you wish to be executed.
57 * @param bool $feedback Set this argument to true if the results generated should be printed. Default is true.
60 function execute_sql($command, $feedback=true) {
61 /// Completely general function - it just runs some SQL and reports success.
65 $olddebug = $db->debug
;
71 if ($CFG->version
>= 2006101007) { //Look for trailing ; from Moodle 1.7.0
72 $command = trim($command);
73 /// If the trailing ; is there, fix and warn!
74 if (substr($command, strlen($command)-1, 1) == ';') {
75 /// One noticeable exception, Oracle PL/SQL blocks require ending in ";"
76 if ($CFG->dbfamily
== 'oracle' && substr($command, -4) == 'END;') {
77 /// Nothing to fix/warn. The command is one PL/SQL block, so it's ok.
79 $command = trim($command, ';');
80 debugging('Warning. Avoid to end your SQL commands with a trailing ";".', DEBUG_DEVELOPER
);
85 $empty_rs_cache = array(); // Clear out the cache, just in case changes were made to table structures
87 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++
; };
89 $result = $db->Execute($command);
91 $db->debug
= $olddebug;
95 notify(get_string('success'), 'notifysuccess');
100 notify('<strong>' . get_string('error') . '</strong>');
102 if (!empty($CFG->dblogerror
)) {
103 $debug=array_shift(debug_backtrace());
104 error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: $command");
111 * on DBs that support it, switch to transaction mode and begin a transaction
112 * you'll need to ensure you call commit_sql() or your changes *will* be lost.
114 * Now using ADOdb standard transactions. Some day, we should switch to
115 * Smart Transactions (http://phplens.com/adodb/tutorial.smart.transactions.html)
116 * as they autodetect errors and are nestable and easier to write
118 * this is _very_ useful for massive updates
120 function begin_sql() {
130 * on DBs that support it, commit the transaction
132 * Now using ADOdb standard transactions. Some day, we should switch to
133 * Smart Transactions (http://phplens.com/adodb/tutorial.smart.transactions.html)
134 * as they autodetect errors and are nestable and easier to write
136 function commit_sql() {
146 * on DBs that support it, rollback the transaction
148 * Now using ADOdb standard transactions. Some day, we should switch to
149 * Smart Transactions (http://phplens.com/adodb/tutorial.smart.transactions.html)
150 * as they autodetect errors and are nestable and easier to write
152 function rollback_sql() {
156 $db->RollbackTrans();
162 * returns db specific uppercase function
163 * @deprecated Moodle 1.7 because all the RDBMS use upper()
165 function db_uppercase() {
170 * returns db specific lowercase function
171 * @deprecated Moodle 1.7 because all the RDBMS use lower()
173 function db_lowercase() {
179 * Run an arbitrary sequence of semicolon-delimited SQL commands
181 * Assumes that the input text (file or string) consists of
182 * a number of SQL statements ENDING WITH SEMICOLONS. The
183 * semicolons MUST be the last character in a line.
184 * Lines that are blank or that start with "#" or "--" (postgres) are ignored.
185 * Only tested with mysql dump files (mysqldump -p -d moodle)
189 * @deprecated Moodle 1.7 use the new XMLDB stuff in lib/ddllib.php
191 * @param string $sqlfile The path where a file with sql commands can be found on the server.
192 * @param string $sqlstring If no path is supplied then a string with semicolon delimited sql
193 * commands can be supplied in this argument.
194 * @return bool Returns true if databse was modified successfully.
196 function modify_database($sqlfile='', $sqlstring='') {
200 if ($CFG->version
> 2006101007) {
201 debugging('Function modify_database() is deprecated. Replace it with the new XMLDB stuff.', DEBUG_DEVELOPER
);
204 $success = true; // Let's be optimistic
206 if (!empty($sqlfile)) {
207 if (!is_readable($sqlfile)) {
209 echo '<p>Tried to modify database, but "'. $sqlfile .'" doesn\'t exist!</p>';
212 $lines = file($sqlfile);
215 $sqlstring = trim($sqlstring);
216 if ($sqlstring{strlen($sqlstring)-1} != ";") {
217 $sqlstring .= ";"; // add it in if it's not there.
219 $lines[] = $sqlstring;
224 foreach ($lines as $line) {
225 $line = rtrim($line);
226 $length = strlen($line);
228 if ($length and $line[0] <> '#' and $line[0].$line[1] <> '--') {
229 if (substr($line, $length-1, 1) == ';') {
230 $line = substr($line, 0, $length-1); // strip ;
232 $command = str_replace('prefix_', $CFG->prefix
, $command); // Table prefixes
233 if (! execute_sql($command)) {
247 /// GENERIC FUNCTIONS TO CHECK AND COUNT RECORDS ////////////////////////////////////////
250 * Test whether a record exists in a table where all the given fields match the given values.
252 * The record to test is specified by giving up to three fields that must
253 * equal the corresponding values.
256 * @param string $table The table to check.
257 * @param string $field1 the first field to check (optional).
258 * @param string $value1 the value field1 must have (requred if field1 is given, else optional).
259 * @param string $field2 the second field to check (optional).
260 * @param string $value2 the value field2 must have (requred if field2 is given, else optional).
261 * @param string $field3 the third field to check (optional).
262 * @param string $value3 the value field3 must have (requred if field3 is given, else optional).
263 * @return bool true if a matching record exists, else false.
265 function record_exists($table, $field1='', $value1='', $field2='', $value2='', $field3='', $value3='') {
269 $select = where_clause($field1, $value1, $field2, $value2, $field3, $value3);
271 return record_exists_sql('SELECT * FROM '. $CFG->prefix
. $table .' '. $select);
275 * Test whether any records exists in a table which match a particular WHERE clause.
278 * @param string $table The database table to be checked against.
279 * @param string $select A fragment of SQL to be used in a WHERE clause in the SQL call.
280 * @return bool true if a matching record exists, else false.
282 function record_exists_select($table, $select='') {
287 $select = 'WHERE '.$select;
290 return record_exists_sql('SELECT * FROM '. $CFG->prefix
. $table . ' ' . $select);
294 * Test whether a SQL SELECT statement returns any records.
296 * This function returns true if the SQL statement executes
297 * without any errors and returns at least one record.
299 * @param string $sql The SQL statement to execute.
300 * @return bool true if the SQL executes without errors and returns at least one record.
302 function record_exists_sql($sql) {
304 $limitfrom = 0; /// Number of records to skip
305 $limitnum = 1; /// Number of records to retrieve
307 $rs = get_recordset_sql($sql, $limitfrom, $limitnum);
309 if ($rs && $rs->RecordCount() > 0) {
317 * Count the records in a table where all the given fields match the given values.
320 * @param string $table The table to query.
321 * @param string $field1 the first field to check (optional).
322 * @param string $value1 the value field1 must have (requred if field1 is given, else optional).
323 * @param string $field2 the second field to check (optional).
324 * @param string $value2 the value field2 must have (requred if field2 is given, else optional).
325 * @param string $field3 the third field to check (optional).
326 * @param string $value3 the value field3 must have (requred if field3 is given, else optional).
327 * @return int The count of records returned from the specified criteria.
329 function count_records($table, $field1='', $value1='', $field2='', $value2='', $field3='', $value3='') {
333 $select = where_clause($field1, $value1, $field2, $value2, $field3, $value3);
335 return count_records_sql('SELECT COUNT(*) FROM '. $CFG->prefix
. $table .' '. $select);
339 * Count the records in a table which match a particular WHERE clause.
342 * @param string $table The database table to be checked against.
343 * @param string $select A fragment of SQL to be used in a WHERE clause in the SQL call.
344 * @param string $countitem The count string to be used in the SQL call. Default is COUNT(*).
345 * @return int The count of records returned from the specified criteria.
347 function count_records_select($table, $select='', $countitem='COUNT(*)') {
352 $select = 'WHERE '.$select;
355 return count_records_sql('SELECT '. $countitem .' FROM '. $CFG->prefix
. $table .' '. $select);
359 * Get the result of a SQL SELECT COUNT(...) query.
361 * Given a query that counts rows, return that count. (In fact,
362 * given any query, return the first field of the first record
363 * returned. However, this method should only be used for the
364 * intended purpose.) If an error occurrs, 0 is returned.
368 * @param string $sql The SQL string you wish to be executed.
369 * @return int the count. If an error occurrs, 0 is returned.
371 function count_records_sql($sql) {
372 $rs = get_recordset_sql($sql);
375 return reset($rs->fields
);
381 /// GENERIC FUNCTIONS TO GET, INSERT, OR UPDATE DATA ///////////////////////////////////
385 * Get a single record as an object
388 * @param string $table The table to select from.
389 * @param string $field1 the first field to check (optional).
390 * @param string $value1 the value field1 must have (requred if field1 is given, else optional).
391 * @param string $field2 the second field to check (optional).
392 * @param string $value2 the value field2 must have (requred if field2 is given, else optional).
393 * @param string $field3 the third field to check (optional).
394 * @param string $value3 the value field3 must have (requred if field3 is given, else optional).
395 * @return mixed a fieldset object containing the first mathcing record, or false if none found.
397 function get_record($table, $field1, $value1, $field2='', $value2='', $field3='', $value3='', $fields='*') {
401 // Check to see whether this record is eligible for caching (fields=*, only condition is id)
403 if (!empty($CFG->rcache
) && $CFG->rcache
=== true && $field1=='id' && !$field2 && !$field3 && $fields=='*') {
405 // If it's in the cache, return it
406 $cached = rcache_getforfill($table, $value1);
407 if (!empty($cached)) {
412 $select = where_clause($field1, $value1, $field2, $value2, $field3, $value3);
414 $record = get_record_sql('SELECT '.$fields.' FROM '. $CFG->prefix
. $table .' '. $select);
416 // If we're caching records, store this one
417 // (supposing we got something - we don't cache failures)
419 if (isset($record)) {
420 rcache_set($table, $value1, $record);
422 rcache_releaseforfill($table, $value1);
429 * Get a single record as an object using an SQL statement
431 * The SQL statement should normally only return one record. In debug mode
432 * you will get a warning if more record is returned (unless you
433 * set $expectmultiple to true). In non-debug mode, it just returns
438 * @param string $sql The SQL string you wish to be executed, should normally only return one record.
439 * @param bool $expectmultiple If the SQL cannot be written to conviniently return just one record,
440 * set this to true to hide the debug message.
441 * @param bool $nolimit sometimes appending ' LIMIT 1' to the SQL causes an error. Set this to true
442 * to stop your SQL being modified. This argument should probably be deprecated.
443 * @return Found record as object. False if not found or error
445 function get_record_sql($sql, $expectmultiple=false, $nolimit=false) {
449 /// Default situation
450 $limitfrom = 0; /// Number of records to skip
451 $limitnum = 1; /// Number of records to retrieve
453 /// Only a few uses of the 2nd and 3rd parameter have been found
454 /// I think that we should avoid to use them completely, one
455 /// record is one record, and everything else should return error.
456 /// So the proposal is to change all the uses, (4-5 inside Moodle
457 /// Core), drop them from the definition and delete the next two
458 /// "if" sentences. (eloy, 2006-08-19)
463 } else if ($expectmultiple) {
466 } else if (debugging()) {
467 // Debugging mode - don't use a limit of 1, but do change the SQL, because sometimes that
468 // causes errors, and in non-debug mode you don't see the error message and it is
469 // impossible to know what's wrong.
474 if (!$rs = get_recordset_sql($sql, $limitfrom, $limitnum)) {
478 $recordcount = $rs->RecordCount();
480 if ($recordcount == 0) { // Found no records
483 } else if ($recordcount == 1) { // Found one record
484 /// DIRTY HACK to retrieve all the ' ' (1 space) fields converted back
485 /// to '' (empty string) for Oracle. It's the only way to work with
486 /// all those NOT NULL DEFAULT '' fields until we definetively delete them
487 if ($CFG->dbfamily
== 'oracle') {
488 array_walk($rs->fields
, 'onespace2empty');
490 /// End od DIRTY HACK
491 return (object)$rs->fields
;
493 } else { // Error: found more than one record
494 notify('Error: Turn off debugging to hide this error.');
495 notify($sql . '(with limits ' . $limitfrom . ', ' . $limitnum . ')');
496 if ($records = $rs->GetAssoc(true)) {
497 notify('Found more than one record in get_record_sql !');
498 print_object($records);
500 notify('Very strange error in get_record_sql !');
503 print_continue("$CFG->wwwroot/$CFG->admin/config.php");
508 * Gets one record from a table, as an object
511 * @param string $table The database table to be checked against.
512 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
513 * @param string $fields A comma separated list of fields to be returned from the chosen table.
514 * @return object|false Returns an array of found records (as objects) or false if no records or error occured.
516 function get_record_select($table, $select='', $fields='*') {
521 $select = 'WHERE '. $select;
524 return get_record_sql('SELECT '. $fields .' FROM '. $CFG->prefix
. $table .' '. $select);
528 * Get a number of records as an ADODB RecordSet.
530 * Selects records from the table $table.
532 * If specified, only records where the field $field has value $value are retured.
534 * If specified, the results will be sorted as specified by $sort. This
535 * is added to the SQL as "ORDER BY $sort". Example values of $sort
536 * mightbe "time ASC" or "time DESC".
538 * If $fields is specified, only those fields are returned.
540 * This function is internal to datalib, and should NEVER should be called directly
541 * from general Moodle scripts. Use get_record, get_records etc.
543 * If you only want some of the records, specify $limitfrom and $limitnum.
544 * The query will skip the first $limitfrom records (according to the sort
545 * order) and then return the next $limitnum records. If either of $limitfrom
546 * or $limitnum is specified, both must be present.
548 * The return value is an ADODB RecordSet object
549 * @link http://phplens.com/adodb/reference.functions.adorecordset.html
550 * if the query succeeds. If an error occurrs, false is returned.
552 * @param string $table the table to query.
553 * @param string $field a field to check (optional).
554 * @param string $value the value the field must have (requred if field1 is given, else optional).
555 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
556 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
557 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
558 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
559 * @return mixed an ADODB RecordSet object, or false if an error occured.
561 function get_recordset($table, $field='', $value='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
564 $select = "$field = '$value'";
569 return get_recordset_select($table, $select, $sort, $fields, $limitfrom, $limitnum);
573 * Get a number of records as an ADODB RecordSet.
575 * If given, $select is used as the SELECT parameter in the SQL query,
576 * otherwise all records from the table are returned.
578 * Other arguments and the return type as for @see function get_recordset.
581 * @param string $table the table to query.
582 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
583 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
584 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
585 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
586 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
587 * @return mixed an ADODB RecordSet object, or false if an error occured.
589 function get_recordset_select($table, $select='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
594 $select = ' WHERE '. $select;
598 $sort = ' ORDER BY '. $sort;
601 return get_recordset_sql('SELECT '. $fields .' FROM '. $CFG->prefix
. $table . $select . $sort, $limitfrom, $limitnum);
605 * Get a number of records as an ADODB RecordSet.
607 * Only records where $field takes one of the values $values are returned.
608 * $values should be a comma-separated list of values, for example "4,5,6,10"
609 * or "'foo','bar','baz'".
611 * Other arguments and the return type as for @see function get_recordset.
613 * @param string $table the table to query.
614 * @param string $field a field to check (optional).
615 * @param string $values comma separated list of values the field must have (requred if field is given, else optional).
616 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
617 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
618 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
619 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
620 * @return mixed an ADODB RecordSet object, or false if an error occured.
622 function get_recordset_list($table, $field='', $values='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
625 $select = "$field IN ($values)";
630 return get_recordset_select($table, $select, $sort, $fields, $limitfrom, $limitnum);
634 * Get a number of records as an ADODB RecordSet. $sql must be a complete SQL query.
635 * This function is internal to datalib, and should NEVER should be called directly
636 * from general Moodle scripts. Use get_record, get_records etc.
638 * The return type is as for @see function get_recordset.
642 * @param string $sql the SQL select query to execute.
643 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
644 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
645 * @return mixed an ADODB RecordSet object, or false if an error occured.
647 function get_recordset_sql($sql, $limitfrom=null, $limitnum=null) {
654 /// Temporary hack as part of phasing out all access to obsolete user tables XXX
655 if (!empty($CFG->rolesactive
)) {
656 if (strpos($sql, ' '.$CFG->prefix
.'user_students ') ||
657 strpos($sql, ' '.$CFG->prefix
.'user_teachers ') ||
658 strpos($sql, ' '.$CFG->prefix
.'user_coursecreators ') ||
659 strpos($sql, ' '.$CFG->prefix
.'user_admins ')) {
660 if (debugging()) { var_dump(debug_backtrace()); }
661 error('This SQL relies on obsolete tables! Your code must be fixed by a developer.');
666 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++
; };
668 if ($limitfrom ||
$limitnum) {
669 ///Special case, 0 must be -1 for ADOdb
670 $limitfrom = empty($limitfrom) ?
-1 : $limitfrom;
671 $limitnum = empty($limitnum) ?
-1 : $limitnum;
672 $rs = $db->SelectLimit($sql, $limitnum, $limitfrom);
674 $rs = $db->Execute($sql);
677 debugging($db->ErrorMsg() .'<br /><br />'. $sql);
678 if (!empty($CFG->dblogerror
)) {
679 $debug=array_shift(debug_backtrace());
680 error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: $sql with limits ($limitfrom, $limitnum)");
689 * Utility function used by the following 4 methods. Note that for this to work, the first column
690 * in the recordset must contain unique values, as it is used as the key to the associative array.
692 * @param object an ADODB RecordSet object.
693 * @return mixed mixed an array of objects, or false if an error occured or the RecordSet was empty.
695 function recordset_to_array($rs) {
699 if ($rs && $rs->RecordCount() > 0) {
700 /// First of all, we are going to get the name of the first column
701 /// to introduce it back after transforming the recordset to assoc array
702 /// See http://docs.moodle.org/en/XMLDB_Problems, fetch mode problem.
703 $firstcolumn = $rs->FetchField(0);
704 /// Get the whole associative array
705 if ($records = $rs->GetAssoc(true)) {
706 foreach ($records as $key => $record) {
707 /// Really DIRTY HACK for Oracle, but it's the only way to make it work
708 /// until we got all those NOT NULL DEFAULT '' out from Moodle
709 if ($CFG->dbfamily
== 'oracle') {
710 array_walk($record, 'onespace2empty');
712 /// End of DIRTY HACK
713 $record[$firstcolumn->name
] = $key;/// Re-add the assoc field
714 $objects[$key] = (object) $record; /// To object
717 /// Fallback in case we only have 1 field in the recordset. MDL-5877
718 } else if ($rs->_numOfFields
== 1 && $records = $rs->GetRows()) {
719 foreach ($records as $key => $record) {
720 /// Really DIRTY HACK for Oracle, but it's the only way to make it work
721 /// until we got all those NOT NULL DEFAULT '' out from Moodle
722 if ($CFG->dbfamily
== 'oracle') {
723 array_walk($record, 'onespace2empty');
725 /// End of DIRTY HACK
726 $objects[$record[$firstcolumn->name
]] = (object) $record; /// The key is the first column value (like Assoc)
738 * This function is used to get the current record from the recordset. It
739 * doesn't advance the recordset position. You'll need to do that by
740 * using the rs_next_record($recordset) function.
741 * @param ADORecordSet the recordset to fetch current record from
742 * @return ADOFetchObj the object containing the fetched information
744 function rs_fetch_record(&$rs) {
748 $rec = $rs->FetchObj(); //Retrieve record as object without advance the pointer
750 if ($rs->EOF
) { //FetchObj requires manual checking of EOF to detect if it's the last record
753 /// DIRTY HACK to retrieve all the ' ' (1 space) fields converted back
754 /// to '' (empty string) for Oracle. It's the only way to work with
755 /// all those NOT NULL DEFAULT '' fields until we definetively delete them
756 if ($CFG->dbfamily
== 'oracle') {
757 $recarr = (array)$rec; /// Cast to array
758 array_walk($recarr, 'onespace2empty');
759 $rec = (object)$recarr;/// Cast back to object
768 * This function is used to advance the pointer of the recordset
769 * to its next position/record.
770 * @param ADORecordSet the recordset to be moved to the next record
771 * @return boolean true if the movement was successful and false if not (end of recordset)
773 function rs_next_record(&$rs) {
775 return $rs->MoveNext(); //Move the pointer to the next record
779 * This function is used to get the current record from the recordset. It
780 * does advance the recordset position.
781 * This is the prefered way to iterate over recordsets with code blocks like this:
783 * $rs = get_recordset('SELECT .....');
784 * while ($rec = rs_fetch_next_record($rs)) {
785 * /// Perform actions with the $rec record here
787 * rs_close($rs); /// Close the recordset if not used anymore. Saves memory (optional but recommended).
789 * @param ADORecordSet the recordset to fetch current record from
790 * @return mixed ADOFetchObj the object containing the fetched information or boolean false if no record (end of recordset)
792 function rs_fetch_next_record(&$rs) {
797 $recarr = $rs->FetchRow(); //Retrieve record as object without advance the pointer. It's quicker that FetchNextObj()
800 /// DIRTY HACK to retrieve all the ' ' (1 space) fields converted back
801 /// to '' (empty string) for Oracle. It's the only way to work with
802 /// all those NOT NULL DEFAULT '' fields until we definetively delete them
803 if ($CFG->dbfamily
== 'oracle') {
804 array_walk($recarr, 'onespace2empty');
807 /// Cast array to object
808 $rec = (object)$recarr;
815 * This function closes the recordset, freeing all the memory and associated resources.
816 * Note that, once closed, the recordset must not be used anymore along the request.
817 * Saves memory (optional but recommended).
818 * @param ADORecordSet the recordset to be closed
820 function rs_close(&$rs) {
826 * This function is used to convert all the Oracle 1-space defaults to the empty string
827 * like a really DIRTY HACK to allow it to work better until all those NOT NULL DEFAULT ''
828 * fields will be out from Moodle.
829 * @param string the string to be converted to '' (empty string) if it's ' ' (one space)
830 * @param mixed the key of the array in case we are using this function from array_walk,
831 * defaults to null for other (direct) uses
832 * @return boolean always true (the converted variable is returned by reference)
834 function onespace2empty(&$item, $key=null) {
835 $item = $item == ' ' ?
'' : $item;
842 * Get a number of records as an array of objects.
844 * If the query succeeds and returns at least one record, the
845 * return value is an array of objects, one object for each
846 * record found. The array key is the value from the first
847 * column of the result set. The object associated with that key
848 * has a member variable for each column of the results.
850 * @param string $table the table to query.
851 * @param string $field a field to check (optional).
852 * @param string $value the value the field must have (requred if field1 is given, else optional).
853 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
854 * @param string $fields a comma separated list of fields to return (optional, by default
855 * all fields are returned). The first field will be used as key for the
856 * array so must be a unique field such as 'id'.
857 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
858 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
859 * @return mixed an array of objects, or false if no records were found or an error occured.
861 function get_records($table, $field='', $value='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
862 $rs = get_recordset($table, $field, $value, $sort, $fields, $limitfrom, $limitnum);
863 return recordset_to_array($rs);
867 * Get a number of records as an array of objects.
869 * Return value as for @see function get_records.
871 * @param string $table the table to query.
872 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
873 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
874 * @param string $fields a comma separated list of fields to return
875 * (optional, by default all fields are returned). The first field will be used as key for the
876 * array so must be a unique field such as 'id'.
877 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
878 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
879 * @return mixed an array of objects, or false if no records were found or an error occured.
881 function get_records_select($table, $select='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
882 $rs = get_recordset_select($table, $select, $sort, $fields, $limitfrom, $limitnum);
883 return recordset_to_array($rs);
887 * Get a number of records as an array of objects.
889 * Return value as for @see function get_records.
891 * @param string $table The database table to be checked against.
892 * @param string $field The field to search
893 * @param string $values Comma separated list of possible value
894 * @param string $sort Sort order (as valid SQL sort parameter)
895 * @param string $fields A comma separated list of fields to be returned from the chosen table. If specified,
896 * the first field should be a unique one such as 'id' since it will be used as a key in the associative
898 * @return mixed an array of objects, or false if no records were found or an error occured.
900 function get_records_list($table, $field='', $values='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
901 $rs = get_recordset_list($table, $field, $values, $sort, $fields, $limitfrom, $limitnum);
902 return recordset_to_array($rs);
906 * Get a number of records as an array of objects.
908 * Return value as for @see function get_records.
910 * @param string $sql the SQL select query to execute. The first column of this SELECT statement
911 * must be a unique value (usually the 'id' field), as it will be used as the key of the
913 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
914 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
915 * @return mixed an array of objects, or false if no records were found or an error occured.
917 function get_records_sql($sql, $limitfrom='', $limitnum='') {
918 $rs = get_recordset_sql($sql, $limitfrom, $limitnum);
919 return recordset_to_array($rs);
923 * Utility function used by the following 3 methods.
925 * @param object an ADODB RecordSet object with two columns.
926 * @return mixed an associative array, or false if an error occured or the RecordSet was empty.
928 function recordset_to_menu($rs) {
931 if ($rs && $rs->RecordCount() > 0) {
932 $keys = array_keys($rs->fields
);
936 $menu[$rs->fields
[$key0]] = $rs->fields
[$key1];
939 /// Really DIRTY HACK for Oracle, but it's the only way to make it work
940 /// until we got all those NOT NULL DEFAULT '' out from Moodle
941 if ($CFG->dbfamily
== 'oracle') {
942 array_walk($menu, 'onespace2empty');
944 /// End of DIRTY HACK
952 * Get the first two columns from a number of records as an associative array.
954 * Arguments as for @see function get_recordset.
956 * If no errors occur, and at least one records is found, the return value
957 * is an associative whose keys come from the first field of each record,
958 * and whose values are the corresponding second fields. If no records are found,
959 * or an error occurs, false is returned.
961 * @param string $table the table to query.
962 * @param string $field a field to check (optional).
963 * @param string $value the value the field must have (requred if field1 is given, else optional).
964 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
965 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
966 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
967 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
968 * @return mixed an associative array, or false if no records were found or an error occured.
970 function get_records_menu($table, $field='', $value='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
971 $rs = get_recordset($table, $field, $value, $sort, $fields, $limitfrom, $limitnum);
972 return recordset_to_menu($rs);
976 * Get the first two columns from a number of records as an associative array.
978 * Arguments as for @see function get_recordset_select.
979 * Return value as for @see function get_records_menu.
981 * @param string $table The database table to be checked against.
982 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
983 * @param string $sort Sort order (optional) - a valid SQL order parameter
984 * @param string $fields A comma separated list of fields to be returned from the chosen table.
985 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
986 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
987 * @return mixed an associative array, or false if no records were found or an error occured.
989 function get_records_select_menu($table, $select='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
990 $rs = get_recordset_select($table, $select, $sort, $fields, $limitfrom, $limitnum);
991 return recordset_to_menu($rs);
995 * Get the first two columns from a number of records as an associative array.
997 * Arguments as for @see function get_recordset_sql.
998 * Return value as for @see function get_records_menu.
1000 * @param string $sql The SQL string you wish to be executed.
1001 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
1002 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1003 * @return mixed an associative array, or false if no records were found or an error occured.
1005 function get_records_sql_menu($sql, $limitfrom='', $limitnum='') {
1006 $rs = get_recordset_sql($sql, $limitfrom, $limitnum);
1007 return recordset_to_menu($rs);
1011 * Get a single value from a table row where all the given fields match the given values.
1013 * @param string $table the table to query.
1014 * @param string $return the field to return the value of.
1015 * @param string $field1 the first field to check (optional).
1016 * @param string $value1 the value field1 must have (requred if field1 is given, else optional).
1017 * @param string $field2 the second field to check (optional).
1018 * @param string $value2 the value field2 must have (requred if field2 is given, else optional).
1019 * @param string $field3 the third field to check (optional).
1020 * @param string $value3 the value field3 must have (requred if field3 is given, else optional).
1021 * @return mixed the specified value, or false if an error occured.
1023 function get_field($table, $return, $field1, $value1, $field2='', $value2='', $field3='', $value3='') {
1025 $select = where_clause($field1, $value1, $field2, $value2, $field3, $value3);
1026 return get_field_sql('SELECT ' . $return . ' FROM ' . $CFG->prefix
. $table . ' ' . $select);
1030 * Get a single value from a table row where a particular select clause is true.
1033 * @param string $table the table to query.
1034 * @param string $return the field to return the value of.
1035 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1036 * @return mixed the specified value, or false if an error occured.
1038 function get_field_select($table, $return, $select) {
1041 $select = 'WHERE '. $select;
1043 return get_field_sql('SELECT ' . $return . ' FROM ' . $CFG->prefix
. $table . ' ' . $select);
1047 * Get a single value from a table.
1049 * @param string $sql an SQL statement expected to return a single value.
1050 * @return mixed the specified value, or false if an error occured.
1052 function get_field_sql($sql) {
1055 /// Strip potential LIMIT uses arriving here, debugging them (MDL-7173)
1056 $newsql = preg_replace('/ LIMIT [0-9, ]+$/is', '', $sql);
1057 if ($newsql != $sql) {
1058 debugging('Incorrect use of LIMIT clause (not cross-db) in call to get_field_sql(): ' . $sql, DEBUG_DEVELOPER
);
1062 $rs = get_recordset_sql($sql, 0, 1);
1064 if ($rs && $rs->RecordCount() == 1) {
1065 /// DIRTY HACK to retrieve all the ' ' (1 space) fields converted back
1066 /// to '' (empty string) for Oracle. It's the only way to work with
1067 /// all those NOT NULL DEFAULT '' fields until we definetively delete them
1068 if ($CFG->dbfamily
== 'oracle') {
1069 $value = reset($rs->fields
);
1070 onespace2empty($value);
1073 /// End of DIRTY HACK
1074 return reset($rs->fields
);
1081 * Get a single value from a table row where a particular select clause is true.
1084 * @param string $table the table to query.
1085 * @param string $return the field to return the value of.
1086 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1087 * @return mixed|false Returns the value return from the SQL statment or false if an error occured.
1089 function get_fieldset_select($table, $return, $select) {
1092 $select = ' WHERE '. $select;
1094 return get_fieldset_sql('SELECT ' . $return . ' FROM ' . $CFG->prefix
. $table . $select);
1098 * Get an array of data from one or more fields from a database
1099 * use to get a column, or a series of distinct values
1103 * @param string $sql The SQL string you wish to be executed.
1104 * @return mixed|false Returns the value return from the SQL statment or false if an error occured.
1105 * @todo Finish documenting this function
1107 function get_fieldset_sql($sql) {
1111 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++
; };
1113 $rs = $db->Execute($sql);
1115 debugging($db->ErrorMsg() .'<br /><br />'. $sql);
1116 if (!empty($CFG->dblogerror
)) {
1117 $debug=array_shift(debug_backtrace());
1118 error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: $sql");
1123 if ( $rs->RecordCount() > 0 ) {
1124 $keys = array_keys($rs->fields
);
1128 array_push($results, $rs->fields
[$key0]);
1131 /// DIRTY HACK to retrieve all the ' ' (1 space) fields converted back
1132 /// to '' (empty string) for Oracle. It's the only way to work with
1133 /// all those NOT NULL DEFAULT '' fields until we definetively delete them
1134 if ($CFG->dbfamily
== 'oracle') {
1135 array_walk($results, 'onespace2empty');
1137 /// End of DIRTY HACK
1145 * Set a single field in every table row where all the given fields match the given values.
1149 * @param string $table The database table to be checked against.
1150 * @param string $newfield the field to set.
1151 * @param string $newvalue the value to set the field to.
1152 * @param string $field1 the first field to check (optional).
1153 * @param string $value1 the value field1 must have (requred if field1 is given, else optional).
1154 * @param string $field2 the second field to check (optional).
1155 * @param string $value2 the value field2 must have (requred if field2 is given, else optional).
1156 * @param string $field3 the third field to check (optional).
1157 * @param string $value3 the value field3 must have (requred if field3 is given, else optional).
1158 * @return mixed An ADODB RecordSet object with the results from the SQL call or false.
1160 function set_field($table, $newfield, $newvalue, $field1, $value1, $field2='', $value2='', $field3='', $value3='') {
1164 // Clear record_cache based on the parameters passed
1165 // (individual record or whole table)
1166 if ($CFG->rcache
=== true) {
1167 if ($field1 == 'id') {
1168 rcache_unset($table, $value1);
1169 } else if ($field2 == 'id') {
1170 rcache_unset($table, $value1);
1171 } else if ($field3 == 'id') {
1172 rcache_unset($table, $value1);
1174 rcache_unset_table($table);
1178 $select = where_clause($field1, $value1, $field2, $value2, $field3, $value3);
1180 return set_field_select($table, $newfield, $newvalue, $select, true);
1184 * Set a single field in every table row where the select statement evaluates to true.
1188 * @param string $table The database table to be checked against.
1189 * @param string $newfield the field to set.
1190 * @param string $newvalue the value to set the field to.
1191 * @param string $select a fragment of SQL to be used in a where clause in the SQL call.
1192 * @param boolean $localcall Leave this set to false. (Should only be set to true by set_field.)
1193 * @return mixed An ADODB RecordSet object with the results from the SQL call or false.
1195 function set_field_select($table, $newfield, $newvalue, $select, $localcall = false) {
1199 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++
; };
1203 $select = 'WHERE ' . $select;
1206 // Clear record_cache based on the parameters passed
1207 // (individual record or whole table)
1208 if ($CFG->rcache
=== true) {
1209 rcache_unset_table($table);
1213 $dataobject = new StdClass
;
1214 $dataobject->{$newfield} = $newvalue;
1215 // Oracle DIRTY HACK -
1216 if ($CFG->dbfamily
== 'oracle') {
1217 oracle_dirty_hack($table, $dataobject); // Convert object to the correct "empty" values for Oracle DB
1218 $newvalue = $dataobject->{$newfield};
1222 /// Under Oracle, MSSQL and PostgreSQL we have our own set field process
1223 /// If the field being updated is clob/blob, we use our alternate update here
1224 /// They will be updated later
1225 if (($CFG->dbfamily
== 'oracle' ||
$CFG->dbfamily
== 'mssql' ||
$CFG->dbfamily
== 'postgres') && !empty($select)) {
1227 $foundclobs = array();
1228 $foundblobs = array();
1229 db_detect_lobs($table, $dataobject, $foundclobs, $foundblobs);
1232 /// Under Oracle, MSSQL and PostgreSQL, finally, update all the Clobs and Blobs present in the record
1233 /// if we know we have some of them in the query
1234 if (($CFG->dbfamily
== 'oracle' ||
$CFG->dbfamily
== 'mssql' ||
$CFG->dbfamily
== 'postgres') && !empty($select) &&
1235 (!empty($foundclobs) ||
!empty($foundblobs))) {
1236 if (!db_update_lobs($table, $select, $foundclobs, $foundblobs)) {
1237 return false; //Some error happened while updating LOBs
1239 return true; //Everrything was ok
1243 /// NULL inserts - introduced in 1.9
1244 if (is_null($newvalue)) {
1245 $update = "$newfield = NULL";
1247 $update = "$newfield = '$newvalue'";
1250 /// Arriving here, standard update
1251 return $db->Execute('UPDATE '. $CFG->prefix
. $table .' SET '.$update.' '.$select);
1255 * Delete the records from a table where all the given fields match the given values.
1259 * @param string $table the table to delete from.
1260 * @param string $field1 the first field to check (optional).
1261 * @param string $value1 the value field1 must have (requred if field1 is given, else optional).
1262 * @param string $field2 the second field to check (optional).
1263 * @param string $value2 the value field2 must have (requred if field2 is given, else optional).
1264 * @param string $field3 the third field to check (optional).
1265 * @param string $value3 the value field3 must have (requred if field3 is given, else optional).
1266 * @return mixed An ADODB RecordSet object with the results from the SQL call or false.
1268 function delete_records($table, $field1='', $value1='', $field2='', $value2='', $field3='', $value3='') {
1272 // Clear record_cache based on the parameters passed
1273 // (individual record or whole table)
1274 if ($CFG->rcache
=== true) {
1275 if ($field1 == 'id') {
1276 rcache_unset($table, $value1);
1277 } else if ($field2 == 'id') {
1278 rcache_unset($table, $value2);
1279 } else if ($field3 == 'id') {
1280 rcache_unset($table, $value3);
1282 rcache_unset_table($table);
1286 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++
; };
1288 $select = where_clause($field1, $value1, $field2, $value2, $field3, $value3);
1290 return $db->Execute('DELETE FROM '. $CFG->prefix
. $table .' '. $select);
1294 * Delete one or more records from a table
1298 * @param string $table The database table to be checked against.
1299 * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
1300 * @return object A PHP standard object with the results from the SQL call.
1301 * @todo Verify return type.
1303 function delete_records_select($table, $select='') {
1307 // Clear record_cache (whole table)
1308 if ($CFG->rcache
=== true) {
1309 rcache_unset_table($table);
1312 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++
; };
1315 $select = 'WHERE '.$select;
1318 return $db->Execute('DELETE FROM '. $CFG->prefix
. $table .' '. $select);
1322 * Insert a record into a table and return the "id" field if required
1324 * If the return ID isn't required, then this just reports success as true/false.
1325 * $dataobject is an object containing needed data
1329 * @param string $table The database table to be checked against.
1330 * @param object $dataobject A data object with values for one or more fields in the record
1331 * @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.
1332 * @param string $primarykey The primary key of the table we are inserting into (almost always "id")
1334 function insert_record($table, $dataobject, $returnid=true, $primarykey='id') {
1336 global $db, $CFG, $empty_rs_cache;
1342 /// Check we are handling a proper $dataobject
1343 if (is_array($dataobject)) {
1344 debugging('Warning. Wrong call to insert_record(). $dataobject must be an object. array found instead', DEBUG_DEVELOPER
);
1345 $dataobject = (object)$dataobject;
1348 /// Temporary hack as part of phasing out all access to obsolete user tables XXX
1349 if (!empty($CFG->rolesactive
)) {
1350 if (in_array($table, array('user_students', 'user_teachers', 'user_coursecreators', 'user_admins'))) {
1351 if (debugging()) { var_dump(debug_backtrace()); }
1352 error('This SQL relies on obsolete tables ('.$table.')! Your code must be fixed by a developer.');
1356 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++
; };
1358 /// In Moodle we always use auto-numbering fields for the primary key
1359 /// so let's unset it now before it causes any trouble later
1360 unset($dataobject->{$primarykey});
1362 /// Get an empty recordset. Cache for multiple inserts.
1363 if (empty($empty_rs_cache[$table])) {
1364 /// Execute a dummy query to get an empty recordset
1365 if (!$empty_rs_cache[$table] = $db->Execute('SELECT * FROM '. $CFG->prefix
. $table .' WHERE '. $primarykey .' = \'-1\'')) {
1370 $rs = $empty_rs_cache[$table];
1372 /// Postgres doesn't have the concept of primary key built in
1373 /// and will return the OID which isn't what we want.
1374 /// The efficient and transaction-safe strategy is to
1375 /// move the sequence forward first, and make the insert
1376 /// with an explicit id.
1377 if ( $CFG->dbfamily
=== 'postgres' && $returnid == true ) {
1378 if ($nextval = (int)get_field_sql("SELECT NEXTVAL('{$CFG->prefix}{$table}_{$primarykey}_seq')")) {
1379 $dataobject->{$primarykey} = $nextval;
1383 /// Begin DIRTY HACK
1384 if ($CFG->dbfamily
== 'oracle') {
1385 oracle_dirty_hack($table, $dataobject); // Convert object to the correct "empty" values for Oracle DB
1389 /// Under Oracle, MSSQL and PostgreSQL we have our own insert record process
1390 /// detect all the clob/blob fields and change their contents to @#CLOB#@ and @#BLOB#@
1391 /// saving them into $foundclobs and $foundblobs [$fieldname]->contents
1392 /// Same for mssql (only processing blobs - image fields)
1393 if ($CFG->dbfamily
== 'oracle' ||
$CFG->dbfamily
== 'mssql' ||
$CFG->dbfamily
== 'postgres') {
1394 $foundclobs = array();
1395 $foundblobs = array();
1396 db_detect_lobs($table, $dataobject, $foundclobs, $foundblobs);
1399 /// Under Oracle, if the primary key inserted has been requested OR
1400 /// if there are LOBs to insert, we calculate the next value via
1401 /// explicit query to the sequence.
1402 /// Else, the pre-insert trigger will do the job, because the primary
1403 /// key isn't needed at all by the rest of PHP code
1404 if ($CFG->dbfamily
=== 'oracle' && ($returnid == true ||
!empty($foundclobs) ||
!empty($foundblobs))) {
1405 /// We need this here (move this function to dmlib?)
1406 include_once($CFG->libdir
. '/ddllib.php');
1407 $xmldb_table = new XMLDBTable($table);
1408 $seqname = find_sequence_name($xmldb_table);
1410 /// Fallback, seqname not found, something is wrong. Inform and use the alternative getNameForObject() method
1411 debugging('Sequence name for table ' . $table->getName() . ' not found', DEBUG_DEVELOPER
);
1412 $generator = new XMLDBoci8po();
1413 $generator->setPrefix($CFG->prefix
);
1414 $seqname = $generator->getNameForObject($table, $primarykey, 'seq');
1416 if ($nextval = (int)$db->GenID($seqname)) {
1417 $dataobject->{$primarykey} = $nextval;
1419 debugging('Not able to get value from sequence ' . $seqname, DEBUG_DEVELOPER
);
1423 /// Get the correct SQL from adoDB
1424 if (!$insertSQL = $db->GetInsertSQL($rs, (array)$dataobject, true)) {
1428 /// Under Oracle, MSSQL and PostgreSQL, replace all the '@#CLOB#@' and '@#BLOB#@' ocurrences to proper default values
1429 /// if we know we have some of them in the query
1430 if (($CFG->dbfamily
== 'oracle' ||
$CFG->dbfamily
== 'mssql' ||
$CFG->dbfamily
== 'postgres') &&
1431 (!empty($foundclobs) ||
!empty($foundblobs))) {
1432 /// Initial configuration, based on DB
1433 switch ($CFG->dbfamily
) {
1435 $clobdefault = 'empty_clob()'; //Value of empty default clobs for this DB
1436 $blobdefault = 'empty_blob()'; //Value of empty default blobs for this DB
1440 $clobdefault = 'null'; //Value of empty default clobs for this DB (under mssql this won't be executed
1441 $blobdefault = 'null'; //Value of empty default blobs for this DB
1444 $insertSQL = str_replace("'@#CLOB#@'", $clobdefault, $insertSQL);
1445 $insertSQL = str_replace("'@#BLOB#@'", $blobdefault, $insertSQL);
1448 /// Run the SQL statement
1449 if (!$rs = $db->Execute($insertSQL)) {
1450 debugging($db->ErrorMsg() .'<br /><br />'.$insertSQL);
1451 if (!empty($CFG->dblogerror
)) {
1452 $debug=array_shift(debug_backtrace());
1453 error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: $insertSQL");
1458 /// Under Oracle and PostgreSQL, finally, update all the Clobs and Blobs present in the record
1459 /// if we know we have some of them in the query
1460 if (($CFG->dbfamily
== 'oracle' ||
$CFG->dbfamily
== 'postgres') &&
1461 !empty($dataobject->{$primarykey}) &&
1462 (!empty($foundclobs) ||
!empty($foundblobs))) {
1463 if (!db_update_lobs($table, $dataobject->{$primarykey}, $foundclobs, $foundblobs)) {
1464 return false; //Some error happened while updating LOBs
1468 /// If a return ID is not needed then just return true now (but not in MSSQL DBs, where we may have some pending tasks)
1469 if (!$returnid && $CFG->dbfamily
!= 'mssql') {
1473 /// We already know the record PK if it's been passed explicitly,
1474 /// or if we've retrieved it from a sequence (Postgres and Oracle).
1475 if (!empty($dataobject->{$primarykey})) {
1476 return $dataobject->{$primarykey};
1479 /// This only gets triggered with MySQL and MSQL databases
1480 /// however we have some postgres fallback in case we failed
1481 /// to find the sequence.
1482 $id = $db->Insert_ID();
1484 /// Under MSSQL all the Clobs and Blobs (IMAGE) present in the record
1485 /// if we know we have some of them in the query
1486 if (($CFG->dbfamily
== 'mssql') &&
1488 (!empty($foundclobs) ||
!empty($foundblobs))) {
1489 if (!db_update_lobs($table, $id, $foundclobs, $foundblobs)) {
1490 return false; //Some error happened while updating LOBs
1494 if ($CFG->dbfamily
=== 'postgres') {
1495 // try to get the primary key based on id
1496 if ( ($rs = $db->Execute('SELECT '. $primarykey .' FROM '. $CFG->prefix
. $table .' WHERE oid = '. $id))
1497 && ($rs->RecordCount() == 1) ) {
1498 trigger_error("Retrieved $primarykey from oid on table $table because we could not find the sequence.");
1499 return (integer)reset($rs->fields
);
1501 trigger_error('Failed to retrieve primary key after insert: SELECT '. $primarykey .
1502 ' FROM '. $CFG->prefix
. $table .' WHERE oid = '. $id);
1506 return (integer)$id;
1510 * Update a record in a table
1512 * $dataobject is an object containing needed data
1513 * Relies on $dataobject having a variable "id" to
1514 * specify the record to update
1518 * @param string $table The database table to be checked against.
1519 * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
1522 function update_record($table, $dataobject) {
1526 if (! isset($dataobject->id
) ) {
1530 /// Check we are handling a proper $dataobject
1531 if (is_array($dataobject)) {
1532 debugging('Warning. Wrong call to update_record(). $dataobject must be an object. array found instead', DEBUG_DEVELOPER
);
1533 $dataobject = (object)$dataobject;
1536 // Remove this record from record cache since it will change
1537 if ($CFG->rcache
=== true) {
1538 rcache_unset($table, $dataobject->id
);
1541 /// Temporary hack as part of phasing out all access to obsolete user tables XXX
1542 if (!empty($CFG->rolesactive
)) {
1543 if (in_array($table, array('user_students', 'user_teachers', 'user_coursecreators', 'user_admins'))) {
1544 if (debugging()) { var_dump(debug_backtrace()); }
1545 error('This SQL relies on obsolete tables ('.$table.')! Your code must be fixed by a developer.');
1549 /// Begin DIRTY HACK
1550 if ($CFG->dbfamily
== 'oracle') {
1551 oracle_dirty_hack($table, $dataobject); // Convert object to the correct "empty" values for Oracle DB
1555 /// Under Oracle, MSSQL and PostgreSQL we have our own update record process
1556 /// detect all the clob/blob fields and delete them from the record being updated
1557 /// saving them into $foundclobs and $foundblobs [$fieldname]->contents
1558 /// They will be updated later
1559 if (($CFG->dbfamily
== 'oracle' ||
$CFG->dbfamily
== 'mssql' ||
$CFG->dbfamily
== 'postgres')
1560 && !empty($dataobject->id
)) {
1562 $foundclobs = array();
1563 $foundblobs = array();
1564 db_detect_lobs($table, $dataobject, $foundclobs, $foundblobs, true);
1567 // Determine all the fields in the table
1568 if (!$columns = $db->MetaColumns($CFG->prefix
. $table)) {
1571 $data = (array)$dataobject;
1573 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++
; };
1575 // Pull out data matching these fields
1577 foreach ($columns as $column) {
1578 if ($column->name
<> 'id' and array_key_exists($column->name
, $data)) {
1579 $ddd[$column->name
] = $data[$column->name
];
1583 // Construct SQL queries
1584 $numddd = count($ddd);
1588 /// Only if we have fields to be updated (this will prevent both wrong updates +
1589 /// updates of only LOBs in Oracle
1591 foreach ($ddd as $key => $value) {
1593 if ($value === NULL) {
1594 $update .= $key .' = NULL'; // previously NULLs were not updated
1596 $update .= $key .' = \''. $value .'\''; // All incoming data is already quoted
1598 if ($count < $numddd) {
1603 if (!$rs = $db->Execute('UPDATE '. $CFG->prefix
. $table .' SET '. $update .' WHERE id = \''. $dataobject->id
.'\'')) {
1604 debugging($db->ErrorMsg() .'<br /><br />UPDATE '. $CFG->prefix
. $table .' SET '. $update .' WHERE id = \''. $dataobject->id
.'\'');
1605 if (!empty($CFG->dblogerror
)) {
1606 $debug=array_shift(debug_backtrace());
1607 error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: UPDATE $CFG->prefix$table SET $update WHERE id = '$dataobject->id'");
1613 /// Under Oracle, MSSQL and PostgreSQL, finally, update all the Clobs and Blobs present in the record
1614 /// if we know we have some of them in the query
1615 if (($CFG->dbfamily
== 'oracle' ||
$CFG->dbfamily
== 'mssql' ||
$CFG->dbfamily
== 'postgres') &&
1616 !empty($dataobject->id
) &&
1617 (!empty($foundclobs) ||
!empty($foundblobs))) {
1618 if (!db_update_lobs($table, $dataobject->id
, $foundclobs, $foundblobs)) {
1619 return false; //Some error happened while updating LOBs
1629 * Returns the proper SQL to do paging
1632 * @param string $page Offset page number
1633 * @param string $recordsperpage Number of records per page
1634 * @deprecated Moodle 1.7 use the new $limitfrom, $limitnum available in all
1635 * the get_recordXXX() funcions.
1638 function sql_paging_limit($page, $recordsperpage) {
1641 debugging('Function sql_paging_limit() is deprecated. Replace it with the correct use of limitfrom, limitnum parameters', DEBUG_DEVELOPER
);
1643 switch ($CFG->dbfamily
) {
1645 return 'LIMIT '. $recordsperpage .' OFFSET '. $page;
1647 return 'LIMIT '. $page .','. $recordsperpage;
1652 * Returns the proper SQL to do LIKE in a case-insensitive way
1654 * Note the LIKE are case sensitive for Oracle. Oracle 10g is required to use
1655 * the caseinsensitive search using regexp_like() or NLS_COMP=LINGUISTIC :-(
1656 * See http://docs.moodle.org/en/XMLDB_Problems#Case-insensitive_searches
1661 function sql_ilike() {
1664 switch ($CFG->dbfamily
) {
1674 * Returns the proper SQL to do MAX
1677 * @param string $field
1680 function sql_max($field) {
1683 switch ($CFG->dbfamily
) {
1685 return "MAX($field)";
1690 * Returns the proper SQL (for the dbms in use) to concatenate $firstname and $lastname
1693 * @param string $firstname User's first name
1694 * @param string $lastname User's last name
1697 function sql_fullname($firstname='firstname', $lastname='lastname') {
1698 return sql_concat($firstname, "' '", $lastname);
1702 * Returns the proper SQL to do CONCAT between the elements passed
1703 * Can take many parameters - just a passthrough to $db->Concat()
1706 * @param string $element
1709 function sql_concat() {
1712 $args = func_get_args();
1713 return call_user_func_array(array($db, 'Concat'), $args);
1717 * Returns the proper SQL to do CONCAT between the elements passed
1718 * with a given separator
1721 * @param string $separator
1722 * @param array $elements
1725 function sql_concat_join($separator="' '", $elements=array()) {
1728 // copy to ensure pass by value
1731 // Intersperse $elements in the array.
1732 // Add items to the array on the fly, walking it
1733 // _backwards_ splicing the elements in. The loop definition
1734 // should skip first and last positions.
1735 for ($n=count($elem)-1; $n > 0 ; $n--) {
1736 array_splice($elem, $n, 0, $separator);
1738 return call_user_func_array(array($db, 'Concat'), $elem);
1742 * Returns the proper SQL to do IS NULL
1744 * @param string $fieldname The field to add IS NULL to
1747 function sql_isnull($fieldname) {
1750 switch ($CFG->dbfamily
) {
1752 return $fieldname.' IS NULL';
1754 return $fieldname.' IS NULL';
1759 * Returns the proper AS keyword to be used to aliase columns
1760 * SQL defines the keyword as optional and nobody but PG
1761 * seems to require it. This function should be used inside all
1762 * the statements using column aliases.
1763 * Note than the use of table aliases doesn't require the
1764 * AS keyword at all, only columns for postgres.
1766 * @ return string the keyword
1767 * @deprecated Moodle 1.7 because coding guidelines now enforce to use AS in column aliases
1772 switch ($CFG->dbfamily
) {
1781 * Returns the empty string char used by every supported DB. To be used when
1782 * we are searching for that values in our queries. Only Oracle uses this
1783 * for now (will be out, once we migrate to proper NULLs if that days arrives)
1785 function sql_empty() {
1788 switch ($CFG->dbfamily
) {
1790 return ' '; //Only Oracle uses 1 white-space
1797 * Returns the proper substr() function for each DB
1798 * Relies on ADOdb $db->substr property
1800 function sql_substr() {
1808 * Returns the SQL text to be used to compare one TEXT (clob) column with
1809 * one varchar column, because some RDBMS doesn't support such direct
1811 * @param string fieldname the name of the TEXT field we need to order by
1812 * @param string number of chars to use for the ordering (defaults to 32)
1813 * @return string the piece of SQL code to be used in your statement.
1815 function sql_compare_text($fieldname, $numchars=32) {
1816 return sql_order_by_text($fieldname, $numchars);
1821 * Returns the SQL text to be used to order by one TEXT (clob) column, because
1822 * some RDBMS doesn't support direct ordering of such fields.
1823 * Note that the use or queries being ordered by TEXT columns must be minimised,
1824 * because it's really slooooooow.
1825 * @param string fieldname the name of the TEXT field we need to order by
1826 * @param string number of chars to use for the ordering (defaults to 32)
1827 * @return string the piece of SQL code to be used in your statement.
1829 function sql_order_by_text($fieldname, $numchars=32) {
1833 switch ($CFG->dbfamily
) {
1835 return 'CONVERT(varchar, ' . $fieldname . ', ' . $numchars . ')';
1838 return 'dbms_lob.substr(' . $fieldname . ', ' . $numchars . ',1)';
1846 * Returns the SQL text to be used in order to perform one bitwise AND operation
1847 * between 2 integers.
1848 * @param integer int1 first integer in the operation
1849 * @param integer int2 second integer in the operation
1850 * @return string the piece of SQL code to be used in your statement.
1852 function sql_bitand($int1, $int2) {
1856 switch ($CFG->dbfamily
) {
1858 return 'bitand((' . $int1 . '), (' . $int2 . '))';
1861 return '((' . $int1 . ') & (' . $int2 . '))';
1866 * Returns the SQL text to be used in order to perform one bitwise OR operation
1867 * between 2 integers.
1868 * @param integer int1 first integer in the operation
1869 * @param integer int2 second integer in the operation
1870 * @return string the piece of SQL code to be used in your statement.
1872 function sql_bitor($int1, $int2) {
1876 switch ($CFG->dbfamily
) {
1878 return '((' . $int1 . ') + (' . $int2 . ') - ' . sql_bitand($int1, $int2) . ')';
1881 return '((' . $int1 . ') | (' . $int2 . '))';
1886 * Returns the SQL text to be used in order to perform one bitwise XOR operation
1887 * between 2 integers.
1888 * @param integer int1 first integer in the operation
1889 * @param integer int2 second integer in the operation
1890 * @return string the piece of SQL code to be used in your statement.
1892 function sql_bitxor($int1, $int2) {
1896 switch ($CFG->dbfamily
) {
1898 return '(' . sql_bitor($int1, $int2) . ' - ' . sql_bitand($int1, $int2) . ')';
1901 return '((' . $int1 . ') # (' . $int2 . '))';
1904 return '((' . $int1 . ') ^ (' . $int2 . '))';
1909 * Returns the SQL text to be used in order to perform one bitwise NOT operation
1911 * @param integer int1 integer in the operation
1912 * @return string the piece of SQL code to be used in your statement.
1914 function sql_bitnot($int1) {
1918 switch ($CFG->dbfamily
) {
1920 return '((0 - (' . $int1 . ')) - 1)';
1923 return '(~(' . $int1 . '))';
1928 * Returns SQL to be used as a subselect to find the primary role of users.
1929 * Geoff Cant <geoff@catalyst.net.nz> (the author) is very keen for this to
1930 * be implemented as a view in future versions.
1932 * eg if this function returns a string called $primaryroles, then you could:
1933 * $sql = 'SELECT COUNT(DISTINCT prs.userid) FROM ('.$primary_roles.') prs
1934 * WHERE prs.primary_roleid='.$role->id.' AND prs.courseid='.$course->id.
1935 * ' AND prs.contextlevel = '.CONTEXT_COURSE;
1937 * @return string the piece of SQL code to be used in your FROM( ) statement.
1939 function sql_primary_role_subselect() {
1941 return 'SELECT ra.userid,
1942 ra.roleid AS primary_roleid,
1948 c.instanceid AS courseid,
1950 FROM '.$CFG->prefix
.'role_assignments ra
1951 INNER JOIN '.$CFG->prefix
.'role r ON ra.roleid = r.id
1952 INNER JOIN '.$CFG->prefix
.'context c ON ra.contextid = c.id
1955 FROM '.$CFG->prefix
.'role_assignments i_ra
1956 INNER JOIN '.$CFG->prefix
.'role i_r ON i_ra.roleid = i_r.id
1957 WHERE ra.userid = i_ra.userid AND
1958 ra.contextid = i_ra.contextid AND
1959 i_r.sortorder < r.sortorder
1964 * Prepare a SQL WHERE clause to select records where the given fields match the given values.
1966 * Prepares a where clause of the form
1967 * WHERE field1 = value1 AND field2 = value2 AND field3 = value3
1968 * except that you need only specify as many arguments (zero to three) as you need.
1970 * @param string $field1 the first field to check (optional).
1971 * @param string $value1 the value field1 must have (requred if field1 is given, else optional).
1972 * @param string $field2 the second field to check (optional).
1973 * @param string $value2 the value field2 must have (requred if field2 is given, else optional).
1974 * @param string $field3 the third field to check (optional).
1975 * @param string $value3 the value field3 must have (requred if field3 is given, else optional).
1977 function where_clause($field1='', $value1='', $field2='', $value2='', $field3='', $value3='') {
1979 $select = is_null($value1) ?
"WHERE $field1 IS NULL" : "WHERE $field1 = '$value1'";
1981 $select .= is_null($value2) ?
" AND $field2 IS NULL" : " AND $field2 = '$value2'";
1983 $select .= is_null($value3) ?
" AND $field3 IS NULL" : " AND $field3 = '$value3'";
1993 * Get the data type of a table column, using an ADOdb MetaType() call.
1997 * @param string $table The name of the database table
1998 * @param string $column The name of the field in the table
1999 * @return string Field type or false if error
2002 function column_type($table, $column) {
2005 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++
; };
2007 if(!$rs = $db->Execute('SELECT '.$column.' FROM '.$CFG->prefix
.$table.' WHERE 1=2')) {
2011 $field = $rs->FetchField(0);
2012 return $rs->MetaType($field->type
);
2016 * This function will execute an array of SQL commands, returning
2017 * true/false if any error is found and stopping/continue as desired.
2018 * It's widely used by all the ddllib.php functions
2020 * @param array sqlarr array of sql statements to execute
2021 * @param boolean continue to specify if must continue on error (true) or stop (false)
2022 * @param boolean feedback to specify to show status info (true) or not (false)
2023 * @param boolean true if everything was ok, false if some error was found
2025 function execute_sql_arr($sqlarr, $continue=true, $feedback=true) {
2027 if (!is_array($sqlarr)) {
2032 foreach($sqlarr as $sql) {
2033 if (!execute_sql($sql, $feedback)) {
2044 * This internal function, called from setup.php, sets all the configuration
2045 * needed to work properly against any DB. It setups connection encoding
2046 * and some other variables. Also, ir defines the $CFG->dbfamily variable
2047 * to handle conditional code better than using $CFG->dbtype directly.
2049 * This function must contain the init code needed for each dbtype supported.
2051 function configure_dbconnection() {
2055 switch ($CFG->dbtype
) {
2058 $db->Execute("SET NAMES 'utf8'");
2061 $db->Execute("SET NAMES 'utf8'");
2066 /// No need to set charset. It must be specified in the driver conf
2067 /// Allow quoted identifiers
2068 $db->Execute('SET QUOTED_IDENTIFIER ON');
2069 /// Force ANSI nulls so the NULL check was done by IS NULL and NOT IS NULL
2070 /// instead of equal(=) and distinct(<>) simbols
2071 $db->Execute('SET ANSI_NULLS ON');
2072 /// Enable sybase quotes, so addslashes and stripslashes will use "'"
2073 ini_set('magic_quotes_sybase', '1');
2074 /// NOTE: Not 100% useful because GPC has been addslashed with the setting off
2075 /// so IT'S MANDATORY TO CHANGE THIS UNDER php.ini or .htaccess for this DB
2076 /// or to turn off magic_quotes to allow Moodle to do it properly
2079 /// No need to set charset. It must be specified by the NLS_LANG env. variable
2080 /// Enable sybase quotes, so addslashes and stripslashes will use "'"
2081 ini_set('magic_quotes_sybase', '1');
2082 /// NOTE: Not 100% useful because GPC has been addslashed with the setting off
2083 /// so IT'S MANDATORY TO ENABLE THIS UNDER php.ini or .htaccess for this DB
2084 /// or to turn off magic_quotes to allow Moodle to do it properly
2087 /// Finally define dbfamily
2092 * This function will handle all the records before being inserted/updated to DB for Oracle
2093 * installations. This is because the "special feature" of Oracle where the empty string is
2094 * equal to NULL and this presents a problem with all our currently NOT NULL default '' fields.
2096 * Once Moodle DB will be free of this sort of false NOT NULLS, this hack could be removed safely
2098 * Note that this function is 100% private and should be used, exclusively by DML functions
2099 * in this file. Also, this is considered a DIRTY HACK to be removed when possible. (stronk7)
2101 * This function is private and must not be used outside dmllib at all
2103 * @param $table string the table where the record is going to be inserted/updated (without prefix)
2104 * @param $dataobject object the object to be inserted/updated
2105 * @param $usecache boolean flag to determinate if we must use the per request cache of metadata
2106 * true to use it, false to ignore and delete it
2108 function oracle_dirty_hack ($table, &$dataobject, $usecache = true) {
2110 global $CFG, $db, $metadata_cache;
2112 /// Init and delete metadata cache
2113 if (!isset($metadata_cache) ||
!$usecache) {
2114 $metadata_cache = array();
2117 /// For Oracle DB, empty strings are converted to NULLs in DB
2118 /// and this breaks a lot of NOT NULL columns currenty Moodle. In the future it's
2119 /// planned to move some of them to NULL, if they must accept empty values and this
2120 /// piece of code will become less and less used. But, for now, we need it.
2121 /// What we are going to do is to examine all the data being inserted and if it's
2122 /// an empty string (NULL for Oracle) and the field is defined as NOT NULL, we'll modify
2123 /// such data in the best form possible ("0" for booleans and numbers and " " for the
2124 /// rest of strings. It isn't optimal, but the only way to do so.
2125 /// In the oppsite, when retrieving records from Oracle, we'll decode " " back to
2126 /// empty strings to allow everything to work properly. DIRTY HACK.
2128 /// If the db isn't Oracle, return without modif
2129 if ( $CFG->dbfamily
!= 'oracle') {
2133 /// Get Meta info to know what to change, using the cached meta if exists
2134 if (!isset($metadata_cache[$table])) {
2135 $metadata_cache[$table] = array_change_key_case($db->MetaColumns($CFG->prefix
. $table), CASE_LOWER
);
2137 $columns = $metadata_cache[$table];
2138 /// Iterate over all the fields in the insert, transforming values
2139 /// in the best possible form
2140 foreach ($dataobject as $fieldname => $fieldvalue) {
2141 /// If the field doesn't exist in metadata, skip
2142 if (!isset($columns[strtolower($fieldname)])) {
2145 /// If the field ins't VARCHAR or CLOB, skip
2146 if ($columns[strtolower($fieldname)]->type
!= 'VARCHAR2' && $columns[strtolower($fieldname)]->type
!= 'CLOB') {
2149 /// If the field isn't NOT NULL, skip (it's nullable, so accept empty values)
2150 if (!$columns[strtolower($fieldname)]->not_null
) {
2153 /// If the value isn't empty, skip
2154 if (!empty($fieldvalue)) {
2157 /// Now, we have one empty value, going to be inserted to one NOT NULL, VARCHAR2 or CLOB field
2158 /// Try to get the best value to be inserted
2159 if (gettype($fieldvalue) == 'boolean') {
2160 $dataobject->$fieldname = '0'; /// Transform false to '0' that evaluates the same for PHP
2161 } else if (gettype($fieldvalue) == 'integer') {
2162 $dataobject->$fieldname = '0'; /// Transform 0 to '0' that evaluates the same for PHP
2163 } else if (gettype($fieldvalue) == 'NULL') {
2164 $dataobject->$fieldname = '0'; /// Transform NULL to '0' that evaluates the same for PHP
2166 $dataobject->$fieldname = ' '; /// Transform '' to ' ' that DONT'T EVALUATE THE SAME
2167 /// (we'll transform back again on get_records_XXX functions and others)!!
2171 /// End of DIRTY HACK
2174 * This function will search for all the CLOBs and BLOBs fields passed in the dataobject, replacing
2175 * their contents by the fixed strings '@#CLOB#@' and '@#BLOB#@' and returning one array for all the
2176 * found CLOBS and another for all the found BLOBS
2177 * Used by Oracle drivers to perform the two-step insertion/update of LOBs and
2178 * by MSSQL to perform the same exclusively for BLOBs (IMAGE fields)
2180 * This function is private and must not be used outside dmllib at all
2182 * @param $table string the table where the record is going to be inserted/updated (without prefix)
2183 * @param $dataobject object the object to be inserted/updated
2184 * @param $clobs array of clobs detected
2185 * @param $dataobject array of blobs detected
2186 * @param $unset boolean to specify if we must unset found LOBs from the original object (true) or
2187 * just return them modified to @#CLOB#@ and @#BLOB#@ (false)
2188 * @param $usecache boolean flag to determinate if we must use the per request cache of metadata
2189 * true to use it, false to ignore and delete it
2191 function db_detect_lobs ($table, &$dataobject, &$clobs, &$blobs, $unset = false, $usecache = true) {
2193 global $CFG, $db, $metadata_cache;
2195 $dataarray = (array)$dataobject; //Convert to array. It's supposed that PHP 4.3 doesn't iterate over objects
2197 /// Initial configuration, based on DB
2198 switch ($CFG->dbfamily
) {
2200 $clobdbtype = 'CLOB'; //Name of clobs for this DB
2201 $blobdbtype = 'BLOB'; //Name of blobs for this DB
2204 $clobdbtype = 'NOTPROCESSES'; //Name of clobs for this DB (under mssql flavours we don't process CLOBS)
2205 $blobdbtype = 'IMAGE'; //Name of blobs for this DB
2208 $clobdbtype = 'NOTPROCESSES'; //Name of clobs for this DB (under postgres flavours we don't process CLOBS)
2209 $blobdbtype = 'BYTEA'; //Name of blobs for this DB
2212 return; //Other DB doesn't need this two step to happen, prevent continue
2215 /// Init and delete metadata cache
2216 if (!isset($metadata_cache) ||
!$usecache) {
2217 $metadata_cache = array();
2220 /// Get Meta info to know what to change, using the cached meta if exists
2221 if (!isset($metadata_cache[$table])) {
2222 $metadata_cache[$table] = array_change_key_case($db->MetaColumns($CFG->prefix
. $table), CASE_LOWER
);
2224 $columns = $metadata_cache[$table];
2226 foreach ($dataarray as $fieldname => $fieldvalue) {
2227 /// If the field doesn't exist in metadata, skip
2228 if (!isset($columns[strtolower($fieldname)])) {
2231 /// If the field is CLOB, update its value to '@#CLOB#@' and store it in the $clobs array
2232 if (strtoupper($columns[strtolower($fieldname)]->type
) == $clobdbtype) {
2233 /// Oracle optimization. CLOBs under 4000cc can be directly inserted (no need to apply 2-phases to them)
2234 if ($CFG->dbfamily
== 'oracle' && strlen($dataobject->$fieldname) < 4000) {
2237 $clobs[$fieldname] = $dataobject->$fieldname;
2239 unset($dataobject->$fieldname);
2241 $dataobject->$fieldname = '@#CLOB#@';
2246 /// If the field is BLOB OR IMAGE OR BYTEA, update its value to '@#BLOB#@' and store it in the $blobs array
2247 if (strtoupper($columns[strtolower($fieldname)]->type
) == $blobdbtype) {
2248 $blobs[$fieldname] = $dataobject->$fieldname;
2250 unset($dataobject->$fieldname);
2252 $dataobject->$fieldname = '@#BLOB#@';
2260 * This function will iterate over $clobs and $blobs array, executing the needed
2261 * UpdateClob() and UpdateBlob() ADOdb function calls to store LOBs contents properly
2262 * Records to be updated are always searched by PK (id always!)
2264 * Used by Orace CLOBS and BLOBS and MSSQL IMAGES
2266 * This function is private and must not be used outside dmllib at all
2268 * @param $table string the table where the record is going to be inserted/updated (without prefix)
2269 * @param $sqlcondition mixed value defining the records to be LOB-updated. It it's a number, must point
2270 * to the PK og the table (id field), else it's processed as one harcoded SQL condition (WHERE clause)
2271 * @param $clobs array of clobs to be updated
2272 * @param $blobs array of blobs to be updated
2274 function db_update_lobs ($table, $sqlcondition, &$clobs, &$blobs) {
2280 /// Initial configuration, based on DB
2281 switch ($CFG->dbfamily
) {
2283 $clobdbtype = 'CLOB'; //Name of clobs for this DB
2284 $blobdbtype = 'BLOB'; //Name of blobs for this DB
2287 $clobdbtype = 'NOTPROCESSES'; //Name of clobs for this DB (under mssql flavours we don't process CLOBS)
2288 $blobdbtype = 'IMAGE'; //Name of blobs for this DB
2291 $clobdbtype = 'NOTPROCESSES'; //Name of clobs for this DB (under postgres flavours we don't process CLOBS)
2292 $blobdbtype = 'BYTEA'; //Name of blobs for this DB
2295 return; //Other DB doesn't need this two step to happen, prevent continue
2298 /// Calculate the update sql condition
2299 if (is_numeric($sqlcondition)) { /// If passing a number, it's the PK of the table (id)
2300 $sqlcondition = 'id=' . $sqlcondition;
2301 } else { /// Else, it's a formal standard SQL condition, we try to delete the WHERE in case it exists
2302 $sqlcondition = trim(preg_replace('/^WHERE/is', '', trim($sqlcondition)));
2305 /// Update all the clobs
2307 foreach ($clobs as $key => $value) {
2309 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++
; }; /// Count the extra updates in PERF
2311 /// Oracle CLOBs doesn't like quoted strings (are inserted via prepared statemets)
2312 if ($CFG->dbfamily
== 'oracle') {
2313 $value = stripslashes_safe($value);
2316 if (!$db->UpdateClob($CFG->prefix
.$table, $key, $value, $sqlcondition)) {
2318 $statement = "UpdateClob('$CFG->prefix$table', '$key', '" . substr($value, 0, 100) . "...', '$sqlcondition')";
2319 debugging($db->ErrorMsg() ."<br /><br />$statement");
2320 if (!empty($CFG->dblogerror
)) {
2321 $debug=array_shift(debug_backtrace());
2322 error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: $statement");
2327 /// Update all the blobs
2329 foreach ($blobs as $key => $value) {
2331 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++
; }; /// Count the extra updates in PERF
2333 /// Oracle, MSSQL and PostgreSQL BLOBs doesn't like quoted strings (are inserted via prepared statemets)
2334 if ($CFG->dbfamily
== 'oracle' ||
$CFG->dbfamily
== 'mssql' ||
$CFG->dbfamily
== 'postgres') {
2335 $value = stripslashes_safe($value);
2338 if(!$db->UpdateBlob($CFG->prefix
.$table, $key, $value, $sqlcondition)) {
2340 $statement = "UpdateBlob('$CFG->prefix$table', '$key', '" . substr($value, 0, 100) . "...', '$sqlcondition')";
2341 debugging($db->ErrorMsg() ."<br /><br />$statement");
2342 if (!empty($CFG->dblogerror
)) {
2343 $debug=array_shift(debug_backtrace());
2344 error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT: $statement");
2353 * Set cached record.
2355 * If you have called rcache_getforfill() before, it will also
2358 * This function is private and must not be used outside dmllib at all
2360 * @param $table string
2361 * @param $id integer
2365 function rcache_set($table, $id, $rec) {
2366 global $CFG, $MCACHE, $rcache;
2368 if ($CFG->cachetype
=== 'internal') {
2369 $rcache->data
[$table][$id] = $rec;
2371 $key = $table . '|' . $id;
2373 if (isset($MCACHE)) {
2374 // $table is a flag used to mark
2375 // a table as dirty & uncacheable
2376 // when an UPDATE or DELETE not bound by ID
2378 if (!$MCACHE->get($table)) {
2379 // this will also release the _forfill lock
2380 $MCACHE->set($key, $rec, $CFG->rcachettl
);
2389 * Unset cached record if it exists.
2391 * This function is private and must not be used outside dmllib at all
2393 * @param $table string
2394 * @param $id integer
2397 function rcache_unset($table, $id) {
2398 global $CFG, $MCACHE, $rcache;
2400 if ($CFG->cachetype
=== 'internal') {
2401 if (isset($rcache->data
[$table][$id])) {
2402 unset($rcache->data
[$table][$id]);
2405 $key = $table . '|' . $id;
2406 if (isset($MCACHE)) {
2407 $MCACHE->delete($key);
2414 * Get cached record if available. ONLY use if you
2415 * are trying to get the cached record and will NOT
2416 * fetch it yourself if not cached.
2418 * Use rcache_getforfill() if you are going to fetch
2419 * the record if not cached...
2421 * This function is private and must not be used outside dmllib at all
2423 * @param $table string
2424 * @param $id integer
2425 * @return mixed object-like record on cache hit, false otherwise
2427 function rcache_get($table, $id) {
2428 global $CFG, $MCACHE, $rcache;
2430 if ($CFG->cachetype
=== 'internal') {
2431 if (isset($rcache->data
[$table][$id])) {
2433 return $rcache->data
[$table][$id];
2440 if (isset($MCACHE)) {
2441 $key = $table . '|' . $id;
2442 // we set $table as a flag used to mark
2443 // a table as dirty & uncacheable
2444 // when an UPDATE or DELETE not bound by ID
2446 if ($MCACHE->get($table)) {
2450 $rec = $MCACHE->get($key);
2464 * Get cached record if available. In most cases you want
2465 * to use this function -- namely if you are trying to get
2466 * the cached record and will fetch it yourself if not cached.
2467 * (and set the cache ;-)
2469 * Uses the getforfill caching mechanism. See lib/eaccelerator.class.php
2470 * for a detailed description of the technique.
2472 * Note: if you call rcache_getforfill() you are making an implicit promise
2473 * that if the cache is empty, you will later populate it, or cancel the promise
2474 * calling rcache_releaseforfill();
2476 * This function is private and must not be used outside dmllib at all
2478 * @param $table string
2479 * @param $id integer
2480 * @return mixed object-like record on cache hit, false otherwise
2482 function rcache_getforfill($table, $id) {
2483 global $CFG, $MCACHE, $rcache;
2485 if ($CFG->cachetype
=== 'internal') {
2486 return rcache_get($table, $id);
2489 if (isset($MCACHE)) {
2490 $key = $table . '|' . $id;
2491 // if $table is set - we won't take the
2493 if ($MCACHE->get($table)) {
2497 $rec = $MCACHE->getforfill($key);
2509 * Release the exclusive lock obtained by
2510 * rcache_getforfill(). See rcache_getforfill()
2513 * This function is private and must not be used outside dmllib at all
2515 * @param $table string
2516 * @param $id integer
2519 function rcache_releaseforfill($table, $id) {
2520 global $CFG, $MCACHE;
2522 if (isset($MCACHE)) {
2523 $key = $table . '|' . $id;
2524 return $MCACHE->releaseforfill($key);
2530 * Remove or invalidate all rcache entries related to
2531 * a table. Not all caching mechanisms cluster entries
2532 * by table so in those cases we use alternative strategies.
2534 * This function is private and must not be used outside dmllib at all
2536 * @param $table string the table to invalidate records for
2539 function rcache_unset_table ($table) {
2540 global $CFG, $MCACHE, $rcache;
2542 if ($CFG->cachetype
=== 'internal') {
2543 if (isset($rcache->data
[$table])) {
2544 unset($rcache->data
[$table]);
2549 if (isset($MCACHE)) {
2550 // at least as long as content keys to ensure they expire
2551 // before the dirty flag
2552 $MCACHE->set($table, true, $CFG->rcachettl
);