Postgres.php 26 KB

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