3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
20 * Native pgsql class representing moodle database interface.
23 * @subpackage dml_driver
24 * @copyright 2008 Petr Skoda (http://skodak.org)
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') || die();
30 require_once($CFG->libdir.'/dml/moodle_database.php');
31 require_once($CFG->libdir.'/dml/pgsql_native_moodle_recordset.php');
32 require_once($CFG->libdir.'/dml/pgsql_native_moodle_temptables.php');
35 * Native pgsql class representing moodle database interface.
38 * @subpackage dml_driver
39 * @copyright 2008 Petr Skoda (http://skodak.org)
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42 class pgsql_native_moodle_database extends moodle_database {
44 protected $pgsql = null;
45 protected $bytea_oid = null;
47 protected $last_error_reporting; // To handle pgsql driver default verbosity
50 * Detects if all needed PHP stuff installed.
51 * Note: can be used before connect()
52 * @return mixed true if ok, string if something
54 public function driver_installed() {
55 if (!extension_loaded('pgsql')) {
56 return get_string('pgsqlextensionisnotpresentinphp', 'install');
62 * Returns database family type - describes SQL dialect
63 * Note: can be used before connect()
64 * @return string db family name (mysql, postgres, mssql, oracle, etc.)
66 public function get_dbfamily() {
71 * Returns more specific database driver type
72 * Note: can be used before connect()
73 * @return string db type mysqli, pgsql, oci, mssql, sqlsrv
75 protected function get_dbtype() {
80 * Returns general database library name
81 * Note: can be used before connect()
82 * @return string db type pdo, native
84 protected function get_dblibrary() {
89 * Returns localised database type name
90 * Note: can be used before connect()
93 public function get_name() {
94 return get_string('nativepgsql', 'install');
98 * Returns localised database configuration help.
99 * Note: can be used before connect()
102 public function get_configuration_help() {
103 return get_string('nativepgsqlhelp', 'install');
107 * Returns localised database description
108 * Note: can be used before connect()
111 public function get_configuration_hints() {
112 return get_string('databasesettingssub_postgres7', 'install');
117 * Must be called before other methods.
118 * @param string $dbhost The database host.
119 * @param string $dbuser The database username.
120 * @param string $dbpass The database username's password.
121 * @param string $dbname The name of the database being connected to.
122 * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
123 * @param array $dboptions driver specific options
125 * @throws dml_connection_exception if error
127 public function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null) {
128 if ($prefix == '' and !$this->external) {
129 //Enforce prefixes for everybody but mysql
130 throw new dml_exception('prefixcannotbeempty', $this->get_dbfamily());
133 $driverstatus = $this->driver_installed();
135 if ($driverstatus !== true) {
136 throw new dml_exception('dbdriverproblem', $driverstatus);
139 $this->store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions);
141 $pass = addcslashes($this->dbpass, "'\\");
143 // Unix socket connections should have lower overhead
144 if (!empty($this->dboptions['dbsocket']) and ($this->dbhost === 'localhost' or $this->dbhost === '127.0.0.1')) {
145 $connection = "user='$this->dbuser' password='$pass' dbname='$this->dbname'";
146 if (strpos($this->dboptions['dbsocket'], '/') !== false) {
147 $connection = $connection." host='".$this->dboptions['dbsocket']."'";
150 $this->dboptions['dbsocket'] = '';
151 if (empty($this->dbname)) {
152 // probably old style socket connection - do not add port
154 } else if (empty($this->dboptions['dbport'])) {
155 $port = "port ='5432'";
157 $port = "port ='".$this->dboptions['dbport']."'";
159 $connection = "host='$this->dbhost' $port user='$this->dbuser' password='$pass' dbname='$this->dbname'";
163 if (empty($this->dboptions['dbpersist'])) {
164 $this->pgsql = pg_connect($connection, PGSQL_CONNECT_FORCE_NEW);
166 $this->pgsql = pg_pconnect($connection, PGSQL_CONNECT_FORCE_NEW);
168 $dberr = ob_get_contents();
171 $status = pg_connection_status($this->pgsql);
173 if ($status === false or $status === PGSQL_CONNECTION_BAD) {
175 throw new dml_connection_exception($dberr);
178 $this->query_start("--pg_set_client_encoding()", null, SQL_QUERY_AUX);
179 pg_set_client_encoding($this->pgsql, 'utf8');
180 $this->query_end(true);
182 // find out the bytea oid
183 $sql = "SELECT oid FROM pg_type WHERE typname = 'bytea'";
184 $this->query_start($sql, null, SQL_QUERY_AUX);
185 $result = pg_query($this->pgsql, $sql);
186 $this->query_end($result);
188 $this->bytea_oid = pg_fetch_result($result, 0, 0);
189 pg_free_result($result);
190 if ($this->bytea_oid === false) {
192 throw new dml_connection_exception('Can not read bytea type.');
195 // Connection stabilised and configured, going to instantiate the temptables controller
196 $this->temptables = new pgsql_native_moodle_temptables($this);
202 * Close database connection and release all resources
203 * and memory (especially circular memory references).
204 * Do NOT use connect() again, create a new instance if needed.
206 public function dispose() {
207 parent::dispose(); // Call parent dispose to write/close session and other common stuff before closing connection
209 pg_close($this->pgsql);
216 * Called before each db query.
218 * @param array array of parameters
219 * @param int $type type of query
220 * @param mixed $extrainfo driver specific extra information
223 protected function query_start($sql, array $params=null, $type, $extrainfo=null) {
224 parent::query_start($sql, $params, $type, $extrainfo);
225 // pgsql driver tents to send debug to output, we do not need that ;-)
226 $this->last_error_reporting = error_reporting(0);
230 * Called immediately after each db query.
231 * @param mixed db specific result
234 protected function query_end($result) {
235 // reset original debug level
236 error_reporting($this->last_error_reporting);
237 parent::query_end($result);
241 * Returns database server info array
242 * @return array Array containing 'description' and 'version' info
244 public function get_server_info() {
247 $this->query_start("--pg_version()", null, SQL_QUERY_AUX);
248 $info = pg_version($this->pgsql);
249 $this->query_end(true);
251 return array('description'=>$info['server'], 'version'=>$info['server']);
254 protected function is_min_version($version) {
255 $server = $this->get_server_info();
256 $server = $server['version'];
257 return version_compare($server, $version, '>=');
261 * Returns supported query parameter types
262 * @return int bitmask of accepted SQL_PARAMS_*
264 protected function allowed_param_types() {
265 return SQL_PARAMS_DOLLAR;
269 * Returns last error reported by database engine.
270 * @return string error message
272 public function get_last_error() {
273 return pg_last_error($this->pgsql);
277 * Return tables in database WITHOUT current prefix.
278 * @param bool $usecache if true, returns list of cached tables.
279 * @return array of table names in lowercase and without prefix
281 public function get_tables($usecache=true) {
282 if ($usecache and $this->tables !== null) {
283 return $this->tables;
285 $this->tables = array();
286 $prefix = str_replace('_', '|_', $this->prefix);
287 // Get them from information_schema instead of catalog as far as
288 // we want to get only own session temp objects (catalog returns all)
289 $sql = "SELECT table_name
290 FROM information_schema.tables
291 WHERE table_name LIKE '$prefix%' ESCAPE '|'
292 AND table_type IN ('BASE TABLE', 'LOCAL TEMPORARY')";
293 $this->query_start($sql, null, SQL_QUERY_AUX);
294 $result = pg_query($this->pgsql, $sql);
295 $this->query_end($result);
298 while ($row = pg_fetch_row($result)) {
299 $tablename = reset($row);
300 if (strpos($tablename, $this->prefix) !== 0) {
303 $tablename = substr($tablename, strlen($this->prefix));
304 $this->tables[$tablename] = $tablename;
306 pg_free_result($result);
308 return $this->tables;
312 * Return table indexes - everything lowercased.
313 * @param string $table The table we want to get indexes from.
314 * @return array of arrays
316 public function get_indexes($table) {
318 $tablename = $this->prefix.$table;
321 FROM pg_catalog.pg_indexes
322 WHERE tablename = '$tablename'";
324 $this->query_start($sql, null, SQL_QUERY_AUX);
325 $result = pg_query($this->pgsql, $sql);
326 $this->query_end($result);
329 while ($row = pg_fetch_assoc($result)) {
330 if (!preg_match('/CREATE (|UNIQUE )INDEX ([^\s]+) ON '.$tablename.' USING ([^\s]+) \(([^\)]+)\)/i', $row['indexdef'], $matches)) {
333 if ($matches[4] === 'id') {
336 $columns = explode(',', $matches[4]);
337 $columns = array_map(array($this, 'trim_quotes'), $columns);
338 $indexes[$row['indexname']] = array('unique'=>!empty($matches[1]),
339 'columns'=>$columns);
341 pg_free_result($result);
347 * Returns detailed information about columns in table. This information is cached internally.
348 * @param string $table name
349 * @param bool $usecache
350 * @return array array of database_column_info objects indexed with column names
352 public function get_columns($table, $usecache=true) {
353 if ($usecache and isset($this->columns[$table])) {
354 return $this->columns[$table];
357 $this->columns[$table] = array();
359 $tablename = $this->prefix.$table;
361 $sql = "SELECT a.attnum, a.attname AS field, t.typname AS type, a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, d.adsrc
362 FROM pg_catalog.pg_class c
363 JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid
364 JOIN pg_catalog.pg_type t ON t.oid = a.atttypid
365 LEFT JOIN pg_catalog.pg_attrdef d ON (d.adrelid = c.oid AND d.adnum = a.attnum)
366 WHERE relkind = 'r' AND c.relname = '$tablename' AND c.reltype > 0 AND a.attnum > 0
369 $this->query_start($sql, null, SQL_QUERY_AUX);
370 $result = pg_query($this->pgsql, $sql);
371 $this->query_end($result);
376 while ($rawcolumn = pg_fetch_object($result)) {
378 $info = new stdClass();
379 $info->name = $rawcolumn->field;
382 if ($rawcolumn->type === 'varchar') {
383 $info->type = 'varchar';
384 $info->meta_type = 'C';
385 $info->max_length = $rawcolumn->atttypmod - 4;
387 $info->not_null = ($rawcolumn->attnotnull === 't');
388 $info->has_default = ($rawcolumn->atthasdef === 't');
389 if ($info->has_default) {
390 $parts = explode('::', $rawcolumn->adsrc);
391 if (count($parts) > 1) {
392 $info->default_value = reset($parts);
393 $info->default_value = trim($info->default_value, "'");
395 $info->default_value = $rawcolumn->adsrc;
398 $info->default_value = null;
400 $info->primary_key = false;
401 $info->binary = false;
402 $info->unsigned = null;
403 $info->auto_increment= false;
404 $info->unique = null;
406 } else if (preg_match('/int(\d)/i', $rawcolumn->type, $matches)) {
408 if (strpos($rawcolumn->adsrc, 'nextval') === 0) {
409 $info->primary_key = true;
410 $info->meta_type = 'R';
411 $info->unique = true;
412 $info->auto_increment= true;
413 $info->has_default = false;
415 $info->primary_key = false;
416 $info->meta_type = 'I';
417 $info->unique = null;
418 $info->auto_increment= false;
419 $info->has_default = ($rawcolumn->atthasdef === 't');
421 $info->max_length = $matches[1];
423 $info->not_null = ($rawcolumn->attnotnull === 't');
424 if ($info->has_default) {
425 $info->default_value = trim($rawcolumn->adsrc, '()');
427 $info->default_value = null;
429 $info->binary = false;
430 $info->unsigned = false;
432 } else if ($rawcolumn->type === 'numeric') {
433 $info->type = $rawcolumn->type;
434 $info->meta_type = 'N';
435 $info->primary_key = false;
436 $info->binary = false;
437 $info->unsigned = null;
438 $info->auto_increment= false;
439 $info->unique = null;
440 $info->not_null = ($rawcolumn->attnotnull === 't');
441 $info->has_default = ($rawcolumn->atthasdef === 't');
442 if ($info->has_default) {
443 $info->default_value = trim($rawcolumn->adsrc, '()');
445 $info->default_value = null;
447 $info->max_length = $rawcolumn->atttypmod >> 16;
448 $info->scale = ($rawcolumn->atttypmod & 0xFFFF) - 4;
450 } else if (preg_match('/float(\d)/i', $rawcolumn->type, $matches)) {
451 $info->type = 'float';
452 $info->meta_type = 'N';
453 $info->primary_key = false;
454 $info->binary = false;
455 $info->unsigned = null;
456 $info->auto_increment= false;
457 $info->unique = null;
458 $info->not_null = ($rawcolumn->attnotnull === 't');
459 $info->has_default = ($rawcolumn->atthasdef === 't');
460 if ($info->has_default) {
461 $info->default_value = trim($rawcolumn->adsrc, '()');
463 $info->default_value = null;
465 // just guess expected number of deciaml places :-(
466 if ($matches[1] == 8) {
468 $info->max_length = 8;
472 $info->max_length = 4;
476 } else if ($rawcolumn->type === 'text') {
477 $info->type = $rawcolumn->type;
478 $info->meta_type = 'X';
479 $info->max_length = -1;
481 $info->not_null = ($rawcolumn->attnotnull === 't');
482 $info->has_default = ($rawcolumn->atthasdef === 't');
483 if ($info->has_default) {
484 $parts = explode('::', $rawcolumn->adsrc);
485 if (count($parts) > 1) {
486 $info->default_value = reset($parts);
487 $info->default_value = trim($info->default_value, "'");
489 $info->default_value = $rawcolumn->adsrc;
492 $info->default_value = null;
494 $info->primary_key = false;
495 $info->binary = false;
496 $info->unsigned = null;
497 $info->auto_increment= false;
498 $info->unique = null;
500 } else if ($rawcolumn->type === 'bytea') {
501 $info->type = $rawcolumn->type;
502 $info->meta_type = 'B';
503 $info->max_length = -1;
505 $info->not_null = ($rawcolumn->attnotnull === 't');
506 $info->has_default = false;
507 $info->default_value = null;
508 $info->primary_key = false;
509 $info->binary = true;
510 $info->unsigned = null;
511 $info->auto_increment= false;
512 $info->unique = null;
516 $this->columns[$table][$info->name] = new database_column_info($info);
519 pg_free_result($result);
521 return $this->columns[$table];
525 * Normalise values based in RDBMS dependencies (booleans, LOBs...)
527 * @param database_column_info $column column metadata corresponding with the value we are going to normalise
528 * @param mixed $value value we are going to normalise
529 * @return mixed the normalised value
531 protected function normalise_value($column, $value) {
532 if (is_bool($value)) { // Always, convert boolean to int
533 $value = (int)$value;
535 } else if ($column->meta_type === 'B') { // BLOB detected, we return 'blob' array instead of raw value to allow
536 if (!is_null($value)) { // binding/executing code later to know about its nature
537 $value = array('blob' => $value);
540 } else if ($value === '') {
541 if ($column->meta_type === 'I' or $column->meta_type === 'F' or $column->meta_type === 'N') {
542 $value = 0; // prevent '' problems in numeric fields
549 * Is db in unicode mode?
552 public function setup_is_unicodedb() {
553 /// Get PostgreSQL server_encoding value
554 $sql = "SHOW server_encoding";
555 $this->query_start($sql, null, SQL_QUERY_AUX);
556 $result = pg_query($this->pgsql, $sql);
557 $this->query_end($result);
562 $rawcolumn = pg_fetch_object($result);
563 $encoding = $rawcolumn->server_encoding;
564 pg_free_result($result);
566 return (strtoupper($encoding) == 'UNICODE' || strtoupper($encoding) == 'UTF8');
570 * Do NOT use in code, to be used by database_manager only!
571 * @param string $sql query
573 * @throws dml_exception A DML specific exception is thrown for any errors.
575 public function change_database_structure($sql) {
576 $this->reset_caches();
578 $this->query_start($sql, null, SQL_QUERY_STRUCTURE);
579 $result = pg_query($this->pgsql, $sql);
580 $this->query_end($result);
582 pg_free_result($result);
587 * Execute general sql query. Should be used only when no other method suitable.
588 * Do NOT use this to make changes in db structure, use database_manager methods instead!
589 * @param string $sql query
590 * @param array $params query parameters
592 * @throws dml_exception A DML specific exception is thrown for any errors.
594 public function execute($sql, array $params=null) {
595 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
597 if (strpos($sql, ';') !== false) {
598 throw new coding_exception('moodle_database::execute() Multiple sql statements found or bound parameters not used properly in query!');
601 $this->query_start($sql, $params, SQL_QUERY_UPDATE);
602 $result = pg_query_params($this->pgsql, $sql, $params);
603 $this->query_end($result);
605 pg_free_result($result);
610 * Get a number of records as a moodle_recordset using a SQL statement.
612 * Since this method is a little less readable, use of it should be restricted to
613 * code where it's possible there might be large datasets being returned. For known
614 * small datasets use get_records_sql - it leads to simpler code.
616 * The return type is like:
617 * @see function get_recordset.
619 * @param string $sql the SQL select query to execute.
620 * @param array $params array of sql parameters
621 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
622 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
623 * @return moodle_recordset instance
624 * @throws dml_exception A DML specific exception is thrown for any errors.
626 public function get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
627 $limitfrom = (int)$limitfrom;
628 $limitnum = (int)$limitnum;
629 $limitfrom = ($limitfrom < 0) ? 0 : $limitfrom;
630 $limitnum = ($limitnum < 0) ? 0 : $limitnum;
631 if ($limitfrom or $limitnum) {
634 } else if (PHP_INT_MAX - $limitnum < $limitfrom) {
635 // this is a workaround for weird max int problem
638 $sql .= " LIMIT $limitnum OFFSET $limitfrom";
641 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
643 $this->query_start($sql, $params, SQL_QUERY_SELECT);
644 $result = pg_query_params($this->pgsql, $sql, $params);
645 $this->query_end($result);
647 return $this->create_recordset($result);
650 protected function create_recordset($result) {
651 return new pgsql_native_moodle_recordset($result, $this->bytea_oid);
655 * Get a number of records as an array of objects using a SQL statement.
657 * Return value is like:
658 * @see function get_records.
660 * @param string $sql the SQL select query to execute. The first column of this SELECT statement
661 * must be a unique value (usually the 'id' field), as it will be used as the key of the
663 * @param array $params array of sql parameters
664 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
665 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
666 * @return array of objects, or empty array if no records were found
667 * @throws dml_exception A DML specific exception is thrown for any errors.
669 public function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
670 $limitfrom = (int)$limitfrom;
671 $limitnum = (int)$limitnum;
672 $limitfrom = ($limitfrom < 0) ? 0 : $limitfrom;
673 $limitnum = ($limitnum < 0) ? 0 : $limitnum;
674 if ($limitfrom or $limitnum) {
677 } else if (PHP_INT_MAX - $limitnum < $limitfrom) {
678 // this is a workaround for weird max int problem
681 $sql .= " LIMIT $limitnum OFFSET $limitfrom";
684 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
685 $this->query_start($sql, $params, SQL_QUERY_SELECT);
686 $result = pg_query_params($this->pgsql, $sql, $params);
687 $this->query_end($result);
689 // find out if there are any blobs
690 $numrows = pg_num_fields($result);
692 for($i=0; $i<$numrows; $i++) {
693 $type_oid = pg_field_type_oid($result, $i);
694 if ($type_oid == $this->bytea_oid) {
695 $blobs[] = pg_field_name($result, $i);
699 $rows = pg_fetch_all($result);
700 pg_free_result($result);
704 foreach ($rows as $row) {
707 foreach ($blobs as $blob) {
708 // note: in PostgreSQL 9.0 the returned blobs are hexencoded by default - see http://www.postgresql.org/docs/9.0/static/runtime-config-client.html#GUC-BYTEA-OUTPUT
709 $row[$blob] = $row[$blob] !== null ? pg_unescape_bytea($row[$blob]) : null;
712 if (isset($return[$id])) {
713 $colname = key($row);
714 debugging("Did you remember to make the first column something unique in your call to get_records? Duplicate value '$id' found in column '$colname'.", DEBUG_DEVELOPER);
716 $return[$id] = (object)$row;
724 * Selects records and return values (first field) as an array using a SQL statement.
726 * @param string $sql The SQL query
727 * @param array $params array of sql parameters
728 * @return array of values
729 * @throws dml_exception A DML specific exception is thrown for any errors.
731 public function get_fieldset_sql($sql, array $params=null) {
732 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
734 $this->query_start($sql, $params, SQL_QUERY_SELECT);
735 $result = pg_query_params($this->pgsql, $sql, $params);
736 $this->query_end($result);
738 $return = pg_fetch_all_columns($result, 0);
739 pg_free_result($result);
745 * Insert new record into database, as fast as possible, no safety checks, lobs not supported.
746 * @param string $table name
747 * @param mixed $params data record as object or array
748 * @param bool $returnit return it of inserted record
749 * @param bool $bulk true means repeated inserts expected
750 * @param bool $customsequence true if 'id' included in $params, disables $returnid
751 * @return bool|int true or new id
752 * @throws dml_exception A DML specific exception is thrown for any errors.
754 public function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false) {
755 if (!is_array($params)) {
756 $params = (array)$params;
761 if ($customsequence) {
762 if (!isset($params['id'])) {
763 throw new coding_exception('moodle_database::insert_record_raw() id field must be specified if custom sequences used.');
768 $returning = "RETURNING id";
769 unset($params['id']);
771 unset($params['id']);
775 if (empty($params)) {
776 throw new coding_exception('moodle_database::insert_record_raw() no fields found.');
779 $fields = implode(',', array_keys($params));
781 $count = count($params);
782 for ($i=1; $i<=$count; $i++) {
785 $values = implode(',', $values);
787 $sql = "INSERT INTO {$this->prefix}$table ($fields) VALUES($values) $returning";
788 $this->query_start($sql, $params, SQL_QUERY_INSERT);
789 $result = pg_query_params($this->pgsql, $sql, $params);
790 $this->query_end($result);
792 if ($returning !== "") {
793 $row = pg_fetch_assoc($result);
794 $params['id'] = reset($row);
796 pg_free_result($result);
802 return (int)$params['id'];
806 * Insert a record into a table and return the "id" field if required.
808 * Some conversions and safety checks are carried out. Lobs are supported.
809 * If the return ID isn't required, then this just reports success as true/false.
810 * $data is an object containing needed data
811 * @param string $table The database table to be inserted into
812 * @param object $data A data object with values for one or more fields in the record
813 * @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.
814 * @return bool|int true or new id
815 * @throws dml_exception A DML specific exception is thrown for any errors.
817 public function insert_record($table, $dataobject, $returnid=true, $bulk=false) {
818 $dataobject = (array)$dataobject;
820 $columns = $this->get_columns($table);
824 foreach ($dataobject as $field=>$value) {
825 if ($field === 'id') {
828 if (!isset($columns[$field])) {
831 $column = $columns[$field];
832 $normalised_value = $this->normalise_value($column, $value);
833 if (is_array($normalised_value) && array_key_exists('blob', $normalised_value)) {
834 $cleaned[$field] = '@#BLOB#@';
835 $blobs[$field] = $normalised_value['blob'];
837 $cleaned[$field] = $normalised_value;
842 return $this->insert_record_raw($table, $cleaned, $returnid, $bulk);
845 $id = $this->insert_record_raw($table, $cleaned, true, $bulk);
847 foreach ($blobs as $key=>$value) {
848 $value = pg_escape_bytea($this->pgsql, $value);
849 $sql = "UPDATE {$this->prefix}$table SET $key = '$value'::bytea WHERE id = $id";
850 $this->query_start($sql, NULL, SQL_QUERY_UPDATE);
851 $result = pg_query($this->pgsql, $sql);
852 $this->query_end($result);
853 if ($result !== false) {
854 pg_free_result($result);
858 return ($returnid ? $id : true);
863 * Import a record into a table, id field is required.
864 * Safety checks are NOT carried out. Lobs are supported.
866 * @param string $table name of database table to be inserted into
867 * @param object $dataobject A data object with values for one or more fields in the record
869 * @throws dml_exception A DML specific exception is thrown for any errors.
871 public function import_record($table, $dataobject) {
872 $dataobject = (array)$dataobject;
874 $columns = $this->get_columns($table);
878 foreach ($dataobject as $field=>$value) {
879 if (!isset($columns[$field])) {
882 if ($columns[$field]->meta_type === 'B') {
883 if (!is_null($value)) {
884 $cleaned[$field] = '@#BLOB#@';
885 $blobs[$field] = $value;
890 $cleaned[$field] = $value;
893 $this->insert_record_raw($table, $cleaned, false, true, true);
894 $id = $dataobject['id'];
896 foreach ($blobs as $key=>$value) {
897 $value = pg_escape_bytea($this->pgsql, $value);
898 $sql = "UPDATE {$this->prefix}$table SET $key = '$value'::bytea WHERE id = $id";
899 $this->query_start($sql, NULL, SQL_QUERY_UPDATE);
900 $result = pg_query($this->pgsql, $sql);
901 $this->query_end($result);
902 if ($result !== false) {
903 pg_free_result($result);
911 * Update record in database, as fast as possible, no safety checks, lobs not supported.
912 * @param string $table name
913 * @param mixed $params data record as object or array
914 * @param bool true means repeated updates expected
916 * @throws dml_exception A DML specific exception is thrown for any errors.
918 public function update_record_raw($table, $params, $bulk=false) {
919 $params = (array)$params;
921 if (!isset($params['id'])) {
922 throw new coding_exception('moodle_database::update_record_raw() id field must be specified.');
925 unset($params['id']);
927 if (empty($params)) {
928 throw new coding_exception('moodle_database::update_record_raw() no fields found.');
934 foreach ($params as $field=>$value) {
935 $sets[] = "$field = \$".$i++;
938 $params[] = $id; // last ? in WHERE condition
940 $sets = implode(',', $sets);
941 $sql = "UPDATE {$this->prefix}$table SET $sets WHERE id=\$".$i;
943 $this->query_start($sql, $params, SQL_QUERY_UPDATE);
944 $result = pg_query_params($this->pgsql, $sql, $params);
945 $this->query_end($result);
947 pg_free_result($result);
952 * Update a record in a table
954 * $dataobject is an object containing needed data
955 * Relies on $dataobject having a variable "id" to
956 * specify the record to update
958 * @param string $table The database table to be checked against.
959 * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
960 * @param bool true means repeated updates expected
962 * @throws dml_exception A DML specific exception is thrown for any errors.
964 public function update_record($table, $dataobject, $bulk=false) {
965 $dataobject = (array)$dataobject;
967 $columns = $this->get_columns($table);
971 foreach ($dataobject as $field=>$value) {
972 if (!isset($columns[$field])) {
975 $column = $columns[$field];
976 $normalised_value = $this->normalise_value($column, $value);
977 if (is_array($normalised_value) && array_key_exists('blob', $normalised_value)) {
978 $cleaned[$field] = '@#BLOB#@';
979 $blobs[$field] = $normalised_value['blob'];
981 $cleaned[$field] = $normalised_value;
985 $this->update_record_raw($table, $cleaned, $bulk);
991 $id = (int)$dataobject['id'];
993 foreach ($blobs as $key=>$value) {
994 $value = pg_escape_bytea($this->pgsql, $value);
995 $sql = "UPDATE {$this->prefix}$table SET $key = '$value'::bytea WHERE id = $id";
996 $this->query_start($sql, NULL, SQL_QUERY_UPDATE);
997 $result = pg_query($this->pgsql, $sql);
998 $this->query_end($result);
1000 pg_free_result($result);
1007 * Set a single field in every table record which match a particular WHERE clause.
1009 * @param string $table The database table to be checked against.
1010 * @param string $newfield the field to set.
1011 * @param string $newvalue the value to set the field to.
1012 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1013 * @param array $params array of sql parameters
1015 * @throws dml_exception A DML specific exception is thrown for any errors.
1017 public function set_field_select($table, $newfield, $newvalue, $select, array $params=null) {
1020 $select = "WHERE $select";
1022 if (is_null($params)) {
1025 list($select, $params, $type) = $this->fix_sql_params($select, $params);
1026 $i = count($params)+1;
1028 /// Get column metadata
1029 $columns = $this->get_columns($table);
1030 $column = $columns[$newfield];
1032 $normalised_value = $this->normalise_value($column, $newvalue);
1033 if (is_array($normalised_value) && array_key_exists('blob', $normalised_value)) {
1034 /// Update BYTEA and return
1035 $normalised_value = pg_escape_bytea($this->pgsql, $normalised_value['blob']);
1036 $sql = "UPDATE {$this->prefix}$table SET $newfield = '$normalised_value'::bytea $select";
1037 $this->query_start($sql, NULL, SQL_QUERY_UPDATE);
1038 $result = pg_query_params($this->pgsql, $sql, $params);
1039 $this->query_end($result);
1040 pg_free_result($result);
1044 if (is_null($normalised_value)) {
1045 $newfield = "$newfield = NULL";
1047 $newfield = "$newfield = \$".$i;
1048 $params[] = $normalised_value;
1050 $sql = "UPDATE {$this->prefix}$table SET $newfield $select";
1052 $this->query_start($sql, $params, SQL_QUERY_UPDATE);
1053 $result = pg_query_params($this->pgsql, $sql, $params);
1054 $this->query_end($result);
1056 pg_free_result($result);
1062 * Delete one or more records from a table which match a particular WHERE clause.
1064 * @param string $table The database table to be checked against.
1065 * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
1066 * @param array $params array of sql parameters
1068 * @throws dml_exception A DML specific exception is thrown for any errors.
1070 public function delete_records_select($table, $select, array $params=null) {
1072 $select = "WHERE $select";
1074 $sql = "DELETE FROM {$this->prefix}$table $select";
1076 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
1078 $this->query_start($sql, $params, SQL_QUERY_UPDATE);
1079 $result = pg_query_params($this->pgsql, $sql, $params);
1080 $this->query_end($result);
1082 pg_free_result($result);
1088 * Returns 'LIKE' part of a query.
1090 * @param string $fieldname usually name of the table column
1091 * @param string $param usually bound query parameter (?, :named)
1092 * @param bool $casesensitive use case sensitive search
1093 * @param bool $accensensitive use accent sensitive search (not all databases support accent insensitive)
1094 * @param bool $notlike true means "NOT LIKE"
1095 * @param string $escapechar escape char for '%' and '_'
1096 * @return string SQL code fragment
1098 public function sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = '\\') {
1099 if (strpos($param, '%') !== false) {
1100 debugging('Potential SQL injection detected, sql_ilike() expects bound parameters (? or :named)');
1102 $escapechar = pg_escape_string($this->pgsql, $escapechar); // prevents problems with C-style escapes of enclosing '\'
1104 // postgresql does not support accent insensitive text comparisons, sorry
1105 if ($casesensitive) {
1106 $LIKE = $notlike ? 'NOT LIKE' : 'LIKE';
1108 $LIKE = $notlike ? 'NOT ILIKE' : 'ILIKE';
1110 return "$fieldname $LIKE $param ESCAPE '$escapechar'";
1113 public function sql_ilike() {
1114 debugging('sql_ilike() is deprecated, please use sql_like() instead');
1118 public function sql_bitxor($int1, $int2) {
1119 return '((' . $int1 . ') # (' . $int2 . '))';
1122 public function sql_cast_char2int($fieldname, $text=false) {
1123 return ' CAST(' . $fieldname . ' AS INT) ';
1126 public function sql_cast_char2real($fieldname, $text=false) {
1127 return " $fieldname::real ";
1130 public function sql_concat() {
1131 $arr = func_get_args();
1132 $s = implode(' || ', $arr);
1136 // Add always empty string element so integer-exclusive concats
1137 // will work without needing to cast each element explicity
1138 return " '' || $s ";
1141 public function sql_concat_join($separator="' '", $elements=array()) {
1142 for ($n=count($elements)-1; $n > 0 ; $n--) {
1143 array_splice($elements, $n, 0, $separator);
1145 $s = implode(' || ', $elements);
1152 public function sql_regex_supported() {
1156 public function sql_regex($positivematch=true) {
1157 return $positivematch ? '~*' : '!~*';
1161 public function session_lock_supported() {
1166 * Obtain session lock
1167 * @param int $rowid id of the row with session record
1168 * @param int $timeout max allowed time to wait for the lock in seconds
1169 * @return bool success
1171 public function get_session_lock($rowid, $timeout) {
1172 // NOTE: there is a potential locking problem for database running
1173 // multiple instances of moodle, we could try to use pg_advisory_lock(int, int),
1174 // luckily there is not a big chance that they would collide
1175 if (!$this->session_lock_supported()) {
1179 parent::get_session_lock($rowid, $timeout);
1181 $timeoutmilli = $timeout * 1000;
1183 $sql = "SET statement_timeout TO $timeoutmilli";
1184 $this->query_start($sql, null, SQL_QUERY_AUX);
1185 $result = pg_query($this->pgsql, $sql);
1186 $this->query_end($result);
1189 pg_free_result($result);
1192 $sql = "SELECT pg_advisory_lock($rowid)";
1193 $this->query_start($sql, null, SQL_QUERY_AUX);
1195 $result = pg_query($this->pgsql, $sql);
1198 $this->query_end($result);
1199 } catch (dml_exception $ex) {
1200 if ($end - $start >= $timeout) {
1201 throw new dml_sessionwait_exception();
1208 pg_free_result($result);
1211 $sql = "SET statement_timeout TO DEFAULT";
1212 $this->query_start($sql, null, SQL_QUERY_AUX);
1213 $result = pg_query($this->pgsql, $sql);
1214 $this->query_end($result);
1217 pg_free_result($result);
1221 public function release_session_lock($rowid) {
1222 if (!$this->session_lock_supported()) {
1225 parent::release_session_lock($rowid);
1227 $sql = "SELECT pg_advisory_unlock($rowid)";
1228 $this->query_start($sql, null, SQL_QUERY_AUX);
1229 $result = pg_query($this->pgsql, $sql);
1230 $this->query_end($result);
1233 pg_free_result($result);
1239 * Driver specific start of real database transaction,
1240 * this can not be used directly in code.
1243 protected function begin_transaction() {
1244 $sql = "BEGIN ISOLATION LEVEL READ COMMITTED";
1245 $this->query_start($sql, NULL, SQL_QUERY_AUX);
1246 $result = pg_query($this->pgsql, $sql);
1247 $this->query_end($result);
1249 pg_free_result($result);
1253 * Driver specific commit of real database transaction,
1254 * this can not be used directly in code.
1257 protected function commit_transaction() {
1259 $this->query_start($sql, NULL, SQL_QUERY_AUX);
1260 $result = pg_query($this->pgsql, $sql);
1261 $this->query_end($result);
1263 pg_free_result($result);
1267 * Driver specific abort of real database transaction,
1268 * this can not be used directly in code.
1271 protected function rollback_transaction() {
1273 $this->query_start($sql, NULL, SQL_QUERY_AUX);
1274 $result = pg_query($this->pgsql, $sql);
1275 $this->query_end($result);
1277 pg_free_result($result);
1281 * Helper function trimming (whitespace + quotes) any string
1282 * needed because PG uses to enclose with double quotes some
1283 * fields in indexes definition and others
1285 * @param string $str string to apply whitespace + quotes trim
1286 * @return string trimmed string
1288 private function trim_quotes($str) {
1289 return trim(trim($str), "'\"");