You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

620 lines
14 KiB

7 years ago
  1. <?php
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP
  6. *
  7. * This content is released under the MIT License (MIT)
  8. *
  9. * Copyright (c) 2014 - 2017, British Columbia Institute of Technology
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in
  19. * all copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. * THE SOFTWARE.
  28. *
  29. * @package CodeIgniter
  30. * @author EllisLab Dev Team
  31. * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
  32. * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
  33. * @license http://opensource.org/licenses/MIT MIT License
  34. * @link https://codeigniter.com
  35. * @since Version 1.3.0
  36. * @filesource
  37. */
  38. defined('BASEPATH') OR exit('No direct script access allowed');
  39. /**
  40. * Postgre Database Adapter Class
  41. *
  42. * Note: _DB is an extender class that the app controller
  43. * creates dynamically based on whether the query builder
  44. * class is being used or not.
  45. *
  46. * @package CodeIgniter
  47. * @subpackage Drivers
  48. * @category Database
  49. * @author EllisLab Dev Team
  50. * @link https://codeigniter.com/user_guide/database/
  51. */
  52. class CI_DB_postgre_driver extends CI_DB {
  53. /**
  54. * Database driver
  55. *
  56. * @var string
  57. */
  58. public $dbdriver = 'postgre';
  59. /**
  60. * Database schema
  61. *
  62. * @var string
  63. */
  64. public $schema = 'public';
  65. // --------------------------------------------------------------------
  66. /**
  67. * ORDER BY random keyword
  68. *
  69. * @var array
  70. */
  71. protected $_random_keyword = array('RANDOM()', 'RANDOM()');
  72. // --------------------------------------------------------------------
  73. /**
  74. * Class constructor
  75. *
  76. * Creates a DSN string to be used for db_connect() and db_pconnect()
  77. *
  78. * @param array $params
  79. * @return void
  80. */
  81. public function __construct($params)
  82. {
  83. parent::__construct($params);
  84. if ( ! empty($this->dsn))
  85. {
  86. return;
  87. }
  88. $this->dsn === '' OR $this->dsn = '';
  89. if (strpos($this->hostname, '/') !== FALSE)
  90. {
  91. // If UNIX sockets are used, we shouldn't set a port
  92. $this->port = '';
  93. }
  94. $this->hostname === '' OR $this->dsn = 'host='.$this->hostname.' ';
  95. if ( ! empty($this->port) && ctype_digit($this->port))
  96. {
  97. $this->dsn .= 'port='.$this->port.' ';
  98. }
  99. if ($this->username !== '')
  100. {
  101. $this->dsn .= 'user='.$this->username.' ';
  102. /* An empty password is valid!
  103. *
  104. * $db['password'] = NULL must be done in order to ignore it.
  105. */
  106. $this->password === NULL OR $this->dsn .= "password='".$this->password."' ";
  107. }
  108. $this->database === '' OR $this->dsn .= 'dbname='.$this->database.' ';
  109. /* We don't have these options as elements in our standard configuration
  110. * array, but they might be set by parse_url() if the configuration was
  111. * provided via string. Example:
  112. *
  113. * postgre://username:password@localhost:5432/database?connect_timeout=5&sslmode=1
  114. */
  115. foreach (array('connect_timeout', 'options', 'sslmode', 'service') as $key)
  116. {
  117. if (isset($this->$key) && is_string($this->$key) && $this->$key !== '')
  118. {
  119. $this->dsn .= $key."='".$this->$key."' ";
  120. }
  121. }
  122. $this->dsn = rtrim($this->dsn);
  123. }
  124. // --------------------------------------------------------------------
  125. /**
  126. * Database connection
  127. *
  128. * @param bool $persistent
  129. * @return resource
  130. */
  131. public function db_connect($persistent = FALSE)
  132. {
  133. $this->conn_id = ($persistent === TRUE)
  134. ? pg_pconnect($this->dsn)
  135. : pg_connect($this->dsn);
  136. if ($this->conn_id !== FALSE)
  137. {
  138. if ($persistent === TRUE
  139. && pg_connection_status($this->conn_id) === PGSQL_CONNECTION_BAD
  140. && pg_ping($this->conn_id) === FALSE
  141. )
  142. {
  143. return FALSE;
  144. }
  145. empty($this->schema) OR $this->simple_query('SET search_path TO '.$this->schema.',public');
  146. }
  147. return $this->conn_id;
  148. }
  149. // --------------------------------------------------------------------
  150. /**
  151. * Reconnect
  152. *
  153. * Keep / reestablish the db connection if no queries have been
  154. * sent for a length of time exceeding the server's idle timeout
  155. *
  156. * @return void
  157. */
  158. public function reconnect()
  159. {
  160. if (pg_ping($this->conn_id) === FALSE)
  161. {
  162. $this->conn_id = FALSE;
  163. }
  164. }
  165. // --------------------------------------------------------------------
  166. /**
  167. * Set client character set
  168. *
  169. * @param string $charset
  170. * @return bool
  171. */
  172. protected function _db_set_charset($charset)
  173. {
  174. return (pg_set_client_encoding($this->conn_id, $charset) === 0);
  175. }
  176. // --------------------------------------------------------------------
  177. /**
  178. * Database version number
  179. *
  180. * @return string
  181. */
  182. public function version()
  183. {
  184. if (isset($this->data_cache['version']))
  185. {
  186. return $this->data_cache['version'];
  187. }
  188. if ( ! $this->conn_id OR ($pg_version = pg_version($this->conn_id)) === FALSE)
  189. {
  190. return FALSE;
  191. }
  192. /* If PHP was compiled with PostgreSQL lib versions earlier
  193. * than 7.4, pg_version() won't return the server version
  194. * and so we'll have to fall back to running a query in
  195. * order to get it.
  196. */
  197. return isset($pg_version['server'])
  198. ? $this->data_cache['version'] = $pg_version['server']
  199. : parent::version();
  200. }
  201. // --------------------------------------------------------------------
  202. /**
  203. * Execute the query
  204. *
  205. * @param string $sql an SQL query
  206. * @return resource
  207. */
  208. protected function _execute($sql)
  209. {
  210. return pg_query($this->conn_id, $sql);
  211. }
  212. // --------------------------------------------------------------------
  213. /**
  214. * Begin Transaction
  215. *
  216. * @return bool
  217. */
  218. protected function _trans_begin()
  219. {
  220. return (bool) pg_query($this->conn_id, 'BEGIN');
  221. }
  222. // --------------------------------------------------------------------
  223. /**
  224. * Commit Transaction
  225. *
  226. * @return bool
  227. */
  228. protected function _trans_commit()
  229. {
  230. return (bool) pg_query($this->conn_id, 'COMMIT');
  231. }
  232. // --------------------------------------------------------------------
  233. /**
  234. * Rollback Transaction
  235. *
  236. * @return bool
  237. */
  238. protected function _trans_rollback()
  239. {
  240. return (bool) pg_query($this->conn_id, 'ROLLBACK');
  241. }
  242. // --------------------------------------------------------------------
  243. /**
  244. * Determines if a query is a "write" type.
  245. *
  246. * @param string An SQL query string
  247. * @return bool
  248. */
  249. public function is_write_type($sql)
  250. {
  251. if (preg_match('#^(INSERT|UPDATE).*RETURNING\s.+(\,\s?.+)*$#is', $sql))
  252. {
  253. return FALSE;
  254. }
  255. return parent::is_write_type($sql);
  256. }
  257. // --------------------------------------------------------------------
  258. /**
  259. * Platform-dependent string escape
  260. *
  261. * @param string
  262. * @return string
  263. */
  264. protected function _escape_str($str)
  265. {
  266. return pg_escape_string($this->conn_id, $str);
  267. }
  268. // --------------------------------------------------------------------
  269. /**
  270. * "Smart" Escape String
  271. *
  272. * Escapes data based on type
  273. *
  274. * @param string $str
  275. * @return mixed
  276. */
  277. public function escape($str)
  278. {
  279. if (is_php('5.4.4') && (is_string($str) OR (is_object($str) && method_exists($str, '__toString'))))
  280. {
  281. return pg_escape_literal($this->conn_id, $str);
  282. }
  283. elseif (is_bool($str))
  284. {
  285. return ($str) ? 'TRUE' : 'FALSE';
  286. }
  287. return parent::escape($str);
  288. }
  289. // --------------------------------------------------------------------
  290. /**
  291. * Affected Rows
  292. *
  293. * @return int
  294. */
  295. public function affected_rows()
  296. {
  297. return pg_affected_rows($this->result_id);
  298. }
  299. // --------------------------------------------------------------------
  300. /**
  301. * Insert ID
  302. *
  303. * @return string
  304. */
  305. public function insert_id()
  306. {
  307. $v = pg_version($this->conn_id);
  308. $v = isset($v['server']) ? $v['server'] : 0; // 'server' key is only available since PosgreSQL 7.4
  309. $table = (func_num_args() > 0) ? func_get_arg(0) : NULL;
  310. $column = (func_num_args() > 1) ? func_get_arg(1) : NULL;
  311. if ($table === NULL && $v >= '8.1')
  312. {
  313. $sql = 'SELECT LASTVAL() AS ins_id';
  314. }
  315. elseif ($table !== NULL)
  316. {
  317. if ($column !== NULL && $v >= '8.0')
  318. {
  319. $sql = 'SELECT pg_get_serial_sequence(\''.$table."', '".$column."') AS seq";
  320. $query = $this->query($sql);
  321. $query = $query->row();
  322. $seq = $query->seq;
  323. }
  324. else
  325. {
  326. // seq_name passed in table parameter
  327. $seq = $table;
  328. }
  329. $sql = 'SELECT CURRVAL(\''.$seq."') AS ins_id";
  330. }
  331. else
  332. {
  333. return pg_last_oid($this->result_id);
  334. }
  335. $query = $this->query($sql);
  336. $query = $query->row();
  337. return (int) $query->ins_id;
  338. }
  339. // --------------------------------------------------------------------
  340. /**
  341. * Show table query
  342. *
  343. * Generates a platform-specific query string so that the table names can be fetched
  344. *
  345. * @param bool $prefix_limit
  346. * @return string
  347. */
  348. protected function _list_tables($prefix_limit = FALSE)
  349. {
  350. $sql = 'SELECT "table_name" FROM "information_schema"."tables" WHERE "table_schema" = \''.$this->schema."'";
  351. if ($prefix_limit !== FALSE && $this->dbprefix !== '')
  352. {
  353. return $sql.' AND "table_name" LIKE \''
  354. .$this->escape_like_str($this->dbprefix)."%' "
  355. .sprintf($this->_like_escape_str, $this->_like_escape_chr);
  356. }
  357. return $sql;
  358. }
  359. // --------------------------------------------------------------------
  360. /**
  361. * List column query
  362. *
  363. * Generates a platform-specific query string so that the column names can be fetched
  364. *
  365. * @param string $table
  366. * @return string
  367. */
  368. protected function _list_columns($table = '')
  369. {
  370. return 'SELECT "column_name"
  371. FROM "information_schema"."columns"
  372. WHERE LOWER("table_name") = '.$this->escape(strtolower($table));
  373. }
  374. // --------------------------------------------------------------------
  375. /**
  376. * Returns an object with field data
  377. *
  378. * @param string $table
  379. * @return array
  380. */
  381. public function field_data($table)
  382. {
  383. $sql = 'SELECT "column_name", "data_type", "character_maximum_length", "numeric_precision", "column_default"
  384. FROM "information_schema"."columns"
  385. WHERE LOWER("table_name") = '.$this->escape(strtolower($table));
  386. if (($query = $this->query($sql)) === FALSE)
  387. {
  388. return FALSE;
  389. }
  390. $query = $query->result_object();
  391. $retval = array();
  392. for ($i = 0, $c = count($query); $i < $c; $i++)
  393. {
  394. $retval[$i] = new stdClass();
  395. $retval[$i]->name = $query[$i]->column_name;
  396. $retval[$i]->type = $query[$i]->data_type;
  397. $retval[$i]->max_length = ($query[$i]->character_maximum_length > 0) ? $query[$i]->character_maximum_length : $query[$i]->numeric_precision;
  398. $retval[$i]->default = $query[$i]->column_default;
  399. }
  400. return $retval;
  401. }
  402. // --------------------------------------------------------------------
  403. /**
  404. * Error
  405. *
  406. * Returns an array containing code and message of the last
  407. * database error that has occurred.
  408. *
  409. * @return array
  410. */
  411. public function error()
  412. {
  413. return array('code' => '', 'message' => pg_last_error($this->conn_id));
  414. }
  415. // --------------------------------------------------------------------
  416. /**
  417. * ORDER BY
  418. *
  419. * @param string $orderby
  420. * @param string $direction ASC, DESC or RANDOM
  421. * @param bool $escape
  422. * @return object
  423. */
  424. public function order_by($orderby, $direction = '', $escape = NULL)
  425. {
  426. $direction = strtoupper(trim($direction));
  427. if ($direction === 'RANDOM')
  428. {
  429. if ( ! is_float($orderby) && ctype_digit((string) $orderby))
  430. {
  431. $orderby = ($orderby > 1)
  432. ? (float) '0.'.$orderby
  433. : (float) $orderby;
  434. }
  435. if (is_float($orderby))
  436. {
  437. $this->simple_query('SET SEED '.$orderby);
  438. }
  439. $orderby = $this->_random_keyword[0];
  440. $direction = '';
  441. $escape = FALSE;
  442. }
  443. return parent::order_by($orderby, $direction, $escape);
  444. }
  445. // --------------------------------------------------------------------
  446. /**
  447. * Update statement
  448. *
  449. * Generates a platform-specific update string from the supplied data
  450. *
  451. * @param string $table
  452. * @param array $values
  453. * @return string
  454. */
  455. protected function _update($table, $values)
  456. {
  457. $this->qb_limit = FALSE;
  458. $this->qb_orderby = array();
  459. return parent::_update($table, $values);
  460. }
  461. // --------------------------------------------------------------------
  462. /**
  463. * Update_Batch statement
  464. *
  465. * Generates a platform-specific batch update string from the supplied data
  466. *
  467. * @param string $table Table name
  468. * @param array $values Update data
  469. * @param string $index WHERE key
  470. * @return string
  471. */
  472. protected function _update_batch($table, $values, $index)
  473. {
  474. $ids = array();
  475. foreach ($values as $key => $val)
  476. {
  477. $ids[] = $val[$index]['value'];
  478. foreach (array_keys($val) as $field)
  479. {
  480. if ($field !== $index)
  481. {
  482. $final[$val[$field]['field']][] = 'WHEN '.$val[$index]['value'].' THEN '.$val[$field]['value'];
  483. }
  484. }
  485. }
  486. $cases = '';
  487. foreach ($final as $k => $v)
  488. {
  489. $cases .= $k.' = (CASE '.$val[$index]['field']."\n"
  490. .implode("\n", $v)."\n"
  491. .'ELSE '.$k.' END), ';
  492. }
  493. $this->where($val[$index]['field'].' IN('.implode(',', $ids).')', NULL, FALSE);
  494. return 'UPDATE '.$table.' SET '.substr($cases, 0, -2).$this->_compile_wh('qb_where');
  495. }
  496. // --------------------------------------------------------------------
  497. /**
  498. * Delete statement
  499. *
  500. * Generates a platform-specific delete string from the supplied data
  501. *
  502. * @param string $table
  503. * @return string
  504. */
  505. protected function _delete($table)
  506. {
  507. $this->qb_limit = FALSE;
  508. return parent::_delete($table);
  509. }
  510. // --------------------------------------------------------------------
  511. /**
  512. * LIMIT
  513. *
  514. * Generates a platform-specific LIMIT clause
  515. *
  516. * @param string $sql SQL Query
  517. * @return string
  518. */
  519. protected function _limit($sql)
  520. {
  521. return $sql.' LIMIT '.$this->qb_limit.($this->qb_offset ? ' OFFSET '.$this->qb_offset : '');
  522. }
  523. // --------------------------------------------------------------------
  524. /**
  525. * Close DB Connection
  526. *
  527. * @return void
  528. */
  529. protected function _close()
  530. {
  531. pg_close($this->conn_id);
  532. }
  533. }