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

/cake/libs/model/datasources/dbo/dbo_postgres.php

http://github.com/Datawalke/Coordino
PHP | 978 lines | 649 code | 75 blank | 254 comment | 153 complexity | 44968479282ed135cf6d6ed083e02b8d MD5 | raw file
  1. <?php
  2. /**
  3. * PostgreSQL layer for DBO.
  4. *
  5. * PHP versions 4 and 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package cake
  16. * @subpackage cake.cake.libs.model.datasources.dbo
  17. * @since CakePHP(tm) v 0.9.1.114
  18. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  19. */
  20. /**
  21. * PostgreSQL layer for DBO.
  22. *
  23. * Long description for class
  24. *
  25. * @package cake
  26. * @subpackage cake.cake.libs.model.datasources.dbo
  27. */
  28. class DboPostgres extends DboSource {
  29. /**
  30. * Driver description
  31. *
  32. * @var string
  33. * @access public
  34. */
  35. var $description = "PostgreSQL DBO Driver";
  36. /**
  37. * Index of basic SQL commands
  38. *
  39. * @var array
  40. * @access protected
  41. */
  42. var $_commands = array(
  43. 'begin' => 'BEGIN',
  44. 'commit' => 'COMMIT',
  45. 'rollback' => 'ROLLBACK'
  46. );
  47. /**
  48. * Base driver configuration settings. Merged with user settings.
  49. *
  50. * @var array
  51. * @access protected
  52. */
  53. var $_baseConfig = array(
  54. 'persistent' => true,
  55. 'host' => 'localhost',
  56. 'login' => 'root',
  57. 'password' => '',
  58. 'database' => 'cake',
  59. 'schema' => 'public',
  60. 'port' => 5432,
  61. 'encoding' => ''
  62. );
  63. var $columns = array(
  64. 'primary_key' => array('name' => 'serial NOT NULL'),
  65. 'string' => array('name' => 'varchar', 'limit' => '255'),
  66. 'text' => array('name' => 'text'),
  67. 'integer' => array('name' => 'integer', 'formatter' => 'intval'),
  68. 'float' => array('name' => 'float', 'formatter' => 'floatval'),
  69. 'datetime' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
  70. 'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
  71. 'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
  72. 'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
  73. 'binary' => array('name' => 'bytea'),
  74. 'boolean' => array('name' => 'boolean'),
  75. 'number' => array('name' => 'numeric'),
  76. 'inet' => array('name' => 'inet')
  77. );
  78. /**
  79. * Starting Quote
  80. *
  81. * @var string
  82. * @access public
  83. */
  84. var $startQuote = '"';
  85. /**
  86. * Ending Quote
  87. *
  88. * @var string
  89. * @access public
  90. */
  91. var $endQuote = '"';
  92. /**
  93. * Contains mappings of custom auto-increment sequences, if a table uses a sequence name
  94. * other than what is dictated by convention.
  95. *
  96. * @var array
  97. */
  98. var $_sequenceMap = array();
  99. /**
  100. * Connects to the database using options in the given configuration array.
  101. *
  102. * @return True if successfully connected.
  103. */
  104. function connect() {
  105. $config = $this->config;
  106. $conn = "host='{$config['host']}' port='{$config['port']}' dbname='{$config['database']}' ";
  107. $conn .= "user='{$config['login']}' password='{$config['password']}'";
  108. if (!$config['persistent']) {
  109. $this->connection = pg_connect($conn, PGSQL_CONNECT_FORCE_NEW);
  110. } else {
  111. $this->connection = pg_pconnect($conn);
  112. }
  113. $this->connected = false;
  114. if ($this->connection) {
  115. $this->connected = true;
  116. $this->_execute("SET search_path TO " . $config['schema']);
  117. }
  118. if (!empty($config['encoding'])) {
  119. $this->setEncoding($config['encoding']);
  120. }
  121. return $this->connected;
  122. }
  123. /**
  124. * Check if PostgreSQL is enabled/loaded
  125. *
  126. * @return boolean
  127. */
  128. function enabled() {
  129. return extension_loaded('pgsql');
  130. }
  131. /**
  132. * Disconnects from database.
  133. *
  134. * @return boolean True if the database could be disconnected, else false
  135. */
  136. function disconnect() {
  137. if ($this->hasResult()) {
  138. pg_free_result($this->_result);
  139. }
  140. if (is_resource($this->connection)) {
  141. $this->connected = !pg_close($this->connection);
  142. } else {
  143. $this->connected = false;
  144. }
  145. return !$this->connected;
  146. }
  147. /**
  148. * Executes given SQL statement.
  149. *
  150. * @param string $sql SQL statement
  151. * @return resource Result resource identifier
  152. */
  153. function _execute($sql) {
  154. return pg_query($this->connection, $sql);
  155. }
  156. /**
  157. * Returns an array of tables in the database. If there are no tables, an error is raised and the application exits.
  158. *
  159. * @return array Array of tablenames in the database
  160. */
  161. function listSources() {
  162. $cache = parent::listSources();
  163. if ($cache != null) {
  164. return $cache;
  165. }
  166. $schema = $this->config['schema'];
  167. $sql = "SELECT table_name as name FROM INFORMATION_SCHEMA.tables WHERE table_schema = '{$schema}';";
  168. $result = $this->fetchAll($sql, false);
  169. if (!$result) {
  170. return array();
  171. } else {
  172. $tables = array();
  173. foreach ($result as $item) {
  174. $tables[] = $item[0]['name'];
  175. }
  176. parent::listSources($tables);
  177. return $tables;
  178. }
  179. }
  180. /**
  181. * Returns an array of the fields in given table name.
  182. *
  183. * @param string $tableName Name of database table to inspect
  184. * @return array Fields in table. Keys are name and type
  185. */
  186. function &describe(&$model) {
  187. $fields = parent::describe($model);
  188. $table = $this->fullTableName($model, false);
  189. $this->_sequenceMap[$table] = array();
  190. if ($fields === null) {
  191. $cols = $this->fetchAll(
  192. "SELECT DISTINCT column_name AS name, data_type AS type, is_nullable AS null,
  193. column_default AS default, ordinal_position AS position, character_maximum_length AS char_length,
  194. character_octet_length AS oct_length FROM information_schema.columns
  195. WHERE table_name = " . $this->value($table) . " AND table_schema = " .
  196. $this->value($this->config['schema'])." ORDER BY position",
  197. false
  198. );
  199. foreach ($cols as $column) {
  200. $colKey = array_keys($column);
  201. if (isset($column[$colKey[0]]) && !isset($column[0])) {
  202. $column[0] = $column[$colKey[0]];
  203. }
  204. if (isset($column[0])) {
  205. $c = $column[0];
  206. if (!empty($c['char_length'])) {
  207. $length = intval($c['char_length']);
  208. } elseif (!empty($c['oct_length'])) {
  209. if ($c['type'] == 'character varying') {
  210. $length = null;
  211. $c['type'] = 'text';
  212. } else {
  213. $length = intval($c['oct_length']);
  214. }
  215. } else {
  216. $length = $this->length($c['type']);
  217. }
  218. $fields[$c['name']] = array(
  219. 'type' => $this->column($c['type']),
  220. 'null' => ($c['null'] == 'NO' ? false : true),
  221. 'default' => preg_replace(
  222. "/^'(.*)'$/",
  223. "$1",
  224. preg_replace('/::.*/', '', $c['default'])
  225. ),
  226. 'length' => $length
  227. );
  228. if ($c['name'] == $model->primaryKey) {
  229. $fields[$c['name']]['key'] = 'primary';
  230. if ($fields[$c['name']]['type'] !== 'string') {
  231. $fields[$c['name']]['length'] = 11;
  232. }
  233. }
  234. if (
  235. $fields[$c['name']]['default'] == 'NULL' ||
  236. preg_match('/nextval\([\'"]?([\w.]+)/', $c['default'], $seq)
  237. ) {
  238. $fields[$c['name']]['default'] = null;
  239. if (!empty($seq) && isset($seq[1])) {
  240. $this->_sequenceMap[$table][$c['name']] = $seq[1];
  241. }
  242. }
  243. if ($fields[$c['name']]['type'] == 'boolean' && !empty($fields[$c['name']]['default'])) {
  244. $fields[$c['name']]['default'] = constant($fields[$c['name']]['default']);
  245. }
  246. }
  247. }
  248. $this->__cacheDescription($table, $fields);
  249. }
  250. if (isset($model->sequence)) {
  251. $this->_sequenceMap[$table][$model->primaryKey] = $model->sequence;
  252. }
  253. return $fields;
  254. }
  255. /**
  256. * Returns a quoted and escaped string of $data for use in an SQL statement.
  257. *
  258. * @param string $data String to be prepared for use in an SQL statement
  259. * @param string $column The column into which this data will be inserted
  260. * @param boolean $read Value to be used in READ or WRITE context
  261. * @return string Quoted and escaped
  262. * @todo Add logic that formats/escapes data based on column type
  263. */
  264. function value($data, $column = null, $read = true) {
  265. $parent = parent::value($data, $column);
  266. if ($parent != null) {
  267. return $parent;
  268. }
  269. if ($data === null || (is_array($data) && empty($data))) {
  270. return 'NULL';
  271. }
  272. if (empty($column)) {
  273. $column = $this->introspectType($data);
  274. }
  275. switch($column) {
  276. case 'binary':
  277. $data = pg_escape_bytea($data);
  278. break;
  279. case 'boolean':
  280. if ($data === true || $data === 't' || $data === 'true') {
  281. return 'TRUE';
  282. } elseif ($data === false || $data === 'f' || $data === 'false') {
  283. return 'FALSE';
  284. }
  285. return (!empty($data) ? 'TRUE' : 'FALSE');
  286. break;
  287. case 'float':
  288. if (is_float($data)) {
  289. $data = sprintf('%F', $data);
  290. }
  291. case 'inet':
  292. case 'integer':
  293. case 'date':
  294. case 'datetime':
  295. case 'timestamp':
  296. case 'time':
  297. if ($data === '') {
  298. return $read ? 'NULL' : 'DEFAULT';
  299. }
  300. default:
  301. $data = pg_escape_string($data);
  302. break;
  303. }
  304. return "'" . $data . "'";
  305. }
  306. /**
  307. * Returns a formatted error message from previous database operation.
  308. *
  309. * @return string Error message
  310. */
  311. function lastError() {
  312. $error = pg_last_error($this->connection);
  313. return ($error) ? $error : null;
  314. }
  315. /**
  316. * Returns number of affected rows in previous database operation. If no previous operation exists, this returns false.
  317. *
  318. * @return integer Number of affected rows
  319. */
  320. function lastAffected() {
  321. return ($this->_result) ? pg_affected_rows($this->_result) : false;
  322. }
  323. /**
  324. * Returns number of rows in previous resultset. If no previous resultset exists,
  325. * this returns false.
  326. *
  327. * @return integer Number of rows in resultset
  328. */
  329. function lastNumRows() {
  330. return ($this->_result) ? pg_num_rows($this->_result) : false;
  331. }
  332. /**
  333. * Returns the ID generated from the previous INSERT operation.
  334. *
  335. * @param string $source Name of the database table
  336. * @param string $field Name of the ID database field. Defaults to "id"
  337. * @return integer
  338. */
  339. function lastInsertId($source, $field = 'id') {
  340. $seq = $this->getSequence($source, $field);
  341. $data = $this->fetchRow("SELECT currval('{$seq}') as max");
  342. return $data[0]['max'];
  343. }
  344. /**
  345. * Gets the associated sequence for the given table/field
  346. *
  347. * @param mixed $table Either a full table name (with prefix) as a string, or a model object
  348. * @param string $field Name of the ID database field. Defaults to "id"
  349. * @return string The associated sequence name from the sequence map, defaults to "{$table}_{$field}_seq"
  350. */
  351. function getSequence($table, $field = 'id') {
  352. if (is_object($table)) {
  353. $table = $this->fullTableName($table, false);
  354. }
  355. if (isset($this->_sequenceMap[$table]) && isset($this->_sequenceMap[$table][$field])) {
  356. return $this->_sequenceMap[$table][$field];
  357. } else {
  358. return "{$table}_{$field}_seq";
  359. }
  360. }
  361. /**
  362. * Deletes all the records in a table and drops all associated auto-increment sequences
  363. *
  364. * @param mixed $table A string or model class representing the table to be truncated
  365. * @param integer $reset If -1, sequences are dropped, if 0 (default), sequences are reset,
  366. * and if 1, sequences are not modified
  367. * @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
  368. * @access public
  369. */
  370. function truncate($table, $reset = 0) {
  371. if ($this->execute('DELETE FROM ' . $this->fullTableName($table))) {
  372. $table = $this->fullTableName($table, false);
  373. if (isset($this->_sequenceMap[$table]) && $reset !== 1) {
  374. foreach ($this->_sequenceMap[$table] as $field => $sequence) {
  375. if ($reset === 0) {
  376. $this->execute("ALTER SEQUENCE \"{$sequence}\" RESTART WITH 1");
  377. } elseif ($reset === -1) {
  378. $this->execute("DROP SEQUENCE IF EXISTS \"{$sequence}\"");
  379. }
  380. }
  381. }
  382. return true;
  383. }
  384. return false;
  385. }
  386. /**
  387. * Prepares field names to be quoted by parent
  388. *
  389. * @param string $data
  390. * @return string SQL field
  391. */
  392. function name($data) {
  393. if (is_string($data)) {
  394. $data = str_replace('"__"', '__', $data);
  395. }
  396. return parent::name($data);
  397. }
  398. /**
  399. * Generates the fields list of an SQL query.
  400. *
  401. * @param Model $model
  402. * @param string $alias Alias tablename
  403. * @param mixed $fields
  404. * @return array
  405. */
  406. function fields(&$model, $alias = null, $fields = array(), $quote = true) {
  407. if (empty($alias)) {
  408. $alias = $model->alias;
  409. }
  410. $fields = parent::fields($model, $alias, $fields, false);
  411. if (!$quote) {
  412. return $fields;
  413. }
  414. $count = count($fields);
  415. if ($count >= 1 && strpos($fields[0], 'COUNT(*)') === false) {
  416. $result = array();
  417. for ($i = 0; $i < $count; $i++) {
  418. if (!preg_match('/^.+\\(.*\\)/', $fields[$i]) && !preg_match('/\s+AS\s+/', $fields[$i])) {
  419. if (substr($fields[$i], -1) == '*') {
  420. if (strpos($fields[$i], '.') !== false && $fields[$i] != $alias . '.*') {
  421. $build = explode('.', $fields[$i]);
  422. $AssociatedModel = $model->{$build[0]};
  423. } else {
  424. $AssociatedModel = $model;
  425. }
  426. $_fields = $this->fields($AssociatedModel, $AssociatedModel->alias, array_keys($AssociatedModel->schema()));
  427. $result = array_merge($result, $_fields);
  428. continue;
  429. }
  430. $prepend = '';
  431. if (strpos($fields[$i], 'DISTINCT') !== false) {
  432. $prepend = 'DISTINCT ';
  433. $fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
  434. }
  435. if (strrpos($fields[$i], '.') === false) {
  436. $fields[$i] = $prepend . $this->name($alias) . '.' . $this->name($fields[$i]) . ' AS ' . $this->name($alias . '__' . $fields[$i]);
  437. } else {
  438. $build = explode('.', $fields[$i]);
  439. $fields[$i] = $prepend . $this->name($build[0]) . '.' . $this->name($build[1]) . ' AS ' . $this->name($build[0] . '__' . $build[1]);
  440. }
  441. } else {
  442. $fields[$i] = preg_replace_callback('/\(([\s\.\w]+)\)/', array(&$this, '__quoteFunctionField'), $fields[$i]);
  443. }
  444. $result[] = $fields[$i];
  445. }
  446. return $result;
  447. }
  448. return $fields;
  449. }
  450. /**
  451. * Auxiliary function to quote matched `(Model.fields)` from a preg_replace_callback call
  452. * Quotes the fields in a function call.
  453. *
  454. * @param string matched string
  455. * @return string quoted strig
  456. * @access private
  457. */
  458. function __quoteFunctionField($match) {
  459. $prepend = '';
  460. if (strpos($match[1], 'DISTINCT') !== false) {
  461. $prepend = 'DISTINCT ';
  462. $match[1] = trim(str_replace('DISTINCT', '', $match[1]));
  463. }
  464. $constant = preg_match('/^\d+|NULL|FALSE|TRUE$/i', $match[1]);
  465. if (!$constant && strpos($match[1], '.') === false) {
  466. $match[1] = $this->name($match[1]);
  467. } elseif (!$constant){
  468. $parts = explode('.', $match[1]);
  469. if (!Set::numeric($parts)) {
  470. $match[1] = $this->name($match[1]);
  471. }
  472. }
  473. return '(' . $prepend .$match[1] . ')';
  474. }
  475. /**
  476. * Returns an array of the indexes in given datasource name.
  477. *
  478. * @param string $model Name of model to inspect
  479. * @return array Fields in table. Keys are column and unique
  480. */
  481. function index($model) {
  482. $index = array();
  483. $table = $this->fullTableName($model, false);
  484. if ($table) {
  485. $indexes = $this->query("SELECT c2.relname, i.indisprimary, i.indisunique, i.indisclustered, i.indisvalid, pg_catalog.pg_get_indexdef(i.indexrelid, 0, true) as statement, c2.reltablespace
  486. FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i
  487. WHERE c.oid = (
  488. SELECT c.oid
  489. FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
  490. WHERE c.relname ~ '^(" . $table . ")$'
  491. AND pg_catalog.pg_table_is_visible(c.oid)
  492. AND n.nspname ~ '^(" . $this->config['schema'] . ")$'
  493. )
  494. AND c.oid = i.indrelid AND i.indexrelid = c2.oid
  495. ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname", false);
  496. foreach ($indexes as $i => $info) {
  497. $key = array_pop($info);
  498. if ($key['indisprimary']) {
  499. $key['relname'] = 'PRIMARY';
  500. }
  501. $col = array();
  502. preg_match('/\(([^\)]+)\)/', $key['statement'], $indexColumns);
  503. $parsedColumn = $indexColumns[1];
  504. if (strpos($indexColumns[1], ',') !== false) {
  505. $parsedColumn = explode(', ', $indexColumns[1]);
  506. }
  507. $index[$key['relname']]['unique'] = $key['indisunique'];
  508. $index[$key['relname']]['column'] = $parsedColumn;
  509. }
  510. }
  511. return $index;
  512. }
  513. /**
  514. * Alter the Schema of a table.
  515. *
  516. * @param array $compare Results of CakeSchema::compare()
  517. * @param string $table name of the table
  518. * @access public
  519. * @return array
  520. */
  521. function alterSchema($compare, $table = null) {
  522. if (!is_array($compare)) {
  523. return false;
  524. }
  525. $out = '';
  526. $colList = array();
  527. foreach ($compare as $curTable => $types) {
  528. $indexes = $colList = array();
  529. if (!$table || $table == $curTable) {
  530. $out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n";
  531. foreach ($types as $type => $column) {
  532. if (isset($column['indexes'])) {
  533. $indexes[$type] = $column['indexes'];
  534. unset($column['indexes']);
  535. }
  536. switch ($type) {
  537. case 'add':
  538. foreach ($column as $field => $col) {
  539. $col['name'] = $field;
  540. $colList[] = 'ADD COLUMN '.$this->buildColumn($col);
  541. }
  542. break;
  543. case 'drop':
  544. foreach ($column as $field => $col) {
  545. $col['name'] = $field;
  546. $colList[] = 'DROP COLUMN '.$this->name($field);
  547. }
  548. break;
  549. case 'change':
  550. foreach ($column as $field => $col) {
  551. if (!isset($col['name'])) {
  552. $col['name'] = $field;
  553. }
  554. $fieldName = $this->name($field);
  555. $default = isset($col['default']) ? $col['default'] : null;
  556. $nullable = isset($col['null']) ? $col['null'] : null;
  557. unset($col['default'], $col['null']);
  558. $colList[] = 'ALTER COLUMN '. $fieldName .' TYPE ' . str_replace(array($fieldName, 'NOT NULL'), '', $this->buildColumn($col));
  559. if (isset($nullable)) {
  560. $nullable = ($nullable) ? 'DROP NOT NULL' : 'SET NOT NULL';
  561. $colList[] = 'ALTER COLUMN '. $fieldName .' ' . $nullable;
  562. }
  563. if (isset($default)) {
  564. $colList[] = 'ALTER COLUMN '. $fieldName .' SET DEFAULT ' . $this->value($default, $col['type']);
  565. } else {
  566. $colList[] = 'ALTER COLUMN '. $fieldName .' DROP DEFAULT';
  567. }
  568. }
  569. break;
  570. }
  571. }
  572. if (isset($indexes['drop']['PRIMARY'])) {
  573. $colList[] = 'DROP CONSTRAINT ' . $curTable . '_pkey';
  574. }
  575. if (isset($indexes['add']['PRIMARY'])) {
  576. $cols = $indexes['add']['PRIMARY']['column'];
  577. if (is_array($cols)) {
  578. $cols = implode(', ', $cols);
  579. }
  580. $colList[] = 'ADD PRIMARY KEY (' . $cols . ')';
  581. }
  582. if (!empty($colList)) {
  583. $out .= "\t" . implode(",\n\t", $colList) . ";\n\n";
  584. } else {
  585. $out = '';
  586. }
  587. $out .= implode(";\n\t", $this->_alterIndexes($curTable, $indexes));
  588. }
  589. }
  590. return $out;
  591. }
  592. /**
  593. * Generate PostgreSQL index alteration statements for a table.
  594. *
  595. * @param string $table Table to alter indexes for
  596. * @param array $new Indexes to add and drop
  597. * @return array Index alteration statements
  598. */
  599. function _alterIndexes($table, $indexes) {
  600. $alter = array();
  601. if (isset($indexes['drop'])) {
  602. foreach($indexes['drop'] as $name => $value) {
  603. $out = 'DROP ';
  604. if ($name == 'PRIMARY') {
  605. continue;
  606. } else {
  607. $out .= 'INDEX ' . $name;
  608. }
  609. $alter[] = $out;
  610. }
  611. }
  612. if (isset($indexes['add'])) {
  613. foreach ($indexes['add'] as $name => $value) {
  614. $out = 'CREATE ';
  615. if ($name == 'PRIMARY') {
  616. continue;
  617. } else {
  618. if (!empty($value['unique'])) {
  619. $out .= 'UNIQUE ';
  620. }
  621. $out .= 'INDEX ';
  622. }
  623. if (is_array($value['column'])) {
  624. $out .= $name . ' ON ' . $table . ' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
  625. } else {
  626. $out .= $name . ' ON ' . $table . ' (' . $this->name($value['column']) . ')';
  627. }
  628. $alter[] = $out;
  629. }
  630. }
  631. return $alter;
  632. }
  633. /**
  634. * Returns a limit statement in the correct format for the particular database.
  635. *
  636. * @param integer $limit Limit of results returned
  637. * @param integer $offset Offset from which to start results
  638. * @return string SQL limit/offset statement
  639. */
  640. function limit($limit, $offset = null) {
  641. if ($limit) {
  642. $rt = '';
  643. if (!strpos(strtolower($limit), 'limit') || strpos(strtolower($limit), 'limit') === 0) {
  644. $rt = ' LIMIT';
  645. }
  646. $rt .= ' ' . $limit;
  647. if ($offset) {
  648. $rt .= ' OFFSET ' . $offset;
  649. }
  650. return $rt;
  651. }
  652. return null;
  653. }
  654. /**
  655. * Converts database-layer column types to basic types
  656. *
  657. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  658. * @return string Abstract column type (i.e. "string")
  659. */
  660. function column($real) {
  661. if (is_array($real)) {
  662. $col = $real['name'];
  663. if (isset($real['limit'])) {
  664. $col .= '(' . $real['limit'] . ')';
  665. }
  666. return $col;
  667. }
  668. $col = str_replace(')', '', $real);
  669. $limit = null;
  670. if (strpos($col, '(') !== false) {
  671. list($col, $limit) = explode('(', $col);
  672. }
  673. $floats = array(
  674. 'float', 'float4', 'float8', 'double', 'double precision', 'decimal', 'real', 'numeric'
  675. );
  676. switch (true) {
  677. case (in_array($col, array('date', 'time', 'inet', 'boolean'))):
  678. return $col;
  679. case (strpos($col, 'timestamp') !== false):
  680. return 'datetime';
  681. case (strpos($col, 'time') === 0):
  682. return 'time';
  683. case (strpos($col, 'int') !== false && $col != 'interval'):
  684. return 'integer';
  685. case (strpos($col, 'char') !== false || $col == 'uuid'):
  686. return 'string';
  687. case (strpos($col, 'text') !== false):
  688. return 'text';
  689. case (strpos($col, 'bytea') !== false):
  690. return 'binary';
  691. case (in_array($col, $floats)):
  692. return 'float';
  693. default:
  694. return 'text';
  695. break;
  696. }
  697. }
  698. /**
  699. * Gets the length of a database-native column description, or null if no length
  700. *
  701. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  702. * @return int An integer representing the length of the column
  703. */
  704. function length($real) {
  705. $col = str_replace(array(')', 'unsigned'), '', $real);
  706. $limit = null;
  707. if (strpos($col, '(') !== false) {
  708. list($col, $limit) = explode('(', $col);
  709. }
  710. if ($col == 'uuid') {
  711. return 36;
  712. }
  713. if ($limit != null) {
  714. return intval($limit);
  715. }
  716. return null;
  717. }
  718. /**
  719. * Enter description here...
  720. *
  721. * @param unknown_type $results
  722. */
  723. function resultSet(&$results) {
  724. $this->results =& $results;
  725. $this->map = array();
  726. $num_fields = pg_num_fields($results);
  727. $index = 0;
  728. $j = 0;
  729. while ($j < $num_fields) {
  730. $columnName = pg_field_name($results, $j);
  731. if (strpos($columnName, '__')) {
  732. $parts = explode('__', $columnName);
  733. $this->map[$index++] = array($parts[0], $parts[1]);
  734. } else {
  735. $this->map[$index++] = array(0, $columnName);
  736. }
  737. $j++;
  738. }
  739. }
  740. /**
  741. * Fetches the next row from the current result set
  742. *
  743. * @return unknown
  744. */
  745. function fetchResult() {
  746. if ($row = pg_fetch_row($this->results)) {
  747. $resultRow = array();
  748. foreach ($row as $index => $field) {
  749. list($table, $column) = $this->map[$index];
  750. $type = pg_field_type($this->results, $index);
  751. switch ($type) {
  752. case 'bool':
  753. $resultRow[$table][$column] = $this->boolean($row[$index], false);
  754. break;
  755. case 'binary':
  756. case 'bytea':
  757. $resultRow[$table][$column] = pg_unescape_bytea($row[$index]);
  758. break;
  759. default:
  760. $resultRow[$table][$column] = $row[$index];
  761. break;
  762. }
  763. }
  764. return $resultRow;
  765. } else {
  766. return false;
  767. }
  768. }
  769. /**
  770. * Translates between PHP boolean values and PostgreSQL boolean values
  771. *
  772. * @param mixed $data Value to be translated
  773. * @param boolean $quote True to quote value, false otherwise
  774. * @return mixed Converted boolean value
  775. */
  776. function boolean($data, $quote = true) {
  777. switch (true) {
  778. case ($data === true || $data === false):
  779. return $data;
  780. case ($data === 't' || $data === 'f'):
  781. return ($data === 't');
  782. case ($data === 'true' || $data === 'false'):
  783. return ($data === 'true');
  784. case ($data === 'TRUE' || $data === 'FALSE'):
  785. return ($data === 'TRUE');
  786. default:
  787. return (bool)$data;
  788. break;
  789. }
  790. }
  791. /**
  792. * Sets the database encoding
  793. *
  794. * @param mixed $enc Database encoding
  795. * @return boolean True on success, false on failure
  796. */
  797. function setEncoding($enc) {
  798. return pg_set_client_encoding($this->connection, $enc) == 0;
  799. }
  800. /**
  801. * Gets the database encoding
  802. *
  803. * @return string The database encoding
  804. */
  805. function getEncoding() {
  806. return pg_client_encoding($this->connection);
  807. }
  808. /**
  809. * Generate a Postgres-native column schema string
  810. *
  811. * @param array $column An array structured like the following:
  812. * array('name'=>'value', 'type'=>'value'[, options]),
  813. * where options can be 'default', 'length', or 'key'.
  814. * @return string
  815. */
  816. function buildColumn($column) {
  817. $col = $this->columns[$column['type']];
  818. if (!isset($col['length']) && !isset($col['limit'])) {
  819. unset($column['length']);
  820. }
  821. $out = preg_replace('/integer\([0-9]+\)/', 'integer', parent::buildColumn($column));
  822. $out = str_replace('integer serial', 'serial', $out);
  823. if (strpos($out, 'timestamp DEFAULT')) {
  824. if (isset($column['null']) && $column['null']) {
  825. $out = str_replace('DEFAULT NULL', '', $out);
  826. } else {
  827. $out = str_replace('DEFAULT NOT NULL', '', $out);
  828. }
  829. }
  830. if (strpos($out, 'DEFAULT DEFAULT')) {
  831. if (isset($column['null']) && $column['null']) {
  832. $out = str_replace('DEFAULT DEFAULT', 'DEFAULT NULL', $out);
  833. } elseif (in_array($column['type'], array('integer', 'float'))) {
  834. $out = str_replace('DEFAULT DEFAULT', 'DEFAULT 0', $out);
  835. } elseif ($column['type'] == 'boolean') {
  836. $out = str_replace('DEFAULT DEFAULT', 'DEFAULT FALSE', $out);
  837. }
  838. }
  839. return $out;
  840. }
  841. /**
  842. * Format indexes for create table
  843. *
  844. * @param array $indexes
  845. * @param string $table
  846. * @return string
  847. */
  848. function buildIndex($indexes, $table = null) {
  849. $join = array();
  850. if (!is_array($indexes)) {
  851. return array();
  852. }
  853. foreach ($indexes as $name => $value) {
  854. if ($name == 'PRIMARY') {
  855. $out = 'PRIMARY KEY (' . $this->name($value['column']) . ')';
  856. } else {
  857. $out = 'CREATE ';
  858. if (!empty($value['unique'])) {
  859. $out .= 'UNIQUE ';
  860. }
  861. if (is_array($value['column'])) {
  862. $value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
  863. } else {
  864. $value['column'] = $this->name($value['column']);
  865. }
  866. $out .= "INDEX {$name} ON {$table}({$value['column']});";
  867. }
  868. $join[] = $out;
  869. }
  870. return $join;
  871. }
  872. /**
  873. * Overrides DboSource::renderStatement to handle schema generation with Postgres-style indexes
  874. *
  875. * @param string $type
  876. * @param array $data
  877. * @return string
  878. */
  879. function renderStatement($type, $data) {
  880. switch (strtolower($type)) {
  881. case 'schema':
  882. extract($data);
  883. foreach ($indexes as $i => $index) {
  884. if (preg_match('/PRIMARY KEY/', $index)) {
  885. unset($indexes[$i]);
  886. $columns[] = $index;
  887. break;
  888. }
  889. }
  890. $join = array('columns' => ",\n\t", 'indexes' => "\n");
  891. foreach (array('columns', 'indexes') as $var) {
  892. if (is_array(${$var})) {
  893. ${$var} = implode($join[$var], array_filter(${$var}));
  894. }
  895. }
  896. return "CREATE TABLE {$table} (\n\t{$columns}\n);\n{$indexes}";
  897. break;
  898. default:
  899. return parent::renderStatement($type, $data);
  900. break;
  901. }
  902. }
  903. }