PageRenderTime 64ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/dml/pgsql_native_moodle_database.php

https://bitbucket.org/kudutest1/moodlegit
PHP | 1343 lines | 1004 code | 118 blank | 221 comment | 100 complexity | cadb3d6eea6dc5d463b7e49f8ec6ebce MD5 | raw file
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Native pgsql class representing moodle database interface.
  18. *
  19. * @package core_dml
  20. * @copyright 2008 Petr Skoda (http://skodak.org)
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. defined('MOODLE_INTERNAL') || die();
  24. require_once(__DIR__.'/moodle_database.php');
  25. require_once(__DIR__.'/pgsql_native_moodle_recordset.php');
  26. require_once(__DIR__.'/pgsql_native_moodle_temptables.php');
  27. /**
  28. * Native pgsql class representing moodle database interface.
  29. *
  30. * @package core_dml
  31. * @copyright 2008 Petr Skoda (http://skodak.org)
  32. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  33. */
  34. class pgsql_native_moodle_database extends moodle_database {
  35. protected $pgsql = null;
  36. protected $bytea_oid = null;
  37. protected $last_error_reporting; // To handle pgsql driver default verbosity
  38. /** @var bool savepoint hack for MDL-35506 - workaround for automatic transaction rollback on error */
  39. protected $savepointpresent = false;
  40. /**
  41. * Detects if all needed PHP stuff installed.
  42. * Note: can be used before connect()
  43. * @return mixed true if ok, string if something
  44. */
  45. public function driver_installed() {
  46. if (!extension_loaded('pgsql')) {
  47. return get_string('pgsqlextensionisnotpresentinphp', 'install');
  48. }
  49. return true;
  50. }
  51. /**
  52. * Returns database family type - describes SQL dialect
  53. * Note: can be used before connect()
  54. * @return string db family name (mysql, postgres, mssql, oracle, etc.)
  55. */
  56. public function get_dbfamily() {
  57. return 'postgres';
  58. }
  59. /**
  60. * Returns more specific database driver type
  61. * Note: can be used before connect()
  62. * @return string db type mysqli, pgsql, oci, mssql, sqlsrv
  63. */
  64. protected function get_dbtype() {
  65. return 'pgsql';
  66. }
  67. /**
  68. * Returns general database library name
  69. * Note: can be used before connect()
  70. * @return string db type pdo, native
  71. */
  72. protected function get_dblibrary() {
  73. return 'native';
  74. }
  75. /**
  76. * Returns localised database type name
  77. * Note: can be used before connect()
  78. * @return string
  79. */
  80. public function get_name() {
  81. return get_string('nativepgsql', 'install');
  82. }
  83. /**
  84. * Returns localised database configuration help.
  85. * Note: can be used before connect()
  86. * @return string
  87. */
  88. public function get_configuration_help() {
  89. return get_string('nativepgsqlhelp', 'install');
  90. }
  91. /**
  92. * Returns localised database description
  93. * Note: can be used before connect()
  94. * @return string
  95. */
  96. public function get_configuration_hints() {
  97. return get_string('databasesettingssub_postgres7', 'install');
  98. }
  99. /**
  100. * Connect to db
  101. * Must be called before other methods.
  102. * @param string $dbhost The database host.
  103. * @param string $dbuser The database username.
  104. * @param string $dbpass The database username's password.
  105. * @param string $dbname The name of the database being connected to.
  106. * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
  107. * @param array $dboptions driver specific options
  108. * @return bool true
  109. * @throws dml_connection_exception if error
  110. */
  111. public function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null) {
  112. if ($prefix == '' and !$this->external) {
  113. //Enforce prefixes for everybody but mysql
  114. throw new dml_exception('prefixcannotbeempty', $this->get_dbfamily());
  115. }
  116. $driverstatus = $this->driver_installed();
  117. if ($driverstatus !== true) {
  118. throw new dml_exception('dbdriverproblem', $driverstatus);
  119. }
  120. $this->store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions);
  121. $pass = addcslashes($this->dbpass, "'\\");
  122. // Unix socket connections should have lower overhead
  123. if (!empty($this->dboptions['dbsocket']) and ($this->dbhost === 'localhost' or $this->dbhost === '127.0.0.1')) {
  124. $connection = "user='$this->dbuser' password='$pass' dbname='$this->dbname'";
  125. if (strpos($this->dboptions['dbsocket'], '/') !== false) {
  126. $connection = $connection." host='".$this->dboptions['dbsocket']."'";
  127. }
  128. } else {
  129. $this->dboptions['dbsocket'] = '';
  130. if (empty($this->dbname)) {
  131. // probably old style socket connection - do not add port
  132. $port = "";
  133. } else if (empty($this->dboptions['dbport'])) {
  134. $port = "port ='5432'";
  135. } else {
  136. $port = "port ='".$this->dboptions['dbport']."'";
  137. }
  138. $connection = "host='$this->dbhost' $port user='$this->dbuser' password='$pass' dbname='$this->dbname'";
  139. }
  140. ob_start();
  141. if (empty($this->dboptions['dbpersist'])) {
  142. $this->pgsql = pg_connect($connection, PGSQL_CONNECT_FORCE_NEW);
  143. } else {
  144. $this->pgsql = pg_pconnect($connection, PGSQL_CONNECT_FORCE_NEW);
  145. }
  146. $dberr = ob_get_contents();
  147. ob_end_clean();
  148. $status = pg_connection_status($this->pgsql);
  149. if ($status === false or $status === PGSQL_CONNECTION_BAD) {
  150. $this->pgsql = null;
  151. throw new dml_connection_exception($dberr);
  152. }
  153. $this->query_start("--pg_set_client_encoding()", null, SQL_QUERY_AUX);
  154. pg_set_client_encoding($this->pgsql, 'utf8');
  155. $this->query_end(true);
  156. $sql = '';
  157. // Only for 9.0 and upwards, set bytea encoding to old format.
  158. if ($this->is_min_version('9.0')) {
  159. $sql = "SET bytea_output = 'escape'; ";
  160. }
  161. // Select schema if specified, otherwise the first one wins.
  162. if (!empty($this->dboptions['dbschema'])) {
  163. $sql .= "SET search_path = '".$this->dboptions['dbschema']."'; ";
  164. }
  165. // Find out the bytea oid.
  166. $sql .= "SELECT oid FROM pg_type WHERE typname = 'bytea'";
  167. $this->query_start($sql, null, SQL_QUERY_AUX);
  168. $result = pg_query($this->pgsql, $sql);
  169. $this->query_end($result);
  170. $this->bytea_oid = pg_fetch_result($result, 0, 0);
  171. pg_free_result($result);
  172. if ($this->bytea_oid === false) {
  173. $this->pgsql = null;
  174. throw new dml_connection_exception('Can not read bytea type.');
  175. }
  176. // Connection stabilised and configured, going to instantiate the temptables controller
  177. $this->temptables = new pgsql_native_moodle_temptables($this);
  178. return true;
  179. }
  180. /**
  181. * Close database connection and release all resources
  182. * and memory (especially circular memory references).
  183. * Do NOT use connect() again, create a new instance if needed.
  184. */
  185. public function dispose() {
  186. parent::dispose(); // Call parent dispose to write/close session and other common stuff before closing connection
  187. if ($this->pgsql) {
  188. pg_close($this->pgsql);
  189. $this->pgsql = null;
  190. }
  191. }
  192. /**
  193. * Called before each db query.
  194. * @param string $sql
  195. * @param array array of parameters
  196. * @param int $type type of query
  197. * @param mixed $extrainfo driver specific extra information
  198. * @return void
  199. */
  200. protected function query_start($sql, array $params=null, $type, $extrainfo=null) {
  201. parent::query_start($sql, $params, $type, $extrainfo);
  202. // pgsql driver tents to send debug to output, we do not need that ;-)
  203. $this->last_error_reporting = error_reporting(0);
  204. }
  205. /**
  206. * Called immediately after each db query.
  207. * @param mixed db specific result
  208. * @return void
  209. */
  210. protected function query_end($result) {
  211. // reset original debug level
  212. error_reporting($this->last_error_reporting);
  213. try {
  214. parent::query_end($result);
  215. if ($this->savepointpresent and $this->last_type != SQL_QUERY_AUX and $this->last_type != SQL_QUERY_SELECT) {
  216. $res = @pg_query($this->pgsql, "RELEASE SAVEPOINT moodle_pg_savepoint; SAVEPOINT moodle_pg_savepoint");
  217. if ($res) {
  218. pg_free_result($res);
  219. }
  220. }
  221. } catch (Exception $e) {
  222. if ($this->savepointpresent) {
  223. $res = @pg_query($this->pgsql, "ROLLBACK TO SAVEPOINT moodle_pg_savepoint; SAVEPOINT moodle_pg_savepoint");
  224. if ($res) {
  225. pg_free_result($res);
  226. }
  227. }
  228. throw $e;
  229. }
  230. }
  231. /**
  232. * Returns database server info array
  233. * @return array Array containing 'description' and 'version' info
  234. */
  235. public function get_server_info() {
  236. static $info;
  237. if (!$info) {
  238. $this->query_start("--pg_version()", null, SQL_QUERY_AUX);
  239. $info = pg_version($this->pgsql);
  240. $this->query_end(true);
  241. }
  242. return array('description'=>$info['server'], 'version'=>$info['server']);
  243. }
  244. /**
  245. * Returns if the RDBMS server fulfills the required version
  246. *
  247. * @param string $version version to check against
  248. * @return bool returns if the version is fulfilled (true) or no (false)
  249. */
  250. private function is_min_version($version) {
  251. $server = $this->get_server_info();
  252. $server = $server['version'];
  253. return version_compare($server, $version, '>=');
  254. }
  255. /**
  256. * Returns supported query parameter types
  257. * @return int bitmask of accepted SQL_PARAMS_*
  258. */
  259. protected function allowed_param_types() {
  260. return SQL_PARAMS_DOLLAR;
  261. }
  262. /**
  263. * Returns last error reported by database engine.
  264. * @return string error message
  265. */
  266. public function get_last_error() {
  267. return pg_last_error($this->pgsql);
  268. }
  269. /**
  270. * Return tables in database WITHOUT current prefix.
  271. * @param bool $usecache if true, returns list of cached tables.
  272. * @return array of table names in lowercase and without prefix
  273. */
  274. public function get_tables($usecache=true) {
  275. if ($usecache and $this->tables !== null) {
  276. return $this->tables;
  277. }
  278. $this->tables = array();
  279. $prefix = str_replace('_', '|_', $this->prefix);
  280. $sql = "SELECT c.relname
  281. FROM pg_catalog.pg_class c
  282. JOIN pg_catalog.pg_namespace as ns ON ns.oid = c.relnamespace
  283. WHERE c.relname LIKE '$prefix%' ESCAPE '|'
  284. AND c.relkind = 'r'
  285. AND (ns.nspname = current_schema() OR ns.oid = pg_my_temp_schema())";
  286. $this->query_start($sql, null, SQL_QUERY_AUX);
  287. $result = pg_query($this->pgsql, $sql);
  288. $this->query_end($result);
  289. if ($result) {
  290. while ($row = pg_fetch_row($result)) {
  291. $tablename = reset($row);
  292. if ($this->prefix !== '') {
  293. if (strpos($tablename, $this->prefix) !== 0) {
  294. continue;
  295. }
  296. $tablename = substr($tablename, strlen($this->prefix));
  297. }
  298. $this->tables[$tablename] = $tablename;
  299. }
  300. pg_free_result($result);
  301. }
  302. return $this->tables;
  303. }
  304. /**
  305. * Return table indexes - everything lowercased.
  306. * @param string $table The table we want to get indexes from.
  307. * @return array of arrays
  308. */
  309. public function get_indexes($table) {
  310. $indexes = array();
  311. $tablename = $this->prefix.$table;
  312. $sql = "SELECT i.*
  313. FROM pg_catalog.pg_indexes i
  314. JOIN pg_catalog.pg_namespace as ns ON ns.nspname = i.schemaname
  315. WHERE i.tablename = '$tablename'
  316. AND (i.schemaname = current_schema() OR ns.oid = pg_my_temp_schema())";
  317. $this->query_start($sql, null, SQL_QUERY_AUX);
  318. $result = pg_query($this->pgsql, $sql);
  319. $this->query_end($result);
  320. if ($result) {
  321. while ($row = pg_fetch_assoc($result)) {
  322. if (!preg_match('/CREATE (|UNIQUE )INDEX ([^\s]+) ON '.$tablename.' USING ([^\s]+) \(([^\)]+)\)/i', $row['indexdef'], $matches)) {
  323. continue;
  324. }
  325. if ($matches[4] === 'id') {
  326. continue;
  327. }
  328. $columns = explode(',', $matches[4]);
  329. foreach ($columns as $k=>$column) {
  330. $column = trim($column);
  331. if ($pos = strpos($column, ' ')) {
  332. // index type is separated by space
  333. $column = substr($column, 0, $pos);
  334. }
  335. $columns[$k] = $this->trim_quotes($column);
  336. }
  337. $indexes[$row['indexname']] = array('unique'=>!empty($matches[1]),
  338. 'columns'=>$columns);
  339. }
  340. pg_free_result($result);
  341. }
  342. return $indexes;
  343. }
  344. /**
  345. * Returns detailed information about columns in table. This information is cached internally.
  346. * @param string $table name
  347. * @param bool $usecache
  348. * @return array array of database_column_info objects indexed with column names
  349. */
  350. public function get_columns($table, $usecache=true) {
  351. if ($usecache) {
  352. $properties = array('dbfamily' => $this->get_dbfamily(), 'settings' => $this->get_settings_hash());
  353. $cache = cache::make('core', 'databasemeta', $properties);
  354. if ($data = $cache->get($table)) {
  355. return $data;
  356. }
  357. }
  358. $structure = array();
  359. $tablename = $this->prefix.$table;
  360. $sql = "SELECT a.attnum, a.attname AS field, t.typname AS type, a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, d.adsrc
  361. FROM pg_catalog.pg_class c
  362. JOIN pg_catalog.pg_namespace as ns ON ns.oid = c.relnamespace
  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
  367. AND (ns.nspname = current_schema() OR ns.oid = pg_my_temp_schema())
  368. ORDER BY a.attnum";
  369. $this->query_start($sql, null, SQL_QUERY_AUX);
  370. $result = pg_query($this->pgsql, $sql);
  371. $this->query_end($result);
  372. if (!$result) {
  373. return array();
  374. }
  375. while ($rawcolumn = pg_fetch_object($result)) {
  376. $info = new stdClass();
  377. $info->name = $rawcolumn->field;
  378. $matches = null;
  379. if ($rawcolumn->type === 'varchar') {
  380. $info->type = 'varchar';
  381. $info->meta_type = 'C';
  382. $info->max_length = $rawcolumn->atttypmod - 4;
  383. $info->scale = null;
  384. $info->not_null = ($rawcolumn->attnotnull === 't');
  385. $info->has_default = ($rawcolumn->atthasdef === 't');
  386. if ($info->has_default) {
  387. $parts = explode('::', $rawcolumn->adsrc);
  388. if (count($parts) > 1) {
  389. $info->default_value = reset($parts);
  390. $info->default_value = trim($info->default_value, "'");
  391. } else {
  392. $info->default_value = $rawcolumn->adsrc;
  393. }
  394. } else {
  395. $info->default_value = null;
  396. }
  397. $info->primary_key = false;
  398. $info->binary = false;
  399. $info->unsigned = null;
  400. $info->auto_increment= false;
  401. $info->unique = null;
  402. } else if (preg_match('/int(\d)/i', $rawcolumn->type, $matches)) {
  403. $info->type = 'int';
  404. if (strpos($rawcolumn->adsrc, 'nextval') === 0) {
  405. $info->primary_key = true;
  406. $info->meta_type = 'R';
  407. $info->unique = true;
  408. $info->auto_increment= true;
  409. $info->has_default = false;
  410. } else {
  411. $info->primary_key = false;
  412. $info->meta_type = 'I';
  413. $info->unique = null;
  414. $info->auto_increment= false;
  415. $info->has_default = ($rawcolumn->atthasdef === 't');
  416. }
  417. // Return number of decimals, not bytes here.
  418. if ($matches[1] >= 8) {
  419. $info->max_length = 18;
  420. } else if ($matches[1] >= 4) {
  421. $info->max_length = 9;
  422. } else if ($matches[1] >= 2) {
  423. $info->max_length = 4;
  424. } else if ($matches[1] >= 1) {
  425. $info->max_length = 2;
  426. } else {
  427. $info->max_length = 0;
  428. }
  429. $info->scale = null;
  430. $info->not_null = ($rawcolumn->attnotnull === 't');
  431. if ($info->has_default) {
  432. $info->default_value = trim($rawcolumn->adsrc, '()');
  433. } else {
  434. $info->default_value = null;
  435. }
  436. $info->binary = false;
  437. $info->unsigned = false;
  438. } else if ($rawcolumn->type === 'numeric') {
  439. $info->type = $rawcolumn->type;
  440. $info->meta_type = 'N';
  441. $info->primary_key = false;
  442. $info->binary = false;
  443. $info->unsigned = null;
  444. $info->auto_increment= false;
  445. $info->unique = null;
  446. $info->not_null = ($rawcolumn->attnotnull === 't');
  447. $info->has_default = ($rawcolumn->atthasdef === 't');
  448. if ($info->has_default) {
  449. $info->default_value = trim($rawcolumn->adsrc, '()');
  450. } else {
  451. $info->default_value = null;
  452. }
  453. $info->max_length = $rawcolumn->atttypmod >> 16;
  454. $info->scale = ($rawcolumn->atttypmod & 0xFFFF) - 4;
  455. } else if (preg_match('/float(\d)/i', $rawcolumn->type, $matches)) {
  456. $info->type = 'float';
  457. $info->meta_type = 'N';
  458. $info->primary_key = false;
  459. $info->binary = false;
  460. $info->unsigned = null;
  461. $info->auto_increment= false;
  462. $info->unique = null;
  463. $info->not_null = ($rawcolumn->attnotnull === 't');
  464. $info->has_default = ($rawcolumn->atthasdef === 't');
  465. if ($info->has_default) {
  466. $info->default_value = trim($rawcolumn->adsrc, '()');
  467. } else {
  468. $info->default_value = null;
  469. }
  470. // just guess expected number of deciaml places :-(
  471. if ($matches[1] == 8) {
  472. // total 15 digits
  473. $info->max_length = 8;
  474. $info->scale = 7;
  475. } else {
  476. // total 6 digits
  477. $info->max_length = 4;
  478. $info->scale = 2;
  479. }
  480. } else if ($rawcolumn->type === 'text') {
  481. $info->type = $rawcolumn->type;
  482. $info->meta_type = 'X';
  483. $info->max_length = -1;
  484. $info->scale = null;
  485. $info->not_null = ($rawcolumn->attnotnull === 't');
  486. $info->has_default = ($rawcolumn->atthasdef === 't');
  487. if ($info->has_default) {
  488. $parts = explode('::', $rawcolumn->adsrc);
  489. if (count($parts) > 1) {
  490. $info->default_value = reset($parts);
  491. $info->default_value = trim($info->default_value, "'");
  492. } else {
  493. $info->default_value = $rawcolumn->adsrc;
  494. }
  495. } else {
  496. $info->default_value = null;
  497. }
  498. $info->primary_key = false;
  499. $info->binary = false;
  500. $info->unsigned = null;
  501. $info->auto_increment= false;
  502. $info->unique = null;
  503. } else if ($rawcolumn->type === 'bytea') {
  504. $info->type = $rawcolumn->type;
  505. $info->meta_type = 'B';
  506. $info->max_length = -1;
  507. $info->scale = null;
  508. $info->not_null = ($rawcolumn->attnotnull === 't');
  509. $info->has_default = false;
  510. $info->default_value = null;
  511. $info->primary_key = false;
  512. $info->binary = true;
  513. $info->unsigned = null;
  514. $info->auto_increment= false;
  515. $info->unique = null;
  516. }
  517. $structure[$info->name] = new database_column_info($info);
  518. }
  519. pg_free_result($result);
  520. if ($usecache) {
  521. $result = $cache->set($table, $structure);
  522. }
  523. return $structure;
  524. }
  525. /**
  526. * Normalise values based in RDBMS dependencies (booleans, LOBs...)
  527. *
  528. * @param database_column_info $column column metadata corresponding with the value we are going to normalise
  529. * @param mixed $value value we are going to normalise
  530. * @return mixed the normalised value
  531. */
  532. protected function normalise_value($column, $value) {
  533. $this->detect_objects($value);
  534. if (is_bool($value)) { // Always, convert boolean to int
  535. $value = (int)$value;
  536. } else if ($column->meta_type === 'B') { // BLOB detected, we return 'blob' array instead of raw value to allow
  537. if (!is_null($value)) { // binding/executing code later to know about its nature
  538. $value = array('blob' => $value);
  539. }
  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
  543. }
  544. }
  545. return $value;
  546. }
  547. /**
  548. * Is db in unicode mode?
  549. * @return bool
  550. */
  551. public function setup_is_unicodedb() {
  552. // Get PostgreSQL server_encoding value
  553. $sql = "SHOW server_encoding";
  554. $this->query_start($sql, null, SQL_QUERY_AUX);
  555. $result = pg_query($this->pgsql, $sql);
  556. $this->query_end($result);
  557. if (!$result) {
  558. return false;
  559. }
  560. $rawcolumn = pg_fetch_object($result);
  561. $encoding = $rawcolumn->server_encoding;
  562. pg_free_result($result);
  563. return (strtoupper($encoding) == 'UNICODE' || strtoupper($encoding) == 'UTF8');
  564. }
  565. /**
  566. * Do NOT use in code, to be used by database_manager only!
  567. * @param string $sql query
  568. * @return bool true
  569. * @throws dml_exception A DML specific exception is thrown for any errors.
  570. */
  571. public function change_database_structure($sql) {
  572. $this->reset_caches();
  573. $this->query_start($sql, null, SQL_QUERY_STRUCTURE);
  574. $result = pg_query($this->pgsql, $sql);
  575. $this->query_end($result);
  576. pg_free_result($result);
  577. return true;
  578. }
  579. /**
  580. * Execute general sql query. Should be used only when no other method suitable.
  581. * Do NOT use this to make changes in db structure, use database_manager methods instead!
  582. * @param string $sql query
  583. * @param array $params query parameters
  584. * @return bool true
  585. * @throws dml_exception A DML specific exception is thrown for any errors.
  586. */
  587. public function execute($sql, array $params=null) {
  588. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  589. if (strpos($sql, ';') !== false) {
  590. throw new coding_exception('moodle_database::execute() Multiple sql statements found or bound parameters not used properly in query!');
  591. }
  592. $this->query_start($sql, $params, SQL_QUERY_UPDATE);
  593. $result = pg_query_params($this->pgsql, $sql, $params);
  594. $this->query_end($result);
  595. pg_free_result($result);
  596. return true;
  597. }
  598. /**
  599. * Get a number of records as a moodle_recordset using a SQL statement.
  600. *
  601. * Since this method is a little less readable, use of it should be restricted to
  602. * code where it's possible there might be large datasets being returned. For known
  603. * small datasets use get_records_sql - it leads to simpler code.
  604. *
  605. * The return type is like:
  606. * @see function get_recordset.
  607. *
  608. * @param string $sql the SQL select query to execute.
  609. * @param array $params array of sql parameters
  610. * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
  611. * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
  612. * @return moodle_recordset instance
  613. * @throws dml_exception A DML specific exception is thrown for any errors.
  614. */
  615. public function get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
  616. $limitfrom = (int)$limitfrom;
  617. $limitnum = (int)$limitnum;
  618. $limitfrom = ($limitfrom < 0) ? 0 : $limitfrom;
  619. $limitnum = ($limitnum < 0) ? 0 : $limitnum;
  620. if ($limitfrom or $limitnum) {
  621. if ($limitnum < 1) {
  622. $limitnum = "ALL";
  623. } else if (PHP_INT_MAX - $limitnum < $limitfrom) {
  624. // this is a workaround for weird max int problem
  625. $limitnum = "ALL";
  626. }
  627. $sql .= " LIMIT $limitnum OFFSET $limitfrom";
  628. }
  629. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  630. $this->query_start($sql, $params, SQL_QUERY_SELECT);
  631. $result = pg_query_params($this->pgsql, $sql, $params);
  632. $this->query_end($result);
  633. return $this->create_recordset($result);
  634. }
  635. protected function create_recordset($result) {
  636. return new pgsql_native_moodle_recordset($result, $this->bytea_oid);
  637. }
  638. /**
  639. * Get a number of records as an array of objects using a SQL statement.
  640. *
  641. * Return value is like:
  642. * @see function get_records.
  643. *
  644. * @param string $sql the SQL select query to execute. The first column of this SELECT statement
  645. * must be a unique value (usually the 'id' field), as it will be used as the key of the
  646. * returned array.
  647. * @param array $params array of sql parameters
  648. * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
  649. * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
  650. * @return array of objects, or empty array if no records were found
  651. * @throws dml_exception A DML specific exception is thrown for any errors.
  652. */
  653. public function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
  654. $limitfrom = (int)$limitfrom;
  655. $limitnum = (int)$limitnum;
  656. $limitfrom = ($limitfrom < 0) ? 0 : $limitfrom;
  657. $limitnum = ($limitnum < 0) ? 0 : $limitnum;
  658. if ($limitfrom or $limitnum) {
  659. if ($limitnum < 1) {
  660. $limitnum = "ALL";
  661. } else if (PHP_INT_MAX - $limitnum < $limitfrom) {
  662. // this is a workaround for weird max int problem
  663. $limitnum = "ALL";
  664. }
  665. $sql .= " LIMIT $limitnum OFFSET $limitfrom";
  666. }
  667. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  668. $this->query_start($sql, $params, SQL_QUERY_SELECT);
  669. $result = pg_query_params($this->pgsql, $sql, $params);
  670. $this->query_end($result);
  671. // find out if there are any blobs
  672. $numrows = pg_num_fields($result);
  673. $blobs = array();
  674. for($i=0; $i<$numrows; $i++) {
  675. $type_oid = pg_field_type_oid($result, $i);
  676. if ($type_oid == $this->bytea_oid) {
  677. $blobs[] = pg_field_name($result, $i);
  678. }
  679. }
  680. $rows = pg_fetch_all($result);
  681. pg_free_result($result);
  682. $return = array();
  683. if ($rows) {
  684. foreach ($rows as $row) {
  685. $id = reset($row);
  686. if ($blobs) {
  687. foreach ($blobs as $blob) {
  688. // 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
  689. $row[$blob] = $row[$blob] !== null ? pg_unescape_bytea($row[$blob]) : null;
  690. }
  691. }
  692. if (isset($return[$id])) {
  693. $colname = key($row);
  694. 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);
  695. }
  696. $return[$id] = (object)$row;
  697. }
  698. }
  699. return $return;
  700. }
  701. /**
  702. * Selects records and return values (first field) as an array using a SQL statement.
  703. *
  704. * @param string $sql The SQL query
  705. * @param array $params array of sql parameters
  706. * @return array of values
  707. * @throws dml_exception A DML specific exception is thrown for any errors.
  708. */
  709. public function get_fieldset_sql($sql, array $params=null) {
  710. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  711. $this->query_start($sql, $params, SQL_QUERY_SELECT);
  712. $result = pg_query_params($this->pgsql, $sql, $params);
  713. $this->query_end($result);
  714. $return = pg_fetch_all_columns($result, 0);
  715. pg_free_result($result);
  716. return $return;
  717. }
  718. /**
  719. * Insert new record into database, as fast as possible, no safety checks, lobs not supported.
  720. * @param string $table name
  721. * @param mixed $params data record as object or array
  722. * @param bool $returnit return it of inserted record
  723. * @param bool $bulk true means repeated inserts expected
  724. * @param bool $customsequence true if 'id' included in $params, disables $returnid
  725. * @return bool|int true or new id
  726. * @throws dml_exception A DML specific exception is thrown for any errors.
  727. */
  728. public function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false) {
  729. if (!is_array($params)) {
  730. $params = (array)$params;
  731. }
  732. $returning = "";
  733. if ($customsequence) {
  734. if (!isset($params['id'])) {
  735. throw new coding_exception('moodle_database::insert_record_raw() id field must be specified if custom sequences used.');
  736. }
  737. $returnid = false;
  738. } else {
  739. if ($returnid) {
  740. $returning = "RETURNING id";
  741. unset($params['id']);
  742. } else {
  743. unset($params['id']);
  744. }
  745. }
  746. if (empty($params)) {
  747. throw new coding_exception('moodle_database::insert_record_raw() no fields found.');
  748. }
  749. $fields = implode(',', array_keys($params));
  750. $values = array();
  751. $i = 1;
  752. foreach ($params as $value) {
  753. $this->detect_objects($value);
  754. $values[] = "\$".$i++;
  755. }
  756. $values = implode(',', $values);
  757. $sql = "INSERT INTO {$this->prefix}$table ($fields) VALUES($values) $returning";
  758. $this->query_start($sql, $params, SQL_QUERY_INSERT);
  759. $result = pg_query_params($this->pgsql, $sql, $params);
  760. $this->query_end($result);
  761. if ($returning !== "") {
  762. $row = pg_fetch_assoc($result);
  763. $params['id'] = reset($row);
  764. }
  765. pg_free_result($result);
  766. if (!$returnid) {
  767. return true;
  768. }
  769. return (int)$params['id'];
  770. }
  771. /**
  772. * Insert a record into a table and return the "id" field if required.
  773. *
  774. * Some conversions and safety checks are carried out. Lobs are supported.
  775. * If the return ID isn't required, then this just reports success as true/false.
  776. * $data is an object containing needed data
  777. * @param string $table The database table to be inserted into
  778. * @param object $data A data object with values for one or more fields in the record
  779. * @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.
  780. * @return bool|int true or new id
  781. * @throws dml_exception A DML specific exception is thrown for any errors.
  782. */
  783. public function insert_record($table, $dataobject, $returnid=true, $bulk=false) {
  784. $dataobject = (array)$dataobject;
  785. $columns = $this->get_columns($table);
  786. $cleaned = array();
  787. $blobs = array();
  788. foreach ($dataobject as $field=>$value) {
  789. if ($field === 'id') {
  790. continue;
  791. }
  792. if (!isset($columns[$field])) {
  793. continue;
  794. }
  795. $column = $columns[$field];
  796. $normalised_value = $this->normalise_value($column, $value);
  797. if (is_array($normalised_value) && array_key_exists('blob', $normalised_value)) {
  798. $cleaned[$field] = '@#BLOB#@';
  799. $blobs[$field] = $normalised_value['blob'];
  800. } else {
  801. $cleaned[$field] = $normalised_value;
  802. }
  803. }
  804. if (empty($blobs)) {
  805. return $this->insert_record_raw($table, $cleaned, $returnid, $bulk);
  806. }
  807. $id = $this->insert_record_raw($table, $cleaned, true, $bulk);
  808. foreach ($blobs as $key=>$value) {
  809. $value = pg_escape_bytea($this->pgsql, $value);
  810. $sql = "UPDATE {$this->prefix}$table SET $key = '$value'::bytea WHERE id = $id";
  811. $this->query_start($sql, NULL, SQL_QUERY_UPDATE);
  812. $result = pg_query($this->pgsql, $sql);
  813. $this->query_end($result);
  814. if ($result !== false) {
  815. pg_free_result($result);
  816. }
  817. }
  818. return ($returnid ? $id : true);
  819. }
  820. /**
  821. * Import a record into a table, id field is required.
  822. * Safety checks are NOT carried out. Lobs are supported.
  823. *
  824. * @param string $table name of database table to be inserted into
  825. * @param object $dataobject A data object with values for one or more fields in the record
  826. * @return bool true
  827. * @throws dml_exception A DML specific exception is thrown for any errors.
  828. */
  829. public function import_record($table, $dataobject) {
  830. $dataobject = (array)$dataobject;
  831. $columns = $this->get_columns($table);
  832. $cleaned = array();
  833. $blobs = array();
  834. foreach ($dataobject as $field=>$value) {
  835. $this->detect_objects($value);
  836. if (!isset($columns[$field])) {
  837. continue;
  838. }
  839. if ($columns[$field]->meta_type === 'B') {
  840. if (!is_null($value)) {
  841. $cleaned[$field] = '@#BLOB#@';
  842. $blobs[$field] = $value;
  843. continue;
  844. }
  845. }
  846. $cleaned[$field] = $value;
  847. }
  848. $this->insert_record_raw($table, $cleaned, false, true, true);
  849. $id = $dataobject['id'];
  850. foreach ($blobs as $key=>$value) {
  851. $value = pg_escape_bytea($this->pgsql, $value);
  852. $sql = "UPDATE {$this->prefix}$table SET $key = '$value'::bytea WHERE id = $id";
  853. $this->query_start($sql, NULL, SQL_QUERY_UPDATE);
  854. $result = pg_query($this->pgsql, $sql);
  855. $this->query_end($result);
  856. if ($result !== false) {
  857. pg_free_result($result);
  858. }
  859. }
  860. return true;
  861. }
  862. /**
  863. * Update record in database, as fast as possible, no safety checks, lobs not supported.
  864. * @param string $table name
  865. * @param mixed $params data record as object or array
  866. * @param bool true means repeated updates expected
  867. * @return bool true
  868. * @throws dml_exception A DML specific exception is thrown for any errors.
  869. */
  870. public function update_record_raw($table, $params, $bulk=false) {
  871. $params = (array)$params;
  872. if (!isset($params['id'])) {
  873. throw new coding_exception('moodle_database::update_record_raw() id field must be specified.');
  874. }
  875. $id = $params['id'];
  876. unset($params['id']);
  877. if (empty($params)) {
  878. throw new coding_exception('moodle_database::update_record_raw() no fields found.');
  879. }
  880. $i = 1;
  881. $sets = array();
  882. foreach ($params as $field=>$value) {
  883. $this->detect_objects($value);
  884. $sets[] = "$field = \$".$i++;
  885. }
  886. $params[] = $id; // last ? in WHERE condition
  887. $sets = implode(',', $sets);
  888. $sql = "UPDATE {$this->prefix}$table SET $sets WHERE id=\$".$i;
  889. $this->query_start($sql, $params, SQL_QUERY_UPDATE);
  890. $result = pg_query_params($this->pgsql, $sql, $params);
  891. $this->query_end($result);
  892. pg_free_result($result);
  893. return true;
  894. }
  895. /**
  896. * Update a record in a table
  897. *
  898. * $dataobject is an object containing needed data
  899. * Relies on $dataobject having a variable "id" to
  900. * specify the record to update
  901. *
  902. * @param string $table The database table to be checked against.
  903. * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
  904. * @param bool true means repeated updates expected
  905. * @return bool true
  906. * @throws dml_exception A DML specific exception is thrown for any errors.
  907. */
  908. public function update_record($table, $dataobject, $bulk=false) {
  909. $dataobject = (array)$dataobject;
  910. $columns = $this->get_columns($table);
  911. $cleaned = array();
  912. $blobs = array();
  913. foreach ($dataobject as $field=>$value) {
  914. if (!isset($columns[$field])) {
  915. continue;
  916. }
  917. $column = $columns[$field];
  918. $normalised_value = $this->normalise_value($column, $value);
  919. if (is_array($normalised_value) && array_key_exists('blob', $normalised_value)) {
  920. $cleaned[$field] = '@#BLOB#@';
  921. $blobs[$field] = $normalised_value['blob'];
  922. } else {
  923. $cleaned[$field] = $normalised_value;
  924. }
  925. }
  926. $this->update_record_raw($table, $cleaned, $bulk);
  927. if (empty($blobs)) {
  928. return true;
  929. }
  930. $id = (int)$dataobject['id'];
  931. foreach ($blobs as $key=>$value) {
  932. $value = pg_escape_bytea($this->pgsql, $value);
  933. $sql = "UPDATE {$this->prefix}$table SET $key = '$value'::bytea WHERE id = $id";
  934. $this->query_start($sql, NULL, SQL_QUERY_UPDATE);
  935. $result = pg_query($this->pgsql, $sql);
  936. $this->query_end($result);
  937. pg_free_result($result);
  938. }
  939. return true;
  940. }
  941. /**
  942. * Set a single field in every table record which match a particular WHERE clause.
  943. *
  944. * @param string $table The database table to be checked against.
  945. * @param string $newfield the field to set.
  946. * @param string $newvalue the value to set the field to.
  947. * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
  948. * @param array $params array of sql parameters
  949. * @return bool true
  950. * @throws dml_exception A DML specific exception is thrown for any errors.
  951. */
  952. public function set_field_select($table, $newfield, $newvalue, $select, array $params=null) {
  953. if ($select) {
  954. $select = "WHERE $select";
  955. }
  956. if (is_null($params)) {
  957. $params = array();
  958. }
  959. list($select, $params, $type) = $this->fix_sql_params($select, $params);
  960. $i = count($params)+1;
  961. // Get column metadata
  962. $columns = $this->get_columns($table);
  963. $column = $columns[$newfield];
  964. $normalised_value = $this->normalise_value($column, $newvalue);
  965. if (is_array($normalised_value) && array_key_exists('blob', $normalised_value)) {
  966. // Update BYTEA and return
  967. $normalised_value = pg_escape_bytea($this->pgsql, $normalised_value['blob']);
  968. $sql = "UPDATE {$this->prefix}$table SET $newfield = '$normalised_value'::bytea $select";
  969. $this->query_start($sql, NULL, SQL_QUERY_UPDATE);
  970. $result = pg_query_params($this->pgsql, $sql, $params);
  971. $this->query_end($result);
  972. pg_free_result($result);
  973. return true;
  974. }
  975. if (is_null($normalised_value)) {
  976. $newfield = "$newfield = NULL";
  977. } else {
  978. $newfield = "$newfield = \$".$i;
  979. $params[] = $normalised_value;
  980. }
  981. $sql = "UPDATE {$this->prefix}$table SET $newfield $select";
  982. $this->query_start($sql, $params, SQL_QUERY_UPDATE);
  983. $result = pg_query_params($this->pgsql, $sql, $params);
  984. $this->query_end($result);
  985. pg_free_result($result);
  986. return true;
  987. }
  988. /**
  989. * Delete one or more records from a table which match a particular WHERE clause.
  990. *
  991. * @param string $table The database table to be checked against.
  992. * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
  993. * @param array $params array of sql parameters
  994. * @return bool true
  995. * @throws dml_exception A DML specific exception is thrown for any errors.
  996. */
  997. public function delete_records_select($table, $select, array $params=null) {
  998. if ($select) {
  999. $select = "WHERE $select";
  1000. }
  1001. $sql = "DELETE FROM {$this->prefix}$table $select";
  1002. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  1003. $this->query_start($sql, $params, SQL_QUERY_UPDATE);
  1004. $result = pg_query_params($this->pgsql, $sql, $params);
  1005. $this->query_end($result);
  1006. pg_free_result($result);
  1007. return true;
  1008. }
  1009. /**
  1010. * Returns 'LIKE' part of a query.
  1011. *
  1012. * @param string $fieldname usually name of the table column
  1013. * @param string $param usually bound query parameter (?, :named)
  1014. * @param bool $casesensitive use case sensitive search
  1015. * @param bool $accensensitive use accent sensitive search (not all databases support accent insensitive)
  1016. * @param bool $notlike true means "NOT LIKE"
  1017. * @param string $escapechar escape char for '%' and '_'
  1018. * @return string SQL code fragment
  1019. */
  1020. public function sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = '\\') {
  1021. if (strpos($param, '%') !== false) {
  1022. debugging('Potential SQL injection detected, sql_like() expects bound parameters (? or :named)');
  1023. }
  1024. if ($escapechar === '\\') {
  1025. // Prevents problems with C-style escapes of enclosing '\',
  1026. // E'... bellow prevents compatibility warnings.
  1027. $escapechar = '\\\\';
  1028. }
  1029. // postgresql does not support accent insensitive text comparisons, sorry
  1030. if ($casesensitive) {
  1031. $LIKE = $notlike ? 'NOT LIKE' : 'LIKE';
  1032. } else {
  1033. $LIKE = $notlike ? 'NOT ILIKE' : 'ILIKE';
  1034. }
  1035. return "$fieldname $LIKE $param ESCAPE E'$escapechar'";
  1036. }
  1037. public function sql_bitxor($int1, $int2) {
  1038. return '((' . $int1 . ') # (' . $int2 . '))';
  1039. }
  1040. public function sql_cast_char2int($fieldname, $text=false) {
  1041. return ' CAST(' . $fieldname . ' AS INT) ';
  1042. }
  1043. public function sql_cast_char2real($fieldname, $text=false) {
  1044. return " $fieldname::real ";
  1045. }
  1046. public function sql_concat() {
  1047. $arr = func_get_args();
  1048. $s = implode(' || ', $arr);
  1049. if ($s === '') {
  1050. return " '' ";
  1051. }
  1052. // Add always empty string element so integer-exclusive concats
  1053. // will work without needing to cast each element explicitly
  1054. return " '' || $s ";
  1055. }
  1056. public function sql_concat_join($separator="' '", $elements=array()) {
  1057. for ($n=count($elements)-1; $n > 0 ; $n--) {
  1058. array_splice($elements, $n, 0, $separator);
  1059. }
  1060. $s = implode(' || ', $elements);
  1061. if ($s === '') {
  1062. return " '' ";
  1063. }
  1064. return " $s ";
  1065. }
  1066. public function sql_regex_supported() {
  1067. return true;
  1068. }
  1069. public function sql_regex($positivematch=true) {
  1070. return $positivematch ? '~*' : '!~*';
  1071. }
  1072. public function session_lock_supported() {
  1073. return true;
  1074. }
  1075. /**
  1076. * Obtain session lock
  1077. * @param int $rowid id of the row with session record
  1078. * @param int $timeout max allowed time to wait for the lock in seconds
  1079. * @return bool success
  1080. */
  1081. public function get_session_lock($rowid, $timeout) {
  1082. // NOTE: there is a potential locking problem for database running
  1083. // multiple instances of moodle, we could try to use pg_advisory_lock(int, int),
  1084. // luckily there is not a big chance that they would collide
  1085. if (!$this->session_lock_supported()) {
  1086. return;
  1087. }
  1088. parent::get_session_lock($rowid, $timeout);
  1089. $timeoutmilli = $timeout * 1000;
  1090. $sql = "SET statement_timeout TO $timeoutmilli";
  1091. $this->query_start($sql, null, SQL_QUERY_AUX);
  1092. $result = pg_query($this->pgsql, $sql);
  1093. $this->query_end($result);
  1094. if ($result) {
  1095. pg_free_result($result);
  1096. }
  1097. $sql = "SELECT pg_advisory_lock($rowid)";
  1098. $this->query_start($sql, null, SQL_QUERY_AUX);
  1099. $start = time();
  1100. $result = pg_query($this->pgsql, $sql);
  1101. $end = time();
  1102. try {
  1103. $this->query_end($result);
  1104. } catch (dml_exception $ex) {
  1105. if ($end - $start >= $timeout) {
  1106. throw new dml_sessionwait_exception();
  1107. } else {
  1108. throw $ex;
  1109. }
  1110. }
  1111. if ($result) {
  1112. pg_free_result($result);
  1113. }
  1114. $sql = "SET statement_timeout TO DEFAULT";
  1115. $this->query_start($sql, null, SQL_QUERY_AUX);
  1116. $result = pg_query($this->pgsql, $sql);
  1117. $this->query_end($result);
  1118. if ($result) {
  1119. pg_free_result($result);
  1120. }
  1121. }
  1122. public function release_session_lock($rowid) {
  1123. if (!$this->session_lock_supported()) {
  1124. return;
  1125. }
  1126. if (!$this->used_for_db_sessions) {
  1127. return;
  1128. }
  1129. parent::release_session_lock($rowid);
  1130. $sql = "SELECT pg_advisory_unlock($rowid)";
  1131. $this->query_start($sql, null, SQL_QUERY_AUX);
  1132. $result = pg_query($this->pgsql, $sql);
  1133. $this->query_end($result);
  1134. if ($result) {
  1135. pg_free_result($result);
  1136. }
  1137. }
  1138. /**
  1139. * Driver specific start of real database transaction,
  1140. * this can not be used directly in code.
  1141. * @return void
  1142. */
  1143. protected function begin_transaction() {
  1144. $this->savepointpresent = true;
  1145. $sql = "BEGIN ISOLATION LEVEL READ COMMITTED; SAVEPOINT moodle_pg_savepoint";
  1146. $this->query_start($sql, NULL, SQL_QUERY_AUX);
  1147. $result = pg_query($this->pgsql, $sql);
  1148. $this->query_end($result);
  1149. pg_free_result($result);
  1150. }
  1151. /**
  1152. * Driver specific commit of real database transaction,
  1153. * this can not be used directly in code.
  1154. * @return void
  1155. */
  1156. protected function commit_transaction() {
  1157. $this->savepointpresent = false;
  1158. $sql = "RELEASE SAVEPOINT moodle_pg_savepoint; COMMIT";
  1159. $this->query_start($sql, NULL, SQL_QUERY_AUX);
  1160. $result = pg_query($this->pgsql, $sql);
  1161. $this->query_end($result);
  1162. pg_free_result($result);
  1163. }
  1164. /**
  1165. * Driver specific abort of real database transaction,
  1166. * this can not be used directly in code.
  1167. * @return void
  1168. */
  1169. protected functi