dml.php 63.9 KB
Newer Older
Martyn Smith's avatar
Martyn Smith committed
1
<?php
Penny Leach's avatar
Penny Leach committed
2 3 4
/**
 *
 * @package    mahara
Penny Leach's avatar
Penny Leach committed
5 6
 * @subpackage core
 * @author     Martin Dougiamas <martin@moodle.com>
7 8
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
Penny Leach's avatar
Penny Leach committed
9 10 11
 * @copyright  (C) 2001-3001 Martin Dougiamas http://dougiamas.com
 *
 */
Penny Leach's avatar
Penny Leach committed
12

Penny Leach's avatar
Penny Leach committed
13
defined('INTERNAL') || die();
Penny Leach's avatar
Penny Leach committed
14

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
/**
 * Return a table name, properly prefixed and escaped
 *
 */
function db_table_name($name) {
    return db_quote_identifier(get_config('dbprefix') . $name);
}

/**
 * Searches through a query for strings looking like {name}, to replace with 
 * correctly quoted and prefixed table names
 *
 * @param string $sql The SQL to replace the placeholders in
 * @return string
 */
function db_quote_table_placeholders($sql) {
31
    return preg_replace_callback('/\{([a-z][a-z0-9_]+)\}/', '_db_quote_table_placeholders_callback', $sql);
32 33 34
}

/**
35 36 37 38 39 40 41 42 43
 * A callback function used only in db_quote_table_placeholders
 * @param array $matches
 */
function _db_quote_table_placeholders_callback($matches) {
    return db_table_name($matches[1]);
}

/**
 * Given a table name or other identifier, return it quoted for the appropriate
44 45 46 47 48 49 50 51
 * database engine currently being used
 *
 * @param string $identifier The identifier to quote
 * @return string
 */
function db_quote_identifier($identifier) {
    // Currently, postgres and mysql (in postgres compat. mode) both support 
    // the sql standard "
52 53 54
    if (strpos($identifier, '"') !== false) {
        return $identifier;
    }
55 56 57
    return '"' . $identifier . '"';
}

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
/**
 * Check whether the db's default character encoding is utf8
 *
 * @return bool
 */
function db_is_utf8() {
    global $db;
    if (!is_a($db, 'ADOConnection')) {
        throw new SQLException('Database connection is not available ');
    }
    if (is_mysql()) {
        $result = $db->Execute("SHOW VARIABLES LIKE 'character_set_database'");
        return $result->fields['Value'] == 'utf8';
    }
    if (is_postgres()) {
        $result = $db->Execute("SHOW SERVER_ENCODING");
        return $result->fields['server_encoding'] == 'UTF8';
    }
    return false;
}

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
function db_total_size() {
    global $db;
    if (!is_a($db, 'ADOConnection')) {
        throw new SQLException('Database connection is not available ');
    }
    $dbname = db_quote(get_config('dbname'));
    if (is_mysql()) {
        $result = $db->Execute("
            SELECT SUM( data_length + index_length ) AS dbsize
            FROM information_schema.tables
            WHERE table_schema = $dbname
        ");
        return $result->fields['dbsize'];
    }
    if (is_postgres()) {
        $result = $db->Execute("SELECT * FROM pg_database_size($dbname)");
        return $result->fields['pg_database_size'];
    }
    return false;
}

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
function column_collation_is_default($table, $column) {
    global $db;
    if (!is_a($db, 'ADOConnection')) {
        throw new SQLException('Database connection is not available ');
    }
    if (is_mysql()) {
        $result = $db->Execute("SHOW VARIABLES LIKE 'collation_database'");
        $defaultcollation = $result->fields['Value'];

        $command = 'SHOW FULL COLUMNS FROM ' . db_table_name($table) . ' WHERE field = ?';
        $stmt = $db->Prepare($command);
        $result = $db->Execute($stmt, array($column));
        return $result->fields['Collation'] == $defaultcollation;
    }
    return true;
}

Penny Leach's avatar
Penny Leach committed
117 118 119 120 121 122 123
/**
 * Execute a given sql command string
 *
 * Completely general function - it just runs some SQL and reports success.
 *
 * @uses $db
 * @param string $command The sql string you wish to be executed.
124
 * @param array $values When using prepared statements, this is the value array (optional).
Penny Leach's avatar
Penny Leach committed
125
 * @return string
126
 * @throws SQLException
Penny Leach's avatar
Penny Leach committed
127
 */
128
function execute_sql($command, $values=null) {
129 130 131
    global $db;
    
    if (!is_a($db, 'ADOConnection')) {
132
        throw new SQLException('Database connection is not available ');
133
    }
Penny Leach's avatar
Penny Leach committed
134

135 136
    $command = db_quote_table_placeholders($command);

137 138
    // @todo need to do more research into this flag - what is it for, we
    // probably want to just turn it off because we can catch the exceptions
Penny Leach's avatar
Penny Leach committed
139
    $olddebug = $db->debug;
140
    $db->debug = false;
Penny Leach's avatar
Penny Leach committed
141

142
    try {
143 144 145 146 147 148 149
        if (!empty($values) && is_array($values) && count($values) > 0) {
            $stmt = $db->Prepare($command);
            $result = $db->Execute($stmt, $values);
        }
        else {
            $result = $db->Execute($command);
        }
150 151
    }
    catch (ADODB_Exception $e) {
152
        log_debug($e->getMessage() . "Command was: $command");
153
        $db->debug = $olddebug;
154
        throw new SQLException('Could not execute command: ' . $command);
Penny Leach's avatar
Penny Leach committed
155 156 157
    }

    $db->debug = $olddebug;
158
    return true;
Penny Leach's avatar
Penny Leach committed
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
}

/// GENERIC FUNCTIONS TO CHECK AND COUNT RECORDS ////////////////////////////////////////

/**
 * Test whether a record exists in a table where all the given fields match the given values.
 *
 * The record to test is specified by giving up to three fields that must
 * equal the corresponding values.
 *
 * @param string $table The table to check.
 * @param string $field1 the first field to check (optional).
 * @param string $value1 the value field1 must have (requred if field1 is given, else optional).
 * @param string $field2 the second field to check (optional).
 * @param string $value2 the value field2 must have (requred if field2 is given, else optional).
 * @param string $field3 the third field to check (optional).
 * @param string $value3 the value field3 must have (requred if field3 is given, else optional).
 * @return bool true if a matching record exists, else false.
177
 * @throws SQLException
Penny Leach's avatar
Penny Leach committed
178 179 180 181
 */
function record_exists($table, $field1=null, $value1=null, $field2=null, $value2=null, $field3=null, $value3=null) {
    $select = where_clause_prepared($field1, $field2, $field3);
    $values = where_values_prepared($value1, $value2, $value3);
182
    return record_exists_sql('SELECT * FROM ' . db_table_name($table) .' '. $select, $values);
Penny Leach's avatar
Penny Leach committed
183 184
}

Penny Leach's avatar
Penny Leach committed
185 186 187 188 189 190 191
/**
 * Test whether any records exists in a table which match a particular WHERE clause.
 *
 * This function returns true if at least one record is returned
 * 
 * @param string $table The database table to be checked against.
 * @param string $select A fragment of SQL to be used in a WHERE clause in the SQL call.
192
 * @param array $values When using prepared statements, this is the value array (optional).
Penny Leach's avatar
Penny Leach committed
193 194 195 196 197 198 199 200 201 202 203
 * @return bool true if a matching record exists, else false.
 * @throws SQLException
 */
function record_exists_select($table, $select='', $values=null) {

    global $CFG;

    if ($select) {
        $select = 'WHERE '.$select;
    }

204
    return record_exists_sql('SELECT * FROM '. db_table_name($table) . ' ' . $select, $values);
Penny Leach's avatar
Penny Leach committed
205 206
}

Penny Leach's avatar
Penny Leach committed
207 208 209
/**
 * Test whether a SQL SELECT statement returns any records.
 *
210
 * This function returns true if at least one record is returned.
Penny Leach's avatar
Penny Leach committed
211 212
 *
 * @param string $sql The SQL statement to be executed. If using $values, placeholder ?s are expected. If not, the string should be escaped correctly.
213
 * @param array $values When using prepared statements, this is the value array (optional).
Penny Leach's avatar
Penny Leach committed
214
 * @return bool true if the SQL executes without errors and returns at least one record.
215
 * @throws SQLException
Penny Leach's avatar
Penny Leach committed
216
 */
217 218 219
function record_exists_sql($sql, $values=null) {
    $rs = get_recordset_sql($sql, $values, 0, 1);
    return $rs->RecordCount() > 0;
Penny Leach's avatar
Penny Leach committed
220 221 222 223 224 225 226 227 228 229 230 231 232
}

/**
 * Count the records in a table where all the given fields match the given values.
 *
 * @param string $table The table to query.
 * @param string $field1 the first field to check (optional).
 * @param string $value1 the value field1 must have (requred if field1 is given, else optional).
 * @param string $field2 the second field to check (optional).
 * @param string $value2 the value field2 must have (requred if field2 is given, else optional).
 * @param string $field3 the third field to check (optional).
 * @param string $value3 the value field3 must have (requred if field3 is given, else optional).
 * @return int The count of records returned from the specified criteria.
233
 * @throws SQLException
Penny Leach's avatar
Penny Leach committed
234 235 236 237
 */
function count_records($table, $field1=null, $value1=null, $field2=null, $value2=null, $field3=null, $value3=null) {
    $select = where_clause_prepared($field1, $field2, $field3);
    $values = where_values_prepared($value1, $value2, $value3);
238
    return count_records_sql('SELECT COUNT(*) FROM '. db_table_name($table) . ' ' . $select, $values);
Penny Leach's avatar
Penny Leach committed
239 240 241 242 243 244 245 246 247 248
}

/**
 * Count the records in a table which match a particular WHERE clause.
 *
 * @param string $table The database table to be checked against.
 * @param string $select A fragment of SQL to be used in a WHERE clause in the SQL call.
 * @param array $values if using a prepared statement with placeholders in $select, pass values here. optional
 * @param string $countitem The count string to be used in the SQL call. Default is COUNT(*).
 * @return int The count of records returned from the specified criteria.
249
 * @throws SQLException
Penny Leach's avatar
Penny Leach committed
250 251 252
 */
function count_records_select($table, $select='', $values=null, $countitem='COUNT(*)') {
    if ($select) {
253
        $select = 'WHERE ' . $select;
Penny Leach's avatar
Penny Leach committed
254
    }
255
    return count_records_sql('SELECT '. $countitem .' FROM '. db_table_name($table) . ' ' . $select, $values);
Penny Leach's avatar
Penny Leach committed
256 257 258 259 260 261 262 263 264 265 266 267
}

/**
 * Get the result of a SQL SELECT COUNT(...) query.
 *
 * Given a query that counts rows, return that count. (In fact,
 * given any query, return the first field of the first record
 * returned. However, this method should only be used for the
 * intended purpose.) If an error occurrs, 0 is returned.
 *
 * @uses $db
 * @param string $sql The SQL string you wish to be executed.
268
 * @param array $values When using prepared statements, this is the value array (optional).
269
 * @return int        The count.
270
 * @throws SQLException
Penny Leach's avatar
Penny Leach committed
271
 */
272 273 274
function count_records_sql($sql, $values=null) {
    $rs = get_recordset_sql($sql, $values);
    return reset($rs->fields);
Penny Leach's avatar
Penny Leach committed
275 276 277 278 279 280 281 282 283
}

/// GENERIC FUNCTIONS TO GET, INSERT, OR UPDATE DATA  ///////////////////////////////////

/**
 * Get a single record as an object
 *
 * @param string $table The table to select from.
 * @param string $field1 the first field to check (optional).
284
 * @param string $value1 the value field1 must have (required if field1 is given, else optional).
Penny Leach's avatar
Penny Leach committed
285
 * @param string $field2 the second field to check (optional).
286
 * @param string $value2 the value field2 must have (required if field2 is given, else optional).
Penny Leach's avatar
Penny Leach committed
287
 * @param string $field3 the third field to check (optional).
288
 * @param string $value3 the value field3 must have (required if field3 is given, else optional).
Penny Leach's avatar
Penny Leach committed
289
 * @return mixed a fieldset object containing the first mathcing record, or false if none found.
290
 * @throws SQLException
Penny Leach's avatar
Penny Leach committed
291 292 293 294
 */
function get_record($table, $field1, $value1, $field2=null, $value2=null, $field3=null, $value3=null, $fields='*') {
    $select = where_clause_prepared($field1, $field2, $field3);
    $values = where_values_prepared($value1, $value2, $value3);
295
    return get_record_sql('SELECT ' . $fields . ' FROM ' . db_table_name($table) . ' ' . $select, $values);
Penny Leach's avatar
Penny Leach committed
296 297 298 299 300
}

/**
 * Get a single record as an object using an SQL statement
 *
301
 * This function is designed to retrieve ONE record. If your query returns more than one record,
302
 * an exception is thrown. If you want more than one record, use get_records_sql_array or get_records_sql_assoc
Penny Leach's avatar
Penny Leach committed
303 304
 *
 * @param string $sql The SQL string you wish to be executed, should normally only return one record.
305
 * @param array $values When using prepared statements, this is the value array (optional).
306
 * @return Found record as object. False if not found
307
 * @throws SQLException
Penny Leach's avatar
Penny Leach committed
308 309
 */
function get_record_sql($sql, $values=null) {
310
    $limitfrom = 0;
311 312 313 314 315 316
    $limitnum  = 0;
    # regex borrowed from htdocs/lib/adodb/adodb-lib.inc.php
    if (!preg_match('/\sLIMIT\s+[0-9]+/i', $sql)) {
        $limitfrom = 0;
        $limitnum  = 2;
    }
Penny Leach's avatar
Penny Leach committed
317 318 319 320 321 322 323 324 325

    if (!$rs = get_recordset_sql($sql, $values, $limitfrom, $limitnum)) {
        return false;
    }

    $recordcount = $rs->RecordCount();

    if ($recordcount == 0) {          // Found no records
        return false;
326 327
    }
    else if ($recordcount == 1) {    // Found one record 
Penny Leach's avatar
Penny Leach committed
328
       return (object)$rs->fields;
329 330
    }
    else {                          // Error: found more than one record
331
        throw new SQLException('get_record_sql found more than one row. If you meant to retrieve more '
332
            . 'than one record, use get_records_*, otherwise check your code or database for inconsistencies');
Penny Leach's avatar
Penny Leach committed
333 334 335 336 337 338 339 340
    }
}

/**
 * Gets one record from a table, as an object
 *
 * @param string $table The database table to be checked against.
 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
341
 * @param array $values When using prepared statements, this is the value array (optional).
Penny Leach's avatar
Penny Leach committed
342
 * @param string $fields A comma separated list of fields to be returned from the chosen table.
343
 * @return object Returns an array of found records (as objects)
344
 * @throws SQLException
Penny Leach's avatar
Penny Leach committed
345 346 347 348 349
 */
function get_record_select($table, $select='', $values=null, $fields='*') {
    if ($select) {
        $select = 'WHERE '. $select;
    }
350
    return get_record_sql('SELECT '. $fields .' FROM ' . db_table_name($table) .' '. $select, $values);
Penny Leach's avatar
Penny Leach committed
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
}

/**
 * Get a number of records as an ADODB RecordSet.
 *
 * Selects records from the table $table.
 *
 * If specified, only records where the field $field has value $value are retured.
 *
 * If specified, the results will be sorted as specified by $sort. This
 * is added to the SQL as "ORDER BY $sort". Example values of $sort
 * mightbe "time ASC" or "time DESC".
 *
 * If $fields is specified, only those fields are returned.
 *
 * This function is internal to datalib, and should NEVER should be called directly
367
 * from general Moodle scripts.  Use get_record, get_records_* etc.
Penny Leach's avatar
Penny Leach committed
368 369 370 371 372 373 374 375
 *
 * If you only want some of the records, specify $limitfrom and $limitnum.
 * The query will skip the first $limitfrom records (according to the sort
 * order) and then return the next $limitnum records. If either of $limitfrom
 * or $limitnum is specified, both must be present.
 *
 * The return value is an ADODB RecordSet object
 * @link http://phplens.com/adodb/reference.functions.adorecordset.html
376
 * if the query succeeds. If an error occurrs, an exception is thrown.
Penny Leach's avatar
Penny Leach committed
377 378 379
 *
 * @param string $table the table to query.
 * @param string $field a field to check (optional).
380
 * @param string $value the value the field must have (required if field1 is given, else optional).
Penny Leach's avatar
Penny Leach committed
381 382 383 384
 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
385
 * @return mixed an ADODB RecordSet object.
386
 * @throws SQLException
Penny Leach's avatar
Penny Leach committed
387 388 389 390
 */
function get_recordset($table, $field='', $value='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
    $values = null;
    if ($field) {
391
        $select = db_quote_identifier($field) . " = ?";
Penny Leach's avatar
Penny Leach committed
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
        $values = array($value);
    } else {
        $select = '';
    }

    return get_recordset_select($table, $select, $values, $sort, $fields, $limitfrom, $limitnum);
}

/**
 * Get a number of records as an ADODB RecordSet.
 *
 * If given, $select is used as the SELECT parameter in the SQL query,
 * otherwise all records from the table are returned.
 *
 * Other arguments and the return type as for @see function get_recordset.
 *
 * @param string $table the table to query.
 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
410
 * @param array $values When using prepared statements, this is the value array (optional).
Penny Leach's avatar
Penny Leach committed
411 412 413 414
 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
415
 * @return mixed an ADODB RecordSet object
416
 * @throws SQLException
Penny Leach's avatar
Penny Leach committed
417 418 419 420 421 422 423
 */
function get_recordset_select($table, $select='', $values=null, $sort='', $fields='*', $limitfrom='', $limitnum='') {
    if ($select) {
        $select = ' WHERE '. $select;
    }

    if ($limitfrom !== '') {
424
        $limit = 'LIMIT ' . intval($limitnum)  . ' OFFSET ' . intval($limitfrom);
Penny Leach's avatar
Penny Leach committed
425 426 427 428 429 430 431 432
    } else {
        $limit = '';
    }

    if ($sort) {
        $sort = ' ORDER BY '. $sort;
    }

433
    return get_recordset_sql('SELECT '. $fields .' FROM '. db_table_name($table) . $select . $sort .' '. $limit, $values);
Penny Leach's avatar
Penny Leach committed
434 435 436 437 438
}

/**
 * Get a number of records as an ADODB RecordSet.  $sql must be a complete SQL query.
 * This function is internal to datalib, and should NEVER should be called directly
439
 * from general Moodle scripts.  Use get_record, get_records_* etc.
Penny Leach's avatar
Penny Leach committed
440 441 442 443 444
 *
 * The return type is as for @see function get_recordset.
 *
 * @uses $db
 * @param string $sql the SQL select query to execute.
445
 * @param array $values When using prepared statements, this is the value array (optional).
Penny Leach's avatar
Penny Leach committed
446 447
 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
448
 * @return mixed an ADODB RecordSet object
449
 * @throws SQLException
Penny Leach's avatar
Penny Leach committed
450 451
 */
function get_recordset_sql($sql, $values=null, $limitfrom=null, $limitnum=null) {
452
    global $db;
Penny Leach's avatar
Penny Leach committed
453

454
    if (!is_a($db, 'ADOConnection')) {
455
        throw new SQLException('Database connection is not available ');
Penny Leach's avatar
Penny Leach committed
456 457
    }

458 459
    $sql = db_quote_table_placeholders($sql);

460 461 462 463 464
    try {
        if ($limitfrom || $limitnum) {
            ///Special case, 0 must be -1 for ADOdb
            $limitfrom = empty($limitfrom) ? -1 : $limitfrom;
            $limitnum  = empty($limitnum) ? -1 : $limitnum;
465
            $rs = $db->SelectLimit($sql, $limitnum, $limitfrom, $values);
Penny Leach's avatar
Penny Leach committed
466
        } else {
467 468 469 470 471 472 473
            $rs = false;
            if (!empty($values) && is_array($values) && count($values) > 0) {
                $stmt = $db->Prepare($sql);
                $rs = $db->Execute($stmt, $values);
            } else {
                $rs = $db->Execute($sql);
            }
Penny Leach's avatar
Penny Leach committed
474 475
        }
    }
476
    catch (ADODB_Exception $e) {
477
        throw new SQLException(create_sql_exception_message($e, $sql, $values));
Penny Leach's avatar
Penny Leach committed
478 479 480 481 482 483
    }
 
   return $rs;
}

/**
484
 * Utility function to turn a result set into an array of records
Penny Leach's avatar
Penny Leach committed
485 486
 *
 * @param object an ADODB RecordSet object.
487
 * @return mixed an array of objects, or false if the RecordSet was empty.
488
 * @throws SQLException
Penny Leach's avatar
Penny Leach committed
489 490
 */
function recordset_to_array($rs) {
491
    if ($rs && $rs->RecordCount() > 0) {
492 493 494 495
        $array = $rs->GetArray();
        foreach ($array as &$a) {
            $a = (object)$a;
        }
496
        return $array;
497 498 499 500 501 502
    }
    else {
        return false;
    }
}

503 504 505 506 507

//
// Generic data retrieval functions - get_records*
//

508 509 510 511 512
/**
 * Utility function to turn a result set into an associative array of records
 * This method turns a result set into a hash of records (keyed by the first
 * field in the result set)
 *
513
 * @param  object $rs An ADODB RecordSet object.
514
 * @return mixed  An array of objects, or false if the RecordSet was empty.
515
 * @throws SQLException
516
 * @access private
517 518
 */
function recordset_to_assoc($rs) {
Penny Leach's avatar
Penny Leach committed
519
    if ($rs && $rs->RecordCount() > 0) {
520 521 522
        // First of all, we are going to get the name of the first column
        // to introduce it back after transforming the recordset to assoc array
        // See http://docs.moodle.org/en/XMLDB_Problems, fetch mode problem.
Penny Leach's avatar
Penny Leach committed
523
        $firstcolumn = $rs->FetchField(0);
524
        // Get the whole associative array
Penny Leach's avatar
Penny Leach committed
525 526
        if ($records = $rs->GetAssoc(true)) {
            foreach ($records as $key => $record) {
527 528
                $record[$firstcolumn->name] = $key;
                $objects[$key] = (object) $record; 
Penny Leach's avatar
Penny Leach committed
529 530 531 532 533 534 535 536 537 538 539
            }
            return $objects;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

/**
540 541
 * Get a number of records as an associative array of objects. (WARNING: this
 * does not return an array, it returns an associative array keyed by the first
542
 * column in the result set. As a result, you may lose some rows! Please use
543
 * {@link get_records_*_array} instead where possible)
Penny Leach's avatar
Penny Leach committed
544 545 546 547 548 549 550 551 552 553 554 555 556 557
 *
 * If the query succeeds and returns at least one record, the
 * return value is an array of objects, one object for each
 * record found. The array key is the value from the first
 * column of the result set. The object associated with that key
 * has a member variable for each column of the results.
 *
 * @param string $table the table to query.
 * @param string $field a field to check (optional).
 * @param string $value the value the field must have (requred if field1 is given, else optional).
 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
558
 * @return mixed an array of objects, or false if no records were found.
559
 * @throws SQLException
Penny Leach's avatar
Penny Leach committed
560
 */
561
function get_records_assoc($table, $field='', $value='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
Penny Leach's avatar
Penny Leach committed
562
    $rs = get_recordset($table, $field, $value, $sort, $fields, $limitfrom, $limitnum);
563
    return recordset_to_assoc($rs);
Penny Leach's avatar
Penny Leach committed
564 565 566 567 568
}

/**
 * Get a number of records as an array of objects.
 *
569 570 571 572 573 574 575 576 577 578 579 580 581 582
 * If the query succeeds and returns at least one record, the
 * return value is an array of objects, one object for each
 * record found. The array key is the value from the first
 * column of the result set. The object associated with that key
 * has a member variable for each column of the results.
 *
 * @param string $table the table to query.
 * @param string $field a field to check (optional).
 * @param string $value the value the field must have (requred if field1 is given, else optional).
 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
 * @return mixed an array of objects, or false if no records were found.
583
 * @throws SQLException
584
 */
585
function get_records_array($table, $field='', $value='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
586 587 588 589 590 591 592
    $rs = get_recordset($table, $field, $value, $sort, $fields, $limitfrom, $limitnum);
    return recordset_to_array($rs);
}

/**
 * Get a number of records as an associative array of objects.
 *
593
 * Return value as for @see function get_records_assoc
Penny Leach's avatar
Penny Leach committed
594 595 596
 *
 * @param string $table the table to query.
 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
597
 * @param array $values When using prepared statements, this is the value array (optional).
Penny Leach's avatar
Penny Leach committed
598 599 600 601
 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
602
 * @return mixed an array of objects, or false if no records were found.
603
 * @throws SQLException
Penny Leach's avatar
Penny Leach committed
604
 */
605
function get_records_select_assoc($table, $select='', $values=null, $sort='', $fields='*', $limitfrom='', $limitnum='') {
Penny Leach's avatar
Penny Leach committed
606
    $rs = get_recordset_select($table, $select, $values, $sort, $fields, $limitfrom, $limitnum);
607
    return recordset_to_assoc($rs);
Penny Leach's avatar
Penny Leach committed
608 609 610 611 612
}

/**
 * Get a number of records as an array of objects.
 *
613
 * Return value as for {@link get_records_array}.
614 615 616
 *
 * @param string $table the table to query.
 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
617
 * @param array $values When using prepared statements, this is the value array (optional).
618 619 620 621 622
 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
 * @return mixed an array of objects, or false if no records were found.
623
 * @throws SQLException
624
 */
625
function get_records_select_array($table, $select='', $values=null, $sort='', $fields='*', $limitfrom='', $limitnum='') {
626 627 628 629 630 631 632
    $rs = get_recordset_select($table, $select, $values, $sort, $fields, $limitfrom, $limitnum);
    return recordset_to_array($rs);
}

/**
 * Get a number of records as an associative array of objects.
 *
633
 * Return value as for @see function get_records_assoc
Penny Leach's avatar
Penny Leach committed
634 635
 *
 * @param string $sql the SQL select query to execute.
636
 * @param array $values When using prepared statements, this is the value array.
Penny Leach's avatar
Penny Leach committed
637 638
 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
639
 * @return mixed an array of objects, or false if no records were found.
640
 * @throws SQLException
Penny Leach's avatar
Penny Leach committed
641
 */
642
function get_records_sql_assoc($sql,$values, $limitfrom='', $limitnum='') {
643 644 645 646 647 648 649
    $rs = get_recordset_sql($sql, $values, $limitfrom, $limitnum);
    return recordset_to_assoc($rs);
}

/**
 * Get a number of records as an array of objects.
 *
650
 * Return value as for {@link get_records_array}
651 652
 *
 * @param string $sql the SQL select query to execute.
653
 * @param array $values When using prepared statements, this is the value array.
654 655 656
 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
 * @return mixed an array of objects, or false if no records were found.
657
 * @throws SQLException
658
 */
659
function get_records_sql_array($sql,$values, $limitfrom='', $limitnum='') {
Penny Leach's avatar
Penny Leach committed
660 661 662 663
    $rs = get_recordset_sql($sql, $values, $limitfrom, $limitnum);
    return recordset_to_array($rs);
}

664 665 666 667 668

//
// Menu related functions - get_records_*_menu
//

Penny Leach's avatar
Penny Leach committed
669 670 671
/**
 * Utility function used by the following 3 methods.
 *
672
 * @param object $rs an ADODB RecordSet object with two columns.
673
 * @return mixed an associative array, or false if an error occurred or the RecordSet was empty.
674
 * @access private
Penny Leach's avatar
Penny Leach committed
675 676 677 678 679 680
 */
function recordset_to_menu($rs) {
    global $CFG;

    if ($rs && $rs->RecordCount() > 0) {
        $keys = array_keys($rs->fields);
681 682 683 684 685 686 687
        $key0 = $keys[0];
        if (isset($keys[1])) {
            $key1 = $keys[1];
        }
        else {
            $key1 = $keys[0];
        }
Penny Leach's avatar
Penny Leach committed
688 689 690 691 692 693 694 695 696
        while (!$rs->EOF) {
            $menu[$rs->fields[$key0]] = $rs->fields[$key1];
            $rs->MoveNext();
        }
        return $menu;
    } else {
        return false;
    }
}
697

Penny Leach's avatar
Penny Leach committed
698 699 700
/**
 * Get the first two columns from a number of records as an associative array.
 *
701
 * Arguments as for {@link get_recordset}.
Penny Leach's avatar
Penny Leach committed
702 703 704 705 706 707 708 709 710 711 712
 *
 * If no errors occur, and at least one records is found, the return value
 * is an associative whose keys come from the first field of each record,
 * and whose values are the corresponding second fields. If no records are found,
 * or an error occurs, false is returned.
 *
 * @param string $table the table to query.
 * @param string $field a field to check (optional).
 * @param string $value the value the field must have (requred if field1 is given, else optional).
 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter).
 * @param string $fields a comma separated list of fields to return (optional, by default all fields are returned).
713
 * @return mixed an associative array, or false if no records were found or an error occurred.
Penny Leach's avatar
Penny Leach committed
714 715 716 717 718 719 720 721 722 723 724 725 726 727
 */
function get_records_menu($table, $field='', $value='', $sort='', $fields='*') {
    $rs = get_recordset($table, $field, $value, $sort, $fields);
    return recordset_to_menu($rs);
}

/**
 * Get the first two columns from a number of records as an associative array.
 *
 * Arguments as for @see function get_recordset_select.
 * Return value as for @see function get_records_menu.
 *
 * @param string $table The database table to be checked against.
 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
728
 * @param array $values When using prepared statements, this is the value array (optional).
Penny Leach's avatar
Penny Leach committed
729 730
 * @param string $sort Sort order (optional) - a valid SQL order parameter
 * @param string $fields A comma separated list of fields to be returned from the chosen table.
731
 * @return mixed an associative array, or false if no records were found or an error occurred.
Penny Leach's avatar
Penny Leach committed
732 733 734 735 736 737 738 739 740 741 742 743 744
 */
function get_records_select_menu($table, $select='', $values=null, $sort='', $fields='*') {
    $rs = get_recordset_select($table, $select, $values, $sort, $fields);
    return recordset_to_menu($rs);
}

/**
 * Get the first two columns from a number of records as an associative array.
 *
 * Arguments as for @see function get_recordset_sql.
 * Return value as for @see function get_records_menu.
 *
 * @param string $sql The SQL string you wish to be executed.
745
 * @param array $values When using prepared statements, this is the value array (optional).
Penny Leach's avatar
Penny Leach committed
746 747 748 749 750 751
 * @return mixed an associative array, or false if no records were found or an error occured.
 */
function get_records_sql_menu($sql,$values=null) {
    $rs = get_recordset_sql($sql,$values);
    return recordset_to_menu($rs);
}
752 753 754 755 756


//
// Field related data access - get_field*
//
Penny Leach's avatar
Penny Leach committed
757 758 759 760 761

/**
 * Get a single value from a table row where all the given fields match the given values.
 *
 * @param string $table the table to query.
762
 * @param string $field the field to return the value of.
Penny Leach's avatar
Penny Leach committed
763 764 765 766 767 768
 * @param string $field1 the first field to check (optional).
 * @param string $value1 the value field1 must have (requred if field1 is given, else optional).
 * @param string $field2 the second field to check (optional).
 * @param string $value2 the value field2 must have (requred if field2 is given, else optional).
 * @param string $field3 the third field to check (optional).
 * @param string $value3 the value field3 must have (requred if field3 is given, else optional).
769
 * @return mixed the specified value
770
 * @throws SQLException
Penny Leach's avatar
Penny Leach committed
771
 */
Martyn Smith's avatar
Martyn Smith committed
772
function get_field($table, $field, $field1=null, $value1=null, $field2=null, $value2=null, $field3=null, $value3=null) {
Penny Leach's avatar
Penny Leach committed
773 774
    $select = where_clause_prepared($field1, $field2, $field3);
    $values = where_values_prepared($value1, $value2, $value3);
775
    
776
    return get_field_sql('SELECT ' . $field . ' FROM ' . db_table_name($table) . ' ' . $select, $values);
Penny Leach's avatar
Penny Leach committed
777 778
}

779 780 781 782
/**
 * Get a single value from a table.
 *
 * @param string $sql an SQL statement expected to return a single value.
783
 * @param array $values When using prepared statements, this is the value array (optional).
784 785 786 787 788 789 790 791 792 793 794 795
 * @return mixed the specified value.
 * @throws SQLException
 */
function get_field_sql($sql, $values=null) {
    $rs = get_recordset_sql($sql, $values);
    if ($rs && $rs->RecordCount() == 1) {
        return reset($rs->fields);
    } else {
        return false;
    }
}

796 797 798 799 800

//
// Column related data access - get_column*
//

801 802 803 804
/**
 * Get a single column from a table where all the given fields match the given values.
 *
 * @param string $table the table to query.
805
 * @param string $field the field to return the value of.
806 807 808 809 810 811 812 813 814
 * @param string $field1 the first field to check (optional).
 * @param string $value1 the value field1 must have (requred if field1 is given, else optional).
 * @param string $field2 the second field to check (optional).
 * @param string $value2 the value field2 must have (requred if field2 is given, else optional).
 * @param string $field3 the third field to check (optional).
 * @param string $value3 the value field3 must have (requred if field3 is given, else optional).
 * @return mixed the specified value
 * @throws SQLException
 */
815
function get_column($table, $field, $field1=null, $value1=null, $field2=null, $value2=null, $field3=null, $value3=null) {
816 817 818
    $select = where_clause_prepared($field1, $field2, $field3);
    $values = where_values_prepared($value1, $value2, $value3);
    
819
    return get_column_sql('SELECT ' . $field . ' FROM ' . db_table_name($table) . ' ' . $select, $values);
820 821 822 823 824 825
}

/**
 * Get a single column from a table.
 *
 * @param string $sql an SQL statement expected to return a single value.
826
 * @param array $values When using prepared statements, this is the value array (optional).
827 828 829 830 831 832
 * @return mixed the specified value.
 * @throws SQLException
 */
function get_column_sql($sql, $values=null) {
    global $db;

833 834
    $sql = db_quote_table_placeholders($sql);

835 836 837 838 839 840
    try {
        return $db->GetCol($sql, $values);
    }
    catch (ADODB_Exception $e) {
        throw new SQLException(create_sql_exception_message($e, $sql, $values));
    }
841 842
}

843 844 845 846 847

//
// Field related data modification - set_field*
//

Penny Leach's avatar
Penny Leach committed
848 849 850 851 852 853 854 855 856 857 858 859 860 861
/**
 * Set a single field in every table row where all the given fields match the given values.
 *
 * @uses $db
 * @param string $table The database table to be checked against.
 * @param string $newfield the field to set.
 * @param string $newvalue the value to set the field to.
 * @param string $field1 the first field to check (optional).
 * @param string $value1 the value field1 must have (requred if field1 is given, else optional).
 * @param string $field2 the second field to check (optional).
 * @param string $value2 the value field2 must have (requred if field2 is given, else optional).
 * @param string $field3 the third field to check (optional).
 * @param string $value3 the value field3 must have (requred if field3 is given, else optional).
 * @return mixed An ADODB RecordSet object with the results from the SQL call or false.
862
 * @throws SQLException
Penny Leach's avatar
Penny Leach committed
863
 */
864
function set_field($table, $newfield, $newvalue, $field1=null, $value1=null, $field2=null, $value2=null, $field3=null, $value3=null) {
865
    global $db;
Penny Leach's avatar
Penny Leach committed
866 867

    $select = where_clause_prepared($field1, $field2, $field3);
Penny Leach's avatar
Penny Leach committed
868 869 870 871
    $values = where_values_prepared($value1, $value2, $value3);

    return set_field_select($table, $newfield, $newvalue, $select, $values);
}
Penny Leach's avatar
Penny Leach committed
872

Penny Leach's avatar
Penny Leach committed
873 874 875
function set_field_select($table, $newfield, $newvalue, $select, $values) {
    global $db;

876
    // @todo Catalyst IT Ltd
877
    if (!empty($select) && !preg_match('/^\s*where/i', $select)) {
878 879 880
        $select = ' WHERE ' . $select;
    }

881 882
    $select = db_quote_table_placeholders($select);

Penny Leach's avatar
Penny Leach committed
883
    $values = array_merge(array($newvalue), $values);
884
    $sql = 'UPDATE '. db_table_name($table) .' SET '. db_quote_identifier($newfield)  .' = ? ' . $select;
885
    try {
886
        $stmt = $db->Prepare($sql);
887 888 889
        return $db->Execute($stmt, $values);
    }
    catch (ADODB_Exception $e) {
890
        throw new SQLException(create_sql_exception_message($e, $sql, $values));
891
    }
Penny Leach's avatar
Penny Leach committed
892 893
}

894 895 896 897 898

//
// Delete based functions - delete_records*
//

Penny Leach's avatar
Penny Leach committed
899 900 901 902 903 904 905 906 907 908 909 910
/**
 * Delete the records from a table where all the given fields match the given values.
 *
 * @uses $db
 * @param string $table the table to delete from.
 * @param string $field1 the first field to check (optional).
 * @param string $value1 the value field1 must have (requred if field1 is given, else optional).
 * @param string $field2 the second field to check (optional).
 * @param string $value2 the value field2 must have (requred if field2 is given, else optional).
 * @param string $field3 the third field to check (optional).
 * @param string $value3 the value field3 must have (requred if field3 is given, else optional).
 * @return mixed An ADODB RecordSet object with the results from the SQL call or false.
911
 * @throws SQLException
Penny Leach's avatar
Penny Leach committed
912 913
 */
function delete_records($table, $field1=null, $value1=null, $field2=null, $value2=null, $field3=null, $value3=null) {
914
    global $db;
Penny Leach's avatar
Penny Leach committed
915 916 917

    $select = where_clause_prepared($field1, $field2, $field3);
    $values = where_values_prepared($value1, $value2, $value3);
918

919
    $sql = 'DELETE FROM '. db_table_name($table) . ' ' . $select;
920
    try {
921
        $stmt = $db->Prepare($sql);
922 923 924
        return $db->Execute($stmt,$values);
    }
    catch (ADODB_Exception $e) {
925
        throw new SQLException(create_sql_exception_message($e, $sql, $values));
926
    }
Penny Leach's avatar
Penny Leach committed
927 928 929 930 931 932 933 934
}

/**
 * Delete one or more records from a table
 *
 * @uses $db
 * @param string $table The database table to be checked against.
 * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
935
 * @param array $values When using prepared statements, this is the value array (optional).
Penny Leach's avatar
Penny Leach committed
936
 * @return object A PHP standard object with the results from the SQL call.
937
 * @throws SQLException
Penny Leach's avatar
Penny Leach committed
938 939 940 941 942
 */
function delete_records_select($table, $select='',$values=null) {
    if ($select) {
        $select = 'WHERE '.$select;
    }
943
    return delete_records_sql('DELETE FROM '. db_table_name($table) .' '. $select, $values);
Penny Leach's avatar
Penny Leach committed
944 945
}

946 947 948 949 950
/**
 * @todo <nigel> This function does nothing delete specific. The functionality 
 * it has with the $values parameter should be merged with the execute_sql 
 * function
 */
Penny Leach's avatar
Penny Leach committed
951 952
function delete_records_sql($sql, $values=null) {
    global $db;
Penny Leach's avatar
Penny Leach committed
953

954 955
    $sql = db_quote_table_placeholders($sql);

956 957 958
    try {
        $result = false;
        if (!empty($values) && is_array($values) && count($values) > 0) {
Penny Leach's avatar
Penny Leach committed
959 960
            $stmt = $db->Prepare($sql);
            $result = $db->Execute($stmt, $values);
961
        } else {
Penny Leach's avatar
Penny Leach committed
962
            $result = $db->Execute($sql);
963 964 965
        }
    }
    catch (ADODB_Exception $e) {
966
        throw new SQLException(create_sql_exception_message($e, $sql, $values));
Penny Leach's avatar
Penny Leach committed
967 968 969 970 971 972 973 974 975 976 977 978 979 980
    }
    return $result;
}

/**
 * Insert a record into a table and return the "id" field if required
 *
 * If the return ID isn't required, then this just reports success as true/false.
 * $dataobject is an object containing needed data
 *
 * @uses $db
 * @param string $table The database table to be checked against.
 * @param array $dataobject A data object with values for one or more fields in the record
 * @param string $primarykey The primary key of the table we are inserting into (almost always "id")
981
 * @param bool $returnpk Should the id of the newly created record entry be returned? If this option is not requested then true/false is returned.
982
 * @throws SQLException
Penny Leach's avatar
Penny Leach committed
983 984
 */
function insert_record($table, $dataobject, $primarykey=false, $returnpk=false) {
985 986 987 988 989 990 991 992
    // $INSERTRECORD_NOCACHE is yet another work around of dmllib/adodb's ineptitude.
    // It's all nice to cache the table columns lookup, but what if the table 
    // columns change over the life of the page load? This happens when an 
    // upgrade is running. All of a sudden, the table_column cache is out of 
    // date and we can't insert new data properly.
    // Temporary solution: set INSERTRECORD_NOCACHE to true before your calls 
    // that need a new lookup, and unset it afterwards
    global $db, $INSERTRECORD_NOCACHE;
Penny Leach's avatar
Penny Leach committed
993 994 995
    static $table_columns;
    
    // Determine all the fields in the table
996
    if (empty($INSERTRECORD_NOCACHE) && is_array($table_columns) && array_key_exists($table, $table_columns)) {
Penny Leach's avatar
Penny Leach committed
997
        $columns = $table_columns[$table];
998 999
    }
    else {
1000
        if (!$columns = $db->MetaColumns(get_config('dbprefix') . $table)) {
1001
            throw new SQLException('Table "' . get_config('dbprefix') . $table . '" does not appear to exist');
Penny Leach's avatar
Penny Leach committed
1002 1003 1004 1005 1006 1007
        }
        $table_columns[$table] = $columns;
    }
    
    if (!empty($primarykey)) {
        unset($dataobject->{$primarykey});
1008
        if (!empty($returnpk) && is_postgres()) {
1009
            $pksql = "SELECT NEXTVAL('" . get_config('dbprefix') . "{$table}_{$primarykey}_seq')";
Penny Leach's avatar
Penny Leach committed
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
            if ($nextval = (int)get_field_sql($pksql)) {
                $setfromseq = true;
                $dataobject->{$primarykey} = $nextval;
            }
        }
    }

    $data = (array)$dataobject;

  // Pull out data matching these fields
1020
    $ddd = array();
Penny Leach's avatar
Penny Leach committed
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
    foreach ($columns as $column) {
        if (isset($data[$column->name])) {
            if ($column->name == $primarykey && empty($setfromseq)) {
                continue;
            }
            $ddd[$column->name] = $data[$column->name];
        }
    }

    // Construct SQL queries
    $numddd = count($ddd);
    $count = 0;
1033
    $insertSQL = 'INSERT INTO '. db_table_name($table) .' (';
Penny Leach's avatar
Penny Leach committed
1034 1035 1036 1037
    $fields = '';
    $values = '';
    foreach ($ddd as $key => $value) {
        $count++;
1038
        $fields .= '"' . $key . '"';
Penny Leach's avatar
Penny Leach committed
1039 1040 1041 1042 1043 1044 1045 1046
        $values .= '?';
        if ($count < $numddd) {
            $fields .= ', ';
            $values .= ', ';
        }
    }
    $insertSQL .= $fields.') VALUES ('.$values.')';

1047 1048 1049 1050 1051 1052
    // Run the SQL statement
    try {
        $stmt = $db->Prepare($insertSQL);
        $rs = $db->Execute($stmt,$ddd);
    }
    catch (ADODB_Exception $e) {
1053
        throw new SQLException(create_sql_exception_message($e, $insertSQL, $ddd));
Penny Leach's avatar
Penny Leach committed
1054 1055
    }

1056
    // If a return ID is not needed then just return true now
Penny Leach's avatar
Penny Leach committed
1057 1058 1059 1060
    if (empty($returnpk)) {
        return true;
    }

1061 1062
    // We already know the record PK if it's been passed explicitly,
    // or if we've retrieved it from a sequence (Postgres).
Penny Leach's avatar
Penny Leach committed
1063 1064 1065 1066
    if (!empty($dataobject->{$primarykey})) {
        return $dataobject->{$primarykey};
    }

1067 1068 1069
    // This only gets triggered with non-Postgres databases
    // however we have some postgres fallback in case we failed 
    // to find the sequence.
Penny Leach's avatar
Penny Leach committed
1070 1071 1072 1073
    $id = $db->Insert_ID();  

    if (is_postgres()) {
        // try to get the primary key based on id
1074
        try {
1075
            $oidsql = 'SELECT ' . $primarykey . ' FROM '. db_table_name($table) . ' WHERE oid = ' . $id;
1076 1077 1078 1079
            $rs = $db->Execute($oidsql);
            if ($rs->RecordCount() == 1) {
                return (integer)$rs->fields[0];
            }